text:
First, you may want to [Ramp up](#ramp-up) on Kubernetes and Custom Resource Definitions (CRDs) as Tekton implements several Kubernetes resource controllers configured by Tekton CRDs. Then follow these steps to start developing and contributing project code:

1. [Setting up a development environment](#setting-up-a-development-environment)
    1. [Setup a GitHub account accessible via SSH](#setup-a-github-account-accessible-via-ssh)
    1. [Install tools](#install-tools)
    1. [Configure environment](#configure-environment)
    1. [Setup a fork](#setup-a-fork) of the [tektoncd/pipeline](https://github.com/tektoncd/pipeline) project repository
    1. [Configure a container image registry](#configure-container-registry)
1. [Building and deploying](#building-and-deploying) Tekton source code from a local clone.
    1. [Setup a Kubernetes cluster](#setup-a-kubernetes-cluster)
    1. [Configure kubectl to use your cluster](https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/)
    1. [Set up a docker repository 'ko' can push images to](https://github.com/knative/serving/blob/4a8c859741a4454bdd62c2b60069b7d05f5468e7/docs/setting-up-a-docker-registry.md)
1. [Developing and testing](#developing-and-testing) Tekton pipelines
    1. Learn how to [iterate](#iterating-on-code-changes) on code changes
    1. [Managing Tekton Objects using `ko`](#managing-tekton-objects-using-ko) in Kubernetes
    1. [Accessing logs](#accessing-logs)
    1. [Adding new CRD types](#adding-new-crd-types)

---

### Ramp up

Welcome to the project! :clap::clap::clap:  You may find these resources helpful to "ramp up" on some of the technologies this project builds and runs on.
This project extends Kubernetes (aka `k8s`) with Custom Resource Definitions (CRDs).
To learn about how this works, check out our [developer documentation](docs/developers/controller-logic.md).

After reading the developer docs, you may find it useful to return to these `Tekton Pipeline` docs:

-   [Tekton Pipeline README](https://github.com/tektoncd/pipeline/blob/main/docs/README.md) -
    Some of the terms here may make more sense!
-   Install via
    [official installation docs](https://github.com/tektoncd/pipeline/blob/main/docs/install.md)
    or continue through [getting started for development](#getting-started)
-   [Tekton Pipeline "Hello World" tutorial](https://github.com/tektoncd/pipeline/blob/main/docs/tutorial.md) -
    Define `Tasks` and `Pipelines` (i.e., Tekton CRDs), and see what happens when they are run

---

## Setting up a development environment

### Setup a GitHub account accessible via SSH

GitHub is used for project Source Code Management (SCM) using the SSH protocol for authentication.

1. Create [a GitHub account](https://github.com/join) if you do not already have one.
1. Setup
[GitHub access via SSH](https://help.github.com/articles/connecting-to-github-with-ssh/)

### Install tools

You must install these tools:

1. [`git`](https://help.github.com/articles/set-up-git/): For source control

1. [`go`](https://golang.org/doc/install): The language Tekton Pipelines is
    built in.
    > **Note** Golang [version v1.15](https://golang.org/dl/) or higher is recommended.

1. [`ko`](https://github.com/google/ko#install): The Tekton project  uses `ko` to simplify the building of its container images from `go` source, push these images to the configured image repository and deploy these images into Kubernetes clusters.
    > **Note** `ko` version v0.5.1 or
    higher is required for `pipeline` to work correctly.

1. [`kubectl`](https://kubernetes.io/docs/tasks/tools/install-kubectl/): For
    interacting with your Kubernetes cluster

    > :warning: The user interacting with your K8s cluster **must be a cluster admin** to create role bindings.

    **Google Cloud Platform (GCP) example**:

    ```shell
    # Using gcloud to get your current user
    USER=$(gcloud config get-value core/account)
    # Make that user a cluster admin
    kubectl create clusterrolebinding cluster-admin-binding \
    --clusterrole=cluster-admin \
    --user="${USER}"
    ```

1. [`bash`](https://www.gnu.org/software/bash/) v4 or higher: For scripts used to
   generate code and update dependencies. On MacOS the default bash is too old,
   you can use [Homebrew](https://brew.sh) to install a later version.

### Configure environment

To [build, deploy and run your Tekton Objects with `ko`](#install-pipeline), you'll need to set these environment variables:

1. `GOROOT`: Set `GOROOT` to the location of the Go installation you want `ko` to use for builds.

    > **Note**: You may need to set `GOROOT` if you installed Go tools to a non-default location or have multiple Go versions installed.

    If it is not set, `ko` infers the location by effectively using `go env GOROOT`.

1. `KO_DOCKER_REPO`: The docker repository to which developer images should be pushed.
For example:
    - Using **Google Container Registry (GCR)**:

        ```shell
        # format: `gcr.io/${GCP-PROJECT-NAME}`
        export KO_DOCKER_REPO='gcr.io/my-gcloud-project-name'
        ```

    - Using **Docker Desktop** (Docker Hub):

        ```shell
        # format: 'docker.io/${DOCKER_HUB_USERNAME}'
        export KO_DOCKER_REPO='docker.io/my-dockerhub-username'
        ```

    - You can also [host your own Docker Registry server](https://docs.docker.com/registry/deploying/) and reference it:

        ```shell
        # format: ${localhost:port}/{}
        export KO_DOCKER_REPO=`localhost:5000/mypipelineimages`
        ```

1. Optionally, add `$HOME/go/bin` to your system `PATH` so that any tooling installed via `go get` will work properly. For example:

    ```shell
    export PATH="${PATH}:$HOME/go/bin"
    ```

> **Note**: It is recommended to add these environment variables to your shell's configuration files (e.g., `~/.bash_profile` or `~/.bashrc`).

### Setup a fork

The Tekton project requires that you develop (commit) code changes to branches that belong to a fork of the `tektoncd/pipeline` repository in your GitHub account before submitting them as Pull Requests (PRs) to the actual project repository.

1. [Create a fork](https://help.github.com/articles/fork-a-repo/) of the `tektoncd/pipeline` repository in your GitHub account.

1. Create a clone of your fork on your local machine:

    ```shell
    git clone git@github.com:${YOUR_GITHUB_USERNAME}/pipeline.git
    ```

    > **Note**: Tekton uses [Go Modules](https://golang.org/doc/modules/gomod-ref) (i.e., `go mod`) for package management so you may clone the repository to a location of your choosing.

1. Configure `git` remote repositories

    Adding `tektoncd/pipelines` as the `upstream` and your fork as the `origin` remote repositories to your `.git/config` sets you up nicely for regularly [syncing your fork](https://help.github.com/articles/syncing-a-fork/) and submitting pull requests.

    1. Change into the project directory

        ```shell
        cd pipeline
        ```

    1. Configure Tekton as the `upstream` repository

        ```shell
        git remote add upstream git@github.com:tektoncd/pipeline.git

        # Optional: Prevent accidental pushing of commits by changing the upstream URL to `no_push`
        git remote set-url --push upstream no_push
        ```

    1. Configure your fork as the `origin` repository

        ```shell
        git remote add origin git@github.com:${YOUR_GITHUB_USERNAME}/pipeline.git
        ```

### Configure Container Registry

Depending on your chosen container registry that you set in the `KO_DOCKER_REPO` environment variable, you may need to additionally configure access control to allow `ko` to authenticate to it.

<!-- TODO: Need instructions for MiniKube -->

#### Using Docker Desktop (Docker Hub)

Docker Desktop provides seamless integration with both a local (default) image registry as well as Docker Hub remote registries.  To use Docker Hub registries with `ko`, all you need do is to configure Docker Desktop with your Docker ID and password in its dashboard.

#### Using Google Container Registry (GCR)
If using GCR with `ko`, make sure to configure
[authentication](https://cloud.google.com/container-registry/docs/advanced-authentication#standalone_docker_credential_helper)
for your `KO_DOCKER_REPO` if required. To be able to push images to
`gcr.io/<project>`, you need to run this once:

```shell
gcloud auth configure-docker
```

To be able to pull images from `gcr.io/<project>`, please follow the instructions [here](https://cloud.google.com/container-registry/docs/access-control#grant) to configure IAM policies for the services that will pull iamges from your GCR.

If you choose to run GKE and GCR in the same GCP project, please follow the [example GKE setup](#using-gke) and make sure to add ```storage-full``` to the ```--scopes``` args in the example to give the GKE default service account full access to your GCR. Alternatively, you can grant the GKE default service account read access to your GCR by running:

```
gcloud projects add-iam-policy-binding <project-number> \
--member='serviceAccount:<project-number>-compute@developer.gserviceaccount.com' \
--role='roles/storage.objectViewer'
```

For more information about GCP Compute Engine default service accounts, please check [here](https://cloud.google.com/compute/docs/access/service-accounts)

After configuring IAM policy of your GCR, the [example GKE setup](#using-gke) in this guide now has permissions to push and pull images from your GCR.
If you choose to use a different setup with fewer default permissions, or your GKE cluster that will run Tekton
is in a different project than your GCR registry, you will need to provide the Tekton pipelines
controller and webhook service accounts with GCR credentials.
See documentation on [using GCR with GKE](https://cloud.google.com/container-registry/docs/using-with-google-cloud-platform#gke)
for more information.
To do this, create a secret for your docker credentials and reference this secret from the controller and webhook service accounts,
as follows.

1. Create a secret, for example:

    ```yaml
    kubectl create secret generic ${SECRET_NAME} \
    --from-file=.dockerconfigjson=<path/to/.docker/config.json> \
    --type=kubernetes.io/dockerconfigjson
    --namespace=tekton-pipelines
    ```
   See [Configuring authentication for Docker](./docs/auth.md#configuring-authentication-for-docker)
   for more detailed information on creating secrets containing registry credentials.

2. Update the `tekton-pipelines-controller` and `tekton-pipelines-webhook` service accounts
    to reference the newly created secret by modifying
    the [definitions of these service accounts](./config/200-serviceaccount.yaml)
    as shown below.

    ```yaml
    apiVersion: v1
    kind: ServiceAccount
    metadata:
      name: tekton-pipelines-controller
      namespace: tekton-pipelines
      labels:
        app.kubernetes.io/component: controller
        app.kubernetes.io/instance: default
        app.kubernetes.io/part-of: tekton-pipelines
    imagePullSecrets:
    - name: ${SECRET_NAME}
    ---
    apiVersion: v1
    kind: ServiceAccount
    metadata:
      name: tekton-pipelines-webhook
      namespace: tekton-pipelines
      labels:
        app.kubernetes.io/component: webhook
        app.kubernetes.io/instance: default
        app.kubernetes.io/part-of: tekton-pipelines
    imagePullSecrets:
    - name: ${SECRET_NAME}
    ```

---

## Building and deploying

### Setup a Kubernetes cluster

The recommended minimum development configuration is:

- Kubernetes version 1.22 or later
- 4 (virtual) CPU nodes
  - 8 GB of (actual or virtualized) platform memory
- Node autoscaling, up to 3 nodes

#### Using [KinD](https://kind.sigs.k8s.io/)

[KinD](https://kind.sigs.k8s.io/) is a great tool for working with Kubernetes clusters locally. It is particularly useful to quickly test code against different cluster [configurations](https://kind.sigs.k8s.io/docs/user/quick-start/#advanced).

1. Install [required tools](./DEVELOPMENT.md#install-tools) (note: may require a newer version of Go).
2. Install [Docker](https://www.docker.com/get-started).
3. Create cluster:

   ```sh
   $ kind create cluster
   ```

4. Configure [ko](https://kind.sigs.k8s.io/):

   ```sh
   $ export KO_DOCKER_REPO="kind.local"
   $ export KIND_CLUSTER_NAME="kind"  # only needed if you used a custom name in the previous step
   ```

optional: As a convenience, the [Tekton plumbing project](https://github.com/tektoncd/plumbing) provides a script named ['tekton_in_kind.sh'](https://github.com/tektoncd/plumbing/tree/main/hack#tekton_in_kindsh) that leverages `kind` to create a cluster and install Tekton Pipeline, [Tekton Triggers](https://github.com/tektoncd/triggers) and [Tekton Dashboard](https://github.com/tektoncd/dashboard) components into it.

#### Using MiniKube

- Follow the instructions for [running locally with Minikube](docs/developers/local-setup.md#using-minikube)

#### Using Docker Desktop

- Follow the instructions for [running locally with Docker Desktop](docs/developers/local-setup.md#using-docker-desktop)

#### Using GKE

1. [Set up a GCP Project](https://cloud.google.com/resource-manager/docs/creating-managing-projects) and [enable the GKE API](https://cloud.google.com/kubernetes-engine/docs/quickstart#before-you-begin).
    You may find it useful to save the ID of the project in an environment
    variable (e.g. `PROJECT_ID`).

<!-- TODO: Someone needs to validate the cluster-version-->
1. Create a GKE cluster (with `--cluster-version=latest` but you can use any
    version 1.18 or later):

    ```bash
    export PROJECT_ID=my-gcp-project
    export CLUSTER_NAME=mycoolcluster

    gcloud container clusters create $CLUSTER_NAME \
     --enable-autoscaling \
     --min-nodes=1 \
     --max-nodes=3 \
     --scopes=cloud-platform \
     --no-issue-client-certificate \
     --project=$PROJECT_ID \
     --region=us-central1 \
     --machine-type=e2-standard-4 \
     --num-nodes=1 \
     --cluster-version=1.22
    ```

    > **Note**: The recommended [GCE machine type](https://cloud.google.com/compute/docs/machine-types) is `'e2-standard-4'`.

    > **Note**: [The `'--scopes'` argument](https://cloud.google.com/sdk/gcloud/reference/container/clusters/create#--scopes) on the  `'gcloud container cluster create'` command controls what GCP resources the cluster's default service account has access to; for example, to give the default service account full access to your GCR registry, you can add `'storage-full'` to the `--scopes` arg. See [Authenticating to GCP](https://cloud.google.com/kubernetes-engine/docs/tutorials/authenticating-to-cloud-platform) for more details.

1. Grant cluster-admin permissions to the current user:

   ```bash
   kubectl create clusterrolebinding cluster-admin-binding \
   --clusterrole=cluster-admin \
   --user=$(gcloud config get-value core/account)
   ```

---

## Developing and testing

### Iterating on code changes

While iterating on code changes to the project, you may need to:

1. [Manage Tekton objects](#managing-tekton-objects-using-ko)
1. [Verify installation](#verify-installation) and make sure there are no errors by [accessing the logs](#accessing-logs)
1. Use various development scripts, as needed, in the ['hack' directory](https://github.com/tektoncd/pipeline/tree/main/hack), For example:
    - Update your (external) dependencies with: `./hack/update-deps.sh`
    - Update your type definitions with: `./hack/update-codegen.sh`
    -  Update your OpenAPI specs with: `./hack/update-openapigen.sh`
1. Update or [add new CRD types](#adding-new-types) as needed
1. Update, [add and run tests](./test/README.md#tests)

To make changes to these CRDs, you will probably interact with:

- The CRD type definitions in [./pkg/apis/pipeline/v1beta1](./pkg/apis/pipeline/v1beta1)
- The reconcilers in [./pkg/reconciler](./pkg/reconciler)
- The clients are in [./pkg/client](./pkg/client) (these are generated by
    `./hack/update-codegen.sh`)

---

### Managing Tekton Objects using `ko`

The `ko` command is the preferred method to manage (i.e., create, modify or delete) Tekton Objects in Kubernetes from your local fork of the project. Some common operations include:

#### Install Pipeline

You can stand up a version of Tekton using your local clone's code to the currently configured K8s context (i.e.,  `kubectl config current-context`):

```shell
ko apply -R -f config/
```

#### Verify installation

You can verify your development installation using `ko` was successful by checking to see if the Tekton pipeline pods are running in Kubernetes:

```shell
kubectl get pods -n tekton-pipelines
```

#### Delete Pipeline

You can clean up everything with:

```shell
# If you should not delete the namespace of a pipeline component
ko delete -f config/

# If you also can delete the namespace of a pipeline component
ko delete -R -f config/
```

**Note:** If you use a pipeline component in the same namespace as other components such as dashboard or triggers, executing `ko delete -R -f config/` deletes these other components too.

#### Redeploy controller

As you make changes to the code, you can redeploy your controller with:

```shell
ko apply -f config/controller.yaml
```

#### Installing into custom namespaces

When managing different development branches of code (with changed Tekton objects and controllers) in the same K8s instance, it may be helpful to install them into a custom (non-default) namespace. The ability to map a code branch to a corresponding namespace may make it easier to identify and manage the objects as a group as well as isolate log output.

To install into a different namespace you can use this script:

```bash
#!/usr/bin/env bash
set -e

# Set your target namespace here
TARGET_NAMESPACE=new-target-namespace

ko resolve -R -f config | sed -e '/kind: Namespace/!b;n;n;s/:.*/: '"${TARGET_NAMESPACE}"'/' | \
    sed "s/namespace: tekton-pipelines$/namespace: ${TARGET_NAMESPACE}/" | \
    kubectl apply -R -f-
kubectl set env deployments --all SYSTEM_NAMESPACE=${TARGET_NAMESPACE} -n ${TARGET_NAMESPACE}
```

This script will cause `ko` to:

- Change (resolve) all `namespace` values in K8s configuration files within the `config/` subdirectory to be updated to a name of your choosing.
- Builds and push images with the new namespace to your container registry and
- Update all Tekton Objects in K8s using these images

It will also update the default system namespace used for K8s `deployments` to the new value for all subsequent `kubectl` commands.

---

### Accessing logs

To look at the controller logs, run:

```shell
kubectl -n tekton-pipelines logs $(kubectl -n tekton-pipelines get pods -l app=tekton-pipelines-controller -o name)
```

To look at the webhook logs, run:

```shell
kubectl -n tekton-pipelines logs $(kubectl -n tekton-pipelines get pods -l app=tekton-pipelines-webhook -o name)
```

To look at the logs for individual `TaskRuns` or `PipelineRuns`, see
[docs on accessing logs](docs/logs.md).

### Adding new CRD types

If you need to add a new CRD type, you will need to add:

1. A yaml definition in [config/](./config)
1. Add the type to the cluster roles in:
    - [200-clusterrole.yaml](./config/200-clusterrole.yaml)
    - [clusterrole-aggregate-edit.yaml](./config/clusterrole-aggregate-edit.yaml)
    - [clusterrole-aggregate-view.yaml](./config/clusterrole-aggregate-view.yaml)
1. Add go structs for the types in
    [pkg/apis/pipeline/v1alpha1](./pkg/apis/pipeline/v1alpha1) e.g
    [condition_types.go](./pkg/apis/pipeline/v1alpha1/condition_types.go) This
    should implement the
    [Defaultable](./pkg/apis/pipeline/v1alpha1/condition_defaults.go) and
    [Validatable](./pkg/apis/pipeline/v1alpha1/condition_validation.go)
    interfaces as they are needed for the webhook in the next step.
1. Register it with the [webhook](./cmd/webhook/main.go)
1. Add the new type to the
    [list of known types](./pkg/apis/pipeline/v1alpha1/register.go)

_See [the API compatibility policy](api_compatibility_policy.md)._


text:
package org.emsg.smart_connector.message;

/**
 */
public interface IMatchingCondition {
    boolean match(String key);
}

redpajama_set_name: RedPajamaGithub


text:
/*
 Navicat Premium Data Transfer

 Source Server         : localhost
 Source Server Type    : MySQL
 Source Server Version : 50527
 Source Host           : localhost
 Source Database       : snowy

 Target Server Type    : MySQL
 Target Server Version : 50527
 File Encoding         : utf-8

 Date: 01/02/2013 18:26:36 PM
*/

SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
--  Table structure for `favorite`
-- ----------------------------
DROP TABLE IF EXISTS `favorite`;
CREATE TABLE `favorite` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `owner_user_id` int(11) DEFAULT NULL,
  `involved_type` int(11) DEFAULT NULL,
  `involved_topic_id` int(11) DEFAULT NULL,
  `involved_reply_id` int(11) DEFAULT NULL,
  `created` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Table structure for `node`
-- ----------------------------
DROP TABLE IF EXISTS `node`;
CREATE TABLE `node` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` text,
  `slug` text,
  `thumb` text,
  `introduction` text,
  `created` text,
  `updated` text,
  `plane_id` int(11) DEFAULT NULL,
  `topic_count` int(11) DEFAULT NULL,
  `custom_style` text,
  `limit_reputation` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Table structure for `notification`
-- ----------------------------
DROP TABLE IF EXISTS `notification`;
CREATE TABLE `notification` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `content` text,
  `status` int(11) DEFAULT NULL,
  `involved_type` int(11) DEFAULT NULL,
  `involved_user_id` int(11) DEFAULT NULL,
  `involved_topic_id` int(11) DEFAULT NULL,
  `involved_reply_id` int(11) DEFAULT NULL,
  `trigger_user_id` int(11) DEFAULT NULL,
  `occurrence_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=255 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Table structure for `plane`
-- ----------------------------
DROP TABLE IF EXISTS `plane`;
CREATE TABLE `plane` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` text,
  `created` text,
  `updated` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Table structure for `reply`
-- ----------------------------
DROP TABLE IF EXISTS `reply`;
CREATE TABLE `reply` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `topic_id` int(11) DEFAULT NULL,
  `author_id` int(11) DEFAULT NULL,
  `content` text,
  `created` datetime DEFAULT NULL,
  `updated` datetime DEFAULT NULL,
  `up_vote` int(11) DEFAULT NULL,
  `down_vote` int(11) DEFAULT NULL,
  `last_touched` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=181 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Table structure for `topic`
-- ----------------------------
DROP TABLE IF EXISTS `topic`;
CREATE TABLE `topic` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` text,
  `content` text,
  `status` int(11) DEFAULT NULL,
  `hits` int(11) DEFAULT NULL,
  `created` datetime DEFAULT NULL,
  `updated` datetime DEFAULT NULL,
  `node_id` int(11) DEFAULT NULL,
  `author_id` int(11) DEFAULT NULL,
  `reply_count` int(11) DEFAULT NULL,
  `last_replied_by` text,
  `last_replied_time` datetime DEFAULT NULL,
  `up_vote` int(11) DEFAULT NULL,
  `down_vote` int(11) DEFAULT NULL,
  `last_touched` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8;
delimiter ;;
CREATE TRIGGER `topic_delete_trigger` BEFORE DELETE ON `topic` FOR EACH ROW BEGIN
        DELETE FROM reply WHERE reply.topic_id = OLD.id;
        DELETE FROM notification WHERE notification.involved_topic_id = OLD.id;
    END;
 ;;
delimiter ;

-- ----------------------------
--  Table structure for `transaction`
-- ----------------------------
DROP TABLE IF EXISTS `transaction`;
CREATE TABLE `transaction` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `type` int(11) DEFAULT NULL,
  `reward` int(11) DEFAULT NULL,
  `user_id` int(11) DEFAULT NULL,
  `current_balance` int(11) DEFAULT NULL,
  `involved_user_id` int(11) DEFAULT NULL,
  `involved_topic_id` int(11) DEFAULT NULL,
  `involved_reply_id` int(11) DEFAULT NULL,
  `occurrence_time` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
--  Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `uid` int(11) NOT NULL AUTO_INCREMENT,
  `email` text,
  `password` text,
  `username` text,
  `nickname` text,
  `avatar` text,
  `signature` text,
  `location` text,
  `website` text,
  `company` text,
  `role` int(11) DEFAULT NULL,
  `balance` int(11) DEFAULT NULL,
  `reputation` int(11) DEFAULT NULL,
  `self_intro` text,
  `created` datetime DEFAULT NULL,
  `updated` datetime DEFAULT NULL,
  `twitter` text,
  `github` text,
  `douban` text,
  `last_login` datetime DEFAULT NULL,
  PRIMARY KEY (`uid`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
delimiter ;;
CREATE TRIGGER `user_delete_trigger` BEFORE DELETE ON `user` FOR EACH ROW BEGIN
        DELETE FROM topic WHERE topic.author_id = OLD.uid;
        DELETE FROM reply WHERE reply.author_id = OLD.uid;
        DELETE FROM notification WHERE notification.trigger_user_id = OLD.uid;
        DELETE FROM notification WHERE notification.involved_user_id = OLD.uid;
    END;
 ;;
delimiter ;

-- ----------------------------
--  Table structure for `vote`
-- ----------------------------
DROP TABLE IF EXISTS `vote`;
CREATE TABLE `vote` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `status` int(11) DEFAULT NULL,
  `involved_type` int(11) DEFAULT NULL,
  `involved_user_id` int(11) DEFAULT NULL,
  `involved_topic_id` int(11) DEFAULT NULL,
  `involved_reply_id` int(11) DEFAULT NULL,
  `trigger_user_id` int(11) DEFAULT NULL,
  `occurrence_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

SET FOREIGN_KEY_CHECKS = 1;


text:
class AddInitialClinicalTrialSupport < ActiveRecord::Migration[4.2]
  def change
    create_table :clinical_trials do |t|
      t.text :nct_id, unique: true, index: true
      t.text :name
      t.text :description
      t.timestamps
    end

    create_join_table :clinical_trials, :sources do |t|
      t.integer :clinical_trial_id, null: false
      t.integer :source_id, null: false
      t.references :sources
      t.references :clinical_trials
    end

    add_index :clinical_trials_sources, [:clinical_trial_id, :source_id], name: 'idx_clinical_trials_sources'
    add_index :clinical_trials_sources, :source_id
  end
end


text:
package com.cab404.chumroll.example;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.View;

import com.cab404.chumroll.ChumrollAdapter;
import com.cab404.chumroll.example.item.LabelItem;
import com.cab404.chumroll.example.item.NumberItem;
import com.cab404.chumroll.example.item.SentenceItem;
import com.cab404.chumroll.example.item.Util;

import java.util.Arrays;

/**
 * Common functionality for all of test fragments with Chumroll
 *
 * @author cab404
 */
public abstract class ChumrollTestFragment extends Fragment {

    abstract ChumrollAdapter getAdapter();

    /**
     * Adds item to adapter
     */
    public void addItem(int what) {
        switch (what) {
            case R.id.a:
                getAdapter().addAll(SentenceItem.class,
                        Arrays.asList(
                                Sentence.generateSentence(getContext()),
                                Sentence.generateSentence(getContext())
                        )
                );
                break;
            case R.id.b:
                getAdapter().add(NumberItem.class, Util.generateRandom());
                break;
            case R.id.c:
                getAdapter().add(LabelItem.class, Sentence.generateWord(getContext()));
                break;
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initItems();
    }

    /**
     * Initializes adapter with some items
     */
    void initItems() {
        getAdapter().prepareFor(new LabelItem(), new NumberItem(), new SentenceItem());
        for (int i = 0; i < 5; i++) {
            // Pretty rough approach, but it works since ids a, b and c are declared one after another.
            int item = (int) (R.id.a + (Math.random() * 3));
            addItem(item);
        }
    }

}


text:
package io.vertx.ext.sql;

import io.vertx.codegen.annotations.Fluent;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.json.JsonArray;

import java.util.List;

/**
 * Represents a connection to a SQL database
 *
 * @author Nick Scavelli
 */
@VertxGen
public interface SQLConnection extends AutoCloseable {

  /**
   * Sets the auto commit flag for this connection. True by default.
   *
   * @param autoCommit  the autoCommit flag, true by default.
   * @param resultHandler  the handler which is called once this operation completes.
   * @see java.sql.Connection#setAutoCommit(boolean)
   */
  @Fluent
  SQLConnection setAutoCommit(boolean autoCommit, Handler<AsyncResult<Void>> resultHandler);

  /**
   * Executes the given SQL statement
   *
   * @param sql  the SQL to execute. For example CREATE TABLE IF EXISTS table ...
   * @param resultHandler  the handler which is called once this operation completes.
   * @see java.sql.Statement#execute(String)
   */
  @Fluent
  SQLConnection execute(String sql, Handler<AsyncResult<Void>> resultHandler);

  /**
   * Executes the given SQL SELECT statement which returns the results of the query.
   *
   * @param sql  the SQL to execute. For example SELECT * FROM table ....
   * @param resultHandler  the handler which is called once the operation completes. It will return a {@code ResultSet}.
   *
   * @see java.sql.Statement#executeQuery(String)
   * @see java.sql.PreparedStatement#executeQuery(String)
   */
  @Fluent
  SQLConnection query(String sql, Handler<AsyncResult<ResultSet>> resultHandler);

  /**
   * Executes the given SQL SELECT statement which returns the results of the query as a read stream.
   *
   * @param sql  the SQL to execute. For example SELECT * FROM table ....
   * @param handler  the handler which is called once the operation completes. It will return a {@code SQLRowStream}.
   *
   * @see java.sql.Statement#executeQuery(String)
   * @see java.sql.PreparedStatement#executeQuery(String)
   */
  @Fluent
  SQLConnection queryStream(String sql, Handler<AsyncResult<SQLRowStream>> handler);

  /**
   * Executes the given SQL SELECT prepared statement which returns the results of the query.
   *
   * @param sql  the SQL to execute. For example SELECT * FROM table ....
   * @param params  these are the parameters to fill the statement.
   * @param resultHandler  the handler which is called once the operation completes. It will return a {@code ResultSet}.
   *
   * @see java.sql.Statement#executeQuery(String)
   * @see java.sql.PreparedStatement#executeQuery(String)
   */
  @Fluent
  SQLConnection queryWithParams(String sql, JsonArray params, Handler<AsyncResult<ResultSet>> resultHandler);

  /**
   * Executes the given SQL SELECT statement which returns the results of the query as a read stream.
   *
   * @param sql  the SQL to execute. For example SELECT * FROM table ....
   * @param params  these are the parameters to fill the statement.
   * @param handler  the handler which is called once the operation completes. It will return a {@code SQLRowStream}.
   *
   * @see java.sql.Statement#executeQuery(String)
   * @see java.sql.PreparedStatement#executeQuery(String)
   */
  @Fluent
  SQLConnection queryStreamWithParams(String sql, JsonArray params, Handler<AsyncResult<SQLRowStream>> handler);

  /**
   * Executes the given SQL statement which may be an INSERT, UPDATE, or DELETE
   * statement.
   *
   * @param sql  the SQL to execute. For example INSERT INTO table ...
   * @param resultHandler  the handler which is called once the operation completes.
   *
   * @see java.sql.Statement#executeUpdate(String)
   * @see java.sql.PreparedStatement#executeUpdate(String)
   */
  @Fluent
  SQLConnection update(String sql, Handler<AsyncResult<UpdateResult>> resultHandler);

  /**
   * Executes the given prepared statement which may be an INSERT, UPDATE, or DELETE
   * statement with the given parameters
   *
   * @param sql  the SQL to execute. For example INSERT INTO table ...
   * @param params  these are the parameters to fill the statement.
   * @param resultHandler  the handler which is called once the operation completes.
   *
   * @see java.sql.Statement#executeUpdate(String)
   * @see java.sql.PreparedStatement#executeUpdate(String)
   */
  @Fluent
  SQLConnection updateWithParams(String sql, JsonArray params, Handler<AsyncResult<UpdateResult>> resultHandler);

  /**
   * Calls the given SQL PROCEDURE which returns the result from the procedure.
   *
   * @param sql  the SQL to execute. For example {call getEmpName (?, ?)}.
   * @param resultHandler  the handler which is called once the operation completes. It will return a {@code ResultSet}.
   *
   * @see java.sql.CallableStatement#execute(String)
   */
  @Fluent
  SQLConnection call(String sql, Handler<AsyncResult<ResultSet>> resultHandler);

  /**
   * Calls the given SQL PROCEDURE which returns the result from the procedure.
   *
   * The index of params and outputs are important for both arrays, for example when dealing with a prodecure that
   * takes the first 2 arguments as input values and the 3 arg as an output then the arrays should be like:
   *
   *

   *   params = [VALUE1, VALUE2, null]
   *   outputs = [null, null, "VARCHAR"]
   *

   *
   * @param sql  the SQL to execute. For example {call getEmpName (?, ?)}.
   * @param params  these are the parameters to fill the statement.
   * @param outputs  these are the outputs to fill the statement.
   * @param resultHandler  the handler which is called once the operation completes. It will return a {@code ResultSet}.
   *
   * @see java.sql.CallableStatement#execute(String)
   */
  @Fluent
  SQLConnection callWithParams(String sql, JsonArray params, JsonArray outputs, Handler<AsyncResult<ResultSet>> resultHandler);

  /**
   * Closes the connection. Important to always close the connection when you are done so it's returned to the pool.
   *
   * @param handler the handler called when this operation completes.
   */
  void close(Handler<AsyncResult<Void>> handler);

  /**
   * Closes the connection. Important to always close the connection when you are done so it's returned to the pool.
   */
  void close();

  /**
   * Commits all changes made since the previous commit/rollback.
   *
   * @param handler the handler called when this operation completes.
   */
  @Fluent
  SQLConnection commit(Handler<AsyncResult<Void>> handler);

  /**
   * Rolls back all changes made since the previous commit/rollback.
   *
   * @param handler the handler called when this operation completes.
   */
  @Fluent
  SQLConnection rollback(Handler<AsyncResult<Void>> handler);

  /**
   * Sets a connection wide query timeout.
   *
   * It can be over written at any time and becomes active on the next query call.
   *
   * @param timeoutInSeconds the max amount of seconds the query can take to execute.
   */
  @Fluent
  SQLConnection setQueryTimeout(int timeoutInSeconds);

  /**
   * Batch simple SQL strings and execute the batch where the async result contains a array of Integers.
   *
   * @param sqlStatements sql statement
   * @param handler the result handler
   */
  @Fluent
  SQLConnection batch(List<String> sqlStatements, Handler<AsyncResult<List<Integer>>> handler);

  /**
   * Batch a prepared statement with all entries from the args list. Each entry is a batch.
   * The operation completes with the execution of the batch where the async result contains a array of Integers.
   *
   * @param sqlStatement sql statement
   * @param args the prepared statement arguments
   * @param handler the result handler
   */
  @Fluent
  SQLConnection batchWithParams(String sqlStatement, List<JsonArray> args, Handler<AsyncResult<List<Integer>>> handler);

  /**
   * Batch a callable statement with all entries from the args list. Each entry is a batch.
   * The size of the lists inArgs and outArgs MUST be the equal.
   * The operation completes with the execution of the batch where the async result contains a array of Integers.
   *
   * @param sqlStatement sql statement
   * @param inArgs the callable statement input arguments
   * @param outArgs the callable statement output arguments
   * @param handler the result handler
   */
  @Fluent
  SQLConnection batchCallableWithParams(String sqlStatement, List<JsonArray> inArgs, List<JsonArray> outArgs, Handler<AsyncResult<List<Integer>>> handler);

  /**
   * Attempts to change the transaction isolation level for this Connection object to the one given.
   *
   * The constants defined in the interface Connection are the possible transaction isolation levels.
   *
   * @param isolation the level of isolation
   * @param handler the handler called when this operation completes.
   */
  @Fluent
  SQLConnection setTransactionIsolation(TransactionIsolation isolation, Handler<AsyncResult<Void>> handler);

  /**
   * Attempts to return the transaction isolation level for this Connection object to the one given.
   *
   * @param handler the handler called when this operation completes.
   */
  @Fluent
  SQLConnection getTransactionIsolation(Handler<AsyncResult<TransactionIsolation>> handler);
}


text:
<?php

namespace PragmaRX\Tracker\Vendor\Laravel\Models;

class Referer extends Base
{
    protected $table = 'tracker_referers';

    protected $fillable = [
        'url',
        'host',
        'domain_id',
        'medium',
        'source',
        'search_terms_hash',
    ];

    public function domain()
    {
        return $this->belongsTo($this->getConfig()->get('domain_model'));
    }
}


text:
Duplicate implicit targets.

Title
=====

Paragraph.

Title
=====

Paragraph.


text:
package mount

import (
	"fmt"
	"io/ioutil"
	"os"
	"runtime"
	"strings"
	"testing"

	"k8s.io/utils/exec"
	"k8s.io/utils/exec/testing"
)

type ErrorMounter struct {
	*FakeMounter
	errIndex int
	err      []error
}

func (mounter *ErrorMounter) Mount(source string, target string, fstype string, options []string) error {
	i := mounter.errIndex
	mounter.errIndex++
	if mounter.err != nil && mounter.err[i] != nil {
		return mounter.err[i]
	}
	return mounter.FakeMounter.Mount(source, target, fstype, options)
}

type ExecArgs struct {
	command string
	args    []string
	output  string
	err     error
}

func TestSafeFormatAndMount(t *testing.T) {
	if runtime.GOOS == "darwin" || runtime.GOOS == "windows" {
		t.Skipf("not supported on GOOS=%s", runtime.GOOS)
	}
	mntDir, err := ioutil.TempDir(os.TempDir(), "mount")
	if err != nil {
		t.Fatalf("failed to create tmp dir: %v", err)
	}
	defer os.RemoveAll(mntDir)
	tests := []struct {
		description   string
		fstype        string
		mountOptions  []string
		execScripts   []ExecArgs
		mountErrs     []error
		expectedError error
	}{
		{
			description:  "Test a read only mount",
			fstype:       "ext4",
			mountOptions: []string{"ro"},
		},
		{
			description: "Test a normal mount",
			fstype:      "ext4",
			execScripts: []ExecArgs{
				{"fsck", []string{"-a", "/dev/foo"}, "", nil},
			},
		},
		{
			description: "Test 'fsck' fails with exit status 4",
			fstype:      "ext4",
			execScripts: []ExecArgs{
				{"fsck", []string{"-a", "/dev/foo"}, "", &testingexec.FakeExitError{Status: 4}},
			},
			expectedError: fmt.Errorf("'fsck' found errors on device /dev/foo but could not correct them"),
		},
		{
			description: "Test 'fsck' fails with exit status 1 (errors found and corrected)",
			fstype:      "ext4",
			execScripts: []ExecArgs{
				{"fsck", []string{"-a", "/dev/foo"}, "", &testingexec.FakeExitError{Status: 1}},
			},
		},
		{
			description: "Test 'fsck' fails with exit status other than 1 and 4 (likely unformatted device)",
			fstype:      "ext4",
			execScripts: []ExecArgs{
				{"fsck", []string{"-a", "/dev/foo"}, "", &testingexec.FakeExitError{Status: 8}},
			},
		},
		{
			description: "Test that 'blkid' is called and fails",
			fstype:      "ext4",
			mountErrs:   []error{fmt.Errorf("unknown filesystem type '(null)'")},
			execScripts: []ExecArgs{
				{"fsck", []string{"-a", "/dev/foo"}, "", nil},
				{"blkid", []string{"-p", "-s", "TYPE", "-s", "PTTYPE", "-o", "export", "/dev/foo"}, "DEVNAME=/dev/foo\nTYPE=ext4\n", nil},
			},
			expectedError: fmt.Errorf("unknown filesystem type '(null)'"),
		},
		{
			description: "Test that 'blkid' is called and confirms unformatted disk, format fails",
			fstype:      "ext4",
			mountErrs:   []error{fmt.Errorf("unknown filesystem type '(null)'")},
			execScripts: []ExecArgs{
				{"fsck", []string{"-a", "/dev/foo"}, "", nil},
				{"blkid", []string{"-p", "-s", "TYPE", "-s", "PTTYPE", "-o", "export", "/dev/foo"}, "", &testingexec.FakeExitError{Status: 2}},
				{"mkfs.ext4", []string{"-F", "-m0", "/dev/foo"}, "", fmt.Errorf("formatting failed")},
			},
			expectedError: fmt.Errorf("formatting failed"),
		},
		{
			description: "Test that 'blkid' is called and confirms unformatted disk, format passes, second mount fails",
			fstype:      "ext4",
			mountErrs:   []error{fmt.Errorf("unknown filesystem type '(null)'"), fmt.Errorf("Still cannot mount")},
			execScripts: []ExecArgs{
				{"fsck", []string{"-a", "/dev/foo"}, "", nil},
				{"blkid", []string{"-p", "-s", "TYPE", "-s", "PTTYPE", "-o", "export", "/dev/foo"}, "", &testingexec.FakeExitError{Status: 2}},
				{"mkfs.ext4", []string{"-F", "-m0", "/dev/foo"}, "", nil},
			},
			expectedError: fmt.Errorf("Still cannot mount"),
		},
		{
			description: "Test that 'blkid' is called and confirms unformatted disk, format passes, second mount passes",
			fstype:      "ext4",
			mountErrs:   []error{fmt.Errorf("unknown filesystem type '(null)'"), nil},
			execScripts: []ExecArgs{
				{"fsck", []string{"-a", "/dev/foo"}, "", nil},
				{"blkid", []string{"-p", "-s", "TYPE", "-s", "PTTYPE", "-o", "export", "/dev/foo"}, "", &testingexec.FakeExitError{Status: 2}},
				{"mkfs.ext4", []string{"-F", "-m0", "/dev/foo"}, "", nil},
			},
			expectedError: nil,
		},
		{
			description: "Test that 'blkid' is called and confirms unformatted disk, format passes, second mount passes with ext3",
			fstype:      "ext3",
			mountErrs:   []error{fmt.Errorf("unknown filesystem type '(null)'"), nil},
			execScripts: []ExecArgs{
				{"fsck", []string{"-a", "/dev/foo"}, "", nil},
				{"blkid", []string{"-p", "-s", "TYPE", "-s", "PTTYPE", "-o", "export", "/dev/foo"}, "", &testingexec.FakeExitError{Status: 2}},
				{"mkfs.ext3", []string{"-F", "-m0", "/dev/foo"}, "", nil},
			},
			expectedError: nil,
		},
		{
			description: "test that none ext4 fs does not get called with ext4 options.",
			fstype:      "xfs",
			mountErrs:   []error{fmt.Errorf("unknown filesystem type '(null)'"), nil},
			execScripts: []ExecArgs{
				{"fsck", []string{"-a", "/dev/foo"}, "", nil},
				{"blkid", []string{"-p", "-s", "TYPE", "-s", "PTTYPE", "-o", "export", "/dev/foo"}, "", &testingexec.FakeExitError{Status: 2}},
				{"mkfs.xfs", []string{"/dev/foo"}, "", nil},
			},
			expectedError: nil,
		},
		{
			description: "Test that 'blkid' is called and reports ext4 partition",
			fstype:      "ext3",
			mountErrs:   []error{fmt.Errorf("unknown filesystem type '(null)'")},
			execScripts: []ExecArgs{
				{"fsck", []string{"-a", "/dev/foo"}, "", nil},
				{"blkid", []string{"-p", "-s", "TYPE", "-s", "PTTYPE", "-o", "export", "/dev/foo"}, "DEVNAME=/dev/foo\nPTTYPE=dos\n", nil},
			},
			expectedError: fmt.Errorf("failed to mount the volume as \"ext3\", it already contains unknown data, probably partitions. Mount error: unknown filesystem type '(null)'"),
		},
		{
			description: "Test that 'blkid' is called but has some usage or other errors (an exit code of 4 is returned)",
			fstype:      "xfs",
			mountErrs:   []error{fmt.Errorf("unknown filesystem type '(null)'"), nil},
			execScripts: []ExecArgs{
				{"fsck", []string{"-a", "/dev/foo"}, "", nil},
				{"blkid", []string{"-p", "-s", "TYPE", "-s", "PTTYPE", "-o", "export", "/dev/foo"}, "", &testingexec.FakeExitError{Status: 4}},
				{"mkfs.xfs", []string{"/dev/foo"}, "", nil},
			},
			expectedError: fmt.Errorf("exit 4"),
		},
	}

	for _, test := range tests {
		fakeMounter := ErrorMounter{NewFakeMounter(nil), 0, test.mountErrs}
		fakeExec := &testingexec.FakeExec{ExactOrder: true}
		for _, script := range test.execScripts {
			fakeCmd := &testingexec.FakeCmd{}
			cmdAction := makeFakeCmd(fakeCmd, script.command, script.args...)
			outputAction := makeFakeOutput(script.output, script.err)
			fakeCmd.CombinedOutputScript = append(fakeCmd.CombinedOutputScript, outputAction)
			fakeExec.CommandScript = append(fakeExec.CommandScript, cmdAction)
		}
		mounter := SafeFormatAndMount{
			Interface: &fakeMounter,
			Exec:      fakeExec,
		}

		device := "/dev/foo"
		dest := mntDir
		err := mounter.FormatAndMount(device, dest, test.fstype, test.mountOptions)
		if test.expectedError == nil {
			if err != nil {
				t.Errorf("test \"%s\" unexpected non-error: %v", test.description, err)
			}

			// Check that something was mounted on the directory
			isNotMountPoint, err := fakeMounter.IsLikelyNotMountPoint(dest)
			if err != nil || isNotMountPoint {
				t.Errorf("test \"%s\" the directory was not mounted", test.description)
			}

			//check that the correct device was mounted
			mountedDevice, _, err := GetDeviceNameFromMount(fakeMounter.FakeMounter, dest)
			if err != nil || mountedDevice != device {
				t.Errorf("test \"%s\" the correct device was not mounted", test.description)
			}
		} else {
			if err == nil || !strings.HasPrefix(err.Error(), test.expectedError.Error()) {
				t.Errorf("test \"%s\" unexpected error: \n          [%v]. \nExpecting [%v]", test.description, err, test.expectedError)
			}
		}
	}
}

func makeFakeCmd(fakeCmd *testingexec.FakeCmd, cmd string, args ...string) testingexec.FakeCommandAction {
	c := cmd
	a := args
	return func(cmd string, args ...string) exec.Cmd {
		command := testingexec.InitFakeCmd(fakeCmd, c, a...)
		return command
	}
}

func makeFakeOutput(output string, err error) testingexec.FakeCombinedOutputAction {
	o := output
	return func() ([]byte, error) {
		return []byte(o), err
	}
}


text:
package com.findmeahome.findmeahome.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.findmeahome.findmeahome.R;
import com.findmeahome.findmeahome.model.Advice;

import java.util.ArrayList;

/**
 * Created by Find me a home apps team on 7/07/16.
 */
public class CustomAdapterAdvices extends RecyclerView.Adapter<CustomAdapterAdvices.ElementsByAdvice> {

    Context ctx;
    ArrayList<Advice> mDataset;
    Advice advice;

    public CustomAdapterAdvices(Context ctx, ArrayList<Advice> advice) {
        this.ctx = ctx;
        this.mDataset = advice;
    }

    @Override
    public CustomAdapterAdvices.ElementsByAdvice onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.advice_item, parent, false);
        return new ElementsByAdvice(v);
    }

    @Override
    public void onBindViewHolder(final CustomAdapterAdvices.ElementsByAdvice holder, int position) {

        final boolean[] isClosed = {true};

        advice = mDataset.get(position);

        holder.imageItem.setImageDrawable(advice.getImage());
        holder.titleItem.setText(advice.getTitle());
        holder.descriptionItem.setText(advice.getDescription());

        holder.parentAdvice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isClosed[0]) {
                    FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
                    holder.parentAdvice.setLayoutParams(lp);
                    holder.seeMoreLabel.setVisibility(View.GONE);

                    holder.descriptionItem.setEllipsize(null);
                    holder.descriptionItem.setMaxLines(99999999);
                    isClosed[0] = false;
                } else {
                    FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                    holder.parentAdvice.setLayoutParams(lp);
                    holder.seeMoreLabel.setVisibility(View.VISIBLE);

                    holder.descriptionItem.setMaxLines(3);
                    holder.descriptionItem.setEllipsize(TextUtils.TruncateAt.END);
                    isClosed[0] = true;
                }
            }
        });
    }

    @Override
    public int getItemCount() {

        if(mDataset != null) {
            return mDataset.size();
        }

        return 0;
    }

    public class ElementsByAdvice extends RecyclerView.ViewHolder {

        ImageView imageItem;
        TextView titleItem, descriptionItem, seeMoreLabel;
        LinearLayout parentAdvice;

        public ElementsByAdvice(View itemView) {
            super(itemView);

            imageItem = (ImageView) itemView.findViewById(R.id.imageItem);
            titleItem = (TextView) itemView.findViewById(R.id.titleItem);
            descriptionItem = (TextView) itemView.findViewById(R.id.descriptionItem);
            parentAdvice = (LinearLayout) itemView.findViewById(R.id.parentAdvice);
            seeMoreLabel = (TextView) itemView.findViewById(R.id.seeMoreLabel);
        }
    }
}


text:
$(document).ready(function() {
	if($('div.form.login').length) {  // in login page
		$('input#LoginForm_password').focus();
	}

	$('table.preview input[name="checkAll"]').click(function() {
		$('table.preview .confirm input').attr('checked', this.checked);
	});

	$('table.preview td.confirm input').click(function() {
		$('table.preview input[name="checkAll"]').attr('checked', !$('table.preview td.confirm input:not(:checked)').length);
	});
	$('table.preview input[name="checkAll"]').attr('checked', !$('table.preview td.confirm input:not(:checked)').length);

	$('.form .row.sticky input:not(.error), .form .row.sticky select:not(.error), .form .row.sticky textarea:not(.error)').each(function(){
		var value;
		if(this.tagName=='SELECT')
			value=this.options[this.selectedIndex].text;
		else if(this.tagName=='TEXTAREA')
			value=$(this).html();
		else
			value=$(this).val();
		if(value=='')
			value='[empty]';
		$(this).before('
'+value+'
').hide();
	});

	$('.form.gii .row.sticky .value').live('click', function(){
		$(this).hide();
		$(this).next().show().get(0).focus();
	});

	$('.form.gii .row input, .form.gii .row textarea, .form.gii .row select, .with-tooltip').not('.no-tooltip, .no-tooltip *').tooltip({
	    position: "center right",
		offset: [-2, 10]
	});

	$('.form.gii .row input').change(function(){
		$('.form.gii .feedback').hide();
		$('.form.gii input[name="generate"]').hide();
	});

	$('.form.gii .view-code').click(function(){
		var title=$(this).attr('rel');
		$.fancybox.showActivity();
		$.ajax({
			type: 'POST',
			cache: false,
			url: $(this).attr('href'),
			data: $('.form.gii form').serializeArray(),
			success: function(data){
				$.fancybox(data, {
					'title': title,
					'titlePosition': 'inside',
					'titleFormat': function(title, currentArray, currentIndex, currentOpts) {
						return '
close' + (title && title.length ? '' + title + '' : '' ) + '
';
					},
					'showCloseButton': false,
					'autoDimensions': false,
					'width': 900,
					'height': 'auto',
					'onComplete':function(){
						$('#fancybox-inner').scrollTop(0);
					}
				});
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				$.fancybox('
'+XMLHttpRequest.responseText+'
');
			}
		});
		return false;
	});

	$('#fancybox-inner .close-code').live('click', function(){
		$.fancybox.close();
		return false;
	});
});


text:
const SubscriberModel = require('../../models').subscriber;

module.exports = function(req, res) {
  const subscribers = req.body.subscribers;
  // const fields = req.body.fields;

  subscribers.forEach(subscriber => {
    SubscriberModel.findOne({
      where: {
        email: subscriber.email
      }
    }).then(email => {
      if (email) {
        res.status(400).send({status: 'error', message: 'This email already exists'});
      } else {
        SubscriberModel.create({email: subscriber.email}).then(() => {
          res.status(201).send({status: 'success', message: `${subscriber.email} added succesfully`});
        });
      }
    });
  });
};


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

namespace Moq.Proxy
{
	public class ParameterCollection : IParameterCollection
	{
		List<ParameterInfo> infos = new List<ParameterInfo>();
		List<object> values = new List<object>();

		public ParameterCollection(object[] values, ParameterInfo[] infos)
		{
			this.infos = infos.ToList();
			this.values = values.ToList();
		}

		public ParameterCollection(IEnumerable<object> values, IEnumerable<ParameterInfo> infos)
		{
			this.infos = infos.ToList();
			this.values = values.ToList();
		}

		public object this[int index]
		{
			get { return values[index]; }
			set { values[index] = value; }
		}

		public object this[string parameterName]
		{
			get { return values[IndexOf(parameterName)]; }
			set { values[IndexOf(parameterName)] = value; }
		}

		public int Count => infos.Count;

		public bool Contains(string parameterName) => IndexOf(parameterName) != -1;

		public IEnumerator<object> GetEnumerator() => values.GetEnumerator();

		public ParameterInfo GetInfo(string parameterName) => infos[IndexOf(parameterName)];

		public ParameterInfo GetInfo(int index) => infos[index];

		public string GetName(int index) => infos[index].Name;

		public int IndexOf(string parameterName)
		{
			for (int i = 0; i < infos.Count; ++i)
			{
				if (infos[i].Name == parameterName)
				{
					return i;
				}
			}

			return -1;
		}

		IEnumerator IEnumerable.GetEnumerator() => values.GetEnumerator();
	}
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bull. Soc. mycol. Fr. 12: 136 (1896)

#### Original name
Phyllachora alyxiae Pat., 1896

### Remarks
null


text:
import {InlineKeyboard} from './inline-keyboard'
import {storageSrv} from '../services/storage'

export class ChangeType {
	private name

	constructor() {
		this.name = storageSrv.getSessionData().name
	}

	public $inlineKeyboard() {
		const inlineKeyboard = new InlineKeyboard()

		inlineKeyboard
			.addButton({text: 'gif', callback_data: 'ChangeTypeEnd gif'})
			.addButton({text: 'text', callback_data: 'ChangeTypeEnd text'})
			.addButton({text: 'sticker', callback_data: 'ChangeTypeEnd sticker'})
			.addButton({text: 'photo', callback_data: 'ChangeTypeEnd photo'})
			.newLine()
			.addButton({text: `🔙Back to ${this.name}`, callback_data: `Back Edit ${this.name}`})

		return inlineKeyboard.toString()
	}

	public $answer() {
		return `Choose new type for "${this.name}".`
	}
}


text:
<?php
class Po_ConcretController extends Zend_Controller_Action {
	public function init()
	{
		header('content-type: text/html; charset=utf8');
		defined('BASE_URL')	|| define('BASE_URL', Zend_Controller_Front::getInstance()->getBaseUrl());
	}
	public function indexAction(){
		$rs_rows=array();
		$db = new Po_Model_DbTable_DbConcret();
		try{
			if(!empty($this->getRequest()->isPost())){
				$search=$this->getRequest()->getPost();
			}
			else{
				$search = array(
					'adv_search'=>'',
					'branch_id'=>-1,
					'supplierId'=>-1,
					'status'=>-1,
					'start_date'=> date('Y-m-d'),
					'end_date'=>date('Y-m-d'),
				);
			}

			$rs_rows= $db->getAllReceiveStockConcret($search);

			}catch (Exception $e){
				Application_Form_FrmMessage::message("Application Error");
				Application_Model_DbTable_DbUserLog::writeMessageError($e->getMessage());
			}

			$list = new Application_Form_Frmtable();
			$collumns = array("BRANCH_NAME","SUPPLIER","DN_NO","RECEIVE_DATE","PRODUCT_NAME","QTY","UNIT_PRICE","TOTAL","NOTE","BY_USER","STATUS");
			$link=array('module'=>'po','controller'=>'concret','action'=>'edit');
			$this->view->list=$list->getCheckList(10, $collumns,$rs_rows,array('projectName'=>$link,'supplierName'=>$link,'dnNumber'=>$link,
					'proName'=>$link,'qtyReceive'=>$link));

			$frm_search = new Application_Form_FrmAdvanceSearchStock();
			$frm = $frm_search->AdvanceSearch();
			Application_Model_Decorator::removeAllDecorator($frm);
			$this->view->frm_search = $frm;

	}
	function addAction(){
		if($this->getRequest()->isPost()){
			$_data = $this->getRequest()->getPost();
			try {
				$db = new Po_Model_DbTable_DbConcret();
				$db->addReceiveStock($_data);
				//Application_Form_FrmMessage::Sucessfull("INSERT_SUCCESS","po/concret/add");
			}catch(Exception $e){
				Application_Form_FrmMessage::message("INSERT_FAIL");
				Application_Model_DbTable_DbUserLog::writeMessageError($e->getMessage());
			}
		}
		$fm = new Po_Form_FrmConcretStock();
		$frm = $fm->Frmconcret();
		Application_Model_Decorator::removeAllDecorator($frm);
		$this->view->frm = $frm;
	}
	function editAction(){
		//$db = new Loan_Model_DbTable_DbCancel();
		if($this->getRequest()->isPost()){
			$_data = $this->getRequest()->getPost();
			try {

				Application_Form_FrmMessage::Sucessfull("EDIT_SUCCESS","");
			}catch(Exception $e){
				Application_Form_FrmMessage::message("INSERT_FAIL");
				Application_Model_DbTable_DbUserLog::writeMessageError($e->getMessage());
			}
		}
		//$fm = new Loan_Form_FrmCancel();
		//$frm = $fm->FrmAddFrmCancel();
		//Application_Model_Decorator::removeAllDecorator($frm);
		//$this->view->frm_loan = $frm;
		$id = $this->getRequest()->getParam('id');
		$id = empty($id)?0:$id;
		if(empty($id)){
			Application_Form_FrmMessage::Sucessfull("NO_DATA","//",2);
		}
	}
}


text:
<template name="post_comments_link">

      {{commentCount}}
      {{_ 'comments_'}}

</template>


text:
namespace ca {
	class CompressAlgs {
	public:
		virtual void compress(std::istream&, bit::oBaseStream&) = 0;
		virtual void expand(bit::iBaseStream&, std::ostream&) = 0;
	};
	CompressAlgs &Huffman_algs();
	CompressAlgs &AdaptiveHuffman_algs();
}
#endif


text:
![3 stars](../../images/ic_star_black_18dp_1x.png)![3 stars](../../images/ic_star_black_18dp_1x.png)![3 stars](../../images/ic_star_black_18dp_1x.png)![3 stars](../../images/ic_star_border_black_18dp_1x.png)![3 stars](../../images/ic_star_border_black_18dp_1x.png) 2

To use the Steelers Fan skill, try saying...

* *Alexa, Ask steelers fan whats my flash briefing on the Steelers*

* *Alexa, Ask Steelers fan how are the Steelers doing*

* *Alexa, Ask steelers fan Ben Roethlisberger update*

Get unofficial to-the-minute stats & fun facts on the Steelers supplied by Fresh Digital Group. This skill isn't sponsored or endorsed by the Pittsburgh Steelers.

Here's some ways you can use the skill. We have given you 4 different ways for you to talk to Alexa:

General Updates:

Alexa, Ask Steelers fan whats my flash briefing on the Steelers
Alexa, Ask Steelers fan how are the Steelers doing
Alexa, Ask Steelers fan who do the Steelers play next
Alexa, Ask Steelers fan Ben Roethlisberger (or any player's First name, Last name) update?

Fun Facts about the Steelers:

Alexa, Ask Steelers fan tell me some trivia about the Pittsburgh Steelers
Alexa, Ask Steelers fan what's the number of Steelers Superbowl wins
Alexa, Ask Steelers fan Terry Bradshaw Steelers stats
Alexa, Ask Steelers fan Franco Harris Steelers career
Alexa, Ask Steelers fan when did Santonio Holmes play for the Steelers
Alexa, Ask Steelers fan who is the Steel Curtain
Alexa, Ask Steelers fan who is Joe Greene

Have fun and please let us know if you have any requests. We will work on adding them in!

***

### Skill Details

* **Invocation Name:** steelers fan
* **Category:** null
* **ID:** amzn1.ask.skill.b318489f-5abb-421f-ba94-096d2473866a
* **ASIN:** B01MQYGZ5S
* **Author:** FreshDigitalGroup
* **Release Date:** December 24, 2016 @ 02:49:19
* **In-App Purchasing:** No


text:
package main

type I interface {
	M()
}

func bad() {
	var i I
	var s string

	switch i {
	case s: // ERROR "mismatched types string and I|incompatible types"
	}

	switch s {
	case i: // ERROR "mismatched types I and string|incompatible types"
	}

	var m, m1 map[int]int
	switch m {
	case nil:
	case m1: // ERROR "can only compare map m to nil|map can only be compared to nil|cannot compare"
	default:
	}

	var a, a1 []int
	switch a {
	case nil:
	case a1: // ERROR "can only compare slice a to nil|slice can only be compared to nil|cannot compare"
	default:
	}

	var f, f1 func()
	switch f {
	case nil:
	case f1: // ERROR "can only compare func f to nil|func can only be compared to nil|cannot compare"
	default:
	}

	var ar, ar1 [4]func()
	switch ar { // ERROR "cannot switch on"
	case ar1:
	default:
	}

	var st, st1 struct{ f func() }
	switch st { // ERROR "cannot switch on"
	case st1:
	}
}

func good() {
	var i interface{}
	var s string

	switch i {
	case s:
	}

	switch s {
	case i:
	}
}


text:
unsigned int MaxElement(std::vector<float> input);
std::vector<std::vector<float> > LoadMNIST();

unsigned int MaxElement(std::vector<float> input)
{
  if (input.size() == 0)
    return -1;

  float max = input[0];
  int index = 0;
  for (unsigned int i = 1; i < input.size(); i++)
    if (input[i] > max)
    {
      max = input[i];
      index = i;
    }

  return index;
}

int main()
{
    srand(time(NULL));
    std::vector<std::vector<float> > training_data = LoadMNIST();

    //create the labels
    std::vector<std::vector<float> > labels;
    for (int i = 0; i < 10; i++)
    {
        std::vector<float> label;
        label.resize(10);
        label[i] = 1.0f;
        labels.push_back(label);
    }

    ChaiModel MNISTModel;
    MNISTModel.AddFCL(784, 10);
    MNISTModel.AddSoftmax(10);
    const unsigned int INPUT_SIZE = 784;
    const unsigned int NUM_CLASSES = 10;
    const unsigned int OUTPUT_SIZE = 10;
    const unsigned int NUM_EPOCHS = 10;
    const float LEARNING_RATE = 0.1f;
    const unsigned int NUM_EXAMPLES = training_data[0].size() / INPUT_SIZE;

    for (unsigned int epoch = 0; epoch < NUM_EPOCHS; epoch++)
      for (unsigned int i = 0; i < NUM_EXAMPLES; i++)
        for (unsigned int j = 0; j < NUM_CLASSES; j++)
        {
          std::vector<float> input;
          input.reserve(INPUT_SIZE);
          for (int k = i * INPUT_SIZE; k < i * INPUT_SIZE + INPUT_SIZE; k++)
            input.push_back(training_data[j][k]);

          float loss = MNISTModel.Train(input, labels[j], LEARNING_RATE / pow(10, epoch / 10.0f));

          //train the model
          if (i % 100 == 0)
          std::cout << "Epoch " << epoch + 1 << ", loss: " << loss << std::endl;
        }

  std::cout << "Testing trained model... " << std::endl;

  unsigned int num_tests = 0;
  unsigned int num_correct = 0;
  for (unsigned int i = 0; i < NUM_EXAMPLES; i++)
  {
    for (unsigned int j = 0; j < NUM_CLASSES; j++)
    {
      std::vector<float> input;
      input.reserve(INPUT_SIZE);
      for (int k = i * INPUT_SIZE; k < i * INPUT_SIZE + INPUT_SIZE; k++)
        input.push_back(training_data[j][k]);

      num_tests++;

      if (MaxElement(MNISTModel.Evaluate(input)) == j)
        num_correct++;
    }
  }

  std::cout << "Accuracy: " << (float)num_correct / num_tests * 100.0f << "%" << std::endl;

	return 0;
}


text:
<?php

namespace Modules\Bcrud\Http\Controllers;

use Modules\Bcrud\CrudPanel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Form as Form;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Modules\Bcrud\Http\Controllers\CrudFeatures\Reorder;
use Modules\Bcrud\Http\Controllers\CrudFeatures\AjaxTable;
// CRUD Traits for non-core features
use Modules\Bcrud\Http\Controllers\CrudFeatures\Revisions;
use Modules\Bcrud\Http\Controllers\CrudFeatures\SaveActions;
use Modules\Bcrud\Http\Requests\CrudRequest as StoreRequest;
use Modules\Bcrud\Http\Requests\CrudRequest as UpdateRequest;
use Modules\Bcrud\Http\Controllers\CrudFeatures\ShowDetailsRow;

use Modules\Core\Http\Controllers\Admin\AdminBaseController;
use LiveControl\EloquentDataTable\DataTable;

class BcrudController extends AdminBaseController
{
    use DispatchesJobs, ValidatesRequests;
    use AjaxTable, Reorder, Revisions, ShowDetailsRow, SaveActions;

    public $data = [];
    public $crud;
    public $request;

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

        if (! $this->crud) {
			$this->crud = new CrudPanel();
            //$this->crud = app()->make(CrudPanel::class);

            $pnotify = [
                'pnotifyjs' => 'modules/bcrud/vendor/pnotify/pnotify.custom.min.js',
                'pnotifycss' => 'modules/bcrud/vendor/pnotify/pnotify.custom.min.css'
            ];

			//Imagina
            $adminassets =  config()->get('asgard.core.core.admin-assets');
            $adminassets["ckeditor.js"] = ['module' => 'bcrud:vendor/ckeditor/ckeditor.js'];
            \Config::set('asgard.core.core.admin-assets', $adminassets);

            $this->assetManager->addAssets($pnotify);
            $this->assetPipeline->requireJs('pnotifyjs');
            $this->assetPipeline->requireCss('pnotifycss');

            // call the setup function inside this closure to also have the request there
            // this way, developers can use things stored in session (auth variables, etc)
            $this->middleware(function ($request, $next) {
                $this->request = $request;
                $this->crud->request = $request;
                $this->setup();

                return $next($request);
            });
        }
    }

    /**
     * Allow developers to set their configuration options for a CrudPanel.
     */
    public function setup()
    {
    }

    /**
     * Display all rows in the database for this entity.
     *
     * @return Response
     */
    public function index()
    {
        $this->crud->hasAccessOrFail('list');

        $this->data['crud'] = $this->crud;
        $this->data['title'] = ucfirst($this->crud->entity_name_plural);

        // get all entries if AJAX is not enabled
        if (! $this->data['crud']->ajaxTable()) {
            $this->data['entries'] = $this->data['crud']->getEntries();
        }

        // load the view from /resources/views/vendor/backpack/crud/ if it exists, otherwise load the one in the package
        return view($this->crud->getListView(), $this->data);
		//return view('bcrud::list', $this->data);
    }

    /**
     * Show the form for creating inserting a new row.
     *
     * @return Response
     */
    public function create()
    {
        $this->crud->hasAccessOrFail('create');

        // prepare the fields you need to show
        $this->data['crud'] = $this->crud;
        $this->data['saveAction'] = $this->getSaveAction();
        $this->data['fields'] = $this->crud->getCreateFields();
        $this->data['title'] = trans('bcrud::crud.add').' '.$this->crud->entity_name;

        // load the view from /resources/views/vendor/backpack/crud/ if it exists, otherwise load the one in the package
        return view($this->crud->getCreateView(), $this->data);
    }

    /**
     * Store a newly created resource in the database.
     *
     * @param StoreRequest $request - type injection used for validation using Requests
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function storeCrud(StoreRequest $request = null)
    {
        $this->crud->hasAccessOrFail('create');

        // fallback to global request instance
        if (is_null($request)) {
            $request = \Request::instance();
        }

        // replace empty values with NULL, so that it will work with MySQL strict mode on
        foreach ($request->input() as $key => $value) {
            if (empty($value) && $value !== '0') {
                $request->request->set($key, null);
            }
        }

        // insert item in the db
        $item = $this->crud->create($request->except(['save_action', '_token', '_method']));
        $this->data['entry'] = $this->crud->entry = $item;

        // show a success message
        //\Alert::success(trans('bcrud::crud.insert_success'))->flash();

        // save the redirect choice for next time
        $this->setSaveAction();

        return $this->performSaveAction($item->getKey());
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        $this->crud->hasAccessOrFail('update');

        // get the info for that entry
        $this->data['entry'] = $this->crud->getEntry($id);
        $this->data['crud'] = $this->crud;
        $this->data['saveAction'] = $this->getSaveAction();
        $this->data['fields'] = $this->crud->getUpdateFields($id);
        $this->data['title'] = trans('bcrud::crud.edit').' '.$this->crud->entity_name;

        $this->data['id'] = $id;

        // load the view from /resources/views/vendor/backpack/crud/ if it exists, otherwise load the one in the package
        return view($this->crud->getEditView(), $this->data);
    }

    /**
     * Update the specified resource in the database.
     *
     * @param UpdateRequest $request - type injection used for validation using Requests
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function updateCrud(UpdateRequest $request = null)
    {
        $this->crud->hasAccessOrFail('update');

        // fallback to global request instance
        if (is_null($request)) {
            $request = \Request::instance();
        }

        // replace empty values with NULL, so that it will work with MySQL strict mode on
        foreach ($request->input() as $key => $value) {
            if (empty($value) && $value !== '0') {
                $request->request->set($key, null);
            }
        }

        // update the row in the db
        $item = $this->crud->update($request->get($this->crud->model->getKeyName()),
                            $request->except('save_action', '_token', '_method'));
        $this->data['entry'] = $this->crud->entry = $item;

        // show a success message
        //\Alert::success(trans('bcrud::crud.update_success'))->flash();

        // save the redirect choice for next time
        $this->setSaveAction();

        return $this->performSaveAction($item->getKey());
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $this->crud->hasAccessOrFail('show');

        // set columns from db
        $this->crud->setFromDb();

        // cycle through columns
        foreach ($this->crud->columns as $key => $column) {
            // remove any autoset relationship columns
            if (array_key_exists('model', $column) && array_key_exists('autoset', $column) && $column['autoset']) {
                $this->crud->removeColumn($column['name']);
            }
        }

        // get the info for that entry
        $this->data['entry'] = $this->crud->getEntry($id);
        $this->data['crud'] = $this->crud;
        $this->data['title'] = trans('bcrud::crud.preview').' '.$this->crud->entity_name;

        // remove preview button from stack:line
        $this->crud->removeButton('preview');
        $this->crud->removeButton('delete');

        // load the view from /resources/views/vendor/backpack/crud/ if it exists, otherwise load the one in the package
        return view($this->crud->getShowView(), $this->data);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     *
     * @return string
     */
    public function destroy($id)
    {
        $this->crud->hasAccessOrFail('delete');

        return $this->crud->delete($id);
    }
}


text:
package org.apache.tinkerpop.gremlin.groovy.jsr223;

import org.apache.tinkerpop.gremlin.jsr223.Customizer;
import org.apache.tinkerpop.gremlin.jsr223.GremlinScriptEngine;
import org.apache.tinkerpop.gremlin.jsr223.GremlinScriptEngineFactory;
import org.apache.tinkerpop.gremlin.jsr223.GremlinScriptEngineManager;
import org.apache.tinkerpop.gremlin.util.Gremlin;

import javax.script.ScriptEngine;
import java.util.Collections;
import java.util.List;

/**
 * @author Marko A. Rodriguez (http://markorodriguez.com)
 */
public class GremlinGroovyScriptEngineFactory implements GremlinScriptEngineFactory {

    private static final String ENGINE_NAME = "gremlin-groovy";
    private static final String LANGUAGE_NAME = "gremlin-groovy";
    private static final String PLAIN = "plain";
    private static final List<String> EXTENSIONS = Collections.singletonList("groovy");

    private GremlinScriptEngineManager manager;

    @Override
    public void setCustomizerManager(final GremlinScriptEngineManager manager) {
        this.manager = manager;
    }

    @Override
    public String getEngineName() {
        return ENGINE_NAME;
    }

    @Override
    public String getEngineVersion() {
        return Gremlin.version();
    }

    @Override
    public List<String> getExtensions() {
        return EXTENSIONS;
    }

    @Override
    public String getLanguageName() {
        return LANGUAGE_NAME;
    }

    @Override
    public String getLanguageVersion() {
        return Gremlin.version();
    }

    @Override
    public String getMethodCallSyntax(final String obj, final String m, final String... args) {
        return null;
    }

    @Override
    public List<String> getMimeTypes() {
        return Collections.singletonList(PLAIN);
    }

    @Override
    public List<String> getNames() {
        return Collections.singletonList(LANGUAGE_NAME);
    }

    @Override
    public String getOutputStatement(final String toDisplay) {
        return "println " + toDisplay;
    }

    @Override
    public Object getParameter(final String key) {
        if (key.equals(ScriptEngine.ENGINE)) {
            return this.getEngineName();
        } else if (key.equals(ScriptEngine.ENGINE_VERSION)) {
            return this.getEngineVersion();
        } else if (key.equals(ScriptEngine.NAME)) {
            return ENGINE_NAME;
        } else if (key.equals(ScriptEngine.LANGUAGE)) {
            return this.getLanguageName();
        } else if (key.equals(ScriptEngine.LANGUAGE_VERSION)) {
            return this.getLanguageVersion();
        } else
            return null;
    }

    @Override
    public String getProgram(final String... statements) {
        String program = "";

        for (String statement : statements) {
            program = program + statement + "\n";
        }

        return program;
    }

    @Override
    public GremlinScriptEngine getScriptEngine() {
        final List<Customizer> customizers =  manager.getCustomizers(ENGINE_NAME);
        return (customizers.isEmpty()) ? new GremlinGroovyScriptEngine() :
                new GremlinGroovyScriptEngine(customizers.toArray(new Customizer[customizers.size()]));
    }
}


text:
from os import path

from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.conf import settings

email_template_dir = 'tardis_portal/email/'

def email_user(subject, template_filename, context, user):

    to_email = [user.email]

    from_email = settings.EMAIL_HOST_USER

    msg = EmailMultiAlternatives(subject, build_template_text(template_filename, context), \
        from_email, to_email)

    msg.attach_alternative(build_template_html(template_filename, context), \
    "text/html")

    msg.send()

def build_template_text(template_filename, context):
    template_filename_text = template_filename + '.txt'
    plaintext = get_template(path.join(email_template_dir, template_filename_text))
    text_content = plaintext.render(context)
    return text_content

def build_template_html(template_filename, context):
    template_filename_html = template_filename + '.html'
    htmly = get_template(path.join(email_template_dir, template_filename_html))
    html_content = htmly.render(context)
    return html_content


text:
// [START earthengine__apidocs__ee_geometry_multipoint_dissolve]
// Define a MultiPoint object.
var multiPoint = ee.Geometry.MultiPoint([[-122.082, 37.420], [-122.081, 37.426]]);

// Apply the dissolve method to the MultiPoint object.
var multiPointDissolve = multiPoint.dissolve({'maxError': 1});

// Print the result to the console.
print('multiPoint.dissolve(...) =', multiPointDissolve);

// Display relevant geometries on the map.
Map.setCenter(-122.085, 37.422, 15);
Map.addLayer(multiPoint,
             {'color': 'black'},
             'Geometry [black]: multiPoint');
Map.addLayer(multiPointDissolve,
             {'color': 'red'},
             'Result [red]: multiPoint.dissolve');
// [END earthengine__apidocs__ee_geometry_multipoint_dissolve]


text:
using System;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.DataFactory.Models
{
    public partial class RedshiftUnloadSettings : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("s3LinkedServiceName");
            writer.WriteObjectValue(S3LinkedServiceName);
            writer.WritePropertyName("bucketName");
#if NET6_0_OR_GREATER
				writer.WriteRawValue(BucketName);
#else
            JsonSerializer.Serialize(writer, JsonDocument.Parse(BucketName.ToString()).RootElement);
#endif
            writer.WriteEndObject();
        }

        internal static RedshiftUnloadSettings DeserializeRedshiftUnloadSettings(JsonElement element)
        {
            FactoryLinkedServiceReference s3LinkedServiceName = default;
            BinaryData bucketName = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("s3LinkedServiceName"))
                {
                    s3LinkedServiceName = FactoryLinkedServiceReference.DeserializeFactoryLinkedServiceReference(property.Value);
                    continue;
                }
                if (property.NameEquals("bucketName"))
                {
                    bucketName = BinaryData.FromString(property.Value.GetRawText());
                    continue;
                }
            }
            return new RedshiftUnloadSettings(s3LinkedServiceName, bucketName);
        }
    }
}


text:
**If you're viewing this at https://github.com/collectiveidea/delayed_job,
you're reading the documentation for the master branch.
[View documentation for the latest release
(4.1.1).](https://github.com/collectiveidea/delayed_job/tree/v4.1.1)**

Delayed::Job
============
[![Gem Version](https://badge.fury.io/rb/delayed_job.png)][gem]
[![Build Status](https://travis-ci.org/collectiveidea/delayed_job.png?branch=master)][travis]
[![Dependency Status](https://gemnasium.com/collectiveidea/delayed_job.png?travis)][gemnasium]
[![Code Climate](https://codeclimate.com/github/collectiveidea/delayed_job.png)][codeclimate]
[![Coverage Status](https://coveralls.io/repos/collectiveidea/delayed_job/badge.png?branch=master)][coveralls]

[gem]: https://rubygems.org/gems/delayed_job
[travis]: https://travis-ci.org/collectiveidea/delayed_job
[gemnasium]: https://gemnasium.com/collectiveidea/delayed_job
[codeclimate]: https://codeclimate.com/github/collectiveidea/delayed_job
[coveralls]: https://coveralls.io/r/collectiveidea/delayed_job

Delayed::Job (or DJ) encapsulates the common pattern of asynchronously executing
longer tasks in the background.

It is a direct extraction from Shopify where the job table is responsible for a
multitude of core tasks. Amongst those tasks are:

* sending massive newsletters
* image resizing
* http downloads
* updating smart collections
* updating solr, our search server, after product changes
* batch imports
* spam checks

[Follow us on Twitter][twitter] to get updates and notices about new releases.

[twitter]: https://twitter.com/delayedjob

Installation
============
delayed_job 3.0.0 only supports Rails 3.0+. See the [2.0
branch](https://github.com/collectiveidea/delayed_job/tree/v2.0) for Rails 2.

delayed_job supports multiple backends for storing the job queue. [See the wiki
for other backends](https://github.com/collectiveidea/delayed_job/wiki/Backends).

If you plan to use delayed_job with Active Record, add `delayed_job_active_record` to your `Gemfile`.

```ruby
gem 'delayed_job_active_record'
```

If you plan to use delayed_job with Mongoid, add `delayed_job_mongoid` to your `Gemfile`.

```ruby
gem 'delayed_job_mongoid'
```

Run `bundle install` to install the backend and delayed_job gems.

The Active Record backend requires a jobs table. You can create that table by
running the following command:

    rails generate delayed_job:active_record
    rake db:migrate

For Rails 4.2, see [below](#rails-42)

Development
===========
In development mode, if you are using Rails 3.1+, your application code will automatically reload every 100 jobs or when the queue finishes.
You no longer need to restart Delayed Job every time you update your code in development.

Rails 4.2
=========
Set the queue_adapter in config/application.rb

```ruby
config.active_job.queue_adapter = :delayed_job
```

See the [rails guide](http://guides.rubyonrails.org/active_job_basics.html#setting-the-backend) for more details.

Rails 4.x
=========
If you are using the protected_attributes gem, it must appear before delayed_job in your gemfile. If your jobs are failing with:

     ActiveRecord::StatementInvalid: PG::NotNullViolation: ERROR:  null value in column "handler" violates not-null constraint

then this is the fix you're looking for.

Upgrading from 2.x to 3.0.0 on Active Record
============================================
Delayed Job 3.0.0 introduces a new column to the delayed_jobs table.

If you're upgrading from Delayed Job 2.x, run the upgrade generator to create a migration to add the column.

    rails generate delayed_job:upgrade
    rake db:migrate

Queuing Jobs
============
Call `.delay.method(params)` on any object and it will be processed in the background.

```ruby
# without delayed_job
@user.activate!(@device)

# with delayed_job
@user.delay.activate!(@device)
```

If a method should always be run in the background, you can call
`#handle_asynchronously` after the method declaration:

```ruby
class Device
  def deliver
    # long running method
  end
  handle_asynchronously :deliver
end

device = Device.new
device.deliver
```

## Parameters

`#handle_asynchronously` and `#delay` take these parameters:

- `:priority` (number): lower numbers run first; default is 0 but can be reconfigured (see below)
- `:run_at` (Time): run the job after this time (probably in the future)
- `:queue` (string): named queue to put this job in, an alternative to priorities (see below)

These params can be Proc objects, allowing call-time evaluation of the value.

For example:

```ruby
class LongTasks
  def send_mailer
    # Some other code
  end
  handle_asynchronously :send_mailer, :priority => 20

  def in_the_future
    # Some other code
  end
  # 5.minutes.from_now will be evaluated when in_the_future is called
  handle_asynchronously :in_the_future, :run_at => Proc.new { 5.minutes.from_now }

  def self.when_to_run
    2.hours.from_now
  end

  class << self
    def call_a_class_method
      # Some other code
    end
    handle_asynchronously :call_a_class_method, :run_at => Proc.new { when_to_run }
  end

  attr_reader :how_important

  def call_an_instance_method
    # Some other code
  end
  handle_asynchronously :call_an_instance_method, :priority => Proc.new {|i| i.how_important }
end
```

If you ever want to call a `handle_asynchronously`'d method without Delayed Job, for instance while debugging something at the console, just add `_without_delay` to the method name. For instance, if your original method was `foo`, then call `foo_without_delay`.

Rails 3 Mailers
===============
Due to how mailers are implemented in Rails 3, we had to do a little work around to get delayed_job to work.

```ruby
# without delayed_job
Notifier.signup(@user).deliver

# with delayed_job
Notifier.delay.signup(@user)

# with delayed_job running at a specific time
Notifier.delay(run_at: 5.minutes.from_now).signup(@user)
```

Remove the `.deliver` method to make it work. It's not ideal, but it's the best
we could do for now.

Named Queues
============
DJ 3 introduces Resque-style named queues while still retaining DJ-style
priority. The goal is to provide a system for grouping tasks to be worked by
separate pools of workers, which may be scaled and controlled individually.

Jobs can be assigned to a queue by setting the `queue` option:

```ruby
object.delay(:queue => 'tracking').method

Delayed::Job.enqueue job, :queue => 'tracking'

handle_asynchronously :tweet_later, :queue => 'tweets'
```

Running Jobs
============
`script/delayed_job` can be used to manage a background process which will
start working off jobs.

To do so, add `gem "daemons"` to your `Gemfile` and make sure you've run `rails
generate delayed_job`.

You can then do the following:

    RAILS_ENV=production script/delayed_job start
    RAILS_ENV=production script/delayed_job stop

    # Runs two workers in separate processes.
    RAILS_ENV=production script/delayed_job -n 2 start
    RAILS_ENV=production script/delayed_job stop

    # Set the --queue or --queues option to work from a particular queue.
    RAILS_ENV=production script/delayed_job --queue=tracking start
    RAILS_ENV=production script/delayed_job --queues=mailers,tasks start

    # Use the --pool option to specify a worker pool. You can use this option multiple times to start different numbers of workers for different queues.
    # The following command will start 1 worker for the tracking queue,
    # 2 workers for the mailers and tasks queues, and 2 workers for any jobs:
    RAILS_ENV=production script/delayed_job --pool=tracking --pool=mailers,tasks:2 --pool=*:2 start

    # Runs all available jobs and then exits
    RAILS_ENV=production script/delayed_job start --exit-on-complete
    # or to run in the foreground
    RAILS_ENV=production script/delayed_job run --exit-on-complete

**Rails 4:** *replace script/delayed_job with bin/delayed_job*

Workers can be running on any computer, as long as they have access to the
database and their clock is in sync. Keep in mind that each worker will check
the database at least every 5 seconds.

You can also invoke `rake jobs:work` which will start working off jobs. You can
cancel the rake task with `CTRL-C`.

If you want to just run all available jobs and exit you can use `rake jobs:workoff`

Work off queues by setting the `QUEUE` or `QUEUES` environment variable.

    QUEUE=tracking rake jobs:work
    QUEUES=mailers,tasks rake jobs:work

Restarting delayed_job
======================

The following syntax will restart delayed jobs:

    RAILS_ENV=production script/delayed_job restart

To restart multiple delayed_job workers:

    RAILS_ENV=production script/delayed_job -n2 restart

**Rails 4:** *replace script/delayed_job with bin/delayed_job*

Custom Jobs
===========
Jobs are simple ruby objects with a method called perform. Any object which responds to perform can be stuffed into the jobs table. Job objects are serialized to yaml so that they can later be resurrected by the job runner.

```ruby
NewsletterJob = Struct.new(:text, :emails) do
  def perform
    emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
  end
end

Delayed::Job.enqueue NewsletterJob.new('lorem ipsum...', Customers.pluck(:email))
```

To set a per-job max attempts that overrides the Delayed::Worker.max_attempts you can define a max_attempts method on the job

```ruby
NewsletterJob = Struct.new(:text, :emails) do
  def perform
    emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
  end

  def max_attempts
    3
  end
end
```

To set a per-job max run time that overrides the Delayed::Worker.max_run_time you can define a max_run_time method on the job

NOTE: this can ONLY be used to set a max_run_time that is lower than Delayed::Worker.max_run_time. Otherwise the lock on the job would expire and another worker would start the working on the in progress job.

```ruby
NewsletterJob = Struct.new(:text, :emails) do
  def perform
    emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
  end

  def max_run_time
    120 # seconds
  end
end
```

To set a per-job default for destroying failed jobs that overrides the Delayed::Worker.destroy_failed_jobs you can define a destroy_failed_jobs? method on the job

```ruby
NewsletterJob = Struct.new(:text, :emails) do
  def perform
    emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
  end

  def destroy_failed_jobs?
    false
  end
end
```

To set a default queue name for a custom job that overrides Delayed::Worker.default_queue_name, you can define a queue_name method on the job

```ruby
NewsletterJob = Struct.new(:text, :emails) do
  def perform
    emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
  end

  def queue_name
    'newsletter_queue'
  end
end
```

On error, the job is scheduled again in 5 seconds + N ** 4, where N is the number of attempts. You can define your own `reschedule_at` method to override this default behavior.

```ruby
NewsletterJob = Struct.new(:text, :emails) do
  def perform
    emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
  end

  def reschedule_at(current_time, attempts)
    current_time + 5.seconds
  end
end
```

Hooks
=====
You can define hooks on your job that will be called at different stages in the process:

```ruby
class ParanoidNewsletterJob < NewsletterJob
  def enqueue(job)
    record_stat 'newsletter_job/enqueue'
  end

  def perform
    emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
  end

  def before(job)
    record_stat 'newsletter_job/start'
  end

  def after(job)
    record_stat 'newsletter_job/after'
  end

  def success(job)
    record_stat 'newsletter_job/success'
  end

  def error(job, exception)
    Airbrake.notify(exception)
  end

  def failure(job)
    page_sysadmin_in_the_middle_of_the_night
  end
end
```

Gory Details
============
The library revolves around a delayed_jobs table which looks as follows:

```ruby
create_table :delayed_jobs, :force => true do |table|
  table.integer  :priority, :default => 0      # Allows some jobs to jump to the front of the queue
  table.integer  :attempts, :default => 0      # Provides for retries, but still fail eventually.
  table.text     :handler                      # YAML-encoded string of the object that will do work
  table.text     :last_error                   # reason for last failure (See Note below)
  table.datetime :run_at                       # When to run. Could be Time.zone.now for immediately, or sometime in the future.
  table.datetime :locked_at                    # Set when a client is working on this object
  table.datetime :failed_at                    # Set when all retries have failed (actually, by default, the record is deleted instead)
  table.string   :locked_by                    # Who is working on this object (if locked)
  table.string   :queue                        # The name of the queue this job is in
  table.timestamps
end
```

On error, the job is scheduled again in 5 seconds + N ** 4, where N is the number of attempts or using the job's defined `reschedule_at` method.

The default `Worker.max_attempts` is 25. After this, the job either deleted (default), or left in the database with "failed_at" set.
With the default of 25 attempts, the last retry will be 20 days later, with the last interval being almost 100 hours.

The default `Worker.max_run_time` is 4.hours. If your job takes longer than that, another computer could pick it up. It's up to you to
make sure your job doesn't exceed this time. You should set this to the longest time you think the job could take.

By default, it will delete failed jobs (and it always deletes successful jobs). If you want to keep failed jobs, set
`Delayed::Worker.destroy_failed_jobs = false`. The failed jobs will be marked with non-null failed_at.

By default all jobs are scheduled with `priority = 0`, which is top priority. You can change this by setting `Delayed::Worker.default_priority` to something else. Lower numbers have higher priority.

The default behavior is to read 5 jobs from the queue when finding an available job. You can configure this by setting `Delayed::Worker.read_ahead`.

By default all jobs will be queued without a named queue. A default named queue can be specified by using `Delayed::Worker.default_queue_name`.

It is possible to disable delayed jobs for testing purposes. Set `Delayed::Worker.delay_jobs = false` to execute all jobs realtime.

Or `Delayed::Worker.delay_jobs` can be a Proc that decides whether to execute jobs inline on a per-job basis:

```ruby
Delayed::Worker.delay_jobs = ->(job) {
  job.queue != 'inline'
}
```

You may need to raise exceptions on SIGTERM signals, `Delayed::Worker.raise_signal_exceptions = :term` will cause the worker to raise a `SignalException` causing the running job to abort and be unlocked, which makes the job available to other workers. The default for this option is false.

Here is an example of changing job parameters in Rails:

```ruby
# config/initializers/delayed_job_config.rb
Delayed::Worker.destroy_failed_jobs = false
Delayed::Worker.sleep_delay = 60
Delayed::Worker.max_attempts = 3
Delayed::Worker.max_run_time = 5.minutes
Delayed::Worker.read_ahead = 10
Delayed::Worker.default_queue_name = 'default'
Delayed::Worker.delay_jobs = !Rails.env.test?
Delayed::Worker.raise_signal_exceptions = :term
Delayed::Worker.logger = Logger.new(File.join(Rails.root, 'log', 'delayed_job.log'))
```

Cleaning up
===========
You can invoke `rake jobs:clear` to delete all jobs in the queue.

Having problems?
================
Good places to get help are:
* [Google Groups](http://groups.google.com/group/delayed_job) where you can join our mailing list.
* [StackOverflow](http://stackoverflow.com/questions/tagged/delayed-job)


text:
/* global define */

define([
	'backbone',
	'router'
], function (Backbone, Router) {
    'use strict';

    function initialize() {
        Router.initialize();
    }

    return {
        initialize: initialize
    };
});