text:
package com.example.bigtable;

// [START bigtable_filters_print_hbase]

import static com.google.cloud.bigtable.data.v2.models.Filters.FILTERS;

import com.google.api.gax.rpc.ServerStream;
import com.google.bigtable.v2.ColumnRange;
import com.google.cloud.bigtable.hbase.BigtableConfiguration;
import java.io.IOException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.filter.BinaryComparator;
import org.apache.hadoop.hbase.filter.ColumnCountGetFilter;
import org.apache.hadoop.hbase.filter.ColumnPaginationFilter;
import org.apache.hadoop.hbase.filter.ColumnRangeFilter;
import org.apache.hadoop.hbase.filter.CompareFilter;
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.filter.FamilyFilter;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.FilterList.Operator;
import org.apache.hadoop.hbase.filter.PageFilter;
import org.apache.hadoop.hbase.filter.PrefixFilter;
import org.apache.hadoop.hbase.filter.QualifierFilter;
import org.apache.hadoop.hbase.filter.RandomRowFilter;
import org.apache.hadoop.hbase.filter.RegexStringComparator;
import org.apache.hadoop.hbase.filter.RowFilter;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.apache.hadoop.hbase.filter.SkipFilter;
import org.apache.hadoop.hbase.filter.ValueFilter;
import org.apache.hadoop.hbase.util.Bytes;

public class Filters {

  // Write your code here.
  // [START_EXCLUDE]
  // [START bigtable_filters_limit_row_sample_hbase]
  public static void filterLimitRowSample() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String instanceId = "my-instance-id";
    String tableId = "mobile-time-series";
    filterLimitRowSample(projectId, instanceId, tableId);
  }

  public static void filterLimitRowSample(String projectId, String instanceId, String tableId) {
    // A filter that matches cells from a row with probability .75
    Filter filter = new RandomRowFilter(.75f);
    Scan scan = new Scan().setFilter(filter);
    readWithFilter(projectId, instanceId, tableId, scan);
  }
  // [END bigtable_filters_limit_row_sample_hbase]

  // [START bigtable_filters_limit_row_regex_hbase]
  public static void filterLimitRowRegex() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String instanceId = "my-instance-id";
    String tableId = "mobile-time-series";
    filterLimitRowRegex(projectId, instanceId, tableId);
  }

  public static void filterLimitRowRegex(String projectId, String instanceId, String tableId) {
    // A filter that matches cells from rows whose keys satisfy the given regex
    Filter filter = new RowFilter(CompareOp.EQUAL, new RegexStringComparator(".*#20190501$"));
    Scan scan = new Scan().setFilter(filter).setMaxVersions();
    readWithFilter(projectId, instanceId, tableId, scan);
  }
  // [END bigtable_filters_limit_row_regex_hbase]

  // [START bigtable_filters_limit_cells_per_col_hbase]
  public static void filterLimitCellsPerCol() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String instanceId = "my-instance-id";
    String tableId = "mobile-time-series";
    filterLimitCellsPerCol(projectId, instanceId, tableId);
  }

  public static void filterLimitCellsPerCol(String projectId, String instanceId, String tableId) {
    // A filter that matches only the most recent 2 cells within each column
    Scan scan = new Scan().setMaxVersions(2);
    readWithFilter(projectId, instanceId, tableId, scan);
  }
  // [END bigtable_filters_limit_cells_per_col_hbase]

  // [START bigtable_filters_limit_cells_per_row_hbase]
  public static void filterLimitCellsPerRow() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String instanceId = "my-instance-id";
    String tableId = "mobile-time-series";
    filterLimitCellsPerRow(projectId, instanceId, tableId);
  }

  public static void filterLimitCellsPerRow(String projectId, String instanceId, String tableId) {
    // A filter that matches the first 2 cells of each row
    //    Filter filter = new ColumnCountGetFilter(2);
    Filter filter = new ColumnPaginationFilter(2, 0);

    Scan scan = new Scan().setFilter(filter);
    readWithFilter(projectId, instanceId, tableId, scan);
  }
  // [END bigtable_filters_limit_cells_per_row_hbase]

  // [START bigtable_filters_limit_cells_per_row_offset_hbase]
  public static void filterLimitCellsPerRowOffset() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String instanceId = "my-instance-id";
    String tableId = "mobile-time-series";
    filterLimitCellsPerRowOffset(projectId, instanceId, tableId);
  }

  public static void filterLimitCellsPerRowOffset(
      String projectId, String instanceId, String tableId) {
    // A filter that skips the first 2 cells per row
    Filter filter = new ColumnPaginationFilter(Integer.MAX_VALUE, 2);
    Scan scan = new Scan().setFilter(filter);
    readWithFilter(projectId, instanceId, tableId, scan);
  }
  // [END bigtable_filters_limit_cells_per_row_offset_hbase]

  // [START bigtable_filters_limit_col_family_regex_hbase]
  public static void filterLimitColFamilyRegex() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String instanceId = "my-instance-id";
    String tableId = "mobile-time-series";
    filterLimitColFamilyRegex(projectId, instanceId, tableId);
  }

  public static void filterLimitColFamilyRegex(
      String projectId, String instanceId, String tableId) {
    // A filter that matches cells whose column family satisfies the given regex
    Filter filter = new FamilyFilter(CompareOp.EQUAL, new RegexStringComparator("stats_.*$"));
    Scan scan = new Scan().setFilter(filter);
    readWithFilter(projectId, instanceId, tableId, scan);
  }
  // [END bigtable_filters_limit_col_family_regex_hbase]

  // [START bigtable_filters_limit_col_qualifier_regex_hbase]
  public static void filterLimitColQualifierRegex() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String instanceId = "my-instance-id";
    String tableId = "mobile-time-series";
    filterLimitColQualifierRegex(projectId, instanceId, tableId);
  }

  public static void filterLimitColQualifierRegex(
      String projectId, String instanceId, String tableId) {
    // A filter that matches cells whose column qualifier satisfies the given regex
    Filter filter =
        new QualifierFilter(CompareOp.EQUAL, new RegexStringComparator("connected_.*$"));
    Scan scan = new Scan().setFilter(filter);
    readWithFilter(projectId, instanceId, tableId, scan);
  }
  // [END bigtable_filters_limit_col_qualifier_regex_hbase]

  // [START bigtable_filters_limit_col_range_hbase]
  public static void filterLimitColRange() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String instanceId = "my-instance-id";
    String tableId = "mobile-time-series";
    filterLimitColRange(projectId, instanceId, tableId);
  }

  public static void filterLimitColRange(String projectId, String instanceId, String tableId) {
    // A filter that matches cells whose column qualifiers are between data_plan_01gb and
    // data_plan_10gb in the column family cell_plan
    Filter filter =
        new ColumnRangeFilter(
            Bytes.toBytes("data_plan_01gb"), true, Bytes.toBytes("data_plan_10gb"), false);
    Scan scan = new Scan().addFamily(Bytes.toBytes("cell_plan")).setFilter(filter).setMaxVersions();
    readWithFilter(projectId, instanceId, tableId, scan);
  }
  // [END bigtable_filters_limit_col_range_hbase]

  // [START bigtable_filters_limit_value_range_hbase]
  public static void filterLimitValueRange() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String instanceId = "my-instance-id";
    String tableId = "mobile-time-series";
    filterLimitValueRange(projectId, instanceId, tableId);
  }

  public static void filterLimitValueRange(String projectId, String instanceId, String tableId) {
    // A filter that matches cells whose values are between the given values
    ValueFilter valueGreaterFilter =
        new ValueFilter(
            CompareFilter.CompareOp.GREATER_OR_EQUAL,
            new BinaryComparator(Bytes.toBytes("PQ2A.190405")));
    ValueFilter valueLesserFilter =
        new ValueFilter(
            CompareFilter.CompareOp.LESS_OR_EQUAL,
            new BinaryComparator(Bytes.toBytes("PQ2A.190406")));

    FilterList filter = new FilterList(FilterList.Operator.MUST_PASS_ALL);
    filter.addFilter(valueGreaterFilter);
    filter.addFilter(valueLesserFilter);

    Scan scan = new Scan().setFilter(filter);
    readWithFilter(projectId, instanceId, tableId, scan);
  }
  // [END bigtable_filters_limit_value_range_hbase]

  // [START bigtable_filters_limit_value_regex_hbase]
  public static void filterLimitValueRegex() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String instanceId = "my-instance-id";
    String tableId = "mobile-time-series";
    filterLimitValueRegex(projectId, instanceId, tableId);
  }

  public static void filterLimitValueRegex(String projectId, String instanceId, String tableId) {
    // A filter that matches cells whose value satisfies the given regex
    Filter filter = new ValueFilter(CompareOp.EQUAL, new RegexStringComparator("PQ2A.*$"));

    Scan scan = new Scan().setFilter(filter);
    readWithFilter(projectId, instanceId, tableId, scan);
  }
  // [END bigtable_filters_limit_value_regex_hbase]

  // [START bigtable_filters_limit_timestamp_range_hbase]
  public static void filterLimitTimestampRange() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String instanceId = "my-instance-id";
    String tableId = "mobile-time-series";
    filterLimitTimestampRange(projectId, instanceId, tableId);
  }

  public static void filterLimitTimestampRange(
      String projectId, String instanceId, String tableId) {
    // A filter that matches cells whose timestamp is from an hour ago or earlier
    // Get a time representing one hour ago
    long timestamp = Instant.now().minus(1, ChronoUnit.HOURS).toEpochMilli();
    try {
      Scan scan = new Scan().setTimeRange(0, timestamp).setMaxVersions();
      readWithFilter(projectId, instanceId, tableId, scan);
    } catch (IOException e) {
      System.out.println("There was an issue with your timestamp \n" + e.toString());
    }
  }
  // [END bigtable_filters_limit_timestamp_range_hbase]

  // [START bigtable_filters_limit_block_all_hbase]
  public static void filterLimitBlockAll() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String instanceId = "my-instance-id";
    String tableId = "mobile-time-series";
    filterLimitBlockAll(projectId, instanceId, tableId);
  }

  public static void filterLimitBlockAll(String projectId, String instanceId, String tableId) {
    // A filter that does not match any cells
    Filter filter = new SkipFilter(new RandomRowFilter(1));
    Scan scan = new Scan().setFilter(filter);
    readWithFilter(projectId, instanceId, tableId, scan);
  }
  // [END bigtable_filters_limit_block_all_hbase]

  // [START bigtable_filters_composing_chain_hbase]
  public static void filterComposingChain() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String instanceId = "my-instance-id";
    String tableId = "mobile-time-series";
    filterComposingChain(projectId, instanceId, tableId);
  }

  public static void filterComposingChain(String projectId, String instanceId, String tableId) {
    // A filter that selects one cell per row AND within the column family cell_plan
    Filter familyFilter =
        new FamilyFilter(CompareOp.EQUAL, new BinaryComparator(Bytes.toBytes("cell_plan")));
    Filter columnCountGetFilter = new ColumnCountGetFilter(3);

    FilterList filter = new FilterList(FilterList.Operator.MUST_PASS_ALL);
    filter.addFilter(columnCountGetFilter);
    filter.addFilter(familyFilter);
    Scan scan = new Scan().setFilter(filter);
    readWithFilter(projectId, instanceId, tableId, scan);
  }
  // [END bigtable_filters_composing_chain_hbase]

  // [START bigtable_filters_composing_interleave_hbase]
  public static void filterComposingInterleave() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String instanceId = "my-instance-id";
    String tableId = "mobile-time-series";
    filterComposingInterleave(projectId, instanceId, tableId);
  }

  public static void filterComposingInterleave(
      String projectId, String instanceId, String tableId) {
    // A filter that matches cells with the value true OR with the column qualifier os_build
    Filter qualifierFilter =
        new QualifierFilter(CompareOp.EQUAL, new BinaryComparator(Bytes.toBytes("os_build")));
    Filter valueFilter =
        new ValueFilter(CompareOp.EQUAL, new BinaryComparator(Bytes.toBytes("true")));

    FilterList filter = new FilterList(Operator.MUST_PASS_ONE);
    filter.addFilter(qualifierFilter);
    filter.addFilter(valueFilter);

    Scan scan = new Scan().setFilter(filter).setMaxVersions();
    readWithFilter(projectId, instanceId, tableId, scan);
  }
  // [END bigtable_filters_composing_interleave_hbase]
  // [END_EXCLUDE]

  public static void readWithFilter(
      String projectId, String instanceId, String tableId, Scan scan) {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (Connection connection = BigtableConfiguration.connect(projectId, instanceId)) {
      Table table = connection.getTable(TableName.valueOf(tableId));

      ResultScanner rows = table.getScanner(scan);

      for (Result row : rows) {
        printRow(row);
      }
    } catch (IOException e) {
      System.out.println(
          "Unable to initialize service client, as a network error occurred: \n" + e.toString());
    }
  }

  private static void printRow(Result row) {
    System.out.printf("Reading data for %s%n", Bytes.toString(row.rawCells()[0].getRowArray()));
    String colFamily = "";
    for (Cell cell : row.rawCells()) {
      String currentFamily = Bytes.toString(cell.getFamilyArray());
      if (!currentFamily.equals(colFamily)) {
        colFamily = currentFamily;
        System.out.printf("Column Family %s%n", colFamily);
      }
      System.out.printf(
          "\t%s: %s @%s%n",
          Bytes.toString(cell.getQualifierArray()),
          Bytes.toString(cell.getValueArray()),
          cell.getTimestamp());
    }
    System.out.println();
  }
}
// [END bigtable_filters_print_hbase]


text:
@implementation SentryCrashExceptionApplication

#if TARGET_OS_OSX

- (void)reportException:(NSException *)exception {
    [[NSUserDefaults standardUserDefaults] registerDefaults:@{ @"NSApplicationCrashOnExceptions": @YES }];
    if (nil != SentryCrash.sharedInstance.uncaughtExceptionHandler && nil != exception) {
        SentryCrash.sharedInstance.uncaughtExceptionHandler(exception);
    }
    [super reportException:exception];
}
#endif

@end

redpajama_set_name: RedPajamaGithub


text:
Subscriptions

Get all subscriptions

 GET https://apis.wso2.com/api/am/store/v1/subscriptions

This operation can be used to retrieve a list of subscriptions of the user associated with the provided access token. This operation is capable of

1. Retrieving applications which are subscibed to a specific API.
`GET https://localhost:9443/api/am/store/v1/subscriptions?apiId=c43a325c-260b-4302-81cb-768eafaa3aed`

2. Retrieving APIs which are subscribed by a specific application.
`GET https://localhost:9443/api/am/store/v1/subscriptions?applicationId=c43a325c-260b-4302-81cb-768eafaa3aed`

**IMPORTANT:**
* It is mandatory to provide either **apiId** or **applicationId**.

OAuth 2.0 Scope

                apim:subscribe
                apim:sub_manage

                Examples

Parameters

                <colgroup>
                    <col style="width: 10%;"/>
                    <col style="width: 20%;"/>
                    <col style="width: 40%;"/>
                    <col style="width: 10%;"/>
                    <col style="width: 20%;"/>
                </colgroup>

                    Type
                    Name
                    Description
                    Schema
                    Default

                            Query

apiId

                                optional

**API ID** consisting of the **UUID** of the API.

                                String

                            Query

applicationId

                                optional

**Application Identifier** consisting of the UUID of the Application.

                                String

                            Query

groupId

                                optional

Application Group Id

                                String

                            Header

X-WSO2-Tenant

                                optional

For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be
  retirieved from.

                                String

                            Query

offset

                                optional

Starting point within the complete list of items qualified.

                                Integer

0

                            Query

limit

                                optional

Maximum size of resource array to return.

                                Integer

25

                            Header

If-None-Match

                                optional

Validator for conditional requests; based on the ETag of the formerly retrieved
variant of the resourec.

                                String

Responses

                <colgroup>
                    <col style="width: 15%;"/>
                    <col style="width: 70%;"/>
                    <col style="width: 15%;"/>
                </colgroup>

                    HTTP Code
                    Description
                    Schema

200

OK. Subscription list returned.

                                    SubscriptionList

304

Not Modified. Empty body because the client has already the latest version of the requested resource.

406

Not Acceptable. The requested media type is not supported

                                    Error

Add new subscriptions

 POST https://apis.wso2.com/api/am/store/v1/subscriptions/multiple

This operation can be used to add a new subscriptions providing the ids of the APIs and the applications.

OAuth 2.0 Scope

                apim:subscribe
                apim:sub_manage

                Examples

Parameters

                <colgroup>
                    <col style="width: 10%;"/>
                    <col style="width: 20%;"/>
                    <col style="width: 40%;"/>
                    <col style="width: 10%;"/>
                    <col style="width: 20%;"/>
                </colgroup>

                    Type
                    Name
                    Description
                    Schema
                    Default

                            Body

body

                                required

Subscription objects that should to be added

                                List
                                    (Subscription)

                            Header

X-WSO2-Tenant

                                optional

For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be
  retirieved from.

                                String

Responses

                <colgroup>
                    <col style="width: 15%;"/>
                    <col style="width: 70%;"/>
                    <col style="width: 15%;"/>
                </colgroup>

                    HTTP Code
                    Description
                    Schema

200

OK. Successful response with the newly created objects as entity in the body.

                                    Subscription

400

Bad Request. Invalid request or validation error.

                                    Error

415

Unsupported media type. The entity of the request was in a not supported format.

Add a new subscription

 POST https://apis.wso2.com/api/am/store/v1/subscriptions

This operation can be used to add a new subscription providing the id of the API and the application.

OAuth 2.0 Scope

                apim:subscribe
                apim:sub_manage

                Examples

Parameters

                <colgroup>
                    <col style="width: 10%;"/>
                    <col style="width: 20%;"/>
                    <col style="width: 40%;"/>
                    <col style="width: 10%;"/>
                    <col style="width: 20%;"/>
                </colgroup>

                    Type
                    Name
                    Description
                    Schema
                    Default

                            Body

body

                                required

Subscription object that should to be added

                                Subscription
                                    (Subscription)

                            Header

X-WSO2-Tenant

                                optional

For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be
  retirieved from.

                                String

Responses

                <colgroup>
                    <col style="width: 15%;"/>
                    <col style="width: 70%;"/>
                    <col style="width: 15%;"/>
                </colgroup>

                    HTTP Code
                    Description
                    Schema

201

Created. Successful response with the newly created object as entity in the body. Location header contains URL of newly created entity.

                                    Subscription

202

Accepted. The request has been accepted.

                                    WorkflowResponse

400

Bad Request. Invalid request or validation error.

                                    Error

415

Unsupported media type. The entity of the request was in a not supported format.

Remove a subscription

 DELETE https://apis.wso2.com/api/am/store/v1/subscriptions/{subscriptionId}

This operation can be used to remove a subscription.

OAuth 2.0 Scope

                apim:subscribe
                apim:sub_manage

                Examples

Parameters

                <colgroup>
                    <col style="width: 10%;"/>
                    <col style="width: 20%;"/>
                    <col style="width: 40%;"/>
                    <col style="width: 10%;"/>
                    <col style="width: 20%;"/>
                </colgroup>

                    Type
                    Name
                    Description
                    Schema
                    Default

                            Path

subscriptionId

                                required

Subscription Id

                                String

                            Header

If-Match

                                optional

Validator for conditional requests; based on ETag.

                                String

Responses

                <colgroup>
                    <col style="width: 15%;"/>
                    <col style="width: 70%;"/>
                    <col style="width: 15%;"/>
                </colgroup>

                    HTTP Code
                    Description
                    Schema

200

OK. Resource successfully deleted.

202

Accepted. The request has been accepted.

                                    WorkflowResponse

404

Not Found. Resource to be deleted does not exist.

                                    Error

412

Precondition Failed. The request has not been performed because one of the preconditions is not met.

                                    Error

Get details of a subscription

 GET https://apis.wso2.com/api/am/store/v1/subscriptions/{subscriptionId}

This operation can be used to get details of a single subscription.

OAuth 2.0 Scope

                apim:subscribe
                apim:sub_manage

                Examples

Parameters

                <colgroup>
                    <col style="width: 10%;"/>
                    <col style="width: 20%;"/>
                    <col style="width: 40%;"/>
                    <col style="width: 10%;"/>
                    <col style="width: 20%;"/>
                </colgroup>

                    Type
                    Name
                    Description
                    Schema
                    Default

                            Path

subscriptionId

                                required

Subscription Id

                                String

                            Header

If-None-Match

                                optional

Validator for conditional requests; based on the ETag of the formerly retrieved
variant of the resourec.

                                String

Responses

                <colgroup>
                    <col style="width: 15%;"/>
                    <col style="width: 70%;"/>
                    <col style="width: 15%;"/>
                </colgroup>

                    HTTP Code
                    Description
                    Schema

200

OK. Subscription returned

                                    Subscription

304

Not Modified. Empty body because the client has already the latest version of the requested resource.

404

Not Found. Requested Subscription does not exist.

                                    Error

Update existing subscription

 PUT https://apis.wso2.com/api/am/store/v1/subscriptions/{subscriptionId}

This operation can be used to update a subscription providing the subscription id, api id, application Id, status and updated throttling policy tier.

OAuth 2.0 Scope

                apim:subscribe
                apim:sub_manage

                Examples

Parameters

                <colgroup>
                    <col style="width: 10%;"/>
                    <col style="width: 20%;"/>
                    <col style="width: 40%;"/>
                    <col style="width: 10%;"/>
                    <col style="width: 20%;"/>
                </colgroup>

                    Type
                    Name
                    Description
                    Schema
                    Default

                            Body

body

                                required

Subscription object that should to be added

                                Subscription
                                    (Subscription)

                            Path

subscriptionId

                                required

Subscription Id

                                String

                            Header

X-WSO2-Tenant

                                optional

For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be
  retirieved from.

                                String

Responses

                <colgroup>
                    <col style="width: 15%;"/>
                    <col style="width: 70%;"/>
                    <col style="width: 15%;"/>
                </colgroup>

                    HTTP Code
                    Description
                    Schema

200

Subscription Updated. Successful response with the updated object as entity in the body. Location header contains URL of newly updates entity.

                                    Subscription

202

Accepted. The request has been accepted.

                                    WorkflowResponse

304

Not Modified. Empty body because the client has already the latest version of the requested resource.

400

Bad Request. Invalid request or validation error.

                                    Error

404

Not Found. Requested Subscription does not exist.

415

Unsupported media type. The entity of the request was in a not supported format.


text:
from platform import app
import os

app.secret_key = os.urandom(24)
app.run(host="0.0.0.0", debug=True)


text:
Imports BVSoftware.Bvc5.Core

Partial Class BVAdmin_Controls_CategoryPicker
    Inherits System.Web.UI.UserControl

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack() Then
            BindCategoriesGridView()
        End If
    End Sub

    Protected Sub BindCategoriesGridView()
        CategoriesGridView.DataSource = Catalog.Category.ListFullTreeWithIndents(True)
        CategoriesGridView.DataKeyNames = New String() {"value"}
        CategoriesGridView.DataBind()
    End Sub

    Public ReadOnly Property SelectedCategories() As StringCollection
        Get
            Dim result As New StringCollection
            For Each row As GridViewRow In CategoriesGridView.Rows
                If DirectCast(row.Cells(0).FindControl("chkSelected"), CheckBox).Checked Then
                    result.Add(CategoriesGridView.DataKeys(row.RowIndex).Value)
                End If
            Next
            Return result
        End Get
    End Property
End Class


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="jp.a34910.android.accelerogram2.MainActivity$PlaceholderFragment" >

    <LinearLayout
        android:id="@+id/surfaceLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <jp.a34910.android.accelerogram2.SurfaceGraph
            android:id="@+id/surfaceGraph"
            android:layout_width="match_parent"
            android:layout_height="@dimen/graph_height" />

        <jp.a34910.android.accelerogram2.SurfaceCursor
            android:id="@+id/surfaceCursor"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />

	</LinearLayout>

	<WebView
        android:id="@+id/map_view"
        android:layout_width="@dimen/webview_width"
        android:layout_height="@dimen/webview_height"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true" />

	<ImageButton
	    android:id="@+id/calibration_btn"
	    android:layout_width="@dimen/imagebtn_width"
	    android:layout_height="@dimen/imagebtn_height"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:contentDescription="@string/btn_calibration"
	    android:src="@drawable/ic_calibration" />

    <LinearLayout
        android:id="@+id/commander_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:gravity="center_vertical"
        android:background="@drawable/frame_shape" >

        <ImageButton
            android:id="@+id/rec_btn"
            android:layout_width="@dimen/imagebtn_width"
            android:layout_height="@dimen/imagebtn_height"
            android:layout_marginRight="5dp"
            android:contentDescription="@string/btn_rec"
            android:src="@drawable/ic_rec" />

        <ImageButton
            android:id="@+id/replay_btn"
            android:layout_width="@dimen/imagebtn_width"
            android:layout_height="@dimen/imagebtn_height"
            android:layout_marginRight="5dp"
            android:contentDescription="@string/btn_replay"
            android:src="@drawable/ic_replay" />

        <ImageButton
            android:id="@+id/stop_btn"
            android:layout_width="@dimen/imagebtn_width"
            android:layout_height="@dimen/imagebtn_height"
            android:layout_marginRight="5dp"
            android:contentDescription="@string/btn_pause"
            android:src="@drawable/ic_stop" />

    	<ImageButton
        	android:id="@+id/gmode_btn"
            android:layout_width="@dimen/imagebtn_width"
            android:layout_height="@dimen/imagebtn_height"
	        android:layout_marginRight="5dp"
        	android:contentDescription="@string/btn_graphmode"
        	android:src="@drawable/ic_graphmode" />

       <Space
            android:layout_width="40dp"
            android:layout_height="match_parent" />

	</LinearLayout>
</RelativeLayout>


text:
class Detour::PercentageFlag < Detour::Flag
  validates_presence_of     :percentage
  validates_numericality_of :percentage, greater_than: 0, less_than_or_equal_to: 100
  validates_uniqueness_of   :feature_id, scope: :flaggable_type

  attr_accessible :percentage
end


text:
[![APEX Community](https://cdn.rawgit.com/Dani3lSun/apex-github-badges/78c5adbe/badges/apex-community-badge.svg)](https://github.com/Dani3lSun/apex-github-badges) [![APEX Plugin](https://cdn.rawgit.com/Dani3lSun/apex-github-badges/b7e95341/badges/apex-plugin-badge.svg)](https://github.com/Dani3lSun/apex-github-badges)
[![APEX Built with Love](https://cdn.rawgit.com/Dani3lSun/apex-github-badges/7919f913/badges/apex-love-badge.svg)](https://github.com/Dani3lSun/apex-github-badges)

Dropzone is a region type plugin that allows you to provide nice looking drag'n'drop file uploads.
It is based on JS Framework dropzone.js (https://github.com/enyo/dropzone).

## Demo Application
https://apex.oracle.com/pls/apex/f?p=APEXPLUGIN

## Changelog

#### 2.4.1 - Use wwv_flow.ajax endpoint instead of wwv_flow.show for all AJAX actions

#### 2.4.0 - changed "Normal" upload method to use multipart/form-data requests, no base64 conversion needed + works with all web servers

#### 2.3.0 - min. APEX version now is 5.1 ! / Changed chunked upload to also use base64 f01 array (double chunked mechanism) / delete AJAX call only when file has no error

#### 2.2.4 - Updated Dropzone framework to 5.5.0

#### 2.2.3 - Fixed displaying of special characters #39 / some server side code improvements

#### 2.2.2 - Updated Dropzone framework to 5.3.0

#### 2.2.1 - server side waiting: use custom procedure instead of APEX_UTIL.PAUSE (thus only full seconds are possible)

#### 2.2.0 - APEX 5.2 compatibility / Updated Dropzone framework to 5.3.0 / enable dynamic substitution strings for table or collection name / removed parallel uploads option / changed client side waiting to server side waiting after file gets uploaded, removed waiting attribute, general improvements of js and pl/sql code

#### 2.1.0 - Added client side image resizing (before sending to server) / Added configurable chunk size of chunked file uploads

#### 2.0.4 - Added much more detailed Total Upload Progress

#### 2.0.3 - New Style *Grey Dashed Border/Background* / Improved deleting Files (No longer via Filename, instead the APEX Collection Seq-ID or PK Value of Custom Table is used)

#### 2.0.2 - Performance Improvements for Chunked File Uploads / Improved Upload Status for Chunked File Uploads / Improved Client Side Debug Logging / Improved Server AJAX Error Handling

#### 2.0.1 - Performance Improvements for Chunked File Uploads / Improved Client Side Debug Logging / Oracle Database EPG Note in Docs & Help Pages

#### 2.0.0 - Complete new Version built from ground up. Now much easier to use and with more features

- Choose where to save the Files (APEX Collection or Custom Table)
- No more writing of custom PL/SQL Code inside the Plugin (much more Update save)
- More Events that Developers can use for custom Interactions
- Choose the Upload Method (**Normal: 1 Request** or **Chunked: Multiple Requests**)
- Improved Error Handling and Logging for the whole AJAX based Upload Process
- Possibility to delete Files which were accidentally uploaded to the Server
- Better Documentation on Github and in the Plugin Attribute Help
- Much better Internationalization and App Wide definition of Messages
- And of course all the "old" Features as well

***Upgrade Notes:***

- As the Plugin was rewritten from ground up, Version 2.0.0 is completely incompatible with prior Versions! It is recommended that you install Version 2.0.0 beside Version 1.XX and replace all Dropzone Regions in your App.
- If you didn´t touch the default PL/SQL Code of Version 1.XX and used the default Settings then the Upgrade Process should be straight forward (APEX Collection is the same).
- If you used Plugin Events in Version 1.XX, you have to change these to the Plugin Events of Dropzone 2.*
- If you customized the PL/SQL Code of Version 1.XX to insert additional information, please see [Inserting uploaded files into your own tables](#inserting-uploaded-files-into-your-own-tables) for information on conveting to the Plugin's default upload method to an APEX Collection, with a PL/SQL dynamic action to perform your custom insert.

---

<details>
  <summary>Changelog Version 1.XX</summary>

#### 1.9.6 - fixed issue #15 (Page Items to Submit) / Added new event "Dropzone max files exceeded" (issue #13)
*Update Note from v1.9.5: It may be required to renew the PL/SQL Code (Upload) to the default which is shipped with this plugin. Unfortunately Plugin Attributes are not updated automatically.*

#### 1.9.5 - fully compatible with APEX 5.1 / Delete files inside Dropzone / General Code Cleanup / New Plugin Events / Float number as max Filesize
*Update Note: It may be required to renew the PL/SQL Code (Upload) to the default which is shipped with this plugin. Unfortunately Plugin Attributes are not updated automatically.*

#### 1.9.4 - updated dropzone library to 4.3.0 / added a much more detailed upload progress bar per file

#### 1.9.3 - solved performance issues when converting larger files from base64 CLOB to BLOB

#### 1.9.2 - added a random file id to APEX collection (better identification of file by it´s id) / empty file mime types now set to "application/octet-stream" / code cleanup

#### 1.9.1 - added more file preview images / more structured file paths / APEX event triggers on Region (not body) / no global js functions any more, wrapped code in namespace "apexDropzone" / cleaned up js code

#### 1.9 - added option to include a custom callback javascript function which get executed on chosen events (added file & upload completed) + added APEX events for added file & upload completed to trigger Dynamic Actions

#### 1.8 - added option to select a default dropzone style (1: grey border / 2: blue dashed border) / added option to display file type preview images for common file types / minified css/js files (full files for debug mode)

#### 1.7 - solved lots of performance issues (file + base64 data get uploaded to server) / stability improvements

#### 1.6 - added number of parallel uploads option (1 or 2 concurrent) / performance improvements (base64 encoding when file was added instead of sending moment) / better error handling

#### 1.5 - performance improvements(removed redundant AJAX call) / split the clob into a 30k param array (OHS 32k limit for params) / added callback function to apex.server.plugin that processes the files queue

#### 1.4 - added option to refresh a chosen region (with REGION_STATIC_ID) after uploading of all files is complete / Copy&Paste support of images in modern Browsers (like Chrome)

#### 1.3 - set default for "max Files" to dropzone default of 256

#### 1.2 - added max files per upload option / added customizable messages for better multilingual support

#### 1.1 - added options to limit uploading of declared file types (file endings, mime_types, wildcards) / clear dropzone area after uploading of all files finished

#### 1.0 - Initial Release

#### Beta - In development

</details>

## Install
- Import plugin file "region_type_plugin_de_danielh_dropzone2.sql" from source directory into your application
- (Optional) Deploy the CSS/JS files from "server" directory on your webserver and change the "File Prefix" to web servers folder (Inside the Plugin Settings).

## Plugin Settings
The plugin settings are highly customizable and you can change:

- **Storage Type**

  - Choose where the uploaded Files are saved. You can either save your Files to a APEX Collection or to a Custom Table.

- **Collection / Table Name**

  - Name of the APEX Collection or of your Custom Table. Default APEX Collection: **DROPZONE_UPLOAD**.
  - *Note: "Custom Table" setting is limited to storing the filename, mime type, and upload date, in addition to the file content itself. To store additional information, please use **APEX Collection** and see the [Inserting uploaded files into your own tables](#inserting-uploaded-files-into-your-own-tables) section below.*

- **Filename Column**

  - Column of your custom Table which holds the information for the Filename. Only if **Storage Type** is set to **Custom Table**

- **Mime Type Column**

  - Column of your custom Table which holds the information for the File Mime-Type. Only if **Storage Type** is set to **Custom Table**

- **BLOB Column**

  - Column of your custom Table which holds the information for the File Content (BLOB). Only if **Storage Type** is set to **Custom Table**

  - **PK Column**

    - Primary Key (PK) Column of your custom file Table. Only if **Storage Type** is set to **Custom Table**

- **Date Column**

  - Column of your custom Table which holds the information for the File Upload Date. Only if **Storage Type** is set to **Custom Table**

- **Upload Mechanism**

  - **Normal**
    - **AJAX:** Async Method

    - This Upload Method encodes the File into a Base64 String. This String is then split into an 30kb Array which sends the encoded/splitted File in **1 Request** to the Server. This Method works on all Web Servers including Oracle OHS, Oracle WebTier, Oracle Database EPG, Oracle ORDS, Apache, Tomcat. But for large Files the **maxPostSize** Parameter have to be increased on Tomcat Servers (Default 2MB). **Max. File size should not exceed ~50MB.**

  - **Chunked**
    - **AJAX:** Async Method

    - This Upload Method splits a File into 1MB Pieces *(Default / Please Change Component Setting "Chunk Size (in KB))")*. Then this 1MB Chunks are base64 encoded and sent via **Multiple Requests** (For every MB 1 Request) to the Server. This Method works best on modern Web Servers like ORDS, Tomcat or Apache, but not on Oracle OHS, Oracle WebTier or Oracle Database EPG! This Method is good, when you don´t have the possibility to configure Parameters of the Web Server like **maxPostSize**  or want to Upload **large Files (> 50MB)**. If you can edit the Web Servers Config you should go with the *Normal* Mechanism. But if you expect a lot of big files that get uploaded this Method should be fine for that!

- **Delete Files**

  - Possibility for end users to delete each file that was uploaded to the server. Only if no Page Refresh has occurred.

- **Dropzone Style**

  - UI Style of your Dropzone Region. You can choose either *Grey Border, Blue Dashed Border or Red Dashed Border*

- **Width**

  - Enter the default width of your Dropzone Region. Valid values are px and % data. E.g. 700px or 100%

- **Height**

  - Enter the default height of Dropzone Region. Valid values in px. E.g. 400px or 500px

- **max. Filesize in MB**

  - max. File Size (Float Number) that is allowed per File. If a File is larger, it will be removed.

- **max. Files**

  - Maximum number of allowed files that can be uploaded at once.

- **Accepted File Types**

  - If you only want that users can upload Files of declared types. Valid values: comma separated list of Mime-Types (with Wildcard support) or File endings: image/\*,application/pdf,.psd

- **Clickable**

  - If true, the Dropzone Region will be clickable, if false nothing will be clickable and only Drag & Drop is possible.

- **Show File Previews**

  - Show Preview Images for common File types when adding files. Image-Files got displayed with real content. If you want to add more images or others just Copy/Upload the PNG Files to *img* directory. Naming: **\<file-extension\>.png**

- **Copy & Paste Support**

  - Adds support for Copy & Paste of Images in modern Browsers (like Chrome or Firefox > 50).

- **Image Resizing**

  - If true, images are resized to a specified size. This happens on client side before uploading the file to server. Saving upload bandwidth and reducing upload time. Please set at least one resize attribute, e.g. Resize Width or Resize Height.

- **Resize Width**

  - If set, images will be resized to these dimensions before being uploaded. If only one, resize Width or resize Height is provided, the original aspect ratio of the file will be preserved. Please provide a width in pixels.

- **Resize Height**

  - If set, images will be resized to these dimensions before being uploaded. If only one, resize Width or resize Height is provided, the original aspect ratio of the file will be preserved. Please provide a height in pixels.

- **Remove Files after Upload**

  - If true, clears all Files from Dropzone Region after uploading has finished.

- **Chunk Size (in KB) (Application Scope)**

  - This is the default chunk size if you choose the Chunked upload mechanism. The file is split into pieces of that size. Each piece is sent to the server separately. Thus the files are base64 encoded, there is a little overhead in the file size, so please consider a plus of about 10-15% in file size. Default is 1MB = 1048576 KB.

- **Display Message (Application Scope)**

  - Message that is displayed inside of the Dropzone Region

- **Fallback Message (Application Scope)**

  - Message that is displayed when your Browser doesn´t support HTML5 Drag & Drop File Uploads

- **File too Big Message (Application Scope)**

  - Message that is displayed per File, if the File is bigger than you allowed in the settings. You can use Placeholders like: **{{filesize}}** or **{{maxFilesize}}**

- **max. Files Message (Application Scope)**

  - Message that is displayed per File, if the uploaded Files exceed the max. Files settings. You can use Placeholders like: **{{maxFiles}}**

- **Remove File Message (Application Scope)**

  - Message that is displayed below a single File to remove the File. Only when **Delete Files** is set.

- **Cancel Upload Message (Application Scope)**

  - Message that is displayed below a single File to Cancel Uploading during the actual Upload Process. Only when **Delete Files** is set.

- **Cancel Upload Confirm Message (Application Scope)**

  - Message that is displayed in the Confirm Dialog if you clicked the Upload Cancel Link. Only when **Delete Files** is set.

- **Invalid File Type Message (Application Scope)**

  - Message that is displayed per File, if the File´s Mime-Type is in the Exclude List.

## Plugin Events
- **Dropzone File added**

  - DA event that fires when a single file was added to the Dropzone Region (Client Side)
  - this.data holds the file element, e.g file.name or file.size

- **Dropzone Chunked File Upload Success (AJAX)**

  - DA event that fires when uploading 1 Chunk of a File was successful (Server Side) (Upload Mechanism **Chunked**)
  - this.data holds the Server response object

- **Dropzone Chunked File Upload Error (AJAX)**

  - DA event that fires when uploading 1 Chunk of a File has an error (Server Side) (Upload Mechanism **Chunked**)
  - this.data holds the Server response object

- **Dropzone File Upload Success (AJAX)**

  - DA event that fires when uploading a File was successful (Server Side) (Upload Mechanism **Normal**)
  - this.data holds the Server response object

- **Dropzone File Upload Error (AJAX)**

  - DA event that fires when uploading a File has an error (Server Side) (Upload Mechanism **Normal**)
  - this.data holds the Server response object

- **Dropzone Upload completed**

  - DA event that fires when uploading all files completed (Client Side)

- **Dropzone File deleted**

  - DA event that fires if the Remove File Link of a File is pressed (Client Side)
  - this.data holds the file element, e.g file.name or file.size

- **Dropzone File Delete Success (AJAX)**

  - DA event that fires when deleting a single files was successful (Server Side)
  - this.data holds the Server response object

- **Dropzone File Delete Error (AJAX)**

  - DA event that fires when deleting a single files has an error (Server Side)
  - this.data holds the Server response object

- **Dropzone max Files exceeded**

  - DA event that fires per file when more files are added to the Dropzone than allowed (Client Side)
  - this.data holds the file element, e.g file.name or file.size

- **Dropzone Total Upload Progress**

  - DA that fires from time to time during upload of all files and return the Total Upload Progress (Client Side)
  - this.data holds the totalPercentage element

- **Dropzone File Error**
  - DA that fires when processing a file has an error (Client Side)
  - this.data holds the file element, e.g file.name, file.size or file.errorMessage

- **Dropzone Dragging File over Region**
  - DA that fires when dragging a file over the Dropzone Region (Client Side)

## How to use
- Create a Dropzone region on target page
- Choose best fitting Plugin Attributes (Help included)

#### Get files from APEX Collection
If you use the default Options provided with this Plugin, the files are saved in a APEX collection called **DROPZONE_UPLOAD**. Select it like that:

```language-sql
SELECT c001    AS filename,
       c002    AS mime_type,
       d001    AS date_created,
       n001    AS file_id,
       blob001 AS file_content
  FROM apex_collections
 WHERE collection_name = 'DROPZONE_UPLOAD';
 ```

#### Inserting uploaded files into your own tables

Although the plugin settings allow you to upload the files directly into your custom table, the default setting of **APEX Collection** is preferred, as this method provides the flexibility to do custom processing prior to inserting the data into the custom table.
A typical use case for this is referencing foreign keys. This is easily accomplished using Dynamic Action with PL/SQL code, as follows, assuming the foreign key ID is stored in page item `P1_FK_ID`:

- Event: Dropzone Upload completed
- Selection: *your dropzone region*
- PL/SQL Code:

```plsql
DECLARE
  -- get files data from saved apex_collection
  CURSOR l_cur_files IS
    SELECT c001    AS filename,
           c002    AS mime_type,
           d001    AS date_created,
           n001    AS file_id,
           blob001 AS file_content
      FROM apex_collections
     WHERE collection_name = 'DROPZONE_UPLOAD';
BEGIN
  -- loop over files cursor
  FOR l_rec_files IN l_cur_files LOOP
    -- do whatever processing is required prior to the insert into your own table
    INSERT INTO custom_table (
        filename,
        mime_type,
        upload_date,
        file_content,
        fk_id
    ) VALUES (
        l_rec_files.filename,
        l_rec_files.mime_type,
        l_rec_files.date_created,
        l_rec_files.file_content,
        :P1_FK_ID
    );
  END LOOP;
  -- clear original apex collection (only if exist)
  IF apex_collection.collection_exists(p_collection_name => 'DROPZONE_UPLOAD') THEN
    apex_collection.delete_collection(p_collection_name => 'DROPZONE_UPLOAD');
  END IF;
END;
```

## Hint for ORDS and Tomcat users
If you have Problems uploading larger Files **(only with prefered Upload Mechanism "Normal")**, then it could be a Issue with the max. allowed Post Size of Tomcat Server (default is 2MB). To get around this issue please add the Parameter **maxPostSize** with a Byte value to your Connector in server.xml file of Tomcat.

For AJP connector:
```
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" address="127.0.0.1" maxPostSize="15728640" />
```

For HTTP connector:
```
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" address="127.0.0.1" maxPostSize="15728640" />
```

This example sets maxPostSize to 15MB or 15728640 bytes. Setting the maxPostSize attribute to a value less than zero (e.g -1) disables the whole limitation.
More about it in the [Tomcat 8 Documentation](https://tomcat.apache.org/tomcat-8.0-doc/config/http.html#Attributes)

## Preview
![](https://github.com/Dani3lSun/apex-plugin-dropzone/blob/master/preview.gif)

#### Preview Copy&Paste
![](https://github.com/Dani3lSun/apex-plugin-dropzone/blob/master/preview_copy_paste.gif)
---


text:
using namespace std;
using namespace DirectX;

class Triangle :public D3D12AppBase, public D3D12Base
{
public:
	Triangle(const HWND _hwnd, const int _width, const int _height);
	~Triangle();

	virtual void OnInit();
	virtual void OnRelease();
	virtual void OnUpdate();
	virtual void OnRender();

	virtual void OnKeyUp();
	virtual void OnKeyDown();

private:
	struct Vertex
	{
		XMFLOAT3 position;
		XMFLOAT4 color;
	};// A struct

	ComPtr<ID3D12Resource> vertexBuffer;
	D3D12_VERTEX_BUFFER_VIEW vertexBufferView;
	// Ó¦ÓóÌÐò×ÊÔ´

	virtual void InitializePipeline();
	virtual void InitializeAssets();
	void PopulateCommandList();
	void WaitForPreviousFrame();
	void WaitForGpu();
	void NextFrame();
};

#endif // !__TRIANGLE_H__


text:
package com.wind.common.plugin;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.*;

import java.util.List;
import java.util.Properties;

/**
 * Example类和model类实现序列化插件
 * Created by liuqijie on 2017/6/26.
 */
public class SerializablePlugin extends PluginAdapter {
    private FullyQualifiedJavaType serializable = new FullyQualifiedJavaType("java.io.Serializable");
    private FullyQualifiedJavaType gwtSerializable = new FullyQualifiedJavaType("com.google.gwt.user.client.rpc.IsSerializable");
    private boolean addGWTInterface;
    private boolean suppressJavaInterface;

    public SerializablePlugin() {
    }

    public boolean validate(List<String> warnings) {
        return true;
    }

    public void setProperties(Properties properties) {
        super.setProperties(properties);
        this.addGWTInterface = Boolean.valueOf(properties.getProperty("addGWTInterface")).booleanValue();
        this.suppressJavaInterface = Boolean.valueOf(properties.getProperty("suppressJavaInterface")).booleanValue();
    }

    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        this.makeSerializable(topLevelClass, introspectedTable);
        return true;
    }

    public boolean modelPrimaryKeyClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        this.makeSerializable(topLevelClass, introspectedTable);
        return true;
    }

    public boolean modelRecordWithBLOBsClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        this.makeSerializable(topLevelClass, introspectedTable);
        return true;
    }

    protected void makeSerializable(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        if(this.addGWTInterface) {
            topLevelClass.addImportedType(this.gwtSerializable);
            topLevelClass.addSuperInterface(this.gwtSerializable);
        }

        if(!this.suppressJavaInterface) {
            topLevelClass.addImportedType(this.serializable);
            topLevelClass.addSuperInterface(this.serializable);
            Field field = new Field();
            field.setFinal(true);
            field.setInitializationString("1L");
            field.setName("serialVersionUID");
            field.setStatic(true);
            field.setType(new FullyQualifiedJavaType("long"));
            field.setVisibility(JavaVisibility.PRIVATE);
            this.context.getCommentGenerator().addFieldComment(field, introspectedTable);
            topLevelClass.addField(field);
        }

    }

    /**
     * 添加给Example类序列化的方法
     * @param topLevelClass
     * @param introspectedTable
     * @return
     */
    @Override
    public boolean modelExampleClassGenerated(TopLevelClass topLevelClass,IntrospectedTable introspectedTable){
        makeSerializable(topLevelClass, introspectedTable);

        for (InnerClass innerClass : topLevelClass.getInnerClasses()) {
            if ("GeneratedCriteria".equals(innerClass.getType().getShortName())) {
                innerClass.addSuperInterface(serializable);
            }
            if ("Criteria".equals(innerClass.getType().getShortName())) {
                innerClass.addSuperInterface(serializable);
            }
            if ("Criterion".equals(innerClass.getType().getShortName())) {
                innerClass.addSuperInterface(serializable);
            }
        }

        return true;
    }

}


text:
<?php

declare(strict_types=1);

namespace DoctrineMigrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
final class Version20190619203125 extends AbstractMigration
{
    public function getDescription() : string
    {
        return '';
    }

    public function up(Schema $schema) : void
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE department ADD slug VARCHAR(128) NOT NULL');
        $this->addSql('CREATE UNIQUE INDEX UNIQ_CD1DE18A989D9B62 ON department (slug)');
    }

    public function down(Schema $schema) : void
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('DROP INDEX UNIQ_CD1DE18A989D9B62 ON department');
        $this->addSql('ALTER TABLE department DROP slug');
    }
}


text:
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { setupIntl } from 'ember-intl/test-support';
import setupMirage from 'ember-cli-mirage/test-support/setup-mirage';
import { render } from '@ember/test-helpers';
import { hbs } from 'ember-cli-htmlbars';
import { component } from 'ilios/tests/pages/components/school-competencies-collapsed';

module('Integration | Component | school competencies collapsed', function (hooks) {
  setupRenderingTest(hooks);
  setupIntl(hooks, 'en-us');
  setupMirage(hooks);

  test('it renders', async function (assert) {
    const school = this.server.create('school');
    const domain = this.server.create('competency', { school });
    const domain2 = this.server.create('competency', { school });
    this.server.create('competency', { school });
    this.server.create('competency', { school, parent: domain2 });
    this.server.createList('competency', 3, { school, parent: domain });
    const schoolModel = await this.owner.lookup('service:store').find('school', school.id);

    this.set('school', schoolModel);
    await render(hbs`<SchoolCompetenciesCollapsed @school={{this.school}} @expand={{(noop)}} />`);

    assert.strictEqual(component.expandButton.text, 'Competencies (3/4)');
    assert.strictEqual(component.domains.length, 3);
    assert.strictEqual(component.domains[0].title, 'competency 0');
    assert.strictEqual(component.domains[0].summary, 'There are 3 subcompetencies');
    assert.strictEqual(component.domains[1].title, 'competency 1');
    assert.strictEqual(component.domains[1].summary, 'There is 1 subcompetency');
    assert.strictEqual(component.domains[2].title, 'competency 2');
    assert.strictEqual(component.domains[2].summary, 'There are 0 subcompetencies');
  });

  test('clicking expand fires action', async function (assert) {
    assert.expect(1);
    const school = this.server.create('school');
    const schoolModel = await this.owner.lookup('service:store').find('school', school.id);

    this.set('school', schoolModel);
    this.set('expand', () => assert.ok(true));
    await render(
      hbs`<SchoolCompetenciesCollapsed @school={{this.school}} @expand={{this.expand}} />`
    );
    await component.expandButton.click();
  });
});


text:
//===--- DataflowDiagnostics.cpp - Emits diagnostics based on SIL analysis ===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/AST/ASTContext.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Stmt.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/SILConstants.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILLocation.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/ConstExpr.h"

using namespace swift;

template<typename...T, typename...U>
static void diagnose(ASTContext &Context, SourceLoc loc, Diag<T...> diag,
              U &&...args) {
  Context.Diags.diagnose(loc,
                         diag, std::forward<U>(args)...);
}

static void diagnoseMissingReturn(const UnreachableInst *UI,
                                  ASTContext &Context) {
  const SILBasicBlock *BB = UI->getParent();
  const SILFunction *F = BB->getParent();
  SILLocation FLoc = F->getLocation();

  Type ResTy;
  BraceStmt *BS;

  if (auto *FD = FLoc.getAsASTNode<FuncDecl>()) {
    ResTy = FD->getResultInterfaceType();
    BS = FD->getBody(/*canSynthesize=*/false);
  } else if (auto *CD = FLoc.getAsASTNode<ConstructorDecl>()) {
    ResTy = CD->getResultInterfaceType();
    BS = FD->getBody();
  } else if (auto *CE = FLoc.getAsASTNode<ClosureExpr>()) {
    ResTy = CE->getResultType();
    BS = CE->getBody();
  } else {
    llvm_unreachable("unhandled case in MissingReturn");
  }

  SILLocation L = UI->getLoc();
  assert(L && ResTy);
  if (!BS->empty()) {
    auto element = BS->getLastElement();
    if (auto expr = element.dyn_cast<Expr *>()) {
      if (expr->getType()->getRValueType()->isEqual(ResTy)) {
        if (FLoc.isASTNode<ClosureExpr>()) {
          Context.Diags.diagnose(expr->getStartLoc(),
                                 diag::missing_return_closure, ResTy);
        } else {
          auto *DC = FLoc.getAsDeclContext();
          assert(DC && DC->getAsDecl() && "not a declaration?");
          Context.Diags.diagnose(expr->getStartLoc(), diag::missing_return_decl,
                                 ResTy, DC->getAsDecl()->getDescriptiveKind());
        }
        Context.Diags
            .diagnose(expr->getStartLoc(), diag::missing_return_last_expr_note)
            .fixItInsert(expr->getStartLoc(), "return ");

        return;
      }
    }
  }

  bool isNoReturnFn = F->isNoReturnFunction(F->getTypeExpansionContext());
  if (FLoc.isASTNode<ClosureExpr>()) {
    auto diagID = isNoReturnFn ? diag::missing_never_call_closure
                               : diag::missing_return_closure;
    diagnose(Context, L.getEndSourceLoc(), diagID, ResTy);
  } else {
    auto *DC = FLoc.getAsDeclContext();
    assert(DC && DC->getAsDecl() && "not a declaration?");
    auto diagID = isNoReturnFn ? diag::missing_never_call_decl
                               : diag::missing_return_decl;
    diagnose(Context, L.getEndSourceLoc(), diagID, ResTy,
             DC->getAsDecl()->getDescriptiveKind());
  }
}

static void diagnoseUnreachable(const SILInstruction *I,
                                ASTContext &Context) {
  if (auto *UI = dyn_cast<UnreachableInst>(I)) {
    SILLocation L = UI->getLoc();

    // Invalid location means that the instruction has been generated by SIL
    // passes, such as DCE. FIXME: we might want to just introduce a separate
    // instruction kind, instead of keeping this invariant.
    //
    // We also do not want to emit diagnostics for code that was
    // transparently inlined. We should have already emitted these
    // diagnostics when we process the callee function prior to
    // inlining it.
    if (!L || L.is<MandatoryInlinedLocation>())
      return;

    // The most common case of getting an unreachable instruction is a
    // missing return statement. In this case, we know that the instruction
    // location will be the enclosing function.
    if (L.isASTNode<AbstractFunctionDecl>() || L.isASTNode<ClosureExpr>()) {
      diagnoseMissingReturn(UI, Context);
      return;
    }

    if (auto *Guard = L.getAsASTNode<GuardStmt>()) {
      diagnose(Context, Guard->getBody()->getEndLoc(),
               diag::guard_body_must_not_fallthrough);
      return;
    }
  }
}

/// Issue diagnostics whenever we see Builtin.static_report(1, ...).
static void diagnoseStaticReports(const SILInstruction *I,
                                  SILModule &M) {

  // Find out if we are dealing with Builtin.staticReport().
  if (auto *BI = dyn_cast<BuiltinInst>(I)) {
    const BuiltinInfo &B = BI->getBuiltinInfo();
    if (B.ID == BuiltinValueKind::StaticReport) {

      // Report diagnostic if the first argument has been folded to '1'.
      OperandValueArrayRef Args = BI->getArguments();
      auto *V = dyn_cast<IntegerLiteralInst>(Args[0]);
      if (!V || V->getValue() != 1)
        return;

      diagnose(M.getASTContext(), I->getLoc().getSourceLoc(),
               diag::static_report_error);
    }
  }
}

/// Emit a diagnostic for `poundAssert` builtins whose condition is
/// false or whose condition cannot be evaluated.
static void diagnosePoundAssert(const SILInstruction *I,
                                SILModule &M,
                                ConstExprEvaluator &constantEvaluator) {
  auto *builtinInst = dyn_cast<BuiltinInst>(I);
  if (!builtinInst ||
      builtinInst->getBuiltinKind() != BuiltinValueKind::PoundAssert)
    return;

  SmallVector<SymbolicValue, 1> values;
  constantEvaluator.computeConstantValues({builtinInst->getArguments()[0]},
                                          values);
  SymbolicValue value = values[0];
  if (!value.isConstant()) {
    diagnose(M.getASTContext(), I->getLoc().getSourceLoc(),
             diag::pound_assert_condition_not_constant);

    // If we have more specific information about what went wrong, emit
    // notes.
    if (value.getKind() == SymbolicValue::Unknown)
      value.emitUnknownDiagnosticNotes(builtinInst->getLoc());
    return;
  }
  assert(value.getKind() == SymbolicValue::Integer &&
         "sema prevents non-integer #assert condition");

  APInt intValue = value.getIntegerValue();
  assert(intValue.getBitWidth() == 1 &&
         "sema prevents non-int1 #assert condition");
  if (intValue.isNullValue()) {
    auto *message = cast<StringLiteralInst>(builtinInst->getArguments()[1]);
    StringRef messageValue = message->getValue();
    if (messageValue.empty())
      messageValue = "assertion failed";
    diagnose(M.getASTContext(), I->getLoc().getSourceLoc(),
             diag::pound_assert_failure, messageValue);
    return;
  }
}

static void diagnoseUnspecializedPolymorphicBuiltins(SILInstruction *inst) {
  // We only validate if we are in a non-transparent function.
  if (inst->getFunction()->isTransparent())
    return;

  auto *bi = dyn_cast<BuiltinInst>(inst);
  if (!bi)
    return;

  auto kind = bi->getBuiltinKind();
  if (!kind)
    return;

  if (!isPolymorphicBuiltin(*kind))
    return;

  const auto &builtinInfo = bi->getBuiltinInfo();

  // First that the parameters were acceptable so we can emit a nice error to
  // guide the user.
  for (SILValue value : bi->getOperandValues()) {
    SILType type = value->getType();
    SourceLoc loc;
    if (auto *inst = value->getDefiningInstruction()) {
      loc = inst->getLoc().getSourceLoc();
    } else {
      loc = bi->getLoc().getSourceLoc();
    }

    if (!type.is<BuiltinType>() || !type.isTrivial(*bi->getFunction())) {
      diagnose(bi->getModule().getASTContext(), loc,
               diag::polymorphic_builtin_passed_non_trivial_non_builtin_type,
               type.getASTType());
      return;
    }
  }

  // Ok, we have a valid type for a polymorphic builtin. Make sure we actually
  // have a static overload for this type.
  PolymorphicBuiltinSpecializedOverloadInfo overloadInfo;
  bool ableToMapToStaticOverload = overloadInfo.init(bi);
  (void)ableToMapToStaticOverload;
  assert(ableToMapToStaticOverload);
  if (!overloadInfo.doesOverloadExist()) {
    diagnose(bi->getModule().getASTContext(), bi->getLoc().getSourceLoc(),
             diag::polymorphic_builtin_passed_type_without_static_overload,
             overloadInfo.staticOverloadIdentifier,
             getBuiltinName(builtinInfo.ID),
             overloadInfo.argTypes.front().getASTType());
    return;
  }

  // Otherwise, something happen that we did not understand. This can only
  // happen if we specialize the generic type in the builtin /after/ constant
  // propagation runs at -Onone but before dataflow diagnostics. This is an
  // error in implementation, so we assert.
  llvm_unreachable("Found generic builtin with known static overload that it "
                   "could be transformed to. Did this builtin get its generic "
                   "type specialized /after/ constant propagation?");
}

namespace {
class EmitDFDiagnostics : public SILFunctionTransform {
  ~EmitDFDiagnostics() override {}

  /// The entry point to the transformation.
  void run() override {
    // Don't rerun diagnostics on deserialized functions.
    if (getFunction()->wasDeserializedCanonical())
      return;

    SILModule &M = getFunction()->getModule();
    for (auto &BB : *getFunction()) {
      for (auto &I : BB) {
        diagnoseUnreachable(&I, M.getASTContext());
        diagnoseStaticReports(&I, M);
        diagnoseUnspecializedPolymorphicBuiltins(&I);
      }
    }

    if (M.getASTContext().LangOpts.hasFeature(Feature::StaticAssert)) {
      SymbolicValueBumpAllocator allocator;
      ConstExprEvaluator constantEvaluator(allocator,
                                           getOptions().AssertConfig);
      for (auto &BB : *getFunction())
        for (auto &I : BB)
          diagnosePoundAssert(&I, M, constantEvaluator);
    }
  }
};

} // end anonymous namespace

SILTransform *swift::createEmitDFDiagnostics() {
  return new EmitDFDiagnostics();
}


text:
package com.azure.resourcemanager.eventgrid.implementation;

import com.azure.resourcemanager.eventgrid.fluent.models.EventTypeInner;
import com.azure.resourcemanager.eventgrid.models.EventType;

public final class EventTypeImpl implements EventType {
    private EventTypeInner innerObject;

    private final com.azure.resourcemanager.eventgrid.EventGridManager serviceManager;

    EventTypeImpl(EventTypeInner innerObject, com.azure.resourcemanager.eventgrid.EventGridManager serviceManager) {
        this.innerObject = innerObject;
        this.serviceManager = serviceManager;
    }

    public String id() {
        return this.innerModel().id();
    }

    public String name() {
        return this.innerModel().name();
    }

    public String type() {
        return this.innerModel().type();
    }

    public String displayName() {
        return this.innerModel().displayName();
    }

    public String description() {
        return this.innerModel().description();
    }

    public String schemaUrl() {
        return this.innerModel().schemaUrl();
    }

    public Boolean isInDefaultSet() {
        return this.innerModel().isInDefaultSet();
    }

    public EventTypeInner innerModel() {
        return this.innerObject;
    }

    private com.azure.resourcemanager.eventgrid.EventGridManager manager() {
        return this.serviceManager;
    }
}


text:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

	safe_include(COREPATH."controllers/App_controller.php");

class Admin_Controller extends App_Controller
{

	public $namespace;
	public $_search_conditions 			= array("search_type", "search_text");
	public $_narrow_search_conditions 	= array();
	public $_session_namespace;
	public $_session_narrow_namespace;
	public $previous_url				= '';

    protected $_logged_in_only         =    false;
    public $error_message              =    '';
    public $data                       =    array();
    public $role                       =    '';
    public $load_css                   =    array();
    public $load_js                    =    array();
    public $ins_data                   =    array();

    protected $_login_validation_rules =    array (
                                                    array('field' => 'email', 'label' => 'Email', 'rules' => 'trim|required|xss_clean'),
                                                    array('field' => 'password', 'label' => 'Password', 'rules' => 'trim|required|xss_clean|min_length[4]|max_length[20]|alpha_dash')
                                                  );
   protected $useradd_validation_rules =    array();
   protected $role_validation_rules    =    array();
   public $init_scripts = array();

    public function __construct()
    {
        parent::__construct();

        //set name-spaces for session-storage of each controller-method pair.
        $this->namespace = strtolower($this->uri->segment(1, 'admin').'_'.$this->uri->segment(2, 'index'));

        //echo '<pre>';print_r($this->session->all_userdata());
        //get all session keys
        $sess_keys = array_keys($this->session->all_userdata());

        /*unset session-data stored by using namespaces.But except the current controller-methos pair's data.
         There are list of methods if current method is one of those, dont unset the session.*/
        $current_method = $this->uri->segment(3, 'index');
        $methods_list = array('index', 'price_list','test');// these are the methods which are having grid-view
        if(in_array($current_method, $methods_list))
        {
            $keys = array('search_conditions','search_narrow_conditions','fields','per_page','order_field','direction');
            foreach ($sess_keys as $key => $value)
            {
                foreach ($keys as $key)
                {
                    $position1 = strpos($value, $key);
                    $position2 = strpos($value, $this->namespace);
                    if($position2 !== 0 && $position1 !== false && $position1 != 0)
                    $this->session->unset_userdata($value);
                }
            }
        }
//print $this->namespace;exit;

        /*
        if(!is_logged_in()) {

            redirect('login');
        }
        */

        $this->data = array();
        //$this->role = get_user_role();

        $this->load->library("form_validation");

        $this->load->model("user_model");

        $id = $this->session->userdata('admin_data')['id'];
        if($id!="")
        {
            $user_data = $this->user_model->get_user_data("users",array("id" => $id));

            $this->data['user_image'] = $user_data[0]['profile_img'];
        }

        $this->data['img_url']=$this->layout->get_img_dir();

    }

    public function _ajax_output($data, $json_format = FALSE)
    {
    	if(is_array($data) && $json_format)
        	echo json_encode($data);
    	else
    		echo $data;

        exit();
    }

        function get_advance_filter_form( $namespace = '' )
    {
        //load pagination config
        $this->load->config("listing", TRUE);

        //get current grid's config by using namespace.
        $pagination = $this->config->item($namespace, 'listing');

        //To populate the form, get the previous data if available in session.
        $this->data = $this->session->userdata($namespace.'_search_narrow_conditions');
        //print_r($this->data);die;
        //now get the form
        $form = $this->load->view($pagination['advance_search_view'], $this->data, TRUE);

        if($this->input->is_ajax_request())
        $this->_ajax_output(array('advance_filter_form' => $form), TRUE);

        return TRUE;
    }

    /**
     * This function sets the number of records per page for grid.
     *@param string namespace <p>
     * It is the namespace of current grid-view page.
     * </p>
     * @return void.
     */
    function set_records_per_page( $namespace = '' )
    {
        $per_page = ((int)$this->input->post('per_page'))?$this->input->post('per_page'):20;

        $this->session->set_userdata($namespace.'_per_page', $per_page);

        if($this->input->is_ajax_request())
            $this->_ajax_output(array('status' => 'success'), TRUE);

        return TRUE;
    }

}

?>


text:
Released June 24, 2013 ([0.0.3](https://github.com/jonahoffline/cinch-forecast/tree/v0.0.3)).

* Refactor the clean_up method.
* Add yard documentation.
* Update 'Cinch' dependency to '2.0.5' in gemspec
* Add CodeClimate badge to README.
* Add Changelog.

## 0.0.2

Released June 06, 2013 ([0.0.2](https://github.com/jonahoffline/cinch-forecast/tree/v0.0.2)).

* Fix exception issue.
* Refactor the clean_up method.
* Add BadgeFury and Gemnasium badges to README.

## 0.0.1

Released June 05, 2013 ([0.0.1](https://github.com/jonahoffline/cinch-forecast/tree/v0.0.1)).

* Initial Release.


text:
package com.microsoftopentechnologies.intellij.wizards.createvm;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.ui.table.JBTable;
import com.intellij.ui.wizard.WizardNavigationState;
import com.intellij.ui.wizard.WizardStep;
import com.microsoftopentechnologies.tooling.msservices.components.DefaultLoader;
import com.microsoftopentechnologies.tooling.msservices.helpers.azure.AzureCmdException;
import com.microsoftopentechnologies.tooling.msservices.helpers.azure.AzureManagerImpl;
import com.microsoftopentechnologies.tooling.msservices.model.storage.StorageAccount;
import com.microsoftopentechnologies.tooling.msservices.model.vm.Endpoint;
import com.microsoftopentechnologies.tooling.msservices.model.vm.VirtualMachine;
import com.microsoftopentechnologies.tooling.msservices.serviceexplorer.azure.vm.VMNode;
import com.microsoftopentechnologies.tooling.msservices.serviceexplorer.azure.vm.VMServiceModule;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Vector;

public class EndpointStep extends WizardStep<CreateVMWizardModel> {
    private final VMServiceModule node;
    private CreateVMWizardModel model;
    private JPanel rootPanel;
    private JList createVmStepsList;
    private JTable endpointsTable;
    private JComboBox portNameComboBox;
    private JButton addButton;
    private Project project;

    public EndpointStep(final CreateVMWizardModel model, Project project, VMServiceModule node) {
        super("Endpoint Settings", null, null);

        this.node = node;
        this.project = project;
        this.model = model;

        endpointsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        model.configStepList(createVmStepsList, 4);

        Endpoint[] defaultEndpoints = {
                new Endpoint("Remote Desktop", "TCP", 3389, 3389),
                new Endpoint("Powershell", "TCP", 5986, 5986),
                new Endpoint("Http", "TCP", 80, 80),
                new Endpoint("SSH", "TCP", 22, 22),
                new Endpoint("FTP", "TCP", 21, 21),
                new Endpoint("SMTP", "TCP", 25, 25),
                new Endpoint("MYSQL", "TCP", 3306, 3306),
                new Endpoint("MSSQL", "TCP", 1433, 1433),
                new Endpoint("DNS", "TCP", 53, 53),
                new Endpoint("POP3", "TCP", 110, 110),
                new Endpoint("POP3S", "TCP", 995, 995),
                new Endpoint("Https", "TCP", 443, 443),
                new Endpoint("SMTPS", "TCP", 587, 587),
                new Endpoint("LDAP", "TCP", 389, 389),
                new Endpoint("IMAP", "TCP", 143, 143),
                new Endpoint("WebDeploy", "TCP", 8172, 8172),
        };

        portNameComboBox.setModel(new DefaultComboBoxModel(defaultEndpoints));

        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                EndpointTableModel endpointsTableModel = (EndpointTableModel) endpointsTable.getModel();

                if (portNameComboBox.getSelectedItem() instanceof Endpoint) {
                    Endpoint selectedItem = (Endpoint) portNameComboBox.getSelectedItem();
                    endpointsTableModel.getData().add(new Endpoint(
                            selectedItem.getName(),
                            selectedItem.getProtocol(),
                            selectedItem.getPrivatePort(),
                            selectedItem.getPublicPort()));
                } else {
                    endpointsTableModel.getData().add(new Endpoint(portNameComboBox.getSelectedItem().toString(), "TCP", 0, 0));
                }

                endpointsTableModel.fireTableDataChanged();
            }
        });

        final EndpointTableModel endpointTableModel = new EndpointTableModel();

        endpointsTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent evt) {
                int row = endpointsTable.rowAtPoint(evt.getPoint());
                int col = endpointsTable.columnAtPoint(evt.getPoint());

                if (col == 5) {
                    //Determine if click was on the "X" label
                    if (endpointsTable.getWidth() - 30 < evt.getX()) {
                        endpointTableModel.getData().remove(row);
                        endpointTableModel.fireTableDataChanged();
                    }
                }
            }
        });

        endpointTableModel.addTableModelListener(new TableModelListener() {
            @Override
            public void tableChanged(TableModelEvent tableModelEvent) {
                boolean hasErrors = false;

                for (int i = 0; i < endpointTableModel.getRowCount() && !hasErrors; i++) {
                    String errorFromRow = getErrorFromRow(i, endpointTableModel.getData());

                    if (errorFromRow.length() > 0) {
                        hasErrors = true;
                    }
                }

                model.getCurrentNavigationState().FINISH.setEnabled(!hasErrors);
            }
        });

        endpointsTable.setTableHeader(null);

        endpointsTable.setModel(endpointTableModel);
    }

    @Override
    public JComponent prepare(WizardNavigationState wizardNavigationState) {
        rootPanel.revalidate();

        endpointsTable.getColumnModel().getColumn(0).setPreferredWidth(15);
        endpointsTable.getColumnModel().getColumn(1).setPreferredWidth(150);
        endpointsTable.getColumnModel().getColumn(2).setPreferredWidth(75);
        endpointsTable.getColumnModel().getColumn(3).setPreferredWidth(75);
        endpointsTable.getColumnModel().getColumn(4).setPreferredWidth(60);
        endpointsTable.getColumnModel().getColumn(5).setPreferredWidth(205);

        EndpointTableModel endpointTableModel = (EndpointTableModel) endpointsTable.getModel();

        if (model.getEndpoints() == null) {
            if (model.getVirtualMachineImage().getOperatingSystemType().equals("Windows")) {
                endpointTableModel.getData().add(new Endpoint("Powershell", "TCP", 5983, 5983));
                endpointTableModel.getData().add(new Endpoint("Remote Desktop", "TCP", 3389, 3389));
            } else {
                endpointTableModel.getData().add(new Endpoint("SSH", "TCP", 22, 22));
            }
        } else {
            endpointTableModel.getData().removeAllElements();

            for (Endpoint ep : model.getEndpoints()) {
                endpointTableModel.getData().add(ep);
            }
        }

        return rootPanel;
    }

    @Override
    public WizardStep onPrevious(CreateVMWizardModel model) {
        Vector<Endpoint> endpointData = ((EndpointTableModel) endpointsTable.getModel()).getData();
        model.setEndpoints(endpointData.toArray(new Endpoint[endpointData.size()]));

        return super.onPrevious(model);
    }

    @Override
    public boolean onFinish() {
        final EndpointTableModel tableModel = (EndpointTableModel) endpointsTable.getModel();
        ProgressManager.getInstance().run(new Task.Backgroundable(project, "Creating virtual machine...", false) {

            @Override
            public void run(@NotNull ProgressIndicator progressIndicator) {
                progressIndicator.setIndeterminate(true);

                try {
                    VirtualMachine virtualMachine = new VirtualMachine(
                            model.getName(),
                            model.getCloudService().getName(),
                            model.getCloudService().getProductionDeployment().getName(),
                            model.getAvailabilitySet(),
                            model.getSubnet(),
                            model.getSize().getName(),
                            VirtualMachine.Status.Unknown,
                            model.getSubscription().getId()
                    );

                    virtualMachine.getEndpoints().addAll(tableModel.getData());

                    String certificate = model.getCertificate();
                    byte[] certData = new byte[0];

                    if (!certificate.isEmpty()) {
                        File certFile = new File(certificate);

                        if (certFile.exists()) {
                            FileInputStream certStream = null;

                            try {
                                certStream = new FileInputStream(certFile);
                                certData = new byte[(int) certFile.length()];

                                if (certStream.read(certData) != certData.length) {
                                    throw new Exception("Unable to process certificate: stream longer than informed size.");
                                }
                            } finally {
                                if (certStream != null) {
                                    try {
                                        certStream.close();
                                    } catch (IOException ignored) {
                                    }
                                }
                            }
                        }
                    }

                    StorageAccount storageAccount = model.getStorageAccount();

                    for (StorageAccount account : AzureManagerImpl.getManager().getStorageAccounts(
                            model.getSubscription().getId())) {
                        if (account.getName().equals(storageAccount.getName())) {
                            storageAccount = account;
                            break;
                        }
                    }

                    AzureManagerImpl.getManager().createVirtualMachine(virtualMachine,
                            model.getVirtualMachineImage(),
                            storageAccount,
                            model.getVirtualNetwork() != null ? model.getVirtualNetwork().getName() : "",
                            model.getUserName(),
                            model.getPassword(),
                            certData);

                    virtualMachine = AzureManagerImpl.getManager().refreshVirtualMachineInformation(virtualMachine);

                    final VirtualMachine vm = virtualMachine;

                    ApplicationManager.getApplication().invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                node.addChildNode(new VMNode(node, vm));
                            } catch (AzureCmdException e) {
                                DefaultLoader.getUIHelper().showException("An error occurred while trying to refresh the list of virtual machines",
                                        e,
                                        "Error Refreshing VM List",
                                        false,
                                        true);
                            }
                        }
                    });
                } catch (Exception e) {
                    DefaultLoader.getUIHelper().showException("An error occurred while trying to create the specified virtual machine",
                            e,
                            "Error Creating Virtual Machine",
                            false,
                            true);
                }
            }
        });

        return super.onFinish();
    }

    private void createUIComponents() {
        endpointsTable = new JBTable() {
            @Override
            public TableCellRenderer getCellRenderer(int row, int col) {
                switch (col) {
                    case 0:
                        return new ErrorRenderer();
                    case 4:
                        return new ProtocolRenderer();
                    case 5:
                        return new DeleteRenderer();
                    default:
                        return super.getCellRenderer(row, col);
                }
            }

            @Override
            public TableCellEditor getCellEditor(int row, int col) {
                if (col == 4) {
                    return new DefaultCellEditor(new ComboBox(new String[]{"TCP", "UDP"}));
                } else {
                    return super.getCellEditor(row, col);
                }
            }
        };
    }

    private static String getErrorFromRow(int row, Vector<Endpoint> list) {
        String errors = "";
        Endpoint endpoint = list.get(row);

        if (endpoint.getName().length() < 3 && endpoint.getName().length() > 15) {
            errors = errors + "The name must between 3 and 15 character long. \n";
        }

        if (!endpoint.getName().matches("^[A-Za-z0-9][A-Za-z0-9-\\s]+[A-Za-z0-9]$")) {
            errors = errors + "The name must start with a letter or number, " +
                    "contain only letters, numbers, and hyphens, " +
                    "and end with a letter or number. \n";
        }

        if (endpoint.getPrivatePort() < 1 || endpoint.getPrivatePort() > 65535) {
            errors = errors + "The private port must between a number between 1 and 65535. \n";
        }

        boolean containsName = false;
        boolean containsPublicPort = false;
        boolean containsPrivatePort = false;

        for (Endpoint ep : list) {
            if (ep != endpoint && ep.getName().equals(endpoint.getName())) {
                containsName = true;
            }

            if (ep != endpoint && ep.getProtocol().equals(endpoint.getProtocol()) && ep.getPrivatePort() == endpoint.getPrivatePort()) {
                containsPrivatePort = true;
            }

            if (ep != endpoint && ep.getProtocol().equals(endpoint.getProtocol()) && ep.getPublicPort() == endpoint.getPublicPort()) {
                containsPublicPort = true;
            }
        }

        if (containsName) {
            errors = errors + "The name must be unique. \n";
        }

        if (containsPrivatePort) {
            errors = errors + "The private port and the protocol conflicts with another in the virtual machine. \n";
        }

        if (containsPublicPort) {
            errors = errors + "The public port and the protocol conflicts with another in the virtual machine. \n";
        }

        return errors;
    }

    private class DeleteRenderer extends JPanel implements TableCellRenderer {
        public DeleteRenderer() {
            setOpaque(false);
            setLayout(new BorderLayout());
        }

        @Override
        public Component getTableCellRendererComponent(final JTable jTable, Object o, boolean b, boolean b1, final int row, int i1) {
            JLabel jLabel = new JLabel();
            jLabel.setForeground(Color.red);
            jLabel.setText("X  ");
            jLabel.setBackground(Color.WHITE);
            jLabel.setHorizontalAlignment(JButton.RIGHT);
            jLabel.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 14));

            this.add(jLabel, BorderLayout.LINE_END);

            return this;
        }
    }

    private class ProtocolRenderer extends ComboBox implements TableCellRenderer {
        public ProtocolRenderer() {
            super(new String[]{"TCP", "UDP"});
        }

        @Override
        public Component getTableCellRendererComponent(JTable jTable, Object value, boolean b, boolean b1, int i, int i1) {
            setSelectedItem(value);

            return this;
        }
    }

    private class ErrorRenderer extends JLabel implements TableCellRenderer {
        public ErrorRenderer() {
            setOpaque(false);
        }

        @Override
        public Component getTableCellRendererComponent(JTable jTable, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
            setPreferredSize(new Dimension(getSize().width, 15));
            setForeground(Color.red);
            setHorizontalAlignment(CENTER);
            setFont(getFont().deriveFont(Font.BOLD));

            if (jTable.getModel() != null && jTable.getModel() instanceof EndpointTableModel) {
                EndpointTableModel endpointTableModel = (EndpointTableModel) jTable.getModel();
                String errorList = getErrorFromRow(row, endpointTableModel.getData());
                setToolTipText(errorList);
                setText(errorList.isEmpty() ? "" : "!");
            }

            return this;
        }
    }

    private class EndpointTableModel extends AbstractTableModel {
        private Vector<Endpoint> data = new Vector<Endpoint>();
        private String[] columns = new String[]{"", "Port name", "Public port", "Private port", "Protocol", ""};

        @Override
        public int getRowCount() {
            return data.size();
        }

        @Override
        public int getColumnCount() {
            return columns.length;
        }

        @Override
        public String getColumnName(int i) {
            return columns[i];
        }

        @Override
        public boolean isCellEditable(int row, int col) {
            return (col > 0 && col < 5);
        }

        @Override
        public Object getValueAt(int row, int column) {
            Endpoint endpoint = data.get(row);
            switch (column) {
                case 1:
                    return endpoint.getName();
                case 2:
                    return endpoint.getPublicPort();
                case 3:
                    return endpoint.getPrivatePort();
                case 4:
                    return endpoint.getProtocol();
                default:
                    return "";
            }
        }

        @Override
        public void setValueAt(Object object, int row, int col) {
            Endpoint endpoint = data.get(row);
            switch (col) {
                case 1:
                    endpoint.setName(object.toString());
                    break;
                case 2:
                    try {
                        int publicPort = Integer.parseInt(object.toString());
                        endpoint.setPublicPort(publicPort);
                    } catch (NumberFormatException ignored) {
                    }

                    break;
                case 3:
                    try {
                        int privatePort = Integer.parseInt(object.toString());
                        endpoint.setPrivatePort(privatePort);
                    } catch (NumberFormatException ignored) {
                    }

                    break;
                case 4:
                    endpoint.setProtocol(object.toString());
                    break;
            }

            fireTableCellUpdated(row, col);
        }

        public Vector<Endpoint> getData() {
            return data;
        }
    }
}