text:
package org.apache.jackrabbit.oak.index;

import com.google.common.base.Preconditions;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import org.apache.commons.io.FileUtils;
import org.apache.felix.inventory.Format;
import org.apache.jackrabbit.oak.api.Blob;
import org.apache.jackrabbit.oak.api.CommitFailedException;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.commons.PathUtils;
import org.apache.jackrabbit.oak.jcr.Jcr;
import org.apache.jackrabbit.oak.plugins.index.IndexPathService;
import org.apache.jackrabbit.oak.plugins.index.inventory.IndexDefinitionPrinter;
import org.apache.jackrabbit.oak.plugins.memory.MemoryNodeStore;
import org.apache.jackrabbit.oak.spi.commit.CommitInfo;
import org.apache.jackrabbit.oak.spi.commit.EmptyHook;
import org.apache.jackrabbit.oak.spi.lifecycle.RepositoryInitializer;
import org.apache.jackrabbit.oak.spi.state.*;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;
import static java.util.stream.StreamSupport.stream;
import static org.apache.commons.io.FileUtils.byteCountToDisplaySize;
import static org.apache.jackrabbit.oak.api.Type.*;
import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.INDEX_DEFINITIONS_NAME;
import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.REINDEX_PROPERTY_NAME;
import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.TYPE_PROPERTY_NAME;
import static org.apache.jackrabbit.oak.plugins.memory.EmptyNodeState.EMPTY_NODE;
import static org.apache.jackrabbit.oak.plugins.memory.EmptyNodeState.MISSING_NODE;

public class IndexDefinitionUpdater {

    private final NodeStore store;

    private IndexDefinitionUpdater() {
        store = new MemoryNodeStore();
        // initialize as a JCR repo to register namespaces and create initial index structure (/oak:index for our use)
        new Jcr(store).createRepository();
    }

    public static void main(String [] args) throws Exception {
        OptionParser parser = new OptionParser();
        parser.accepts("in", "input index definition file").withRequiredArg().required();
        parser.accepts("out", "output index definition file").withRequiredArg();
        parser.accepts("initializer", "implementation of RepositoryInitializer to update index definitions").withRequiredArg().required();

        OptionSet optionSet = parser.parse(args);

        Preconditions.checkArgument(optionSet.has("in"), "input index definition must be provided");
        String inFilePath = optionSet.valueOf("in").toString();

        Preconditions.checkArgument(optionSet.has("initializer"), "initializer class must be provided");
        String initializerClassName = optionSet.valueOf("initializer").toString();
        Class repoInitClazz = Class.forName(initializerClassName);
        Object obj = repoInitClazz.newInstance();
        Preconditions.checkArgument(obj instanceof RepositoryInitializer, repoInitClazz + " is not a RepositoryInitializer");

        String outFilePath = optionSet.has("out") ? optionSet.valueOf("out").toString() : null;

        new IndexDefinitionUpdater().process(inFilePath, outFilePath, (RepositoryInitializer)obj);
    }

    private void process(String inFilePath, String outFilePath, RepositoryInitializer initializer) throws Exception {
        NodeState before = setupBaseState(inFilePath);
        NodeState after = applyInitializer(before.builder(), initializer);

        List<String> reindexingDefPaths = getReindexIndexPaths();
        List<String> reindexingLuceneDefPaths = getLuceneIndexPaths(reindexingDefPaths);

        if (outFilePath != null) {
            writeReindexingLuceneDefs(outFilePath, reindexingLuceneDefPaths);
        }
        dumpIndexDiff(before, after, reindexingDefPaths);
    }

    private NodeState setupBaseState(String inFilePath) throws Exception {
        org.apache.jackrabbit.oak.plugins.index.importer.IndexDefinitionUpdater indexDefinitionUpdater = new org.apache.jackrabbit.oak.plugins.index.importer.IndexDefinitionUpdater(new File(inFilePath));

        NodeBuilder builder = store.getRoot().builder();
        NodeBuilder oiBuilder = builder.getChildNode(INDEX_DEFINITIONS_NAME);

        for (String indexPath : indexDefinitionUpdater.getIndexPaths()) {
            oiBuilder.setChildNode(PathUtils.getName(indexPath), indexDefinitionUpdater.getIndexState(indexPath));
        }

        return merge(builder);
    }

    private NodeState applyInitializer(NodeBuilder builder, RepositoryInitializer initializer) throws CommitFailedException {
        initializer.initialize(builder);
        return merge(builder);
    }

    private void writeReindexingLuceneDefs(String outFilePath, List<String> reindexingLuceneDefPaths) throws IOException {
        IndexPathService indexPathService = () -> reindexingLuceneDefPaths;

        IndexDefinitionPrinter printer = new IndexDefinitionPrinter(store, indexPathService);

        try (PrintWriter pw = new PrintWriter(
                new BufferedOutputStream(
                        FileUtils.openOutputStream(new File(outFilePath))))) {
            printer.print(pw, Format.JSON, false);
        }
    }

    private List<String> getReindexIndexPaths() {
        return stream(store.getRoot().getChildNode(INDEX_DEFINITIONS_NAME).getChildNodeEntries().spliterator(), false)
                .filter(cne -> !cne.getNodeState().hasProperty(REINDEX_PROPERTY_NAME) || cne.getNodeState().getBoolean(REINDEX_PROPERTY_NAME))
                .filter(cne -> cne.getNodeState().hasProperty(TYPE_PROPERTY_NAME))
                .sorted(comparing(cne -> cne.getNodeState().getString(TYPE_PROPERTY_NAME)))
                .map(cne -> "/" + INDEX_DEFINITIONS_NAME + "/" + cne.getName()).collect(Collectors.toList())
                ;
    }

    private List<String> getLuceneIndexPaths(List<String> indexDefPaths) {
        NodeState root = store.getRoot();
        return indexDefPaths.stream()
                .filter(path -> "lucene".equals(NodeStateUtils.getNode(root, path).getString(TYPE_PROPERTY_NAME)))
                .collect(Collectors.toList());
    }

    private NodeState merge(NodeBuilder builder) throws CommitFailedException {
        store.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
        return store.getRoot();
    }

    private void dumpIndexDiff(NodeState beforeRoot, NodeState afterRoot, List<String> reindexingLuceneDefPaths) {
        try (PrintWriter pw = new PrintWriter(System.out)) {
            for (String indexPath : reindexingLuceneDefPaths) {
                NodeState before = NodeStateUtils.getNode(beforeRoot, indexPath);
                NodeState after = NodeStateUtils.getNode(afterRoot, indexPath);

                pw.println("");
                pw.println("------ " + indexPath + " --------");
                after.compareAgainstBaseState(before, new VisibleChangesDiff(pw));
            }
        }
    }

    static class VisibleChangesDiff implements NodeStateDiff {
        private static final String INDENT = "  ";

        private static final Function<Blob, String> BLOB_LENGTH = new Function<Blob, String>() {

            @Override
            public String apply(Blob b) {
                return safeGetLength(b);
            }

            private String safeGetLength(Blob b) {
                try {
                    return byteCountToDisplaySize(b.length());
                } catch (IllegalStateException e) {
                    // missing BlobStore probably
                }
                return "[N/A]";
            }

        };

        private final PrintWriter pw;
        private final String indent;
        private boolean isRoot;

        VisibleChangesDiff(PrintWriter pw) {
            this(pw, INDENT);
            isRoot = true;
        }

        private VisibleChangesDiff(PrintWriter pw, String indent) {
            this.pw = pw;
            this.indent = indent;
        }

        @Override
        public boolean propertyAdded(PropertyState after) {
            if (!after.getName().startsWith(":")) {
                pw.println(indent + "+ " + toString(after));
            }
            return true;
        }

        @Override
        public boolean propertyChanged(PropertyState before, PropertyState after) {
            if (before.getName().equals("reindex") && isRoot) {
                // don't care if reindex changed on top level
                return true;
            }

            if (before.getName().startsWith(":")) {
                return propertyAdded(after);
            } else if (after.getName().startsWith(":")) {
                return propertyDeleted(before);
            } else {
                pw.println(indent + "^ " + before.getName());
                pw.println(indent + "  - " + toString(before));
                pw.println(indent + "  + " + toString(after));
            }
            return true;
        }

        @Override
        public boolean propertyDeleted(PropertyState before) {
            if (!before.getName().startsWith(":")) {
                pw.println(indent + "- " + toString(before));
            }
            return true;
        }

        @Override
        public boolean childNodeAdded(String name, NodeState after) {
            if (name.startsWith(":")) {
                return true;
            }
            pw.println(indent + "+ " + name);
            return after.compareAgainstBaseState(EMPTY_NODE, new VisibleChangesDiff(
                    pw, indent + INDENT));
        }

        @Override
        public boolean childNodeChanged(String name, NodeState before, NodeState after) {
            if (name.startsWith(":")) {
                return true;
            }

            StringWriter sw = new StringWriter();
            boolean ret;
            try (PrintWriter subPw = new PrintWriter(sw)) {
                ret = after.compareAgainstBaseState(before,
                        new VisibleChangesDiff(subPw, indent + INDENT));
            }

            if (sw.getBuffer().length() > 0) {
                pw.println(indent + "^ " + name);
                pw.print(sw.toString());
            }

            return ret;
        }

        @Override
        public boolean childNodeDeleted(String name, NodeState before) {
            if (name.startsWith(":")) {
                return true;
            }
            pw.println(indent + "- " + name);
            return MISSING_NODE.compareAgainstBaseState(before, new VisibleChangesDiff(pw, indent + INDENT));
        }

        private static String toString(PropertyState ps) {
            StringBuilder val = new StringBuilder();
            val.append(ps.getName()).append("<").append(ps.getType()).append(">");
            if (ps.getType() == BINARY) {
                String v = BLOB_LENGTH.apply(ps.getValue(BINARY));
                val.append(" = {").append(v).append("}");
            } else if (ps.getType() == BINARIES) {
                String v = stream(ps.getValue(BINARIES).spliterator(), false)
                        .map(BLOB_LENGTH)
                        .collect(Collectors.toList()).toString();
                val.append("[").append(ps.count()).append("] = ").append(v);
            } else if (ps.isArray()) {
                val.append("[").append(ps.count()).append("] = ").append(ps.getValue(STRINGS));
            } else {
                val.append(" = ").append(ps.getValue(STRING));
            }
            return ps.getName() + "<" + ps.getType() + ">" + val.toString();
        }
    }
}


text:
package com.github.thealchemist.pg_hibernate;

import java.util.Arrays;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.github.thealchemist.pg_hibernate.spring.IntegerArrayEntity;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
/**
 * @author Jesse Costello-Good, The Alchemist
 */
@RunWith(SpringJUnit4ClassRunner.class)
@Sql
public class IntegerArrayTypeTest extends HibernateTest {

    @Override
    @Test
	public void testSet() throws Exception {
		Integer[] values = new Integer[]{10, 22, 37};
		IntegerArrayEntity entity = new IntegerArrayEntity();
		entity.setIntegers(values);

		this.em.persist(entity);

		assertNotNull(entity.getId());
		assertTrue(entity.getId().intValue() > 0);

		IntegerArrayEntity fromDb = this.em.find(IntegerArrayEntity.class, entity.getId());

		assertNotNull(fromDb);
		assertNotNull(fromDb.getIntegers());

		assertTrue(Arrays.equals(values, fromDb.getIntegers()));
	}

    @Test
    @Sql
    public void testSetViaSql() throws Exception {
        IntegerArrayEntity fromDb = this.em.find(IntegerArrayEntity.class, 39);

        assertNotNull(fromDb);
        assertNotNull(fromDb.getIntegers());

        assertThat(fromDb.getIntegers(), is(equalTo(new Integer[]{76,  -5, 1001})));
    }

    @Test
    @Sql
    public void testGet() throws Exception {

        IntegerArrayEntity fromDb = this.em.find(IntegerArrayEntity.class, 37);

        assertNotNull(fromDb);
        assertThat(fromDb.getIntegers(), is(equalTo(new Integer[]{10, 22, 37})));

    }

    @Override
    @Test
	public void testNull() throws Exception {
        IntegerArrayEntity entity = new IntegerArrayEntity();

		this.em.persist(entity);

		IntegerArrayEntity fromDb = this.em.find(IntegerArrayEntity.class, entity.getId());

		assertNotNull(fromDb);
		assertNull(fromDb.getIntegers());

	}
}

redpajama_set_name: RedPajamaGithub


text:
@implementation CIAPIOrder

@synthesize OrderId;
@synthesize MarketId;
@synthesize ClientAccountId;
@synthesize TradingAccountId;
@synthesize CurrencyId;
@synthesize CurrencyISO;
@synthesize Direction;
@synthesize AutoRollover;
@synthesize ExecutionPrice;
@synthesize LastChangedTime;
@synthesize OpenPrice;
@synthesize OriginalLastChangedDateTime;
@synthesize OriginalQuantity;
@synthesize PositionMethodId;
@synthesize Quantity;
@synthesize Type;
@synthesize Status;
@synthesize ReasonId;

@end


text:
package org.springframework.beans.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.util.ReflectionUtils;

/**
 * General utility methods for working with annotations in JavaBeans style.
 *
 * @author Rob Harrop
 * @author Juergen Hoeller
 * @since 2.0
 */
public abstract class AnnotationBeanUtils {

	/**
	 * Copy the properties of the supplied {@link Annotation} to the supplied target bean.
	 * Any properties defined in excludedProperties will not be copied.
	 * @see org.springframework.beans.BeanWrapper
	 */
	public static void copyPropertiesToBean(Annotation ann, Object bean, String... excludedProperties) {
		Set<String> excluded =  new HashSet<String>(Arrays.asList(excludedProperties));
		Method[] annotationProperties = ann.annotationType().getDeclaredMethods();
		BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(bean);
		for (Method annotationProperty : annotationProperties) {
			String propertyName = annotationProperty.getName();
			if ((!excluded.contains(propertyName)) && bw.isWritableProperty(propertyName)) {
				Object value = ReflectionUtils.invokeMethod(annotationProperty, ann);
				bw.setPropertyValue(propertyName, value);
			}
		}
	}

}


text:
var request = require("request");

module.exports = function(msg) {
	let username = msg.content.split(" ")[1]+"";

	msg.channel.startTyping();
	if (username == "undefined") {
		msg.channel.send("You didn't specify a username. **"+global.prefix+"osu (username)**");
		msg.channel.stopTyping();
		return;
	}

	request("https://osu.ppy.sh/api/get_user?k="+global.token.osu+"&u="+username, function(err, res, body) {
		if (JSON.parse(body)[0].level != null) {
			let json = JSON.parse(body)[0];
			msg.channel.send({
				"embed": {
					"thumbnail": {
						"url": "https://a.ppy.sh/"+json.user_id
					},
					"author": {
						"name": json.username,
						"url": "https://osu.ppy.sh/u/"+json.user_id,
						"icon_url": "https://a.ppy.sh/"+json.user_id
					},
					"fields": [
						{ "name": "Username", "value": json.username+" :flag_"+json.country.toLowerCase()+":", "inline": true },
						{ "name": "Level", "value": json.level.split(".")[0], "inline": true },
						{ "name": "Accuracy", "value": json.accuracy.split(".")[0]+"%", "inline": true },
						{ "name": "Play count", "value": json.playcount, "inline": true },
						{ "name": "Ranks", "value": "SS: "+json.count_rank_ss+" maps"+"\nS: "+json.count_rank_s+" maps"+"\nA: "+json.count_rank_a+" maps", "inline": true },
					]
				}
			});
		} else {
			msg.channel.send("Username not found! Try **"+global.prefix+"osu (username)**");
		}
		msg.channel.stopTyping();
	});
}


text:
This component contains controllers for various CustomResourceDefinitions related to Eventing in Kyma. The following controller comes with this container:

- [`controller`](https://github.com/kyma-project/kyma/blob/main/components/eventing-controller/cmd/eventing-controller/main.go) which lays down the Eventing infrastructure in Business Event Bus (BEB) or [NATS](https://docs.nats.io/nats-concepts/intro).

## Prerequisites

- Install [ko](https://github.com/ko-build/ko/blob/main/docs/install.md) which is used to build and deploy the controller during local development
- Install [kubebuilder](https://github.com/kubernetes-sigs/kubebuilder) which is the base framework for this controller (currently used version: 3.1)
- Install [kustomize](https://github.com/kubernetes-sigs/kustomize) which lets you customize raw, template-free `yaml` files during local development
- Install lint on the local environment
```bash
curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | bash -s -- -b $GOPATH/bin
```

### Installation

- To deploy the controllers inside a cluster, make sure you have `ko` installed and configured according to the [instructions](https://github.com/ko-build/ko/blob/main/docs/install.md). Then run:
> Make sure the environment variables are set. The make target `set-up-local-env` uses default values. Change them as per your needs. If you intend to push your images to dockerhub, set the env variable `KO_DOCKER_REPO` to `index.docker.io/<docker_id>`

> Existing deployment for eventing-controller should be deleted from the Kyma cluster which can interfere with reconciliation process.

```sh
make DOMAIN=custom-domain.com deploy
```

- To verify all the manifests after the processing by Kustomize without applying to the cluster, use make target `deploy-dry-run`:

```sh
make DOMAIN=custom-domain.com deploy-dry-run
```

## Usage

This section explains how to use the Eventing Controller. It expects the following environment variables:

| Environment Variable              | Description                                                                                |
|-----------------------------------|------------------------------------------------------------------------------------------------|
| **For both**                      |                                                                                |
| `APP_LOG_FORMAT`                  | The format of the Application logs.                                                            |
| `APP_LOG_LEVEL`                   | The level of the Application logs.                                                             |
| `BACKEND_CR_NAMESPACE`            | The Namespace of the Backend Resource (CR).                                                    |
| `BACKEND_CR_NAME`                 | The name of the Backend Resource (CR).                                                         |
| `PUBLISHER_IMAGE`                 | The image of the Event Publisher Proxy.                                                        |
| `PUBLISHER_IMAGE_PULL_POLICY`     | The pull-policy of the Event Publisher Proxy.                                                  |
| `PUBLISHER_PORT_NUM`              | The port number of the Event Publisher Proxy itself.                                           |
| `PUBLISHER_METRICS_PORT_NUM`      | The port number of the Event Publisher Proxy metrics.                                          |
| `PUBLISHER_SERVICE_ACCOUNT`       | The service account of the Event Publisher Proxy.                                              |
| `PUBLISHER_REPLICAS`              | The number of replicas of the Event Publisher Proxy.                                           |
| `PUBLISHER_REQUESTS_CPU`          | The CPU requests of the Event Publisher Proxy.                                                 |
| `PUBLISHER_REQUESTS_MEMORY`       | The memory requests of the Event Publish Proxy.                                                |
| `PUBLISHER_LIMITS_CPU`            | The CPU limits of the Event Publisher Proxy.                                                   |
| `PUBLISHER_LIMITS_MEMORY`         | The memory limits of the Event Publisher Proxy.                                                |
| **For NATS**                      |                                                                                |
| `NATS_URL`                        | The URL for the NATS server.                                                                   |
| `EVENT_TYPE_PREFIX`               | The event type prefix for the NATS and BEB backend.                                                    |
| `MAX_IDLE_CONNS`                  | The maximum number of idle connections for the HTTP transport of the NATS backend.             |
| `MAX_CONNS_PER_HOST`              | The maximum connections per host for the HTTP transport of the NATS backend.                   |
| `MAX_IDLE_CONNS_PER_HOST`         | The maximum idle connections per host for the HTTP transport of the NATS backend.              |
| `IDLE_CONN_TIMEOUT`               | The idle timeout duration for the HTTP transport of the NATS backend.                          |
| `DEFAULT_MAX_IN_FLIGHT_MESSAGES`  | The maximum idle "in-flight messages" sent by NATS to the sink without waiting for a response. |
| `DEFAULT_DISPATCHER_RETRY_PERIOD` | The retry period for resending an event to a sink, if the sink doesn't return 2XX.             |
| `DEFAULT_DISPATCHER_MAX_RETRIES`  | The maximum number of retries to send an event to a sink in case of errors.                    |
| **For NATS JetStream**            |                                                                                |
|  `JS_STREAM_NAME`                 | Name of the stream where all events are stored.                                                |
|  `JS_STREAM_STORAGE_TYPE`         | Storage type of the stream: `memory` or `file`.                                                    |
|  `JS_STREAM_RETENTION_POLICY`     | The policy to delete events from the stream: `limits` or `interest`. See https://docs.nats.io/using-nats/developer/develop_jetstream/model_deep_dive#stream-limits-retention-and-policy. |
|  `JS_STREAM_MAX_MSGS`             | The maximum number of messages in the stream. Used only when storage policy is set to `limits`. |
|  `JS_STREAM_MAX_BYTES`            | The maximum size of the stream in bytes. Used only when storage policy is set to `limits`.     |
|  `JS_CONSUMER_DELIVER_POLICY`     | The policy to deliver events to consumers from the stream. Supported values are: `all`, `last`, `last_per_subject`, and `new`. See https://docs.nats.io/nats-concepts/jetstream/consumers#deliverpolicy. |
| **For BEB**                       |                                                                                |
| `TOKEN_ENDPOINT`                  | The Authentication Server Endpoint to provide Access Tokens.                                   |
| `WEBHOOK_ACTIVATION_TIMEOUT`      | The timeout duration used for webhook activation to acquire Access Tokens for Kyma.            |
| `WEBHOOK_TOKEN_ENDPOINT`          | The Kyma public endpoint to provide Access Tokens.                                             |
| `EXEMPT_HANDSHAKE`                | The exemption handshake switch of the subscription protocol settings.                          |
| `QOS`                             | The quality of service setting of the subscription protocol settings.                          |
| `CONTENT_MODE`                    | The content mode of the subscription protocol settings.                                        |
| `DOMAIN`                          | The Kyma cluster public domain.                                                                |

The additional command line arguments are:

| Flag                     | Description                                                                  | Default Value | Backend |
|--------------------------|------------------------------------------------------------------------------|---------------|---------|
| `metrics-addr`           | The TCP address that the controller binds to for serving Prometheus metrics. | `:8080`       | Both    |
| `health-probe-bind-addr` | The TCP address that the controller binds to for serving health probes.      | `:8080`       | Both    |
| `ready-check-endpoint`   | The endpoint of the readiness probe.                                         | `readyz`      | Both    |
| `health-check-endpoint`  | The endpoint of the health probe.                                            | `healthz`     | Both    |
| `reconcile-period`       | The period between triggering of reconciling calls (BEB).                    | 10 minutes    | BEB     |
| `max-reconnects`         | The maximum number of reconnection attempts (NATS).                          | 10            | NATS    |
| `reconnect-wait`         | Wait time between reconnection attempts (NATS).                              | 1 second      | NATS    |

- To install the CustomResourceDefinitions in a cluster, run:

```sh
make install
```

- To uninstall the CustomResourceDefinitions in a cluster, run:

```sh
make uninstall
```

- To install the sample custom resources in a cluster, run:

```sh
make install-samples
```

- To uninstall the sample custom resources in a cluster, run:

```sh
make uninstall-samples
```

## Development

- check code quality before a commit:
```bash
$ make check-code
```

### Project setup

Before running the component, execute the following command once to pull software dependencies and run tests:

```sh
make test
## To download dependencies only
make resolve-local
```

### Generate code during local development

> More details on scaffolding code using kubebuilder can be found [here](https://github.com/kubernetes-sigs/kubebuilder/blob/master/designs/simplified-scaffolding.md).

- Add new APIs using [kubebuilder](https://github.com/kubernetes-sigs/kubebuilder) CLI followed by generating boilerplate code by executing the following script:

```sh
kubebuilder create api --group batch --version v1 --kind CronJob

make manifests
```

- Update fields in the `spec` of an existing CustomResourceDefinition by modifying the Go file for the type i.e. `api/version/<crd>_types.go`. For example, `api/v1alpha1/subscriptions_types.go` for Subscriptions CRD. After that, execute the following command to generate boilerplate code:

```sh
make manifests
```

- To use the newly generated CRDs, copy them to installation folders of Kyma:
```sh
make copy-crds
```

- Add the necessary changes manually in the sample custom resources after updating fields for an existing CustomResourceDefinition inside the folder `config/samples/`. For example, for subscriptions, update the fields manually in `config/samples/eventing_v1alpha1_subscriptioncomponents/eventing-controller/config/crd/bases/eventing.kyma-project.io_subscriptions.yaml.yaml`

- The kubebuilder bootstrapped files have been reduced to the bare minimum. If at a later point one of these files are required (e.g. for a webhook), get them either from [this PR](https://github.com/kyma-project/kyma/pull/9510/commits/6ce5b914c5ef175dea45c27ccca826becb1b5818) or create a sample kubebuilder project and copy all required files from there:

```sh
kubebuilder init --domain kyma-project.io
```

### Set up the environment

#### Start the controller locally

> Running the controller in local developer mode is currently broken and needs adoption of the latest changes.

1. Setup port-forwarding for the in-cluster NATS instance:

```sh
kubectl port-forward -n kyma-system svc/eventing-nats 4222
```

2. Export the following environment variables:

| ENV VAR                  | Description                                        | Optional | Default Value               |
|--------------------------|----------------------------------------------------|----------|-----------------------------|
| `KUBECONFIG`             | Path to a local kubeconfig file.                   | yes      | ~/.kube/config              |
| `NATS_URL`               | URL of the NATS server.                            | no       | nats.nats.svc.cluster.local |
| `EVENT_TYPE_PREFIX`      | The event type prefix for the NATS and BEB backend.        | yes      | sap.kyma.custom             |
| `WEBHOOK_TOKEN_ENDPOINT` | The Kyma public endpoint to provide Access Tokens. | yes      | WEBHOOK_TOKEN_ENDPOINT      |
| `DOMAIN`                 | Domain.                                            | yes      | example.com                 |

```sh
export  NATS_URL=nats://localhost:4222
```

3. Run the controller:

```sh
make run
```

> we currently support a buildtag `local` to avoid setting incorrect OwnerRefs in the PublisherProxy deployment when running the controller on a developer's machine. Essentially the PublisherProxy deployment remains in the cluster although the controller is removed due to no OwnerRef in the PublisherProxy deployment.

> to run the controller via your IDE make sure to specify the buildtag `local`


text:
package net.sf.esfinge.metadata.annotation.validator;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface SearchInsideAnnotations {
}


text:
from __future__ import unicode_literals
import sys
from ajax_select import get_lookup
from django import forms
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.forms.util import flatatt
from django.template.loader import render_to_string
from django.template.defaultfilters import force_escape
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _

try:
    import json
except ImportError:
    from django.utils import simplejson as json

as_default_help = 'Enter text to search.'
IS_PYTHON2 = sys.version_info[0] == 2

def _to_number(got):
    if IS_PYTHON2:
        return long(got)
    return int(got)

def _media(self):
    # unless AJAX_SELECT_BOOTSTRAP == False
    # then load jquery and jquery ui + default css
    # where needed
    js = ('ajax_select/js/bootstrap.js', 'ajax_select/js/ajax_select.js')
    try:
        if not settings.AJAX_SELECT_BOOTSTRAP:
            js = ('ajax_select/js/ajax_select.js',)
    except AttributeError:
        pass
    return forms.Media(css={'all': ('ajax_select/css/ajax_select.css',)}, js=js)

####################################################################################

class AutoCompleteSelectWidget(forms.widgets.TextInput):

    """  widget to select a model and return it as text """

    media = property(_media)

    add_link = None

    def __init__(self,
                 channel,
                 help_text='',
                 show_help_text=True,
                 plugin_options={},
                 *args,
                 **kwargs):
        self.plugin_options = plugin_options
        super(forms.widgets.TextInput, self).__init__(*args, **kwargs)
        self.channel = channel
        self.help_text = help_text
        self.show_help_text = show_help_text

    def render(self, name, value, attrs=None):

        value = value or ''
        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)

        current_repr = ''
        initial = None
        lookup = get_lookup(self.channel)
        if value:
            objs = lookup.get_objects([value])
            try:
                obj = objs[0]
            except IndexError:
                raise Exception("%s cannot find object:%s" % (lookup, value))
            current_repr = lookup.format_item_display(obj)
            initial = [current_repr, obj.pk]

        if self.show_help_text:
            help_text = self.help_text
        else:
            help_text = ''

        context = {
            'name': name,
            'html_id': self.html_id,
            'current_id': value,
            'current_repr': current_repr,
            'help_text': help_text,
            'extra_attrs': mark_safe(flatatt(final_attrs)),
            'func_slug': self.html_id.replace("-", ""),
            'add_link': self.add_link,
        }
        context.update(plugin_options(lookup, self.channel, self.plugin_options, initial))

        return mark_safe(render_to_string(('autocompleteselect_%s.html' % self.channel, 'autocompleteselect.html'), context))

    def value_from_datadict(self, data, files, name):

        got = data.get(name, None)
        if got:
            return _to_number(got)
        else:
            return None

    def id_for_label(self, id_):
        return '%s_text' % id_

class AutoCompleteSelectField(forms.fields.CharField):

    """  form field to select a model for a ForeignKey db field """

    channel = None

    def __init__(self, channel, *args, **kwargs):
        self.channel = channel
        widget = kwargs.get("widget", False)

        if not widget or not isinstance(widget, AutoCompleteSelectWidget):
            widget_kwargs = dict(
                channel=channel,
                help_text=kwargs.get('help_text', _(as_default_help)),
                show_help_text=kwargs.pop('show_help_text', True),
                plugin_options=kwargs.pop('plugin_options', {})
            )
            kwargs["widget"] = AutoCompleteSelectWidget(**widget_kwargs)
        super(AutoCompleteSelectField, self).__init__(max_length=255, *args, **kwargs)

    def clean(self, value):
        if value:
            lookup = get_lookup(self.channel)
            objs = lookup.get_objects([value])
            if len(objs) != 1:
                # someone else might have deleted it while you were editing
                # or your channel is faulty
                # out of the scope of this field to do anything more than tell you it doesn't exist
                raise forms.ValidationError("%s cannot find object: %s" % (lookup, value))
            return objs[0]
        else:
            if self.required:
                raise forms.ValidationError(self.error_messages['required'])
            return None

    def check_can_add(self, user, model):
        _check_can_add(self, user, model)

####################################################################################

class AutoCompleteSelectMultipleWidget(forms.widgets.SelectMultiple):

    """ widget to select multiple models """

    media = property(_media)

    add_link = None

    def __init__(self,
                 channel,
                 help_text='',
                 show_help_text=True,
                 plugin_options={},
                 *args,
                 **kwargs):
        super(AutoCompleteSelectMultipleWidget, self).__init__(*args, **kwargs)
        self.channel = channel

        self.help_text = help_text
        self.show_help_text = show_help_text
        self.plugin_options = plugin_options

    def render(self, name, value, attrs=None):

        if value is None:
            value = []

        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)

        lookup = get_lookup(self.channel)

        # eg. value = [3002L, 1194L]
        if value:
            # |pk|pk| of current
            current_ids = "|" + "|".join(str(pk) for pk in value) + "|"
        else:
            current_ids = "|"

        objects = lookup.get_objects(value)

        # text repr of currently selected items
        initial = []
        for obj in objects:
            display = lookup.format_item_display(obj)
            initial.append([display, obj.pk])

        if self.show_help_text:
            help_text = self.help_text
        else:
            help_text = ''

        context = {
            'name': name,
            'html_id': self.html_id,
            'current': value,
            'current_ids': current_ids,
            'current_reprs': mark_safe(json.dumps(initial)),
            'help_text': help_text,
            'extra_attrs': mark_safe(flatatt(final_attrs)),
            'func_slug': self.html_id.replace("-", ""),
            'add_link': self.add_link,
        }
        context.update(plugin_options(lookup, self.channel, self.plugin_options, initial))

        return mark_safe(render_to_string(('autocompleteselectmultiple_%s.html' % self.channel, 'autocompleteselectmultiple.html'), context))

    def value_from_datadict(self, data, files, name):
        # eg. 'members': ['|229|4688|190|']
        return [_to_number(val) for val in data.get(name, '').split('|') if val]

    def id_for_label(self, id_):
        return '%s_text' % id_

class AutoCompleteSelectMultipleField(forms.fields.CharField):

    """ form field to select multiple models for a ManyToMany db field """

    channel = None

    def __init__(self, channel, *args, **kwargs):
        self.channel = channel

        help_text = kwargs.get('help_text')
        show_help_text = kwargs.pop('show_help_text', False)

        if not (help_text is None):
            # '' will cause translation to fail
            # should be ''
            if type(help_text) == str:
                help_text = force_text(help_text)
            # django admin appends "Hold down "Control",..." to the help text
            # regardless of which widget is used. so even when you specify an explicit help text it appends this other default text onto the end.
            # This monkey patches the help text to remove that
            if help_text != '':
                if not self._is_string(help_text):
                    # ideally this could check request.LANGUAGE_CODE
                    translated = help_text.translate(settings.LANGUAGE_CODE)
                else:
                    translated = help_text
                django_default_help = _('Hold down "Control", or "Command" on a Mac, to select more than one.').translate(settings.LANGUAGE_CODE)
                if django_default_help in translated:
                    cleaned_help = translated.replace(django_default_help, '').strip()
                    # probably will not show up in translations
                    if cleaned_help:
                        help_text = cleaned_help
                    else:
                        help_text = ""
                        show_help_text = False
        else:
            help_text = _(as_default_help)

        # django admin will also show help text outside of the display
        # area of the widget.  this results in duplicated help.
        # it should just let the widget do the rendering
        # so by default do not show it in widget
        # if using in a normal form then set to True when creating the field
        widget_kwargs = {
            'channel': channel,
            'help_text': help_text,
            'show_help_text': show_help_text,
            'plugin_options': kwargs.pop('plugin_options', {})
        }
        kwargs['widget'] = AutoCompleteSelectMultipleWidget(**widget_kwargs)
        kwargs['help_text'] = help_text

        super(AutoCompleteSelectMultipleField, self).__init__(*args, **kwargs)

    @staticmethod
    def _is_string(help_text):
        if IS_PYTHON2:
            return type(help_text) == unicode
        return type(help_text) == str

    def clean(self, value):
        if not value and self.required:
            raise forms.ValidationError(self.error_messages['required'])
        return value  # a list of IDs from widget value_from_datadict

    def check_can_add(self, user, model):
        _check_can_add(self, user, model)

####################################################################################

class AutoCompleteWidget(forms.TextInput):

    """
    Widget to select a search result and enter the result as raw text in the text input field.
    the user may also simply enter text and ignore any auto complete suggestions.
    """

    media = property(_media)

    channel = None
    help_text = ''
    html_id = ''

    def __init__(self, channel, *args, **kwargs):
        self.channel = channel
        self.help_text = kwargs.pop('help_text', '')
        self.show_help_text = kwargs.pop('show_help_text', True)
        self.plugin_options = kwargs.pop('plugin_options', {})

        super(AutoCompleteWidget, self).__init__(*args, **kwargs)

    def render(self, name, value, attrs=None):

        initial = value or ''

        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)

        lookup = get_lookup(self.channel)
        if self.show_help_text:
            help_text = self.help_text
        else:
            help_text = ''

        context = {
            'current_repr': initial,
            'current_id': initial,
            'help_text': help_text,
            'html_id': self.html_id,
            'name': name,
            'extra_attrs': mark_safe(flatatt(final_attrs)),
            'func_slug': self.html_id.replace("-", ""),
        }
        context.update(plugin_options(lookup, self.channel, self.plugin_options, initial))

        templates = ('autocomplete_%s.html' % self.channel,
                     'autocomplete.html')
        return mark_safe(render_to_string(templates, context))

class AutoCompleteField(forms.CharField):
    """
    Field uses an AutoCompleteWidget to lookup possible completions using a channel and stores raw text (not a foreign key)
    """
    channel = None

    def __init__(self, channel, *args, **kwargs):
        self.channel = channel

        widget_kwargs = dict(
            help_text=kwargs.get('help_text', _(as_default_help)),
            show_help_text=kwargs.pop('show_help_text', True),
            plugin_options=kwargs.pop('plugin_options', {})
        )
        if 'attrs' in kwargs:
            widget_kwargs['attrs'] = kwargs.pop('attrs')
        widget = AutoCompleteWidget(channel, **widget_kwargs)

        defaults = {'max_length': 255, 'widget': widget}
        defaults.update(kwargs)

        super(AutoCompleteField, self).__init__(*args, **defaults)

####################################################################################

def _check_can_add(self, user, model):
    """ check if the user can add the model, deferring first to
        the channel if it implements can_add()
        else using django's default perm check.
        if it can add, then enable the widget to show the + link
    """
    lookup = get_lookup(self.channel)
    if hasattr(lookup, 'can_add'):
        can_add = lookup.can_add(user, model)
    else:
        ctype = ContentType.objects.get_for_model(model)
        can_add = user.has_perm("%s.add_%s" % (ctype.app_label, ctype.model))
    if can_add:
        self.widget.add_link = reverse('add_popup', kwargs={'app_label': model._meta.app_label, 'model': model._meta.object_name.lower()})

def autoselect_fields_check_can_add(form, model, user):
    """ check the form's fields for any autoselect fields and enable their widgets with + sign add links if permissions allow"""
    for name, form_field in form.declared_fields.items():
        if isinstance(form_field, (AutoCompleteSelectMultipleField, AutoCompleteSelectField)):
            db_field = model._meta.get_field_by_name(name)[0]
            form_field.check_can_add(user, db_field.rel.to)

def plugin_options(channel, channel_name, widget_plugin_options, initial):
    """ Make a JSON dumped dict of all options for the jquery ui plugin itself """
    po = {}
    if initial:
        po['initial'] = initial
    po.update(getattr(channel, 'plugin_options', {}))
    po.update(widget_plugin_options)
    if not po.get('min_length'):
        # backward compatibility: honor the channel's min_length attribute
        # will deprecate that some day and prefer to use plugin_options
        po['min_length'] = getattr(channel, 'min_length', 1)
    if not po.get('source'):
        po['source'] = reverse('ajax_lookup', kwargs={'channel': channel_name})

    # allow html unless explictly false
    if po.get('html') is None:
        po['html'] = True

    return {
        'plugin_options': mark_safe(json.dumps(po)),
        'data_plugin_options': force_escape(json.dumps(po)),
        # continue to support any custom templates that still expect these
        'lookup_url': po['source'],
        'min_length': po['min_length']
        }


text:
package edu.amc.sakai.user;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.MessageFormat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sakaiproject.component.api.ServerConfigurationService;

import com.novell.ldap.LDAPConnection;
import com.novell.ldap.LDAPEntry;
import com.novell.ldap.LDAPException;
import com.novell.ldap.LDAPSearchConstraints;
import com.novell.ldap.LDAPSearchResults;

/**
 * Tests {@link LDAPConnection} liveness by executing a search filter
 * and verifying that the result contains at least one entry. This
 * strategy is appropriate when {@link LDAPConnection#isConnectionAlive()}
 * is not reliable, e.g. when running against a non-OpenLDAP service
 * provider.
 *
 *
This particular implementation makes an effort to generate
 * filters which will be easily traceable in LDAP logs. Generally,
 * filters take the form
 * (|(objectclass=*)({attr}={unique-string})). The
 * search itself is limited by {@link LDAPConnection#SCOPE_BASE},
 * where "BASE" is specified by baseDn. Often,
 * baseDn corresponds to the DN of the "system user"
 * as whom {@link JLDAPDirectoryProvider} binds when running
 * in "autoBind" mode.

 *
 * @author dmccallum@unicon.net
 */
public class SearchExecutingLdapConnectionLivenessValidator
implements LdapConnectionLivenessValidator {

	public static final String DEFAULT_SEARCH_ATTRIBUTE_NAME = "uid";

	public static final LDAPSearchConstraints DEFAULT_LDAP_CONSTRAINTS =
		new LDAPSearchConstraints();

	{

		DEFAULT_LDAP_CONSTRAINTS.setDereference(LDAPSearchConstraints.DEREF_ALWAYS);
		DEFAULT_LDAP_CONSTRAINTS.setTimeLimit(5000);
		DEFAULT_LDAP_CONSTRAINTS.setReferralFollowing(false);
		DEFAULT_LDAP_CONSTRAINTS.setBatchSize(0);

	}

	public static final String DEFAULT_HOST_NAME = "UNKNOWN_HOST";

	/** Class-specific logger */
	private static Logger log = LoggerFactory.getLogger(SearchExecutingLdapConnectionLivenessValidator.class);

	/**
	 * An ID for this instance
	 */
	private String searchStamp =
		System.currentTimeMillis() + "-" + (int)(1e6*Math.random());

	/**
	 * The attribute against which the search unique ID will
	 * be tested.
	 */
	private String searchAttributeName = DEFAULT_SEARCH_ATTRIBUTE_NAME;

	/**
	 * The searchFilter string with a placeholder for a unique
	 * key for a particular execution. Treated as a {@link MessageFormat}
	 * pattern. Depends on {@link #searchAttributeName}
	 * having already been initialized to some meaningful value.
	 */
	private String searchFilter = newUnformattedSearchFilter();

	/**
	 * Cached copy of constraints common to all searches
	 */
	private LDAPSearchConstraints searchConstraints = DEFAULT_LDAP_CONSTRAINTS;

	/**
	 * The DN to be searched by {@link #searchFilter}. Searches
	 * are restricted to search this DN only.
	 */
	private String baseDn;

	private String hostName = DEFAULT_HOST_NAME;

	private ServerConfigurationService serverConfigService;

	/**
	 * Invoke prior to testing any connections. Caches a host
	 * name to include in search terms.
	 */
	public void init() {
		if (hostName.equals(DEFAULT_HOST_NAME)) {
			hostName = null; // defaults again at bottom
			if (hostName == null) {
				try {
					hostName = getLocalhostName();
				} catch (UnknownHostException e) {
					if (log.isDebugEnabled()) {
						log.debug("Unable to get local host name", e);
					}
				}
			}
			if (hostName == null && serverConfigService != null) {
				hostName = serverConfigService.getServerName();
			}
			if (hostName == null) {
				hostName = DEFAULT_HOST_NAME;
			}
		}
		if ( log.isDebugEnabled() ) {
			log.debug("init(): cached hostName [" + hostName + "]");
		}
	}

	/**
	 * Returns localhost's name as reported by
	 * {@link InetAddress#getLocalHost()#toString()}. Factored
	 * into a method to enable override during testing.
	 *
	 * @return
	 * @throws UnknownHostException
	 */
	protected String getLocalhostName() throws UnknownHostException {
	    return InetAddress.getLocalHost().toString();
	}

	public boolean isConnectionAlive(LDAPConnection connectionToTest) {

		if ( log.isDebugEnabled() ) {
			log.debug("isConnectionAlive(): testing connection liveness via search");
		}

        String formattedSearchFilter = formatSearchFilter();

        try
        {

        	if ( log.isDebugEnabled() ) {
    			log.debug("isConnectionAlive(): executing connection liveness search [base dn = " +
    					baseDn + "][filter = " + formattedSearchFilter + "][return attrib = " +
    					searchAttributeName + "]");
    		}

            LDAPSearchResults searchResults =
            	connectionToTest.search(baseDn,
                        LDAPConnection.SCOPE_BASE,
                        formattedSearchFilter,
                        new String[] {searchAttributeName},
                        false,
                        searchConstraints);

            if ( log.isDebugEnabled() ) {
    			log.debug("isConnectionAlive(): executed search [base dn = " +
    					baseDn + "][filter = " + formattedSearchFilter + "][return attrib = " +
    					searchAttributeName + "]");
    		}

            if ( searchResults.hasMore() ) {
            	if ( log.isDebugEnabled() ) {
        			log.debug("isConnectionAlive(): search contained results [base dn = " +
        					baseDn + "][filter = " + formattedSearchFilter + "][return attrib = " +
        					searchAttributeName + "]");
        		}
            	LDAPEntry entry = searchResults.next();
            	boolean isNonNullEntry = entry != null;
            	if ( log.isDebugEnabled() ) {
        			log.debug("isConnectionAlive(): search [base dn = " +
        					baseDn + "][filter = " + formattedSearchFilter + "][return attrib = " +
        					searchAttributeName + "] had results, returning [" +
        					isNonNullEntry + "]");
        		}
            	return isNonNullEntry;
            } else {
            	if ( log.isDebugEnabled() ) {
        			log.debug("isConnectionAlive(): search had no results [base dn = " +
        					baseDn + "][filter = " + formattedSearchFilter + "][return attrib = " +
        					searchAttributeName + "], returning false");
        		}
            	return false;
            }

        }
        catch (LDAPException le)
        {
        	if ( log.isDebugEnabled() ) {
        		log.debug("isConnectionAlive(): liveness test failed [base dn = " +
        			baseDn + "][filter = " + formattedSearchFilter + "][return attrib = " +
        			searchAttributeName + "]", le);
        	}
        	return false;
        }

	}

	protected String newUnformattedSearchFilter() {
		return new StringBuilder("(|(objectclass=*)(")
		.append(searchAttributeName)
		.append("=validateProbe-")
		.append(searchStamp)
		.append("-{0}))").toString();
	}

	/**
	 * Generates an executable search filter string by injecting
	 * the result of {@link #generateUniqueSearchFilterTerm()} into
	 * the current searchFilter. This term is usually
	 * treated as a portion of the value to match against
	 * searchAttributeName
	 *
	 * @return an LDAP search filter
	 */
	protected String formatSearchFilter() {
		Object uniqueSearchFilterTerm = generateUniqueSearchFilterTerm();
		return MessageFormat.format(searchFilter, uniqueSearchFilterTerm);
	}

	/**
	 * Generates a portion of the search filter which will (likely) uniquely
	 * identify an execution of that filter. By default concatenates a
	 * semi-unique token ({@link #generateUniqueToken()} and the local host
	 * name, separated by a dash ("-").
	 *
	 * @see #setHostName(String)
	 * @see #getHostName()
	 * @see #generateUniqueToken()
	 * @see #setServerConfigService(ServerConfigurationService)
	 * @return
	 */
	protected Object generateUniqueSearchFilterTerm() {
		return generateUniqueToken() + "-" + hostName;
	}

	/**
	 * Just returns the current system time in millis. This
	 * is factored into a method so it can be overriden
	 * in testing (otherwise unique tokens are quite difficult
	 * to verify).
	 *
	 * @see System#currentTimeMillis()
	 * @return
	 */
	protected String generateUniqueToken() {
		return Long.toString(System.currentTimeMillis());
	}

	public String getSearchStamp() {
		return searchStamp;
	}

	public void setSearchStamp(String searchStamp) {
		this.searchStamp = searchStamp;
	}

	public String getSearchAttributeName() {
		return searchAttributeName;
	}

	public void setSearchAttributeName(String searchAttributeName) {
		if ( searchAttributeName == null ) {
			this.searchAttributeName = DEFAULT_SEARCH_ATTRIBUTE_NAME;
		} else {
			this.searchAttributeName = searchAttributeName;
		}
		this.searchFilter = newUnformattedSearchFilter();
	}

	public String getBaseDn() {
		return baseDn;
	}

	public void setBaseDn(String baseDn) {
		this.baseDn = baseDn;
	}

	public LDAPSearchConstraints getSearchConstraints() {
		return searchConstraints;
	}

	public void setSearchConstraints(LDAPSearchConstraints searchConstraints) {
		this.searchConstraints = searchConstraints;
	}

	public String getSearchFilter() {
		return searchFilter;
	}

	public void setSearchFilter(String searchFilter) {
		this.searchFilter = searchFilter;
	}

	public ServerConfigurationService getServerConfigService() {
		return serverConfigService;
	}

	public void setServerConfigService(
			ServerConfigurationService serverConfigService) {
		this.serverConfigService = serverConfigService;
	}

	public String getHostName() {
		return hostName;
	}

	/**
	 * Assign the host name to be appended to (semi) invocation-unique
	 * search terms. Falls back to {@link #DEFAULT_HOST_NAME} if
	 * argument is null. If this setter is not ivoked,
	 * {@link #init()} will control the default value.
	 *
	 * @see #init()
	 * @param hostName
	 */
	public void setHostName(String hostName) {
		if ( hostName == null ) {
			this.hostName = DEFAULT_HOST_NAME;
		} else {
			this.hostName = hostName;
		}
	}

}


text:
<!--
  #%L
  Wildfly Camel :: Testsuite
  %%
  Copyright (C) 2013 - 2014 RedHat
  %%
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  #L%
  -->
<spring:beans xmlns:spring="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://camel.apache.org/schema/spring"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">

    <spring:bean id="salesforce" class="org.apache.camel.component.salesforce.SalesforceComponent">
        <spring:property name="loginConfig">
            <spring:bean class="org.apache.camel.component.salesforce.SalesforceLoginConfig">
                <spring:property name="clientId" value="#{systemEnvironment['SALESFORCE_CONSUMER_KEY']}"/>
                <spring:property name="clientSecret" value="#{systemEnvironment['SALESFORCE_CONSUMER_SECRET']}"/>
                <spring:property name="userName" value="#{systemEnvironment['SALESFORCE_USER']}"/>
                <spring:property name="password" value="#{systemEnvironment['SALESFORCE_PASSWORD']}"/>
            </spring:bean>
        </spring:property>
        <spring:property name="packages">
            <spring:array>
                <spring:value>org.wildfly.camel.test.salesforce.dto</spring:value>
            </spring:array>
        </spring:property>
    </spring:bean>

    <camelContext id="salesforce-context">

        <route id="salesforce-opportunity" trace="true">
            <from uri="direct:opportunity" />
            <to uri="salesforce:query?sObjectQuery=SELECT Id,Name FROM Opportunity&sObjectClass=org.wildfly.camel.test.salesforce.dto.QueryRecordsOpportunity"/>
            <log message="${body}" />
        </route>

        <route id="salesforce-account" trace="true">
            <from uri="direct:account" />
            <to uri="salesforce:query?sObjectQuery=SELECT Id,AccountNumber FROM Account&sObjectClass=org.wildfly.camel.test.salesforce.dto.QueryRecordsAccount"/>
            <log message="${body}" />
        </route>

    </camelContext>

</spring:beans>


text:
package org.dasein.cloud.brightbox;

import org.dasein.cloud.CloudErrorType;
import org.dasein.cloud.CloudException;

import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;

/**
 * Base exception class for errors that occur in MyCloud.
 *
Created by George Reese: 12/06/2012 9:44 AM

 * @author George Reese
 * @version 2013.01 initial version
 * @since 2013.01
 */
public class CloudProviderException extends CloudException {

    public CloudProviderException(@Nonnull Throwable cause) {
        super(cause);
    }

    public CloudProviderException(@Nonnull CloudErrorType type, @Nonnegative int httpCode, @Nonnull String providerCode, @Nonnull String message) {
        super(type, httpCode, providerCode, message);
    }
}


text:
DesertBiome::DesertBiome(BiomeManager *b) : Biome(b, "desert"){}

// tree range is .8
inline float getNoiseValue(const BiomeGenInfo &_info){
    float a = _info.height - (int)_info.height;
    float b = 17*_info.humidity - (int)(17*_info.humidity);
    float c = 31*_info.temperature - (int)(31*_info.temperature);
    return (a+b+c)/3;
}

float DesertBiome::getBlockHeight(const Vector3 &_coordinates, BiomeGenInfo &_info){
    float _height = _info.height;
    _height += getNoiseValue(_info);
    return (int)(_height);
}

// temp height humid
unsigned char DesertBiome::generateBlock(const Vector3 & _coordinates, BiomeGenInfo &_info, bool _isPrimary){
    float _height = getBlockHeight(_coordinates, _info);

    if (_coordinates.y == (int)_height){
        return SAND;
    } else if (_coordinates.y < _height){
        return SAND;
    }

    return AIR;
}

TerrainFeature* DesertBiome::getPotentialBlockFeature(Vector3 _pos, BiomeGenInfo _info){

    float _featureValue = getNoiseValue(_info);

    if (_featureValue > .8){
        if (_info.height > 32){
            return bm->features.at("cactus")->clone(_pos, &_info);
        }
    }

    return NULL;
}


text:
"""
Package for the models.
"""

from os import path
import json

class Poll(object):
    """A poll object for use in the application views and repository."""
    def __init__(self, key=u'', text=u''):
        """Initializes the poll."""
        self.key = key
        self.text = text
        self.choices = []
        self.total_votes = None

    def calculate_stats(self):
        """Calculates some statistics for use in the application views."""
        total = 0
        for choice in self.choices:
            total += choice.votes
        for choice in self.choices:
            choice.votes_percentage = choice.votes / float(total) * 100 \
                if total > 0 else 0
        self.total_votes = total

class Choice(object):
    """A poll choice object for use in the application views and repository."""
    def __init__(self, key=u'', text=u'', votes=0):
        """Initializes the poll choice."""
        self.key = key
        self.text = text
        self.votes = votes
        self.votes_percentage = None

class PollNotFound(Exception):
    """Exception raised when a poll/choice object couldn't be retrieved from
    the repository."""
    pass

def _load_samples_json():
    """Loads polls from samples.json file."""
    samples_path = path.join(path.dirname(__file__), 'samples.json')
    with open(samples_path, 'r') as samples_file:
        return json.load(samples_file)


text:
/* tslint:disable */

import { Arguments, Attribute, Interceptor, Invocation } from '../../../src/dependencies/agent';

export class RandomInterceptor implements Attribute, Interceptor {
  beforeDecorate(
    target: Object | Function,
    targetKey?: string | symbol,
    descriptor?: PropertyDescriptor | number
  ): boolean {
    return true;
  }

  get interceptor(): Interceptor {
    return this;
  }

  intercept(target: Invocation, params: Arguments, receiver: any): any {
    const a = target.invoke(params, receiver);
    expect(a).toBeUndefined();
    return Date.now() + 0.23133;
  }
}


text:
module EbayTrading
  module Schema
    class Enumeration
      include Inflections

      attr_accessor :codes
      def initialize(codes = [])
        codes.delete('CustomCode')
        @codes = codes
      end

      def to_s
        <<-END
CODES = #{@codes.inspect}

class << self
  def codes
    CODES
  end

  CODES.each do |code|
    define_method(ebay_underscore(code) do
      new(code)
    end
  end
end
        END
      end
    end
  end
end


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

import ghidra.program.model.address.Address;
import ghidra.program.model.lang.Register;
import ghidra.program.model.listing.Program;
import ghidra.program.model.pcode.Varnode;

class VarnodeInfo {

	private VarnodeType type;
	private Address address;
	private Integer size;
	private Register register;

	private final Program program;

	VarnodeInfo(Program program, VarnodeType type) {
		this.program = program;
		this.type = type;
	}

	VarnodeInfo(Program program, Varnode varnode) {
		this.program = program;
		setVarnode(varnode);
	}

	public VarnodeType getType() {
		return type;
	}

	public Address getAddress() {
		return address;
	}

	public Integer getSize() {
		return size;
	}

	public void setVarnodeType(VarnodeType type) {
		this.type = type;
		address = null;
		register = null;
		if (type == VarnodeType.Register) {
			size = null;
		}
	}

	public void setVarnode(Address address, Integer size) {
		this.address = address;
		this.size = size;
		register = getRegister(program, address, size);
		if (address == null) {
			return;
		}
		if (address.isRegisterAddress() || register != null) {
			type = VarnodeType.Register;
		}
		else if (address.isStackAddress()) {
			type = VarnodeType.Stack;
		}
		else if (address.isMemoryAddress()) {
			type = VarnodeType.Memory;
		}
		else {
			throw new IllegalArgumentException("Illegal varnode address type");
		}
	}

	public void setVarnode(Varnode varnode) {
		setVarnode(varnode.getAddress(), varnode.getSize());
	}

	public Register getRegister() {
		return register;
	}

	public static Register getRegister(Program program, Address address, Integer size) {
		if (address == null) {
			return null;
		}
		if (!address.isRegisterAddress() && !address.getAddressSpace().hasMappedRegisters()) {
			return null;
		}
		if (size == null) {
			return program.getRegister(address);
		}
		Register register = program.getRegister(address, size);
		if (register == null) {
			register = program.getRegister(address);
		}
		return register;

	}

}


text:
package lombok.test;
public @org.openlegacy.core.annotations.screen.ScreenEntity(supportTerminalData = false) @javax.xml.bind.annotation.XmlAccessorType(value = javax.xml.bind.annotation.XmlAccessType.FIELD) class ScreenEntityFieldDescription implements org.openlegacy.core.terminal.ScreenEntity {
  private @com.fasterxml.jackson.annotation.JsonIgnore() @javax.xml.bind.annotation.XmlTransient() java.lang.String outerQuantityDescription;
  private @com.fasterxml.jackson.annotation.JsonIgnore() @javax.xml.bind.annotation.XmlTransient() java.lang.String outerUnitOfMeasureDescription;
  private @com.fasterxml.jackson.annotation.JsonIgnore() @javax.xml.bind.annotation.XmlTransient() java.lang.String packingMultiplierDescription;
  private @com.fasterxml.jackson.annotation.JsonIgnore() @javax.xml.bind.annotation.XmlTransient() java.lang.String itemNumberDescription;
  private @com.fasterxml.jackson.annotation.JsonIgnore() @javax.xml.bind.annotation.XmlTransient() java.lang.String itemNameDescription;
  private @com.fasterxml.jackson.annotation.JsonIgnore() @javax.xml.bind.annotation.XmlTransient() java.util.List<org.openlegacy.core.terminal.definitions.TerminalActionDefinition> actions = new java.util.ArrayList<org.openlegacy.core.terminal.definitions.TerminalActionDefinition>();
  private @com.fasterxml.jackson.annotation.JsonIgnore() @javax.xml.bind.annotation.XmlTransient() java.lang.String pcCommand;
  private @com.fasterxml.jackson.annotation.JsonIgnore() @javax.xml.bind.annotation.XmlTransient() java.lang.String focusField;
  private @org.openlegacy.core.annotations.screen.ScreenField(row = 6,column = 33,endColumn = 52,labelColumn = 2,displayName = "Item Number",sampleValue = "A") @org.openlegacy.core.annotations.screen.ScreenDescriptionField(column = 1,row = 1) String itemName;
  private @org.openlegacy.core.annotations.screen.ScreenField(row = 6,column = 33,endColumn = 52,labelColumn = 2,displayName = "Item Number",sampleValue = "A") @org.openlegacy.core.annotations.screen.ScreenDescriptionField(column = 1,row = 3) Integer itemNumber;
  private @org.openlegacy.core.annotations.screen.ScreenField(key = true,row = 17,column = 33,endColumn = 37,labelColumn = 2,displayName = "Packing Multiplier",sampleValue = "0") @org.openlegacy.core.annotations.screen.ScreenDescriptionField(column = 1,row = 5) Double packingMultiplier;
  private @org.openlegacy.core.annotations.screen.ScreenField(row = 18,column = 33,endColumn = 37,labelColumn = 2,displayName = "Outer Unit of Measure") @org.openlegacy.core.annotations.screen.ScreenDescriptionField(column = 1,row = 5) java.math.BigInteger outerUnitOfMeasure;
  private @org.openlegacy.core.annotations.screen.ScreenField(row = 19,column = 33,endColumn = 41,labelColumn = 2,displayName = "Outer Quantity",sampleValue = "0") @org.openlegacy.core.annotations.screen.ScreenDescriptionField(column = 1,row = 7) java.math.BigDecimal outerQuantity;
  public ScreenEntityFieldDescription() {
    super();
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getItemName() {
    return this.itemName;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Integer getItemNumber() {
    return this.itemNumber;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Double getPackingMultiplier() {
    return this.packingMultiplier;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.math.BigInteger getOuterUnitOfMeasure() {
    return this.outerUnitOfMeasure;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.math.BigDecimal getOuterQuantity() {
    return this.outerQuantity;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String getFocusField() {
    return this.focusField;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String getPcCommand() {
    return this.pcCommand;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.List<org.openlegacy.core.terminal.definitions.TerminalActionDefinition> getActions() {
    return this.actions;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String getItemNameDescription() {
    return this.itemNameDescription;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String getItemNumberDescription() {
    return this.itemNumberDescription;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String getPackingMultiplierDescription() {
    return this.packingMultiplierDescription;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String getOuterUnitOfMeasureDescription() {
    return this.outerUnitOfMeasureDescription;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String getOuterQuantityDescription() {
    return this.outerQuantityDescription;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setItemName(final String itemName) {
    this.itemName = itemName;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setItemNumber(final Integer itemNumber) {
    this.itemNumber = itemNumber;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setPackingMultiplier(final Double packingMultiplier) {
    this.packingMultiplier = packingMultiplier;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setOuterUnitOfMeasure(final java.math.BigInteger outerUnitOfMeasure) {
    this.outerUnitOfMeasure = outerUnitOfMeasure;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setOuterQuantity(final java.math.BigDecimal outerQuantity) {
    this.outerQuantity = outerQuantity;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setFocusField(final java.lang.String focusField) {
    this.focusField = focusField;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setPcCommand(final java.lang.String pcCommand) {
    this.pcCommand = pcCommand;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setActions(final java.util.List<org.openlegacy.core.terminal.definitions.TerminalActionDefinition> actions) {
    this.actions = actions;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setItemNameDescription(final java.lang.String itemNameDescription) {
    this.itemNameDescription = itemNameDescription;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setItemNumberDescription(final java.lang.String itemNumberDescription) {
    this.itemNumberDescription = itemNumberDescription;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setPackingMultiplierDescription(final java.lang.String packingMultiplierDescription) {
    this.packingMultiplierDescription = packingMultiplierDescription;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setOuterUnitOfMeasureDescription(final java.lang.String outerUnitOfMeasureDescription) {
    this.outerUnitOfMeasureDescription = outerUnitOfMeasureDescription;
  }
  public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setOuterQuantityDescription(final java.lang.String outerQuantityDescription) {
    this.outerQuantityDescription = outerQuantityDescription;
  }
}


text:
/**
 * Created by liumeng on 2017/9/4.
 */
var router = require('koa-router')();
var order_controller = require('../../app/controllers/order');

router.get('/list', order_controller.list);
router.get('/list/page/:pageid', order_controller.list);
router.get('/list/page/:pageid/time/:time', order_controller.list);
router.get('/list/time/:time', order_controller.list);
router.get('/:id', order_controller.getOrder);
router.get('/simple/:id', order_controller.getOrderSimple);
router.post('/save', order_controller.save);

router.post('/saveOrder', order_controller.saveAndSaveOperation);
router.post('/saveOperation', order_controller.saveOperation);

router.get('/delete/:id',order_controller.delete);
router.get('/getorderno/get/:year/:month/:day',order_controller.getOrderNo)

module.exports = router;


text:
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.Sqlite;
using NStore.BaseSqlPersistence;
using NStore.Core.Logging;

namespace NStore.Persistence.Sqlite
{
    public class SqlitePersistenceOptions : BaseSqlPersistenceOptions
    {
        public SqlitePersistenceOptions(INStoreLoggerFactory loggerFactory) : base(loggerFactory)
        {
        }

        protected virtual string GetCreateTableSql()
        {
            return $@"CREATE TABLE [{StreamsTableName}](
                [Position] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                [PartitionId] NVARCHAR(255) NOT NULL,
                [Index] BIGINT NOT NULL,
                [OperationId] NVARCHAR(255) NOT NULL,
                [SerializerInfo] NVARCHAR(255) NOT NULL,
                [Payload] BLOB
            );

            CREATE UNIQUE INDEX IX_{StreamsTableName}_OPID on {StreamsTableName} (PartitionId, OperationId);
            CREATE UNIQUE INDEX IX_{StreamsTableName}_IDX on {StreamsTableName} (PartitionId, [Index]);
";
        }

        public override string GetInsertChunkSql()
        {
            return $@"INSERT INTO [{StreamsTableName}]
                      ([PartitionId], [Index], [Payload], [OperationId], [SerializerInfo])
                      VALUES (@PartitionId, @Index, @Payload, @OperationId, @SerializerInfo);

                      SELECT last_insert_rowid();
";
        }

        public override string GetSelectChunkByStreamAndOperation()
        {
            return $@"SELECT [Position], [PartitionId], [Index], [Payload], [OperationId], [SerializerInfo]
                      FROM [{StreamsTableName}]
                      WHERE [PartitionId] = @PartitionId AND [OperationId] = @OperationId";
        }

        public override string GetSelectAllChunksByOperationSql()
        {
            return $@"SELECT [Position], [PartitionId], [Index], [Payload], [OperationId], [SerializerInfo]
                      FROM [{StreamsTableName}]
                      WHERE [OperationId] = @OperationId";
        }

        public override string GetDeleteStreamChunksSql()
        {
            return $@"DELETE FROM [{StreamsTableName}] WHERE
                          [PartitionId] = @PartitionId
                      AND [Index] BETWEEN @fromLowerIndexInclusive AND @toUpperIndexInclusive";
        }

        public override string GetSelectLastChunkSql()
        {
            return $@"SELECT
                        [Position], [PartitionId], [Index], [Payload], [OperationId], [SerializerInfo]
                      FROM
                        [{StreamsTableName}]
                      WHERE
                          [PartitionId] = @PartitionId
                      AND [Index] <= @toUpperIndexInclusive
                      ORDER BY
                          [Position] DESC
                      LIMIT 1";
        }

        public override string GetCreateTableIfMissingSql()
        {
            return GetCreateTableSql();
        }

        public override string GetReadAllChunksSql(int limit)
        {
            return $@"SELECT
                        [Position], [PartitionId], [Index], [Payload], [OperationId], [SerializerInfo]
                      FROM
                        [{StreamsTableName}]
                      WHERE
                          [Position] >= @fromPositionInclusive
                      ORDER BY
                          [Position] LIMIT {limit}";
        }

        public override string GetRangeSelectChunksSql(long upperIndexInclusive, long lowerIndexInclusive, int limit, bool descending)
        {
            var sb = new StringBuilder("SELECT ");
            sb.Append("[Position], [PartitionId], [Index], [Payload], [OperationId], [SerializerInfo] ");
            sb.Append($"FROM {StreamsTableName} ");
            sb.Append("WHERE [PartitionId] = @PartitionId ");

            if (lowerIndexInclusive > 0 && lowerIndexInclusive != Int64.MinValue)
            {
                sb.Append("AND [Index] >= @lowerIndexInclusive ");
            }

            if (upperIndexInclusive > 0 && upperIndexInclusive != Int64.MaxValue)
            {
                sb.Append("AND [Index] <= @upperIndexInclusive ");
            }

            sb.Append(descending ? "ORDER BY [Index] DESC" : "ORDER BY [Index]");

            if (limit > 0 && limit != int.MaxValue)
            {
                sb.Append($"LIMIT {limit} ");
            }

            return sb.ToString();
        }

        public override async Task<AbstractSqlContext> GetContextAsync(CancellationToken cancellationToken)
        {
            var connection =  new SqliteConnection(ConnectionString);
            try
            {
                await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
            }
            catch (Exception )
            {
                connection.Dispose();
                throw;
            }
            return new SqliteContext(connection, true);
        }

        public override string GetSelectLastPositionSql()
        {
            return $@"SELECT
                        [Position]
                      FROM
                        [{StreamsTableName}]
                      ORDER BY
                          [Position] DESC
                      LIMIT 1";
        }
    }
}


text:
package com.avanza.astrix.versioning.core;

import java.util.List;

class ObjectSerializerFactoryImpl implements ObjectSerializerFactory {

	private List<ObjectSerializerFactoryPlugin> objectSerializerFactoryPlugins;

	public ObjectSerializerFactoryImpl(List<ObjectSerializerFactoryPlugin> versioningPlugins) {
		this.objectSerializerFactoryPlugins = versioningPlugins;
	}

	@Override
	public AstrixObjectSerializer create(ObjectSerializerDefinition serializerDefinition) {
		if (serializerDefinition.isVersioned()) {
			return getObjectSerializerFactoryPlugin(serializerDefinition).create(serializerDefinition);
		}
		return new AstrixObjectSerializer.NoVersioningSupport();
	}

	private ObjectSerializerFactoryPlugin getObjectSerializerFactoryPlugin(
			ObjectSerializerDefinition serializerDefinition) {
		for (ObjectSerializerFactoryPlugin plugin : objectSerializerFactoryPlugins) {
			if (plugin.getConfigurerType().isAssignableFrom(serializerDefinition.getObjectSerializerConfigurerClass())) {
				return plugin;
			}
		}
		throw new IllegalStateException("Cant find ObjectSerializerFactoryPlugin to handle AstrixObjectSerializerConfigurer class: " + serializerDefinition.getObjectSerializerConfigurerClass());
	}

}


text:
class LibraryGroupsController < ApplicationController
  before_action :set_library_group, only: [:show, :edit, :update]
  before_action :check_policy, only: [:index]

  # GET /library_groups
  # GET /library_groups.json
  def index
    @library_groups = LibraryGroup.all

    respond_to do |format|
      format.html # index.html.erb
    end
  end

  # GET /library_groups/1
  # GET /library_groups/1.json
  def show
    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @library_group }
    end
  end

  # GET /library_groups/1/edit
  def edit
    @countries = Country.order(:position)
  end

  # PUT /library_groups/1
  # PUT /library_groups/1.json
  def update
    respond_to do |format|
      if @library_group.update(library_group_params)
        if @library_group.delete_header_logo == '1'
          @library_group.header_logo.destroy
        end

        format.html { redirect_to @library_group, notice: t('controller.successfully_updated', model: t('activerecord.models.library_group')) }
        format.json { head :no_content }
      else
        @countries = Country.order(:position)
        format.html { render action: "edit" }
        format.json { render json: @library_group.errors, status: :unprocessable_entity }
      end
    end
  end

  private

  def set_library_group
    @library_group = LibraryGroup.find(params[:id])
    if request.format == :download
      authorize @library_group, :show_logo?
    else
      authorize @library_group
    end
  end

  def check_policy
    authorize LibraryGroup
  end

  def library_group_params
    params.require(:library_group).permit(
      :name, :display_name, :short_name, :my_networks,
      :login_banner, :note, :country_id, :admin_networks, :url,
      :max_number_of_results, :footer_banner, :email,
      :book_jacket_source, :screenshot_generator, :erms_url,
      :header_logo, :delete_header_logo,
      :allow_bookmark_external_url, # EnjuBookmark
      {
        colors_attributes: [:id, :property, :code]
      },
      {
        user_attributes: [:email]
      },
      *LibraryGroup.globalize_attribute_names
    )
  end
end


text:
using std::cout;
using std::endl;

double invert_sign(double input)
{
     return -1*input;
}

double saturate(double input, const double &min, const double &max)
{
     if (min > max) {
          cout << "saturate(): Invalid Min / Max Combo" << endl;
          return 0;
     } else if (input < min) {
          input = min;
     } else if(input > max) {
          input = max;
     }
     return input;
}

double normalize(double input, const double &in_min, const double &in_max,
                 const double &out_min, const double &out_max)
{
     input = saturate(input, in_min, in_max);

     if (in_min >= in_max || out_min >= out_max) {
          cout << "normalize(): Invalid Min / Max Combo" << endl;
          return 0;
     }

     double ratio = input / (in_max - in_min);
     return ratio * (out_max - out_min);

     return input;
}

double norm_degrees(double input)
{
     if (input < 0) {
          input += 360;
     } else if(input >= 360) {
          input -= 360;
     }
     return input;
}


text:
module Slugforge
  module Helper
    module Config
      def self.included(base)
        base.class_option :'aws-access-key-id', :type => :string, :aliases => '-I', :group => :config,
          :desc => 'The AWS Access ID to use for hosts and buckets, unless overridden'
        base.class_option :'aws-secret-key', :type => :string, :aliases => '-S', :group => :config,
          :desc => 'The AWS Secret Key to use for hosts and buckets, unless overridden'
        base.class_option :'aws-region', :type => :string, :group => :config,
          :desc => 'The AWS region to use for EC2 instances and buckets'
        base.class_option :'slug-bucket', :type => :string, :group => :config,
          :desc => 'The S3 bucket to store the slugs and tags in'
        base.class_option :'aws-session-token', :type => :string, :group => :config,
          :desc => 'The AWS Session Token to use for hosts and buckets'

        base.class_option :project, :type => :string, :aliases => '-P', :group => :config,
          :desc => 'The name of the project as it exists in Slugforge. See the Project Naming section in the main help.'

        base.class_option :'ssh-username', :type => :string, :aliases => '-u', :group => :config,
          :desc => 'The account used to log in to the host (requires sudo privileges)'

        base.class_option :'disable-slugins', :type => :boolean, :group => :config,
          :desc => 'Disable slugin loading'

        base.class_option :verbose, :type => :boolean, :aliases => '-V', :group => :runtime,
          :desc => 'Display verbose output'
        base.class_option :json, :type => :boolean, :aliases => '-j', :group => :runtime,
          :desc => 'Display JSON output'

        # Options intended for slugforge developers
        base.class_option :test, :type => :boolean, :group => :runtime, :hide => true,
          :desc => 'Test mode. Behaves like --pretend but triggers notifications and side effects as if a real action was taken.'
      end
    end
  end
end


text:
import templatesReducer, {defaultState} from 'src/templates/reducers'
import {setTemplateSummary} from 'src/templates/actions'

describe('templatesReducer', () => {
  describe('setTemplateSummary', () => {
    it('can update the name of a template', () => {
      const initialState = defaultState()
      const initialTemplate = {
        id: 'abc',
        labels: [],
        meta: {name: 'Belcalis', version: '1'},
      }
      initialState.items.push(initialTemplate)

      const actual = templatesReducer(
        initialState,
        setTemplateSummary(initialTemplate.id, {
          ...initialTemplate,
          meta: {...initialTemplate.meta, name: 'Cardi B'},
        })
      )

      const expected = {
        ...defaultState(),
        items: [
          {
            ...initialTemplate,
            meta: {...initialTemplate.meta, name: 'Cardi B'},
          },
        ],
      }

      expect(actual).toEqual(expected)
    })
  })
})


text:
<#
.Synopsis
 This script will gather information about the Mellanox driver from the host.

.Description
 This script will use the MLNXProvider module to collect information about the
 Mellanox driver installed on the host and will output it to HostMellanoxInfo.log

 .Parameter vmName
     Name of the test VM.

 .Parameter hvServer
     Name of the Hyper-V server hosting the VM.

.Parameter testParams
 Test data for this test case

.Example
 setupScripts\SR-IOV_GetMLNXInfo.ps1 -vmName vmNmae -hvServer hvserver -testParams "rootDir=C:\myFolder\"
#>

param ([String] $vmName, [String] $hvServer, [string] $testParams)

$params = $testParams.Split(";")
foreach ($p in $params) {
    $fields = $p.Split("=")
    if ($fields[0].Trim() -eq "rootDir") {
        $rootDir = $fields[1].Trim()
    }
    if ($fields[0].Trim() -eq "TestLogDir") {
        $logPath = $fields[1].Trim()
    }
}

# Change directory
cd $rootDir

$summaryLog = $logPath + "\" + "HostMellanoxInfo.log"
if (Test-Path $summaryLog) {
    del $summaryLog
}

# Work around "Kerberos Double Hop" issue
# Use fresh identity (if defined in environment) instead of delegation
if($env:HostUser -and $env:HostPassword){
    $SecurePass = $env:HostPassword| ConvertTo-SecureString -AsPlainText -Force
    $cred = New-Object System.Management.Automation.PSCredential -ArgumentList $env:HostUser, $SecurePass
    $remoteSession = New-PSSession -ComputerName $hvServer -Credential $cred
}
else{
    $remoteSession = New-PSSession -ComputerName $hvServer
}

$checkModule = Get-Module -ListAvailable -PSSession $remoteSession | Select-String -Pattern MLNXProvider -quiet
if ($checkModule) {
    Import-Module MLNXProvider -PSSession $remoteSession
} else {
    Write-Output "Error: No Mellanox module found."
    Remove-PSSession $remoteSession -ErrorAction SilentlyContinue
    Exit 0
}

# After import-module, the imported commands run implicitly in the current session
$driverVersion = (Get-MLNXPCIDevice).DriverVersion
if ($? -ne "True") {
    $driverVersion = "Error: Cannot get driver version."
}

$firmwareVersion = (Get-MlnxFirmwareIdentity).VersionString
if ($? -ne "True") {
    $firmwareVersion = "Error: Cannot get firmware version."
}

$linkSpeed = (Get-MlnxNetAdapter | where {$_.Status -eq 'IfOperStatusUp'}).Speed
if ($? -ne "True") {
    $linkSpeed = "Error: Cannot get link speed."
}

$port1NumVFS = (Get-MlnxPCIDeviceSriovSetting).SriovPort1NumVFs
if ($? -ne "True") {
    $port1NumVFS = "Error: Cannot get SriovPort1NumVFs."
}

Write-Output "Driver Version: $driverVersion" | Tee-Object -Append -file $summaryLog
Write-Output "Firmware Version: $firmwareVersion" | Tee-Object -Append -file $summaryLog
Write-Output "Link Speed: $linkSpeed" | Tee-Object -Append -file $summaryLog
Write-Output "SriovPort1NumVFs: $port1NumVFS" | Tee-Object -Append -file $summaryLog

# If no VM has SR-IOV enabled, the following will return NULL
Get-NetAdapterSriovVf | Select-Object name,FunctionID,VPortID,VmFriendlyName | Format-Table | Tee-Object -Append -file $summaryLog
if ($? -ne "True") {
    $vmFriendlyName = "Error: Cannot get VM Friendly name."
}

Remove-PSSession $remoteSession -ErrorAction SilentlyContinue
return $true


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecidea aglaeiza Nyl.

### Remarks
null


text:
package org.ihtsdo.otf.query.integration.tests.rest;

import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.ws.rs.core.Application;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.ihtsdo.otf.jaxb.chronicle.api.SimpleViewCoordinate;
import org.ihtsdo.otf.jaxb.query.ClauseSemantic;
import org.ihtsdo.otf.jaxb.query.ForCollection;
import org.ihtsdo.otf.jaxb.query.ForCollectionContents;
import org.ihtsdo.otf.jaxb.query.LetMap;
import org.ihtsdo.otf.jaxb.query.ReturnTypes;
import org.ihtsdo.otf.jaxb.query.Where;
import org.ihtsdo.otf.jaxb.query.WhereClause;
import org.ihtsdo.otf.query.implementation.JaxbForQuery;
import org.ihtsdo.otf.query.rest.server.QueryResource;
import org.ihtsdo.otf.tcc.api.metadata.binding.Snomed;
import org.ihtsdo.otf.tcc.junit.BdbTestRunner;
import org.ihtsdo.otf.tcc.junit.BdbTestRunnerConfig;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
 *
 * @author dylangrald
 */
@RunWith(BdbTestRunner.class)
@BdbTestRunnerConfig()
public class RestQueryXMLTest extends JerseyTest {

    public RestQueryXMLTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    @Override
    public void setUp() {
    }

    @After
    @Override
    public void tearDown() {
    }

    @Override
    protected Application configure() {
        return new ResourceConfig(QueryResource.class);
//        return new WebAppDescriptor.Builder()
//            	.initParam(WebComponent.RESOURCE_CONFIG_CLASS,
//                      ClassNamesResourceConfig.class.getName())
//                .initParam(
//                      ClassNamesResourceConfig.PROPERTY_CLASSNAMES,
//                      TodoResource.class.getName() + ";"
//                              + MockTodoServiceProvider.class.getName() + ";"
//                              + NotFoundMapper.class.getName()).build();
    }

    @Ignore
    @Test
    public void testRelRestriction() throws JAXBException, UnsupportedEncodingException {
        ForCollection collection = new ForCollection();
        collection.setForCollectionString(ForCollectionContents.CONCEPT.name());

        LetMap letMap = new LetMap();
        LetMap.Map.Entry entry = new LetMap.Map.Entry();
        entry.setKey("acceleration");
        entry.setValue(Snomed.ACCELERATION);
        LetMap.Map.Entry entry2 = new LetMap.Map.Entry();
        entry2.setKey("is a");
        entry2.setValue(Snomed.IS_A);
        LetMap.Map.Entry entry3 = new LetMap.Map.Entry();
        entry3.setKey("motion");
        entry3.setValue(Snomed.MOTION);
        LetMap.Map.Entry entry4 = new LetMap.Map.Entry();
        entry4.setKey("false");
        entry4.setValue(false);

        LetMap.Map map = new LetMap.Map();
        map.getEntry().add(entry);
        map.getEntry().add(entry2);
        map.getEntry().add(entry3);
        map.getEntry().add(entry4);
        letMap.setMap(map);

        // Set the where clause
        Where where = new Where();
        WhereClause relRestriction = new WhereClause();
        relRestriction.setSemanticString(ClauseSemantic.REL_RESTRICTION.name());
        relRestriction.getLetKeys().add("acceleration");
        relRestriction.getLetKeys().add("is a");
        relRestriction.getLetKeys().add("motion");
        relRestriction.getLetKeys().add("false");
        where.setRootClause(relRestriction);

        //String viewpointXml = URLEncoder.encode(getXmlString(viewpoint), "UTF-8");
        //String forObjectString = URLEncoder.encode(getXmlString(forObject), "UTF-8");
        String letMapString = URLEncoder.encode(getXmlString(letMap), "UTF-8");
        String whereString = URLEncoder.encode(getXmlString(where), "UTF-8");
        //String returnTypeString = URLEncoder.encode(getXmlString(returnType), "UTF-8");

        StringBuilder bi = new StringBuilder();
        bi.append("VIEWPOINT=").append("&FOR=").append("&LET=").append(letMapString).append("&WHERE=").append(whereString).append("&RETURN=").append("NIDS");

        System.out.println("Query URL: ");
        System.out.println(bi.toString());
    }

    private static String getXmlString(Object obj) throws JAXBException {
        JAXBContext ctx = JaxbForQuery.get();
        if (obj instanceof SimpleViewCoordinate) {
            org.ihtsdo.otf.jaxb.chronicle.api.ObjectFactory factory = new org.ihtsdo.otf.jaxb.chronicle.api.ObjectFactory();
            obj = factory.createSimpleViewCoordinate((SimpleViewCoordinate) obj);
        } else if (obj instanceof ForCollection) {
            org.ihtsdo.otf.jaxb.query.ObjectFactory factory = new org.ihtsdo.otf.jaxb.query.ObjectFactory();
            obj = factory.createForCollection((ForCollection) obj);
        } else if (obj instanceof org.ihtsdo.otf.jaxb.query.LetMap) {
            org.ihtsdo.otf.jaxb.query.ObjectFactory factory = new org.ihtsdo.otf.jaxb.query.ObjectFactory();
            obj = factory.createLetMap((org.ihtsdo.otf.jaxb.query.LetMap) obj);
        } else if (obj instanceof Where) {
            org.ihtsdo.otf.jaxb.query.ObjectFactory factory = new org.ihtsdo.otf.jaxb.query.ObjectFactory();
            obj = factory.createWhere((Where) obj);
        } else if (obj instanceof ReturnTypes) {
            org.ihtsdo.otf.jaxb.query.ObjectFactory factory = new org.ihtsdo.otf.jaxb.query.ObjectFactory();
            obj = factory.createReturnTypes((ReturnTypes) obj);
        }
        StringWriter writer = new StringWriter();
        ctx.createMarshaller().marshal(obj, writer);
        return writer.toString();
    }

}


text:
package com.hujiang.library.aspect;

/**
 * class description here
 *
 * @author simon
 * @version 1.0.0
 * @since 2016-03-04
 */
public class FragmentAspect {
}


text:
package org.apache.commons.io.input;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URL;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ExtendedClassUtils;
import org.apache.commons.test.AbstractTestSupport;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

/**
 * @author Lyor G.
 * @since Sep 24, 2013 8:18:54 AM
 */
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ByteArrayAccumulatingInputStreamTest extends AbstractTestSupport {
    public ByteArrayAccumulatingInputStreamTest() {
        super();
    }

    @Test
    public void testStreamCorrectness() throws IOException {
        URL url=ExtendedClassUtils.getClassBytesURL(getClass());
        assertNotNull("Cannot locate class bytes", url);

        byte[]  expected=IOUtils.toByteArray(url);
        ByteArrayAccumulatingInputStream    input=
                new ByteArrayAccumulatingInputStream(new ByteArrayInputStream(expected), expected.length);
        try {
            byte[]  actual=IOUtils.toByteArray(input);
            assertArrayEquals("Mismatched re-read data", expected, actual);
        } finally {
            input.close();
        }

        byte[]  actual=input.toByteArray();
        assertArrayEquals("Mismatched accumulated data", expected, actual);
    }

    @Test
    public void testStreamReset() throws IOException {
        URL url=ExtendedClassUtils.getClassBytesURL(getClass());
        assertNotNull("Cannot locate class bytes", url);

        byte[]  expected=IOUtils.toByteArray(url);
        ByteArrayAccumulatingInputStream    input=
                new ByteArrayAccumulatingInputStream(new ByteArrayInputStream(expected), expected.length);
        try {
            byte[]  readBuf=new byte[expected.length / 8];
            for (int index=0; index < Byte.SIZE; index++) {
                input.read(readBuf);
                input.reset();
            }

            byte[]  actual=IOUtils.toByteArray(input);
            assertArrayEquals("Mismatched re-read data", expected, actual);
        } finally {
            input.close();
        }

        byte[]  actual=input.toByteArray();
        assertArrayEquals("Mismatched accumulated data", expected, actual);
    }

    @Test
    public void testStreamSkip() throws IOException {
        URL url=ExtendedClassUtils.getClassBytesURL(getClass());
        assertNotNull("Cannot locate class bytes", url);

        byte[]  expected=new byte[2 * Byte.MAX_VALUE];
        byte[]  bytes=IOUtils.toByteArray(url);
        System.arraycopy(bytes, 0, expected, 0, Byte.MAX_VALUE);
        System.arraycopy(bytes, bytes.length - Byte.MAX_VALUE, expected, Byte.MAX_VALUE, Byte.MAX_VALUE);
        ByteArrayAccumulatingInputStream    input=
                new ByteArrayAccumulatingInputStream(new ByteArrayInputStream(bytes), expected.length);
        try {
            byte[]  actual=new byte[expected.length];
            assertEquals("Mismatched start bytes read length", actual.length / 2, input.read(actual, 0, actual.length / 2));

            long    toSkip=bytes.length - actual.length, skipped=input.skip(toSkip);
            assertEquals("Mismatched skipped length", toSkip, skipped);
            assertEquals("Mismatched end bytes read length", actual.length / 2, input.read(actual, actual.length / 2, actual.length / 2));
            assertArrayEquals("Mismatched re-read data", expected, actual);
            assertEquals("Unexpected data beyond EOF", (-1), input.read(actual));
        } finally {
            input.close();
        }

        byte[]  actual=input.toByteArray();
        assertArrayEquals("Mismatched accumulated data", expected, actual);
    }
}