text:
from inspect import isclass
from functools import partial

from .router import Router

if __debug__:
	import warnings
	from collections import deque

log = __import__('logging').getLogger(__name__)

class RouteDispatch(object):
	def __call__(self, context, obj, path):
		if __debug__:
			if not isinstance(path, deque):
				warnings.warn(
						"Your code uses auto-casting of paths to a deque; "
						"this will explode gloriously if run in a production environment.",
						RuntimeWarning, stacklevel=1
					)

				if isinstance(path, str):
					path = deque(path.split('/')[1 if not path or path.startswith('/') else 0:])
				else:
					path = deque(path)

			log.debug("Preparing route dispatch.", extra=dict(
					dispatcher = repr(self),
					context = repr(context),
					obj = repr(obj),
					path = list(path)
				))

		router = Router.from_object(obj)
		processed, target, kwargs = router.route(path)

		if isclass(obj):
			obj = obj() if context is None else obj(context)
			yield None, obj, False  # Let everyone know we instantiated something.
			target = partial(target, obj, **kwargs)
		else:
			target = partial(target, **kwargs)

		yield processed, target, True


text:
package net.canang.grapevine.client.widget;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.FlexTable;
import net.canang.grapevine.client.data.DataSource;
import net.canang.grapevine.client.data.ScoopDataSource;
import net.canang.grapevine.client.model.ScoopModel;

import java.util.List;

/**
 * @author rafizan.baharum
 * @since 10/25/13
 */
@SuppressWarnings({"ALL"})
public class ScoopTable extends FlexTable {

    private DataSource<ScoopModel> source;

    private int selectedRow;

    public ScoopTable() {
        setText(0, 0, "ID");
        setText(0, 1, "Name");
        setText(0, 2, "Description");
        setText(0, 3, "Before");
        setText(0, 4, "After");
        setText(0, 5, "Reporter");
        setText(0, 6, "Place");
        setCellPadding(6);

        getRowFormatter().addStyleName(0, "listHeader");
        addStyleName("list");
        getCellFormatter().addStyleName(0, 1, "listTextColumn");
        getCellFormatter().addStyleName(0, 2, "listTextColumn");
        getCellFormatter().addStyleName(0, 3, "listNumericColumn");
        getCellFormatter().addStyleName(0, 4, "listNumericColumn");

        addClickHandler(new ClickHandler() {

            public void onClick(ClickEvent event) {
                Cell td = getCellForEvent(event);
                if (td == null) return;

                boolean sameRow = selectedRow == td.getRowIndex();
                changeRow(selectedRow, false);
                selectedRow = td.getRowIndex();
                changeRow(selectedRow, !sameRow);
                if (sameRow) selectedRow = 0;
            }
        });
    }

    public void fillTable(List<ScoopModel> scoops) {
        source = new ScoopDataSource(scoops);
        updateAll();
    }

    private void updateAll() {
        for (int i = this.getRowCount() - 1; i > 0; i--) {
            this.removeRow(1);
        }

        int rows = source.getRowCount();
        for (int i = 0; i < rows; i++) {
            ScoopModel m = source.getRow(i);
            insertRow(i + 1, m);
        }
        this.selectedRow = 0;
    }

    private void insertRow(final int row, ScoopModel m) {
        setText(row, 0, m.getId().toString());
        setText(row, 1, m.getTitle());
        setText(row, 2, m.getDescription());
        setText(row, 3, m.getPriceBefore().toEngineeringString());
        setText(row, 4, m.getPriceAfter().toEngineeringString());
        setText(row, 5, m.getReporter().getName());
        setText(row, 6, m.getPlace().getName());
        getCellFormatter().addStyleName(row, 3, "listNumericColumn");
        getCellFormatter().addStyleName(row, 4, "listNumericColumn");
    }

    /**
     * Marca a seleção da linha na tabela.
     *
     * @param row
     * @param selected
     */
    private void changeRow(int row, boolean selected) {
        if (row > 0) {
            Element tr = getRowFormatter().getElement(row);
            if (tr != null)
                DOM.setStyleAttribute(tr, "backgroundColor", selected ? "#ffce00" : "#ffffff");
        }
    }

    public ScoopModel getScoopModelSelected() {
        if (source == null || selectedRow == 0)
            return null;

        return source.getRow(selectedRow - 1);
    }

    public void add(ScoopModel m) {
        source.add(m);
        updateAll();
    }

    public void remove(ScoopModel m) {
        source.remove(m);
        updateAll();
    }
}

redpajama_set_name: RedPajamaGithub


text:
Helm uses a packaging format called _charts_. A chart is a collection of files
that describe a related set of Kubernetes resources. A single chart
might be used to deploy something simple, like a memcached pod, or
something complex, like a full web app stack with HTTP servers,
databases, caches, and so on.

Charts are created as files laid out in a particular directory tree,
then they can be packaged into versioned archives to be deployed.

This document explains the chart format, and provides basic guidance for
building charts with Helm.

## The Chart File Structure

A chart is organized as a collection of files inside of a directory. The
directory name is the name of the chart (without versioning information). Thus,
a chart describing Wordpress would be stored in the `wordpress/` directory.

Inside of this directory, Helm will expect a structure that matches this:

```
wordpress/
  Chart.yaml          # A YAML file containing information about the chart
  LICENSE             # OPTIONAL: A plain text file containing the license for the chart
  README.md           # OPTIONAL: A human-readable README file
  values.yaml         # The default configuration values for this chart
  charts/             # OPTIONAL: A directory containing any charts upon which this chart depends.
  templates/          # OPTIONAL: A directory of templates that, when combined with values,
                      # will generate valid Kubernetes manifest files.
  templates/NOTES.txt # OPTIONAL: A plain text file containing short usage notes
```

Helm reserves use of the `charts/` and `templates/` directories, and of
the listed file names. Other files will be left as they are.

## The Chart.yaml File

The `Chart.yaml` file is required for a chart. It contains the following fields:

```yaml
name: The name of the chart (required)
version: A SemVer 2 version (required)
description: A single-sentence description of this project (optional)
keywords:
  - A list of keywords about this project (optional)
home: The URL of this project's home page (optional)
sources:
  - A list of URLs to source code for this project (optional)
maintainers: # (optional)
  - name: The maintainer's name (required for each maintainer)
    email: The maintainer's email (optional for each maintainer)
engine: gotpl # The name of the template engine (optional, defaults to gotpl)
icon: A URL to an SVG or PNG image to be used as an icon (optional).
```

If you are familiar with the `Chart.yaml` file format for Helm Classic, you will
notice that fields specifying dependencies have been removed. That is because
the new Chart format expresses dependencies using the `charts/` directory.

Other fields will be silently ignored.

### Charts and Versioning

Every chart must have a version number. A version must follow the
[SemVer 2](http://semver.org/) standard. Unlike Helm Classic, Kubernetes
Helm uses version numbers as release markers. Packages in repositories
are identified by name plus version.

For example, an `nginx` chart whose version field is set to `version:
1.2.3` will be named:

```
nginx-1.2.3.tgz
```

More complex SemVer 2 names are also supported, such as
`version: 1.2.3-alpha.1+ef365`. But non-SemVer names are explicitly
disallowed by the system.

**NOTE:** Whereas Helm Classic and Deployment Manager were both
very GitHub oriented when it came to charts, Kubernetes Helm does not
rely upon or require GitHub or even Git. Consequently, it does not use
Git SHAs for versioning at all.

The `version` field inside of the `Chart.yaml` is used by many of the
Helm tools, including the CLI and the Tiller server. When generating a
package, the `helm package` command will use the version that it finds
in the `Chart.yaml` as a token in the package name. The system assumes
that the version number in the chart package name matches the version number in
the `Chart.yaml`. Failure to meet this assumption will cause an error.

## Chart LICENSE, README and NOTES

Charts can also contain files that describe the installation, configuration, usage and license of a
chart. A README for a chart should be formatted in Markdown (README.md), and should generally
contain:

- A description of the application or service the chart provides
- Any prerequisites or requirements to run the chart
- Descriptions of options in `values.yaml` and default values
- Any other information that may be relevant to the installation or configuration of the chart

The chart can also contain a short plain text `templates/NOTES.txt` file that will be printed out
after installation, and when viewing the status of a release. This file is evaluated as a
[template](#templates-and-values), and can be used to display usage notes, next steps, or any other
information relevant to a release of the chart. For example, instructions could be provided for
connecting to a database, or accessing a web UI. Since this file is printed to STDOUT when running
`helm install` or `helm status`, it is recommended to keep the content brief and point to the README
for greater detail.

## Chart Dependencies

In Helm, one chart may depend on any number of other charts. These
dependencies are expressed explicitly by copying the dependency charts
into the `charts/` directory.

A dependency can be either a chart archive (`foo-1.2.3.tgz`) or an
unpacked chart directory. But its name cannot start with `_` or `.`.
Such files are ignored by the chart loader.

**Note:** The `dependencies:` section of the `Chart.yaml` from Helm
Classic has been completely removed.

For example, if the Wordpress chart depends on the Apache chart, the
Apache chart (of the correct version) is supplied in the Wordpress
chart's `charts/` directory:

```
wordpress:
  Chart.yaml
  requirements.yaml
  # ...
  charts/
    apache/
      Chart.yaml
      # ...
    mysql/
      Chart.yaml
      # ...
```

The example above shows how the Wordpress chart expresses its dependency
on Apache and MySQL by including those charts inside of its `charts/`
directory.

**TIP:** _To drop a dependency into your `charts/` directory, use the
`helm fetch` command or use a `requirements.yaml` file_

### Managing Dependencies with `requirements.yaml`

While Helm will allow you to manually manage your dependencies, the
preferred method of declaring dependencies is by using a
`requirements.yaml` file inside of your chart.

A `requirements.yaml` file is a simple file for listing your
dependencies.

```yaml
dependencies:
  - name: apache
    version: 1.2.3
    repository: http://example.com/charts
  - name: mysql
    version: 3.2.1
    repository: http://another.example.com/charts
```

- The `name` field is the name of the chart you want.
- The `version` field is the version of the chart you want.
- The `repository` field is the full URL to the chart repository. Note
  that you must also use `helm repo add` to add that repo locally.

Once you have a dependencies file, you can run `helm dependency update`
and it will use your dependency file to download all of the specified
charts into your `charts/` directory for you.

```console
$ helm dep up foochart
Hang tight while we grab the latest from your chart repositories...
...Successfully got an update from the "local" chart repository
...Successfully got an update from the "stable" chart repository
...Successfully got an update from the "example" chart repository
...Successfully got an update from the "another" chart repository
Update Complete. Happy Helming!
Saving 2 charts
Downloading apache from repo http://example.com/charts
Downloading mysql from repo http://another.example.com/charts
```

When `helm dependency update` retrieves charts, it will store them as
chart archives in the `charts/` directory. So for the example above, one
would expect to see the following files in the charts directory:

```
charts/
  apache-1.2.3.tgz
  mysql-3.2.1.tgz
```

Managing charts with `requirements.yaml` is a good way to easily keep
charts updated, and also share requirements information throughout a
team.

## Templates and Values

Helm Chart templates are written in the
[Go template language](https://golang.org/pkg/text/template/), with the
addition of 50 or so add-on template
functions [from the Sprig library](https://github.com/Masterminds/sprig) and a
few other [specialized functions](charts_tips_and_tricks.md).

All template files are stored in a chart's `templates/` folder. When
Helm renders the charts, it will pass every file in that directory
through the template engine.

Values for the templates are supplied two ways:

  - Chart developers may supply a file called `values.yaml` inside of a
    chart. This file can contain default values.
  - Chart users may supply a YAML file that contains values. This can be
    provided on the command line with `helm install`.

When a user supplies custom values, these values will override the
values in the chart's `values.yaml` file.

### Template Files

Template files follow the standard conventions for writing Go templates
(see [the text/template Go package documentation](https://golang.org/pkg/text/template/)
for details).
An example template file might look something like this:

```yaml
apiVersion: v1
kind: ReplicationController
metadata:
  name: deis-database
  namespace: deis
  labels:
    heritage: deis
spec:
  replicas: 1
  selector:
    app: deis-database
  template:
    metadata:
      labels:
        app: deis-database
    spec:
      serviceAccount: deis-database
      containers:
        - name: deis-database
          image: {{.Values.imageRegistry}}/postgres:{{.Values.dockerTag}}
          imagePullPolicy: {{.Values.pullPolicy}}
          ports:
            - containerPort: 5432
          env:
            - name: DATABASE_STORAGE
              value: {{default "minio" .Values.storage}}
```

The above example, based loosely on [https://github.com/deis/charts](https://github.com/deis/charts), is a template for a Kubernetes replication controller.
It can use the following four template values (usually defined in a
`values.yaml` file):

- `imageRegistry`: The source registry for the Docker image.
- `dockerTag`: The tag for the docker image.
- `pullPolicy`: The Kubernetes pull policy.
- `storage`: The storage backend, whose default is set to `"minio"`

All of these values are defined by the template author. Helm does not
require or dictate parameters.

To see many working charts, check out the [Kubernetes Charts
project](https://github.com/kubernetes/charts)

### Predefined Values

Values that are supplied via a `values.yaml` file (or via the `--set`
flag) are accessible from the `.Values` object in a template. But there
are other pre-defined pieces of data you can access in your templates.

The following values are pre-defined, are available to every template, and
cannot be overridden. As with all values, the names are _case
sensitive_.

- `Release.Name`: The name of the release (not the chart)
- `Release.Time`: The time the chart release was last updated. This will
  match the `Last Released` time on a Release object.
- `Release.Namespace`: The namespace the chart was released to.
- `Release.Service`: The service that conducted the release. Usually
  this is `Tiller`.
- `Release.IsUpgrade`: This is set to true if the current operation is an upgrade or rollback.
- `Release.IsInstall`: This is set to true if the current operation is an
  install.
- `Release.Revision`: The revision number. It begins at 1, and increments with
  each `helm upgrade`.
- `Chart`: The contents of the `Chart.yaml`. Thus, the chart version is
  obtainable as `Chart.Version` and the maintainers are in
  `Chart.Maintainers`.
- `Files`: A map-like object containing all non-special files in the chart. This
  will not give you access to templates, but will give you access to additional
  files that are present. Files can be accessed using `{{index .Files "file.name"}}`
  or using the `{{.Files.Get name}}` or `{{.Files.GetString name}}` functions. You can
  also access the contents of the file as `[]byte` using `{{.Files.GetBytes}}`
- `Capabilities`: A map-like object that contains information about the versions
  of Kubernetes (`{{.Capabilities.KubeVersion}}`, Tiller
  (`{{.Capabilities.TillerVersion}}`, and the supported Kubernetes API versions
  (`{{.Capabilities.APIVersions.Has "batch/v1"`)

**NOTE:** Any unknown Chart.yaml fields will be dropped. They will not
be accessible inside of the `Chart` object. Thus, Chart.yaml cannot be
used to pass arbitrarily structured data into the template. The values
file can be used for that, though.

### Values files

Considering the template in the previous section, a `values.yaml` file
that supplies the necessary values would look like this:

```yaml
imageRegistry: "quay.io/deis"
dockerTag: "latest"
pullPolicy: "alwaysPull"
storage: "s3"
```

A values file is formatted in YAML. A chart may include a default
`values.yaml` file. The Helm install command allows a user to override
values by supplying additional YAML values:

```console
$ helm install --values=myvals.yaml wordpress
```

When values are passed in this way, they will be merged into the default
values file. For example, consider a `myvals.yaml` file that looks like
this:

```yaml
storage: "gcs"
```

When this is merged with the `values.yaml` in the chart, the resulting
generated content will be:

```yaml
imageRegistry: "quay.io/deis"
dockerTag: "latest"
pullPolicy: "alwaysPull"
storage: "gcs"
```

Note that only the last field was overridden.

**NOTE:** The default values file included inside of a chart _must_ be named
`values.yaml`. But files specified on the command line can be named
anything.

**NOTE:** If the `--set` flag is used on `helm install` or `helm upgrade`, those
values are simply converted to YAML on the client side.

Any of these values are then accessible inside of templates using the
`.Values` object:

```yaml
apiVersion: v1
kind: ReplicationController
metadata:
  name: deis-database
  namespace: deis
  labels:
    heritage: deis
spec:
  replicas: 1
  selector:
    app: deis-database
  template:
    metadata:
      labels:
        app: deis-database
    spec:
      serviceAccount: deis-database
      containers:
        - name: deis-database
          image: {{.Values.imageRegistry}}/postgres:{{.Values.dockerTag}}
          imagePullPolicy: {{.Values.pullPolicy}}
          ports:
            - containerPort: 5432
          env:
            - name: DATABASE_STORAGE
              value: {{default "minio" .Values.storage}}

```

### Scope, Dependencies, and Values

Values files can declare values for the top-level chart, as well as for
any of the charts that are included in that chart's `charts/` directory.
Or, to phrase it differently, a values file can supply values to the
chart as well as to any of its dependencies. For example, the
demonstration Wordpress chart above has both `mysql` and `apache` as
dependencies. The values file could supply values to all of these
components:

```yaml
title: "My Wordpress Site" # Sent to the Wordpress template

mysql:
  max_connections: 100 # Sent to MySQL
  password: "secret"

apache:
  port: 8080 # Passed to Apache
```

Charts at a higher level have access to all of the variables defined
beneath. So the wordpress chart can access the MySQL password as
`.Values.mysql.password`. But lower level charts cannot access things in
parent charts, so MySQL will not be able to access the `title` property. Nor,
for that matter, can it access `apache.port`.

Values are namespaced, but namespaces are pruned. So for the Wordpress
chart, it can access the MySQL password field as `.Values.mysql.password`. But
for the MySQL chart, the scope of the values has been reduced and the
namespace prefix removed, so it will see the password field simply as
`.Values.password`.

#### Global Values

As of 2.0.0-Alpha.2, Helm supports special "global" value. Consider
this modified version of the previous example:

```yaml
title: "My Wordpress Site" # Sent to the Wordpress template

global:
  app: MyWordpress

mysql:
  max_connections: 100 # Sent to MySQL
  password: "secret"

apache:
  port: 8080 # Passed to Apache
```

The above adds a `global` section with the value `app: MyWordpress`.
This value is available to _all_ charts as `.Values.global.app`.

For example, the `mysql` templates may access `app` as `{{.Values.global.app}}`, and
so can the `apache` chart. Effectively, the values file above is
regenerated like this:

```yaml
title: "My Wordpress Site" # Sent to the Wordpress template

global:
  app: MyWordpress

mysql:
  global:
    app: MyWordpress
  max_connections: 100 # Sent to MySQL
  password: "secret"

apache:
  global:
    app: MyWordpress
  port: 8080 # Passed to Apache
```

This provides a way of sharing one top-level variable with all
subcharts, which is useful for things like setting `metadata` properties
like labels.

If a subchart declares a global variable, that global will be passed
_downward_ (to the subchart's subcharts), but not _upward_ to the parent
chart. There is no way for a subchart to influence the values of the
parent chart.

_Global sections are restricted to only simple key/value pairs. They do
not support nesting._

For example, the following is **illegal** and will not work:

```yaml
global:
  foo:  # It is illegal to nest an object inside of global.
    bar: baz
```

### References

When it comes to writing templates and values files, there are several
standard references that will help you out.

- [Go templates](https://godoc.org/text/template)
- [Extra template functions](https://godoc.org/github.com/Masterminds/sprig)
- [The YAML format](http://yaml.org/spec/)

## Using Helm to Manage Charts

The `helm` tool has several commands for working with charts.

It can create a new chart for you:

```console
$ helm create mychart
Created mychart/
```

Once you have edited a chart, `helm` can package it into a chart archive
for you:

```console
$ helm package mychart
Archived mychart-0.1.-.tgz
```

You can also use `helm` to help you find issues with your chart's
formatting or information:

```console
$ helm lint mychart
No issues found
```

## Chart Repositories

A _chart repository_ is an HTTP server that houses one or more packaged
charts. While `helm` can be used to manage local chart directories, when
it comes to sharing charts, the preferred mechanism is a chart
repository.

Any HTTP server that can serve YAML files and tar files and can answer
GET requests can be used as a repository server.

Helm comes with built-in package server for developer testing (`helm
serve`). The Helm team has tested other servers, including Google Cloud
Storage with website mode enabled, and S3 with website mode enabled.

A repository is characterized primarily by the presence of a special
file called `index.yaml` that has a list of all of the packages supplied
by the repository, together with metadata that allows retrieving and
verifying those packages.

On the client side, repositories are managed with the `helm repo`
commands. However, Helm does not provide tools for uploading charts to
remote repository servers. This is because doing so would add
substantial requirements to an implementing server, and thus raise the
barrier for setting up a repository.

## Chart Starter Packs

The `helm create` command takes an optional `--starter` option that lets you
specify a "starter chart".

Starters are just regular charts, but are located in `$HELM_HOME/starters`.
As a chart developer, you may author charts that are specifically designed
to be used as starters. Such charts should be designed with the following
considerations in mind:

- The `Chart.yaml` will be overwritten by the generator.
- Users will expect to modify such a chart's contents, so documentation
  should indicate how users can do so.

Currently the only way to add a chart to `$HELM_HOME/starters` is to manually
copy it there. In your chart's documentation, you may want to explain that
process.


text:
package org.osgi.test.cases.usbinfo.util;

import java.util.StringTokenizer;
import org.osgi.test.support.step.TestStepProxy;

public class USBTestProxy {
	private static final String	SEPARATOR_COMMA	= ",";
	private static final String	SPACE			= " ";
	private static final String	EMPTY			= "";
	private TestStepProxy		testStepProxy;

	public USBTestProxy(TestStepProxy testStepProxy) {
		this.testStepProxy = testStepProxy;
	}

	public void close(){
		this.testStepProxy.close();
	}

	public String[] executeTestStep(String command, String message, String[] parameters) {
		String stepId = command;
		String userPrompt = message + SEPARATOR_COMMA + toString(parameters);
		String result = testStepProxy.execute(stepId, userPrompt);
		return toStringArray(result);
	}

	private String[] toStringArray(String str) {
		if (str == null || str.length() == 0) {
			return new String[0];
		}
		StringTokenizer tokenizer = new StringTokenizer(str, SEPARATOR_COMMA);
		String[] stringArray = new String[tokenizer.countTokens()];
		for (int i = 0; i < stringArray.length; i++) {
			stringArray[i] = tokenizer.nextToken();
			if (SPACE.equals(stringArray[i])) {
				stringArray[i] = null;
			}
		}
		return stringArray;
	}

	private String toString(String[] stringArray) {
		if (stringArray == null || stringArray.length == 0){
			return new String();
		}
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < stringArray.length; i++) {
			if (stringArray[i] == null || EMPTY.equals(stringArray[i])) {
				buf.append(SPACE);
			} else {
				buf.append(stringArray[i]);
			}
				buf.append(SEPARATOR_COMMA);
		}
		return buf.toString();
	}
}


text:
package models

import models.message._
import models.message.log._

/** json format of model and message.
 * Created by calvin-pc on 6/10/2015.
 */
object JsonFormats {
  import play.api.libs.json.Json

  // Generates Writes and Reads for Feed and User thanks to Json Macros
  implicit val additionalContentFormat = Json.format[AdditionalContent]
  implicit val finishedAnalysisFormat = Json.format[FinishedAnalysis]
  implicit val directJsonRawStreamFormat = Json.format[AddRawStreamMessage]
  implicit val visitedStreamFormat = Json.format[VisitedStream]
  implicit val addUserFormat = Json.format[AddUser]
  implicit val userFormat = Json.format[User]
  implicit val thridPartyFormat = Json.format[ThridParty]
  implicit val updatePasswordFormat = Json.format[UpdatePassword]
  implicit val checkPasswordFormat = Json.format[CheckPassword]
  implicit val addThridPartyFormat = Json.format[AddThridParty]
  implicit val analysisValueNumberFormat = Json.format[AnalysisValueNumber]
  implicit val analysisTypeFormat = Json.format[AnalysisType]
  implicit val returnGetAllTypesFormat = Json.format[ReturnGetAllTypes]
  implicit val rawStreamFormat = Json.format[RawStream]
  implicit val streamFormat = Json.format[Stream]
  implicit val getStreamIdListFormat = Json.format[GetStreamIdList]
  implicit val returnGetStreamIdListFormat = Json.format[ReturnGetStreamIdList]
  implicit val getPreferableAnalysisFormat = Json.format[GetPreferableAnalysis]
  implicit val returnGetPreferableAnalysisFormat = Json.format[ReturnGetPreferableAnalysis]
  implicit val updatePreferableFormat = Json.format[UpdatePreferable]
  implicit val getRandomStreamFormat = Json.format[GetRandomStream]
  implicit val validateStreamFormat = Json.format[ValidateStream]
  implicit val getVisitedStreams = Json.format[GetVisitedStreams]
  implicit val updatePreferableContent= Json.format[UpdatePreferableContent]
  implicit val updatePreferableLog=Json.format[UpdatePreferableLog]
  implicit val addRawStreamContent=Json.format[AddRawStreamContent]
  implicit val addRawStreamLog=Json.format[AddRawStreamLog]
  implicit val validateStreamContent=Json.format[ValidateStreamContent]
  implicit val validateStreamLog=Json.format[ValidateStreamLog]
  implicit val updatePasswordContent=Json.format[UpdatePasswordContent]
  implicit val updatePasswordLog=Json.format[UpdatePasswordLog]
  implicit val userContent=Json.format[UserContent]
  implicit val userLog =Json.format[UserLog]
}


text:
<!--
  ~ *******************************************************************************
  ~   Copyright (c) 2013-2014 Gabriele Mariotti.
  ~
  ~   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.
  ~  *****************************************************************************
  -->

<resources>

    <style name="card">

    </style>

    <!-- Style for Shadow ******************************************************-->

    <!-- Style for Shadow Compound view-->
    <style name="card.shadow_outer_layout">
        <item name="android:layout_marginTop">@dimen/card_shadow_view_margin_top</item>
        <item name="android:layout_marginBottom">@dimen/card_shadow_view_margin_bottom</item>
        <item name="android:layout_marginLeft">@dimen/card_shadow_view_margin_left</item>
        <item name="android:layout_marginRight">@dimen/card_shadow_view_margin_right</item>
    </style>

    <!--Style for shadow image-->
    <style name="card.shadow_image">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">@dimen/card_shadow_height</item>
        <item name="android:src">@drawable/card_shadow</item>
        <item name="android:layout_below">@+id/card_main_content_layout</item>
    </style>

    <!-- Style for Header ******************************************************-->

    <style name="card.header_outer_layout">
        <item name="android:layout_marginTop">@dimen/card_header_outer_view_margin_top</item>
        <item name="android:layout_marginBottom">@dimen/card_header_outer_view_margin_bottom</item>
        <item name="android:layout_marginLeft">@dimen/card_header_outer_view_margin_left</item>
        <item name="android:layout_marginRight">@dimen/card_header_outer_view_margin_right</item>
    </style>

    <!--Style for Header Compound View -->
    <style name="card.header_compound_view">

    </style>

    <!--Style for simple title inner header view-->
    <style name="card.header_simple_title">
        <item name="android:textSize">@dimen/card_header_simple_title_text_size</item>
        <item name="android:textColor">@color/card_text_color_header</item>
        <item name="android:layout_gravity">left|center_vertical</item>
        <item name="android:layout_marginLeft">@dimen/card_header_simple_title_margin_left</item>
        <item name="android:layout_marginTop">@dimen/card_header_simple_title_margin_top</item>
        <item name="android:layout_marginRight">@dimen/card_header_simple_title_margin_right</item>
        <item name="android:layout_marginBottom">@dimen/card_header_simple_title_margin_bottom</item>
    </style>

    <!-- Style for Header Buttons ***********************************************-->

    <style name="card.header_button_frame">

    </style>

    <!-- Button Base in Header-->
    <style name="card.header_button_base">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_alignParentRight">true</item>
        <item name="android:paddingLeft">@dimen/card_header_button_padding_left</item>
        <item name="android:focusable">false</item>
        <item name="android:focusableInTouchMode">false</item>
        <item name="android:clickable">true</item>
        <item name="android:layout_centerVertical">true</item>
        <item name="android:layout_marginRight">@dimen/card_header_button_margin_right</item>
    </style>

    <!-- Button Overflow in Header -->
    <style name="card.header_button_base.overflow" >
        <item name="android:background">@drawable/card_menu_button_rounded_overflow</item>
        <item name="android:layout_marginRight">@dimen/card_header_button_overflow_margin_right</item>
    </style>

    <!-- Button to Expand/Collapse in Header -->
    <style name="card.header_button_base.expand">
        <item name="android:background">@drawable/card_menu_button_expand</item>
    </style>

    <!-- Other Button in Header -->
    <style name="card.header_button_base.other">

    </style>

    <!-- Style for Content ******************************************************-->

    <!--Style for Content View-->
    <style name="card.content_outer_layout">
        <item name="android:layout_width">match_parent</item>
        <item name="android:minHeight">@dimen/card_base_empty_height</item>
        <item name="android:layout_marginTop">@dimen/card_content_outer_view_margin_top</item>
        <item name="android:layout_marginBottom">@dimen/card_content_outer_view_margin_bottom</item>
        <item name="android:layout_marginLeft">@dimen/card_content_outer_view_margin_left</item>
        <item name="android:layout_marginRight">@dimen/card_content_outer_view_margin_right</item>
    </style>

    <!--Style for simple title inner main view-->
    <style name="card.base_simple_title">
        <item name="android:textStyle">bold</item>
        <item name="android:layout_gravity">left|center_vertical</item>
        <item name="android:layout_marginLeft">@dimen/card_main_simple_title_margin_left</item>
        <item name="android:layout_marginTop">@dimen/card_main_simple_title_margin_top</item>
    </style>

    <!-- Style for Main Layout ****************************************-->

    <!-- Style for Main Layout-->
    <style name="card.main_layout">
        <item name="android:background">@drawable/card_selector</item>
        <item name="android:layout_marginTop">@dimen/card_main_layout_view_margin_top</item>
        <item name="android:layout_marginBottom">@dimen/card_main_layout_view_margin_bottom</item>
        <item name="android:layout_marginLeft">@dimen/card_main_layout_view_margin_left</item>
        <item name="android:layout_marginRight">@dimen/card_main_layout_view_margin_right</item>
    </style>

    <!-- Style for Hidden Expand Layout ****************************************-->

    <style name="card.main_contentExpand">
        <item name="android:background">@color/card_backgroundExpand</item>
        <item name="android:padding">@dimen/card_expand_layout_padding</item>
    </style>

    <!--Style for simple title expand/collapse inner view-->
    <style name="card.expand_simple_title">
        <item name="android:layout_gravity">left|center_vertical</item>
        <item name="android:gravity">center_vertical</item>
        <item name="android:textSize">@dimen/card_expand_simple_title_text_size</item>
        <item name="android:paddingLeft">@dimen/card_expand_simple_title_paddingLeft</item>
        <item name="android:paddingRight">@dimen/card_expand_simple_title_paddingRight</item>
        <item name="android:textColor">@color/card_expand_title_color</item>
    </style>

    <!-- Style for Thumbnail ******************************************************-->

    <style name="card_thumbnail_image">
        <item name="android:layout_width">@dimen/card_thumbnail_width</item>
        <item name="android:layout_height">@dimen/card_thumbnail_height</item>
        <item name="android:layout_gravity">center</item>
        <item name="android:gravity">center</item>
        <item name="android:scaleType">centerCrop</item>
    </style>

    <style name="card_thumbnail_outer_layout">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
    </style>

    <style name="card.thumbnail_compound_view"></style>

    <!-- Style for Lists ******************************************************-->

    <style name="list_card">
        <item name="android:paddingLeft">@dimen/list_card_padding_left</item>
        <item name="android:paddingRight">@dimen/list_card_padding_right</item>
        <item name="android:paddingBottom">@dimen/list_card_padding_bottom</item>
        <item name="android:paddingTop">@dimen/list_card_padding_top</item>
    </style>

    <!-- Base list -->
    <style name="list_card.base">

    </style>

    <!-- Thumbnail list -->
    <style name="list_card.thumbnail">

    </style>

    <style name="grid_card">
        <item name="android:paddingLeft">@dimen/grid_card_padding_left</item>
        <item name="android:paddingRight">@dimen/grid_card_padding_right</item>
        <item name="android:paddingBottom">@dimen/grid_card_padding_bottom</item>
        <item name="android:paddingTop">@dimen/grid_card_padding_top</item>
    </style>

</resources>


text:
Huginn is a system for building agents that perform automated tasks for you online.  They can read the web, watch for events, and take actions on your behalf.  Huginn's Agents create and consume events, propagating events along a directed event flow graph.  Think of it as Yahoo! Pipes plus IFTTT on your own server.  You always know who has your data.  You do.

![the origin of the name](doc/imgs/the-name.png)

#### This is just getting started, but here are some of the things that you can do right now with Huginn:

* Watch for air travel deals
* List terms you care about and receive emails when their occurrence on Twitter changes drastically.  (For example, want to know when something interesting has happened in the world of Machine Learning?  Huginn will watch the term "machine learning" on Twitter and tell you when there is a large spike.)
* Track the weather and get an email when it's going to rain (or snow) tomorrow
* Follow your project names on Twitter and get updates when people mention them
* Scrape websites and receive emails when they change
* Track your location over time

Follow [@tectonic](https://twitter.com/tectonic) for updates as Huginn evolves.

## Examples

Please checkout the [Huginn Introductory Screencast](http://vimeo.com/61976251)!

And now, some example screenshots.  Below them are instructions to get you started.

![Example list of agents](doc/imgs/your-agents.png)

![Event flow diagram](doc/imgs/diagram.png)

![Detecting peaks in Twitter](doc/imgs/peaks.png)

![Logging your location over time](doc/imgs/my-locations.png)

![Making a new agent](doc/imgs/new-agent.png)

## Getting Started

### Quick Start

If you just want to play around, you can simply clone this repository, then perform the following steps:

* Copy `.env.example` to `.env` (`cp .env.example .env`) and edit `.env`, at least updating the `APP_SECRET_TOKEN` variable.
* Run `rake db:create`, `rake db:migrate`, and then `rake db:seed` to create a development MySQL database with some example seed data.
* Run `foreman start`, visit [http://localhost:3000/][localhost], and login with the username of `admin` and the password of `password`.
* Setup some Agents!

If you need more detailed instructions, see the [Novice setup guide][novice-setup-guide].

[localhost]: http://localhost:3000/
[novice-setup-guide]: https://github.com/cantino/huginn/wiki/Novice-setup-guide

### Real Start

Follow these instructions if you wish to deploy your own version of Huginn or contribute back to the project.  GitHub doesn't make it easy to work with private forks of public repositories, so I recommend that you follow the following steps:

* Make a public fork of Huginn
* Make a private, empty GitHub repository called `huginn-private`
* Duplicate your public fork into your new private repository (via [GitHub's instructions](https://help.github.com/articles/duplicating-a-repository)):

        git clone --bare git@github.com:you/huginn.git
        cd huginn.git
        git push --mirror git@github.com:you/huginn-private.git
        cd .. && rm -rf huginn.git

* Checkout your new private repository.
* Add your Huginn public fork as a remote to your new private repository (`huginn-private`):

        git remote add public git@github.com:you/huginn.git

* Run the steps from *Quick Start* above to configure your copy of Huginn.
* When you want to contribute patches, do a remote push from your private repository to your public fork of the relevant commits, then make a pull request to this repository.

## Deployment

Please see [the Huginn Wiki](https://github.com/cantino/huginn/wiki#deploying-huginn) for detailed deployment strategies for different providers.

### Optional Setup

#### Enable the WeatherAgent

In order to use the WeatherAgent you need an [API key with Wunderground](http://www.wunderground.com/weather/api/). Signup for one and then change value of `api_key: your-key` in your seeded WeatherAgent.

#### Logging your location to the UserLocationAgent

You can use [Post Location](https://github.com/cantino/post_location) on your iPhone to post your location to an instance of the UserLocationAgent.  Make a new one to see instructions.

#### Enable DelayedJobWeb for handy delayed_job monitoring and control

* Edit `config.ru`, uncomment the DelayedJobWeb section, and change the DelayedJobWeb username and password.
* Uncomment `match "/delayed_job" => DelayedJobWeb, :anchor => false` in `config/routes.rb`.
* Uncomment `gem "delayed_job_web"` in Gemfile and run `bundle`.

#### Disable SSL

We assume your deployment will run over SSL. This is a very good idea! However, if you wish to turn this off, you'll probably need to edit `config/initializers/devise.rb` and modify the line containing `config.rememberable_options = { :secure => true }`.  You will also need to edit `config/environments/production.rb` and modify the value of `config.force_ssl`.

## License

Huginn is provided under the MIT License.

## Contribution

Huginn is a work in progress and is hopefully just getting started.  Please get involved!  You can [add new Agents](https://github.com/cantino/huginn/wiki/Creating-a-new-agent), expand the [Wiki](https://github.com/cantino/huginn/wiki), or help us simplify and strengthen the Agent API or core application.

Please fork, add specs, and send pull requests!

[![Build Status](https://travis-ci.org/cantino/huginn.png)](https://travis-ci.org/cantino/huginn)


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jaist.echonet.gui.aircontroller;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;

/**
 *
 * @author marios
 */
public class MainControlTab implements AcceptsQueryResults{

    private AircondionControlData airdata;
    private JPanel aPanel;
    private JTextField textField;

    public MainControlTab(AircondionControlData airdata) {
        this.airdata = airdata;
    }

    public JPanel getPanel() {
        if (aPanel == null) {
            initPanel();
        }
        return aPanel;
    }

    private void initPanel() {
        aPanel = new JPanel(new BorderLayout());
        JButton aButton = new JButton("Refresh All Properties");
        aButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                airdata.refreshAll();
            }
        });
        //String content = "";
        //JLabel aLabel = new JLabel(content);

        textField = new JTextField();
        textField.setEditable(false);

        aPanel.add(new JLabel("Last output:"), BorderLayout.NORTH);
        aPanel.add(textField, BorderLayout.CENTER);
        //aPanel.add(aLabel, BorderLayout.NORTH);
        aPanel.add(aButton, BorderLayout.EAST);
        aPanel.add(new JSeparator(), BorderLayout.SOUTH);
    }

    @Override
    public void setLastResult(String result, boolean error) {
        textField.setText(result);
        if (error) {
            textField.setBackground(Color.RED);
        } else {
            textField.setBackground(Color.GREEN);
        }
    }
}


text:
module Egauge
  class << self
    def configuration
      @configuration ||= Configuration.new
    end

    def configure
      yield configuration
    end
  end

  class Configuration
    attr_accessor :url
  end
end


text:
import { binarySearch, getLineStartPositions, getPosition } from '../src/languageservice/utils/documentPositionCalculator';
import * as assert from 'assert';

describe('DocumentPositionCalculator Tests', () => {
  describe('binarySearch', function () {
    it('Binary Search where we are looking for element to the left of center', () => {
      const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
      const find = 2;

      const result = binarySearch(arr, find);
      assert.equal(result, 1);
    });

    it('Binary Search where we are looking for element to the right of center', () => {
      const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
      const find = 8;

      const result = binarySearch(arr, find);
      assert.equal(result, 7);
    });

    it('Binary Search found at first check', () => {
      const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
      const find = 5;

      const result = binarySearch(arr, find);
      assert.equal(result, 4);
    });

    it('Binary Search item not found', () => {
      const arr = [1];
      const find = 5;

      const result = binarySearch(arr, find);
      assert.equal(result, -2);
    });
  });

  describe('getLineStartPositions', function () {
    it('getLineStartPositions with windows newline', () => {
      const test_str = 'test: test\r\ntest: test';

      const result = getLineStartPositions(test_str);
      assert.equal(result[0], 0);
      assert.equal(result[1], 12);
    });

    it('getLineStartPositions with normal newline', () => {
      const test_str = 'test: test\ntest: test';

      const result = getLineStartPositions(test_str);
      assert.equal(result[0], 0);
      assert.equal(result[1], 11);
    });
  });

  describe('getPosition', function () {
    it('getPosition', () => {
      const test_str = 'test: test\r\ntest: test';

      const startPositions = getLineStartPositions(test_str);
      const result = getPosition(0, startPositions);
      assert.notEqual(result, undefined);
      assert.equal(result.line, 0);
      assert.equal(result.character, 0);
    });

    it('getPosition when not found', () => {
      const test_str = 'test: test\ntest: test';

      const startPositions = getLineStartPositions(test_str);
      const result = getPosition(5, startPositions);
      assert.notEqual(result, undefined);
      assert.equal(result.line, 0);
      assert.equal(result.character, 5);
    });
  });
});


text:
'use strict';
/**
 * @ngdoc function
 * @name sbAdminApp.controller:MainCtrl
 * @description
 * # MainCtrl
 * Controller of the sbAdminApp
 */
angular.module('sbAdminApp')
    .controller('ChartCtrl', ['$scope', '$timeout', 'progForceService', function ($scope, $timeout, progForceService) {

        /** PROGFORCE TEST TASK STARTS **/
        var barDefault = {
            labels: [],
            datasets: [{
                data: []
            }]
        };

        var progForceBar = document.getElementById("bar-progForce");
        var ctx = progForceBar.getContext("2d");
        var barInstance = new Chart(ctx).Bar(barDefault, {
            responsive: true
        });

        progForceBar.style.width ='100%';
        progForceBar.width  = progForceBar.offsetWidth;

        var lastBarLength = 0;
        $scope.onFileSelect = function(changeEvent) {
            var wordCount;

            var files = changeEvent.target.files;
            if (files.length) {
                var r = new FileReader();
                r.onload = function(e) {
                    wordCount = progForceService.countWord(e.target.result);

                    for (var i = 0; i < lastBarLength; i++) {
                        barInstance.removeData();
                    }

                    for (var i = 0; i < wordCount.length; i++) {
                        barInstance.addData([wordCount[i].count], wordCount[i].word);
                    }
                    lastBarLength = wordCount.length; //remember the amount of bars so we could remove exact same amount
                };
                r.readAsText(files[0]);
            }
        };
        /** PROGFORCE TEST TASK ENDS **/

        $scope.bar = {
            labels: ['2006', '2007', '2008'],
            series: ['Series A', 'Series B'],
            data: [
                [65, 59, 80],
                [28, 48, 40]
            ]
        };

        $scope.line = {
            labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
            series: ['Series A', 'Series B'],
            data: [
                [65, 59, 80, 81, 56, 55, 40],
                [28, 48, 40, 19, 86, 27, 90]
            ],
            onClick: function (points, evt) {
                console.log(points, evt);
            }
        };

        $scope.donut = {
            labels: ["Download Sales", "In-Store Sales", "Mail-Order Sales"],
            data: [300, 500, 100]
        };

        $scope.radar = {
            labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"],

            data: [
                [65, 59, 90, 81, 56, 55, 40],
                [28, 48, 40, 19, 96, 27, 100]
            ]
        };

        $scope.pie = {
            labels: ["Download Sales", "In-Store Sales", "Mail-Order Sales"],
            data: [300, 500, 100]
        };

        $scope.polar = {
            labels: ["Download Sales", "In-Store Sales", "Mail-Order Sales", "Tele Sales", "Corporate Sales"],
            data: [300, 500, 100, 40, 120]
        };

        $scope.dynamic = {
            labels: ["Download Sales", "In-Store Sales", "Mail-Order Sales", "Tele Sales", "Corporate Sales"],
            data: [300, 500, 100, 40, 120],
            type: 'PolarArea',

            toggle: function () {
                this.type = this.type === 'PolarArea' ?
                    'Pie' : 'PolarArea';
            }
        };
    }]);


text:
<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<doxygen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="compound.xsd" version="1.8.6">
  <compounddef id="structboost_1_1geometry_1_1strategy_1_1within_1_1relate__box__box__loop_3_01_sub_strategy_00_01_7c707eae54d923a4056442231cac0358" kind="struct" prot="public">
    <compoundname>boost::geometry::strategy::within::relate_box_box_loop< SubStrategy, Box1, Box2, DimensionCount, DimensionCount ></compoundname>
    <includes local="no">box_in_box.hpp</includes>
    <templateparamlist>
      <param>
        <type>template< typename, std::size_t, typename > class</type>
        <declname>SubStrategy</declname>
        <defname>SubStrategy</defname>
      </param>
      <param>
        <type>typename Box1</type>
      </param>
      <param>
        <type>typename Box2</type>
      </param>
      <param>
        <type>std::size_t</type>
        <declname>DimensionCount</declname>
        <defname>DimensionCount</defname>
      </param>
    </templateparamlist>
      <sectiondef kind="public-static-func">
      <memberdef kind="function" id="structboost_1_1geometry_1_1strategy_1_1within_1_1relate__box__box__loop_3_01_sub_strategy_00_01_7c707eae54d923a4056442231cac0358_1a613dad582baa0f39bfc0f2bc7222e720" prot="public" static="yes" const="no" explicit="no" inline="yes" virt="non-virtual">
        <type>bool</type>
        <definition>static bool boost::geometry::strategy::within::relate_box_box_loop< SubStrategy, Box1, Box2, DimensionCount, DimensionCount >::apply</definition>
        <argsstring>(Box1 const &, Box2 const &)</argsstring>
        <name>apply</name>
        <param>
          <type>Box1 const &</type>
        </param>
        <param>
          <type>Box2 const &</type>
        </param>
        <briefdescription>
        </briefdescription>
        <detaileddescription>
        </detaileddescription>
        <inbodydescription>
        </inbodydescription>
        <location file="/home/ubuntu/boost/boost/geometry/strategies/cartesian/box_in_box.hpp" line="204" column="1" bodyfile="/home/ubuntu/boost/boost/geometry/strategies/cartesian/box_in_box.hpp" bodystart="204" bodyend="207"/>
      </memberdef>
      </sectiondef>
    <briefdescription>
    </briefdescription>
    <detaileddescription>
    </detaileddescription>
    <location file="/home/ubuntu/boost/boost/geometry/strategies/cartesian/box_in_box.hpp" line="203" column="1" bodyfile="/home/ubuntu/boost/boost/geometry/strategies/cartesian/box_in_box.hpp" bodystart="202" bodyend="208"/>
    <listofallmembers>
      <member refid="structboost_1_1geometry_1_1strategy_1_1within_1_1relate__box__box__loop_3_01_sub_strategy_00_01_7c707eae54d923a4056442231cac0358_1a613dad582baa0f39bfc0f2bc7222e720" prot="public" virt="non-virtual"><scope>boost::geometry::strategy::within::relate_box_box_loop< SubStrategy, Box1, Box2, DimensionCount, DimensionCount ></scope><name>apply</name></member>
    </listofallmembers>
  </compounddef>
</doxygen>


text:
namespace mk
{
	template <> inline Type& typecls<Dimension>() { static Type ty; return ty; }
	template <> inline Type& typecls<Sizing>() { static Type ty; return ty; }
	template <> inline Type& typecls<Pivot>() { static Type ty; return ty; }
	template <> inline Type& typecls<Flow>() { static Type ty; return ty; }
	template <> inline Type& typecls<Space>() { static Type ty; return ty; }
	template <> inline Type& typecls<Clipping>() { static Type ty; return ty; }
	template <> inline Type& typecls<BoxLayer>() { static Type ty; return ty; }
	template <> inline Type& typecls<Opacity>() { static Type ty; return ty; }
	template <> inline Type& typecls<Weight>() { static Type ty; return ty; }
	template <> inline Type& typecls<FrameType>() { static Type ty; return ty; }
	template <> inline Type& typecls<WidgetState>() { static Type ty; return ty; }
}

#endif // MK_UITYPES_H_INCLUDED


text:
import { Expression } from './Expression';
import INodeVisitor from '~/syntax/INodeVisitor';
import { nonTerminal, parser } from '~/parser/Parser';
import { TokenType, Token } from '~/parser/Tokenizer';

@nonTerminal({ implements: Expression })
export class IntegerLiteral extends Expression {
    @parser(TokenType.INTEGER_LITERAL, { definite: true })
    setValue(token: Token) {
        this.value = token.value;
        this.registerLocation('self', token.getLocation());
    }

    value: number;

    visit<T>(visitor: INodeVisitor<T>): T {
        return visitor.visitIntegerLiteral(this);
    }
}


text:
package org.wso2.carbon.logging.summarizer.scriptCreator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.wso2.carbon.logging.summarizer.utils.LoggingConfig;
import org.wso2.carbon.logging.summarizer.utils.LoggingConfigManager;

import java.io.*;
import java.util.zip.GZIPOutputStream;

public class OutputFileHandler {

    private static final Log log = LogFactory.getLog(OutputFileHandler.class);
    LoggingConfig config = LoggingConfigManager.loadLoggingConfiguration();
    String archivedLogLocation = config.getArchivedLogLocation();
    String hdfsConfig = config.getHdfsConfig();

    public void fileReStructure(String colFamilyName) throws IOException {
        log.info("CF "+colFamilyName);

        Configuration conf = new Configuration(false);
        /**
         * Create HDFS Client configuration to use name node hosted on host master and port 9000.
         * Client configured to connect to a remote distributed file system.
         */
        conf.set("fs.default.name", hdfsConfig);
        conf.set("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem");

        /**
         * Get connection to remote file sytem
         */
        FileSystem fs = FileSystem.get(conf);

        /**
         * Crate file sourcePath object
         */
        Path filePath = new Path(archivedLogLocation);

        String tmpStrArr[] = colFamilyName.split("_");
        String tenantId = tmpStrArr[1];
        String serverName = tmpStrArr[2];

        String createdDate = tmpStrArr[3] + "_" + tmpStrArr[4] + "_" + tmpStrArr[5];
        String directoryPathName = archivedLogLocation + tenantId + "/" + serverName + "/";
        String filePathName = directoryPathName + createdDate;
        log.info("filePathName "+filePathName);
        log.info("createdDate "+createdDate);
        //Rename the 000000_0 file as a .tmp file
        Path sourceFileName = new Path(filePathName + "/000000_0");
        Path destnFileName = new Path(filePathName + "/" + createdDate + ".tmp");

        boolean  isRenamed = fs.rename(sourceFileName, destnFileName);
        log.info("rename "+isRenamed);

        /*if (!isRenamed) {
            String path = sourceFileName.toString();
            FileStatus[] status = fs.listStatus(new Path("/stratos/archivedLogs/212/")); // you need to
            log.info(status);
            if (status != null) {
                for (int i = 0; i < status.length; i++) {
                    log.info("X:" + status[i].getPath());
                }
            } else {
                log.info("Null");
            }
            // in your hdfs path
        }*/

        //To remove the unicode character in the created .tmp file
        if(isRenamed) {
            Path sanitizedFileName = new Path(filePathName + "/" + createdDate + ".log");
            replaceChar(destnFileName, sanitizedFileName, fs);

            log.info("Logs of Tenant " + tenantId + " of " + serverName + " on " + createdDate + " are successfully archived");
        } else {
            log.info("Logs of Tenant " + tenantId + " of " + serverName + " on " + createdDate + " are not ******* successfully archived");

        }

    }

    public static void replaceChar(Path oldPath, Path newPath, FileSystem fs)
            throws IOException {
        FSDataInputStream in = fs.open(oldPath);
        FSDataOutputStream out = fs.create(newPath);
        BufferedReader dataInput = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line = dataInput.readLine()) != null) {
            out.write(line.replace("\001", "").getBytes());
            out.write("\n".getBytes());
        }

        out.close();
        dataInput.close();
        if (fs.exists(oldPath)) {
            fs.delete(oldPath, true);
        }
        in.close();
    }

    public void compressLogFile(String temp) throws IOException {
        File file = new File(temp);
        FileOutputStream outputStream = new FileOutputStream(file + ".gz");
        GZIPOutputStream gzos = new GZIPOutputStream(outputStream);
        FileInputStream inputStream = new FileInputStream(temp);
        BufferedInputStream in = new BufferedInputStream(inputStream);
        byte[] buffer = new byte[1024];
        int i;
        while ((i = in.read(buffer)) >= 0) {
            gzos.write(buffer, 0, i);
        }
        in.close();
        gzos.close();
    }

    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }

}


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

package org.jdbi.v3.core.argument;

import org.jdbi.v3.core.Handle;
import org.jdbi.v3.core.rule.H2DatabaseRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

public class PrimitivesArgumentFactoryTest {
    @Rule
    public H2DatabaseRule dbRule = new H2DatabaseRule();

    private Handle handle;

    @Before
    public void getHandle() {
        handle = dbRule.getSharedHandle();
    }

    @Test
    public void bindingNullToPrimitiveThrows() {
        assertThat(handle.getConfig(Arguments.class).isBindingNullToPrimitivesPermitted()).isTrue();

        assertThat(handle.createQuery("select :foo").bindByType("foo", null, int.class).mapTo(int.class).one())
            .describedAs("binding a null binds the primitive's default")
            .isZero();

        handle.getConfig(Arguments.class).setBindingNullToPrimitivesPermitted(false);

        assertThatThrownBy(() -> handle.createQuery("select :foo").bindByType("foo", null, int.class).mapTo(int.class).one())
            .isInstanceOf(IllegalArgumentException.class)
            .hasMessage("binding null to a primitive int is forbidden by configuration, declare a boxed type instead");

        assertThat(handle.createQuery("select :foo").bindByType("foo", null, Integer.class).mapTo(Integer.class).one())
            .describedAs("binding a null to a boxed type is fine")
            .isNull();
    }
}


text:
var target_obj = {};
var not_target_obj = {};
var weak_ref = new WeakRef(target_obj);
var weak_ref2 = new WeakRef(target_obj);

assert (weak_ref.deref() === target_obj);
assert (weak_ref.deref() === weak_ref2.deref());
assert (weak_ref.deref() !== not_target_obj);

assert (weak_ref2.deref() === target_obj);
assert (weak_ref2.deref() !== not_target_obj);
assert (weak_ref2.deref() === weak_ref2.deref());

target_obj = undefined;
gc();

assert (weak_ref.deref() === undefined);
assert (weak_ref2.deref() === undefined);

var key_obj_1 = {};
var key_obj_2 = {};
var key_obj_3 = {};
var target_obj_2 = {};
var target_obj_3 = {};
var weak_ref_3 = new WeakRef(key_obj_1);
var weak_ref_4 = new WeakRef(target_obj_2);
var weak_ref_5 = new WeakRef(target_obj_3);

var weak_map = new WeakMap();
weak_map.set(key_obj_1, weak_ref_3);
weak_map.set(key_obj_2, weak_ref_4);
weak_map.set(key_obj_3, weak_ref_5);

assert(weak_map.has(key_obj_1));
assert(weak_map.has(key_obj_2));
assert(weak_map.has(key_obj_3));

assert(weak_map.get(key_obj_1).deref() === key_obj_1);
assert(weak_map.get(key_obj_2).deref() === target_obj_2);
assert(weak_map.get(key_obj_3).deref() === target_obj_3);

key_obj_1 = undefined;
gc();
assert(weak_map.get(key_obj_1) === undefined);
assert(weak_ref_3.deref() === undefined);

key_obj_2 = undefined;
gc();
assert(weak_map.get(key_obj_2) === undefined);
assert(weak_ref_4.deref() === target_obj_2);

target_obj_3 = undefined;
gc();
assert(weak_map.get(key_obj_3) !== undefined);
assert(weak_ref_5.deref() === undefined);


text:
package pl.java.scalatech;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Simple {

    private String name;

    private int value;
    private static String login = "Login X";
    private boolean game;

    public Simple(String name) {
        this.name = name;
    }

    public Simple(String name, int value) {
        this.name = name;
        this.value = value;
    }

    public static String sayLogin() {
        return login;
    }

}


text:
category: catalog
layout: catalog
show_products: true
spread: true
published: true
title: Everyday Supplement
slug: Everyday Supplement
directory: Everyday Supplement
pdf: Everyday_Supplement_NO_PRICE.pdf
filebase: pages/Everyday_Supplement_NO_PRICE
cover: Everyday_Supplement_NO_PRICE_Cover.jpg
numslides: '7'
extension: jpg
---


text:
/**
 * @file navigator_rtl.cpp
 * Helper class to access RTL
 * @author Julian Oes <julian@oes.ch>
 * @author Anton Babushkin <anton.babushkin@me.com>
 */

#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <fcntl.h>

#include <systemlib/mavlink_log.h>
#include <systemlib/err.h>
#include <geo/geo.h>

#include <uORB/uORB.h>
#include <navigator/navigation.h>
#include <uORB/topics/home_position.h>
#include <uORB/topics/vtol_vehicle_status.h>

#include "navigator.h"
#include "rtl.h"

#define DELAY_SIGMA	0.01f

RTL::RTL(Navigator *navigator, const char *name) :
	MissionBlock(navigator, name),
	_rtl_state(RTL_STATE_NONE),
	_rtl_start_lock(false),
	_param_return_alt(this, "RTL_RETURN_ALT", false),
	_param_descend_alt(this, "RTL_DESCEND_ALT", false),
	_param_land_delay(this, "RTL_LAND_DELAY", false),
	_param_rtl_min_dist(this, "RTL_MIN_DIST", false)
{
	/* load initial params */
	updateParams();
	/* initial reset */
	on_inactive();
}

RTL::~RTL()
{
}

void
RTL::on_inactive()
{
	/* reset RTL state only if setpoint moved */
	if (!_navigator->get_can_loiter_at_sp()) {
		_rtl_state = RTL_STATE_NONE;
	}
}

void
RTL::on_activation()
{
	/* reset starting point so we override what the triplet contained from the previous navigation state */
	_rtl_start_lock = false;
	set_current_position_item(&_mission_item);
	struct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet();
	mission_item_to_position_setpoint(&_mission_item, &pos_sp_triplet->current);

	/* check if we are pretty close to home already */
	float home_dist = get_distance_to_next_waypoint(_navigator->get_home_position()->lat, _navigator->get_home_position()->lon,
			_navigator->get_global_position()->lat, _navigator->get_global_position()->lon);

	/* decide where to enter the RTL procedure when we switch into it */
	if (_rtl_state == RTL_STATE_NONE) {
		/* for safety reasons don't go into RTL if landed */
		if (_navigator->get_land_detected()->landed) {
			_rtl_state = RTL_STATE_LANDED;
			mavlink_log_critical(_navigator->get_mavlink_log_pub(), "Already landed, not executing RTL");

		/* if lower than return altitude, climb up first */
		} else if (home_dist > _param_rtl_min_dist.get() && _navigator->get_global_position()->alt < _navigator->get_home_position()->alt
			   + _param_return_alt.get()) {
			_rtl_state = RTL_STATE_CLIMB;

		/* otherwise go straight to return */
		} else {
			/* set altitude setpoint to current altitude */
			_rtl_state = RTL_STATE_RETURN;
			_mission_item.altitude_is_relative = false;
			_mission_item.altitude = _navigator->get_global_position()->alt;
		}

	}

	set_rtl_item();
}

void
RTL::on_active()
{
	if (_rtl_state != RTL_STATE_LANDED && is_mission_item_reached()) {
		advance_rtl();
		set_rtl_item();
	}
}

void
RTL::set_rtl_item()
{
	struct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet();

	/* make sure we have the latest params */
	updateParams();

	if (!_rtl_start_lock) {
		set_previous_pos_setpoint();
	}

	_navigator->set_can_loiter_at_sp(false);

	switch (_rtl_state) {
	case RTL_STATE_CLIMB: {
		float climb_alt = _navigator->get_home_position()->alt + _param_return_alt.get();

		_mission_item.lat = _navigator->get_global_position()->lat;
		_mission_item.lon = _navigator->get_global_position()->lon;
		_mission_item.altitude_is_relative = false;
		_mission_item.altitude = climb_alt;
		_mission_item.yaw = NAN;
		_mission_item.loiter_radius = _navigator->get_loiter_radius();
		_mission_item.loiter_direction = 1;
		_mission_item.nav_cmd = NAV_CMD_WAYPOINT;
		_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
		_mission_item.time_inside = 0.0f;
		_mission_item.pitch_min = 0.0f;
		_mission_item.autocontinue = true;
		_mission_item.origin = ORIGIN_ONBOARD;

		mavlink_log_info(_navigator->get_mavlink_log_pub(), "RTL: climb to %d m (%d m above home)",
			(int)(climb_alt),
			(int)(climb_alt - _navigator->get_home_position()->alt));
		break;
	}

	case RTL_STATE_RETURN: {
		_mission_item.lat = _navigator->get_home_position()->lat;
		_mission_item.lon = _navigator->get_home_position()->lon;
		// don't change altitude

		// use home yaw if close to home
		/* check if we are pretty close to home already */
		float home_dist = get_distance_to_next_waypoint(_navigator->get_home_position()->lat, _navigator->get_home_position()->lon,
				_navigator->get_global_position()->lat, _navigator->get_global_position()->lon);

		if (home_dist < _param_rtl_min_dist.get()) {
			_mission_item.yaw = _navigator->get_home_position()->yaw;

		} else {
			if (pos_sp_triplet->previous.valid) {
				/* if previous setpoint is valid then use it to calculate heading to home */
				_mission_item.yaw = get_bearing_to_next_waypoint(
				        pos_sp_triplet->previous.lat, pos_sp_triplet->previous.lon,
				        _mission_item.lat, _mission_item.lon);

			} else {
				/* else use current position */
				_mission_item.yaw = get_bearing_to_next_waypoint(
				        _navigator->get_global_position()->lat, _navigator->get_global_position()->lon,
				        _mission_item.lat, _mission_item.lon);
			}
		}
		_mission_item.loiter_radius = _navigator->get_loiter_radius();
		_mission_item.loiter_direction = 1;
		_mission_item.nav_cmd = NAV_CMD_WAYPOINT;
		_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
		_mission_item.time_inside = 0.0f;
		_mission_item.pitch_min = 0.0f;
		_mission_item.autocontinue = true;
		_mission_item.origin = ORIGIN_ONBOARD;

		mavlink_log_info(_navigator->get_mavlink_log_pub(), "RTL: return at %d m (%d m above home)",
			(int)(_mission_item.altitude),
			(int)(_mission_item.altitude - _navigator->get_home_position()->alt));

		_rtl_start_lock = true;
		break;
	}

	case RTL_STATE_TRANSITION_TO_MC: {
		_mission_item.nav_cmd = NAV_CMD_DO_VTOL_TRANSITION;
		_mission_item.params[0] = vtol_vehicle_status_s::VEHICLE_VTOL_STATE_MC;
		break;
	}

	case RTL_STATE_DESCEND: {
		_mission_item.lat = _navigator->get_home_position()->lat;
		_mission_item.lon = _navigator->get_home_position()->lon;
		_mission_item.altitude_is_relative = false;
		_mission_item.altitude = _navigator->get_home_position()->alt + _param_descend_alt.get();

		// check if we are already lower - then we will just stay there
		if (_mission_item.altitude > _navigator->get_global_position()->alt) {
			_mission_item.altitude = _navigator->get_global_position()->alt;
		}

		_mission_item.yaw = _navigator->get_home_position()->yaw;

		// except for vtol which might be still off here and should point towards this location
		float d_current = get_distance_to_next_waypoint(
			_navigator->get_global_position()->lat, _navigator->get_global_position()->lon,
			_mission_item.lat, _mission_item.lon);

		if (_navigator->get_vstatus()->is_vtol && d_current > _navigator->get_acceptance_radius()) {
			_mission_item.yaw = get_bearing_to_next_waypoint(
				_navigator->get_global_position()->lat, _navigator->get_global_position()->lon,
				_mission_item.lat, _mission_item.lon);
		}

		_mission_item.loiter_radius = _navigator->get_loiter_radius();
		_mission_item.loiter_direction = 1;
		_mission_item.nav_cmd = NAV_CMD_WAYPOINT;
		_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
		_mission_item.time_inside = 0.0f;
		_mission_item.pitch_min = 0.0f;
		_mission_item.autocontinue = false;
		_mission_item.origin = ORIGIN_ONBOARD;

		/* disable previous setpoint to prevent drift */
		pos_sp_triplet->previous.valid = false;

		mavlink_log_info(_navigator->get_mavlink_log_pub(), "RTL: descend to %d m (%d m above home)",
			(int)(_mission_item.altitude),
			(int)(_mission_item.altitude - _navigator->get_home_position()->alt));
		break;
	}

	case RTL_STATE_LOITER: {
		bool autoland = _param_land_delay.get() > -DELAY_SIGMA;

		_mission_item.lat = _navigator->get_home_position()->lat;
		_mission_item.lon = _navigator->get_home_position()->lon;
		// don't change altitude
		_mission_item.yaw = _navigator->get_home_position()->yaw;
		_mission_item.loiter_radius = _navigator->get_loiter_radius();
		_mission_item.loiter_direction = 1;
		_mission_item.nav_cmd = autoland ? NAV_CMD_LOITER_TIME_LIMIT : NAV_CMD_LOITER_UNLIMITED;
		_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
		_mission_item.time_inside = _param_land_delay.get() < 0.0f ? 0.0f : _param_land_delay.get();
		_mission_item.pitch_min = 0.0f;
		_mission_item.autocontinue = autoland;
		_mission_item.origin = ORIGIN_ONBOARD;

		_navigator->set_can_loiter_at_sp(true);

		if (autoland && (_mission_item.time_inside > FLT_EPSILON)) {
			mavlink_log_info(_navigator->get_mavlink_log_pub(), "RTL: loiter %.1fs", (double)_mission_item.time_inside);

		} else {
			mavlink_log_info(_navigator->get_mavlink_log_pub(), "RTL: completed, loiter");
		}
		break;
	}

	case RTL_STATE_LAND: {
		_mission_item.yaw = _navigator->get_home_position()->yaw;
		set_land_item(&_mission_item, false);

		mavlink_log_info(_navigator->get_mavlink_log_pub(), "RTL: land at home");
		break;
	}

	case RTL_STATE_LANDED: {
		set_idle_item(&_mission_item);

		mavlink_log_info(_navigator->get_mavlink_log_pub(), "RTL: completed, landed");
		break;
	}

	default:
		break;
	}

	reset_mission_item_reached();

	/* execute command if set */
	if (!item_contains_position(&_mission_item)) {
		issue_command(&_mission_item);
	}

	/* convert mission item to current position setpoint and make it valid */
	mission_item_to_position_setpoint(&_mission_item, &pos_sp_triplet->current);
	pos_sp_triplet->next.valid = false;

	_navigator->set_position_setpoint_triplet_updated();
}

void
RTL::advance_rtl()
{
	switch (_rtl_state) {
	case RTL_STATE_CLIMB:
		_rtl_state = RTL_STATE_RETURN;
		break;

	case RTL_STATE_RETURN:
		_rtl_state = RTL_STATE_DESCEND;

		if (_navigator->get_vstatus()->is_vtol && !_navigator->get_vstatus()->is_rotary_wing) {
			_rtl_state = RTL_STATE_TRANSITION_TO_MC;
		}
		break;

	case RTL_STATE_TRANSITION_TO_MC:
		_rtl_state = RTL_STATE_RETURN;
		break;

	case RTL_STATE_DESCEND:
		/* only go to land if autoland is enabled */
		if (_param_land_delay.get() < -DELAY_SIGMA || _param_land_delay.get() > DELAY_SIGMA) {
			_rtl_state = RTL_STATE_LOITER;

		} else {
			_rtl_state = RTL_STATE_LAND;
		}
		break;

	case RTL_STATE_LOITER:
		_rtl_state = RTL_STATE_LAND;
		break;

	case RTL_STATE_LAND:
		_rtl_state = RTL_STATE_LANDED;
		break;

	default:
		break;
	}
}


text:
      Author: Olalekan Ogunmolu.
      Date:   Oct 20, 2016
      Lab Affiliation: Gans' Lab
      ]]
require 'torch'
require 'data.dataparser'
require 'rnn'
require 'nngraph'
nn.LSTM.usenngraph = true -- faster
require 'optim'

local optnet = require 'optnet'
torch.setdefaulttensortype('torch.FloatTensor')

--options and general settings -----------------------------------------------------
opt = {
  batchSize = 1,
  data = 'data',
  gpu = 0,
  noutputs = 1,
  display = 1,
  verbose = false,
  maxIter = 20,
  silent = false,
  hiddenSize = {6, 3, 5},
  backend    = 'cunn',  --cudnn or cunn
  checkpoint = 'network/data_4_fastlstm-net.t7'
}

for k,v in pairs(opt) do opt[k] = tonumber(os.getenv(k)) or os.getenv(k) or opt[k] end
print(opt)

if opt.display==0 then opt.display = false end

local filename = paths.concat('outputs' .. '/testlog.txt')
if paths.filep(filename)
  then os.execute('mv ' .. filename .. ' ' .. filename ..'.old') end
testlogger = optim.Logger(paths.concat('outputs' .. '/testlog.txt'))

local function init()

  --GPU Settings -----------------------------------------------------------------------
  use_cuda = false

  local msg
  if opt.gpu >= 0 then
    require 'cutorch'
    require 'cunn'
    if opt.backend == 'cudnn' then require 'cudnn' end
    use_cuda = true
    cutorch.setDevice(opt.gpu + 1)
    msg = string.format('Code deployed on GPU %d with cudnn backend', opt.gpu+1)
  else
    msg = 'Running in CPU mode'
    require 'nn'
  end
  if opt.verbose == 1 then print(msg) end
  -------------------------------------------------------------------------------

  ---Net Loader---------------------------------------------------------------------------
  local model
  model = torch.load(opt.checkpoint)

  require 'rnn'
  cost = nn.SequencerCriterion(nn.MSECriterion()):cuda()

  assert(model ~='', 'must provide a trained model')

  if use_cuda then
    model:cuda()
    model:evaluate()
  else
    model:double()
    model:evaluate()
  end

  netmods = model.modules;
  if opt.verbose then print('netmods: \n', netmods) end
  --------------------------------------------------------------------------------
  return model
end

local function transfer_data(x)
  if use_cuda then
    x:cuda()
  else
    x:float()
  end
  return x
end

testlogger:setNames{'iter', 'loss'}

--test function-----------------------------------------------------------------
local function test(opt, model)
 -- local vars
 local splitData = {};
 splitData = split_data(opt)
 local time = sys.clock()
 local testHeight = splitData.test_input[1]:size(1)

 -- averaged param use?
 if average then
    cachedparams = parameters:clone()
    parameters:copy(average)
 end
 -- test over given dataset
 -- print('<trainer> on testing Set:')

  local preds;
  local iter = 0;

  -- create mini batch
  local inputs, targets = {}, {}

  for t = 1, math.min(opt.maxIter, testHeight) do
    if(t >= math.min(opt.maxIter, testHeight)) then t = 1 end  --wrap around

    _, _, inputs, targets = get_datapair(opt, t)
    inputs = torch.cat({inputs[1], inputs[2], inputs[3], inputs[4], inputs[5],
                        inputs[6], inputs[7], inputs[8], inputs[9]}, 2)
    targets = torch.cat({targets[1], targets[2], targets[3]}, 2)
    -- test samples
    model:forget()  --forget all past time steps

    print('inputs: \n', inputs)
    local preds = model:forward(inputs)
    local loss = cost:forward(preds, targets)

    local  gradOutputs  = cost:backward(preds, targets)
    -- local gradInputs    = model:backward(inputs, gradOutputs)
    model:updateParameters(5e-3)

    if iter % 2  == 0 then collectgarbage() end

    -- timing
    time = sys.clock() - time
    time = time / testHeight

    testlogger:add{t, loss}
    if (not opt.silent) then
      -- print('loss'); print(loss)
      print('preds:'); print(preds);
      print('weights');
      print(model.modules[1].recurrentModule.modules[7].weight)
      print('inputs: '); print(inputs)
      sys.sleep('30')
    end

    iter = iter + 1
  end
end

local function connect_cb(name, topic)
  print("subscriber connected: " .. name .. " (topic: '" .. topic .. "')")
end

local function disconnect_cb(name, topic)
  print("subscriber diconnected: " .. name .. " (topic: '" .. topic .. "')")
end

local function main()
  local model = init()
  for i=1,20 do
    test(opt, model)
  end
end

main()


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycologia 92(4): 787 (2000)

#### Original name
Dimorphomyces philippinensis W. Rossi & Santam.

### Remarks
null


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <WebView
        android:id="@+id/myWebView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    </WebView>

</RelativeLayout>


text:
/**
 * @file   named exports
 * @author Roman Zanettin <roman.zanettin@ringieraxelspringer.ch>
 * @date   2017-02-05
 */

export { default as branch } from './branch';
export { default as componentFromStream } from './componentFromStream';
export { default as compose } from './compose';
export { default as createEventHandler } from './createEventHandler';
export { default as createSink } from './createSink';
export { default as defaultProps } from './defaultProps';
export { default as flattenProps } from './flattenProps';
export { default as mapProps } from './mapProps';
export { default as nest } from './nest';
export { default as pure } from './pure';
export { default as renderComponent } from './renderComponent';
export { default as renderNothing } from './renderNothing';
export { default as renameProp } from './renameProp';
export { default as renameProps } from './renameProps';
export { default as setObservableConfig } from './setObservableConfig';
export { default as shouldUpdate } from './shouldUpdate';
export { default as withLifecycle } from './withLifecycle';
export { default as withHandlers } from './withHandlers';
export { default as withProps } from './withProps';
export { default as withPropsOnChange } from './withPropsOnChange';
export { default as withReducer } from './withReducer';
export { default as withState } from './withState';


text:
package org.n52.sir.ds.solr;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.AbstractModule;

public class SolrModule extends AbstractModule {

    private static Logger log = LoggerFactory.getLogger(SolrModule.class);

    @Override
    protected void configure() {
        bind(SolrConnection.class);

        // FIXME change .named to recommended explicit binding annotation:
        // http://code.google.com/p/google-guice/wiki/BindingAnnotations

        // bind(ISearchSensorDAO.class).annotatedWith(Names.named(ISearchSensorDAO.AUTOCOMPLETE)).to(SOLRSearchSensorDAO.class);

        log.debug("Configured {}", this);
    }

}


text:
16-February-2016

Move set channel to happen before anything runs because addons might init expecting the channel to exist. [PR75](https://github.com/storybooks/storyshots/pull/75)

### v3.2.1
21-January-2016

Provide mock Storybook Channel to Storybook addons. [PR72](https://github.com/storybooks/storyshots/pull/72)

### v3.2.0
30-December-2016

Add support to filter stories by story name using a regexp. [PR70](https://github.com/storybooks/storyshots/pull/70)

### v3.1.1
27-December-2016

Pass storybook context to render function of stories. [PR69](https://github.com/storybooks/storyshots/pull/69)

### v3.1.0
24-December-2016

Add support for require.context. [PR67](https://github.com/storybooks/storyshots/pull/67)

### v3.0.0
22-December-2016

This is a brand new version of StoryShots where it allows you to use StoryShots inside Jest. Earlier we have also bundled a CLI tool which uses some of the internal modules used by Jest.

But it seems like we are building an our own Jest with that. That's why we decided to go with this approach.

If you still like to use our CLI version, use this [version](https://github.com/storybooks/storyshots/tree/v2.1.0).
(It's working but we no longer maintain it.)

### v2.1.0
8-November-2016

Default loaders support markdown file [PR56](https://github.com/kadirahq/storyshots/pull/56)

### v2.0.2
7-November-2016

* `NODE_ENV` is set to `"development"` by default [PR50](https://github.com/kadirahq/storyshots/pull/50)
* `require.context` regexp test includes the begining `./` of filenames [PR55](https://github.com/kadirahq/storyshots/pull/55)

### v2.0.1
20-October-2016

Prepare channel before reading storybook as some addons use it before running stories. [PR41](https://github.com/kadirahq/storyshots/pull/41)

### v2.0.0
11-October-2016

* Update `jest-snapshot` to version 16.0.0. [PR39](https://github.com/kadirahq/storyshots/pull/39)
* Use a directory and extension different from regular jest snapshots for storyshots. [PR40](https://github.com/kadirahq/storyshots/pull/40)

#### Migrating from 1.x.x

From version 2.0.0 by default storyshot files will be stored in a directory named `__storyshots__` (instead of `__snapshots__`) inside storybook config directory. Further storyshot files will use extension `.shot` instead of `.snap`.

These changes are important because they allow storyshots to be used with jest in the same project. See [issue#34](https://github.com/kadirahq/storyshots/issues/34) for more info.

This mean that once storyshots is updated to 2.0.0 it wont check your existing snapshots. It will create new snapshots in the new location and you can delete old ones.

To update safely, follow these steps.

1. Run your 1.x.x version of storyshots and make sure all stories pass.
2. Update storyshots. `npm install @kadira/storyshots@^2.0.0 --save-dev`
3. Delete `__snapshots__` directory and contents from your storybook config directory. Also remove it from your version control system.
4. Run updated storyshots and add the newly added `__storyshots__` directory to your version control system.

Done!

### v1.1.5
9-October-2016

Fix issue where `require.context` did not work with regexps for full path. [PR37](https://github.com/kadirahq/storyshots/pull/37)

### v1.1.4
6-October-2016

Add support for `require.context` inside storybook config module. The regression introduced in v1.1.2 is addressed. [PR33](https://github.com/kadirahq/storyshots/pull/30)

### v1.1.3
30-September-2016

v1.1.2 introduce a [regression](https://github.com/kadirahq/storyshots/pull/30#issuecomment-250805615). So this revert that version.

### v1.1.2
30-September-2016

Add support for `require.context` inside storybook config module. [PR30](https://github.com/kadirahq/storyshots/pull/30)

### v1.1.1
28-September-2016

* Watch mode Summary shows the stats for the last run only. [PR27](https://github.com/kadirahq/storyshots/pull/27)
* If some tests fail exit with status code 1. [PR28](https://github.com/kadirahq/storyshots/pull/28)

### v1.1.0
27-September-2016

Add `--exclude` flag to avoid running stories matching a given regexp. [PR24](https://github.com/kadirahq/storyshots/pull/24) [PR25](https://github.com/kadirahq/storyshots/pull/25)

### v1.0.5
25-September-2016

* Fix missing dependencies. [PR21](https://github.com/kadirahq/storyshots/pull/21)
* Context should contain only the story name. [PR20](https://github.com/kadirahq/storyshots/pull/20)

### v1.0.4

Invalid Version. Same as v1.0.3

### v1.0.3
23-September-2016

Fix a typo in the console Summary message.

### v1.0.1
22-September-2016

Fix: Allow module loaders to return something. [PR14](https://github.com/kadirahq/storyshots/pull/14)

### v1.0.1
22-September-2016

Fix a typo.

### v1.0.0
22-September-2016

Initial Release.


text:
package org.apache.cassandra.index.sasi.sa;

import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;

import org.apache.cassandra.index.Index;
import org.apache.cassandra.index.sasi.disk.OnDiskIndexBuilder;
import org.apache.cassandra.index.sasi.disk.TokenTreeBuilder;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.utils.Pair;

public class IntegralSA extends SA<ByteBuffer>
{
    public IntegralSA(AbstractType<?> comparator, OnDiskIndexBuilder.Mode mode)
    {
        super(comparator, mode);
    }

    public Term<ByteBuffer> getTerm(ByteBuffer termValue, TokenTreeBuilder tokens)
    {
        return new ByteTerm(charCount, termValue, tokens);
    }

    public TermIterator finish()
    {
        return new IntegralSuffixIterator();
    }

    private class IntegralSuffixIterator extends TermIterator
    {
        private final Iterator<Term<ByteBuffer>> termIterator;

        public IntegralSuffixIterator()
        {
            Collections.sort(terms, new Comparator<Term<?>>()
            {
                public int compare(Term<?> a, Term<?> b)
                {
                    return a.compareTo(comparator, b);
                }
            });

            termIterator = terms.iterator();
        }

        public ByteBuffer minTerm()
        {
            return terms.get(0).getTerm();
        }

        public ByteBuffer maxTerm()
        {
            return terms.get(terms.size() - 1).getTerm();
        }

        protected Pair<IndexedTerm, TokenTreeBuilder> computeNext()
        {
            if (!termIterator.hasNext())
                return endOfData();

            Term<ByteBuffer> term = termIterator.next();
            return Pair.create(new IndexedTerm(term.getTerm(), false), term.getTokens().finish());
        }
    }
}


text:
define(['jquery', 'knockout'], function($, ko) {
    ko.bindingHandlers.scrollSlide = {
        init: function(element, valueAccessor) {
            console.log("init")
            var options = valueAccessor();
            var newValueAccessor = function() {
                return function() {
                    options.action.apply(context, options.params);
                };
            };
            ko.bindingHandlers.click.init(element, newValueAccessor, allBindingsAccessor, context);
        },
        update: function(element, valueAccessor) {
            console.log("update")
            console.log($(element))
        }
    };
});


text:
// This file is automatically generated.

package adila.db;

/*
 * Alcatel POP2 (4)
 *
 * DEVICE: alto4
 * MODEL: 4045A
 */
final class alto4 {
    public static final String DATA = "Alcatel|POP2 (4)|";
}


text:
'use strict';

var express = require('express') // web server
  , logger = require('morgan') // clients requests logger
  , bodyParser = require('body-parser') // body parser
  , methodOverride = require('method-override') // method overryde for clients not supporting all REST verbs
  , path = require('path') // to manipulate paths
  , config = require('./config') // application configuration
  , db = require('./models/db') // database wiring
;

// setup (TODO: define these in config.js)
var staticPathPublic = __dirname + '/..' + '/public.dist'; // path to static public directory
var staticPathData = __dirname + '/..' + '/data'; // path to static data directory
var engineTemplate = 'html'; // template engine name ('jade'...)

// create express application
var app = module.exports = express();

// use modules to become RESTful
app.use(bodyParser.urlencoded({ extended: true })); // only parse urlencoded bodies
app.use(bodyParser.json()); // only parse JSON
app.use(methodOverride()); // override with the X-HTTP-Method-Override header in the request

// enable cross origin resource sharing
// TODO: do we really need this? (only if deploying client apps on different domain from server, perhaps...)
/* TODO: test if with no CORS it works o.k.... */
app.all('/*', function(req, res, next) {
  // CORS headers
  res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  // set custom headers for CORS
  res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key');
  if (req.method == 'OPTIONS') {
    res.status(200).end();
  } else {
    next();
  }
});

// auth middleware: this will check if the token is valid;
// only the requests that start with /api/* will be checked for the token;
// any URLs that do not follow the below pattern will be accessible without authentication
app.all('/api/*', [ require('./middlewares/validateRequest') ]);

// versions handling
app.use(function(req, res, next) { // explicit version requested
  if (req.url.match(/\/api\/v0\//)) { // explicit unsupported version requested: moved permanently
    res.status(301);
    res.json({ error: 'moved permanently' });
  } else
  if (req.url.match(/\/api\/v1\//)) { // explicit supported version requested: alias to no version url
    req.url = req.url.replace(/(\/api\/)v1\//g, '\$1');
  }
  next();
});

// authentication routes
app.use('/auth', require('./routes/auth'));

// server routes
app.use('/api/users', require('./routes/users'));
app.use('/api/persons', require('./routes/persons'));
app.use('/api/providers', require('./routes/providers'));
app.use('/api/places', require('./routes/places'));
app.use('/api/reviews', require('./routes/reviews'));
app.use('/api/tracesImage', require('./routes/tracesImage'));
app.use('/api/tracesPhone', require('./routes/tracesPhone'));

// public routes
app.use(express.static(staticPathPublic));
app.use(express.static(staticPathData));
//app.set('views', pathViews);
//app.set('view engine', engineTemplate);

// error handling
app.use('/api/*', function(req, res, next) { // unforeseen request
  var status = 404;
  res.status(status);
  res.json({ status: status, error: 'API path ' + req.originalUrl + ' not found' });
});

/*
// static resource request
app.use('/static/*', function(req, res, next) {
console.log('STATIC req.originalUrl:', req.originalUrl);
/*
  baseUrl: '/static/geo.html',
  originalUrl: '/static/geo.html?country=ru',
  _parsedUrl:
   Url {
     protocol: null,
     slashes: null,
     auth: null,
     host: null,
     port: null,
     hostname: null,
     hash: null,
     search: '?country=ru',
     query: 'country=ru',
     pathname: '/static/geo.html',
     path: '/static/geo.html?country=ru',
     href: '/static/geo.html?country=ru',
     _raw: '/static/geo.html?country=ru' },
  params: { '0': 'geo.html' },
  query: { country: 'ru' },
* /
  res.sendFile(req.originalUrl, { root: staticPathPublic });
});
*/

// all other (client) requests go to frontend routes
app.use(function(req, res, next) {
  res.sendFile('index.html', { root: staticPathPublic });
});


text:
BSLS_IDENT("$Id: $")

//@PURPOSE: Provide a component for generating test array types.
//
//@CLASSES:
//  s_baltst::GenerateTestArray: generate test array
//  s_baltst::GenerateTestArrayPlaceHolder: generate test array placeholder

#include <s_baltst_testarrayutil.h>
#include <s_baltst_testplaceholder.h>

#include <bsl_vector.h>

namespace BloombergLP {
namespace s_baltst {

                          // =======================
                          // class GenerateTestArray
                          // =======================

class GenerateTestArray {
    // This class provides a function object whose function call operator can
    // be used to generate objects of specializations of 'bsl::vector'.

  public:
    // TYPES
    typedef TestArrayUtil Util;

    // CREATORS
    GenerateTestArray();

    // ACCESSORS
    template <class VALUE_TYPE>
    bsl::vector<VALUE_TYPE> operator()(
                                     const TestPlaceHolder<VALUE_TYPE>&) const;

    template <class VALUE_TYPE>
    bsl::vector<VALUE_TYPE> operator()(const VALUE_TYPE& value) const;

    template <class VALUE_TYPE>
    bsl::vector<VALUE_TYPE> operator()(const VALUE_TYPE& value0,
                                       const VALUE_TYPE& value1) const;

    template <class VALUE_TYPE>
    bsl::vector<VALUE_TYPE> operator()(const VALUE_TYPE& value0,
                                       const VALUE_TYPE& value1,
                                       const VALUE_TYPE& value2) const;
};

                     // ==================================
                     // class GenerateTestArrayPlaceHolder
                     // ==================================

class GenerateTestArrayPlaceHolder {
    // This class provides a function object whose function call operator can
    // be used to generate 'TestPlaceHolder' specializations for 'bsl::vector'
    // types.

  public:
    // TYPES
    typedef TestArrayUtil Util;

    // CREATORS
    GenerateTestArrayPlaceHolder();

    // ACCESSORS
    template <class VALUE_TYPE>
    TestPlaceHolder<bsl::vector<VALUE_TYPE> > operator()(
                                     const TestPlaceHolder<VALUE_TYPE>&) const;
};

// ============================================================================
//                            INLINE DEFINITIONS
// ============================================================================

                          // -----------------------
                          // class GenerateTestArray
                          // -----------------------

// CREATORS
GenerateTestArray::GenerateTestArray()
{
}

// ACCESSORS
template <class VALUE_TYPE>
bsl::vector<VALUE_TYPE> GenerateTestArray::operator()(
                                      const TestPlaceHolder<VALUE_TYPE>&) const
{
    return Util::generate(TestPlaceHolder<VALUE_TYPE>());
}

template <class VALUE_TYPE>
bsl::vector<VALUE_TYPE> GenerateTestArray::operator()(
                                                 const VALUE_TYPE& value) const
{
    return Util::generate(value);
}

template <class VALUE_TYPE>
bsl::vector<VALUE_TYPE> GenerateTestArray::operator()(
                                                const VALUE_TYPE& value0,
                                                const VALUE_TYPE& value1) const
{
    return Util::generate(value0, value1);
}

template <class VALUE_TYPE>
bsl::vector<VALUE_TYPE> GenerateTestArray::operator()(
                                                const VALUE_TYPE& value0,
                                                const VALUE_TYPE& value1,
                                                const VALUE_TYPE& value2) const
{
    return Util::generate(value0, value1, value2);
}

                     // ----------------------------------
                     // class GenerateTestArrayPlaceHolder
                     // ----------------------------------

// CREATORS
GenerateTestArrayPlaceHolder::GenerateTestArrayPlaceHolder()
{
}

// ACCESSORS
template <class VALUE_TYPE>
TestPlaceHolder<bsl::vector<VALUE_TYPE> >
GenerateTestArrayPlaceHolder::operator()(
                                      const TestPlaceHolder<VALUE_TYPE>&) const
{
    return TestPlaceHolder<bsl::vector<VALUE_TYPE> >();
}

}  // close package namespace
}  // close enterprise namespace

#endif // INCLUDED_S_BALTST_GENERATETESTARRAY

// ----------------------------------------------------------------------------
// Copyright 2021 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------


text:
define(function(require) {

  var Marionette = require("marionette");
  var Backbone = require("backbone");
  var Vent = require("vent");
  var Setting = require("lib/settings");

  if (window.Komanda) {
    return window.Komanda;
  }

  window.Komanda = new Marionette.Application();

  window.Komanda.vent = Vent;

  if (!window.Komanda.hasOwnProperty("store")) {
    window.Komanda.store = {};
  }

  window.requireJS = window.require;

  return window.Komanda;
});