text:
Views
=====

Views are part of the [MVC](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) architecture.
They are code responsible for presenting data to end users. In a Web application, views are usually created
in terms of *view templates* which are PHP script files containing mainly HTML code and presentational PHP code.
They are managed by the [[yii\web\View|view]] [application component](structure-application-components.md) which provides commonly used methods
to facilitate view composition and rendering. For simplicity, we often call view templates or view template files
as views.

## Creating Views

As aforementioned, a view is simply a PHP script mixed with HTML and PHP code. The following is the view
that presents a login form. As you can see, PHP code is used to generate the dynamic content, such as the
page title and the form, while HTML code organizes them into a presentable HTML page.

```php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $form yii\widgets\ActiveForm */
/* @var $model app\models\LoginForm */

$this->title = 'Login';
?>
<h1><?= Html::encode($this->title) ?></h1>

<p>Please fill out the following fields to login:</p>

<?php $form = ActiveForm::begin(); ?>
    <?= $form->field($model, 'username') ?>
    <?= $form->field($model, 'password')->passwordInput() ?>
    <?= Html::submitButton('Login') ?>
<?php ActiveForm::end(); ?>
```

Within a view, you can access `$this` which refers to the [[yii\web\View|view component]] managing
and rendering this view template.

Besides `$this`, there may be other predefined variables in a view, such as `$model` in the above
example. These variables represent the data that are *pushed* into the view by [controllers](structure-controllers.md)
or other objects which trigger the [view rendering](#rendering-views).

> Tip: The predefined variables are listed in a comment block at beginning of a view so that they can
  be recognized by IDEs. It is also a good way of documenting your views.

### Security

When creating views that generate HTML pages, it is important that you encode and/or filter the data coming
from end users before presenting them. Otherwise, your application may be subject to
[cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting) attacks.

To display a plain text, encode it first by calling [[yii\helpers\Html::encode()]]. For example, the following code
encodes the user name before displaying it:

```php
<?php
use yii\helpers\Html;
?>

<div class="username">
    <?= Html::encode($user->name) ?>
</div>
```

To display HTML content, use [[yii\helpers\HtmlPurifier]] to filter the content first. For example, the following
code filters the post content before displaying it:

```php
<?php
use yii\helpers\HtmlPurifier;
?>

<div class="post">
    <?= HtmlPurifier::process($post->text) ?>
</div>
```

> Tip: While HTMLPurifier does excellent job in making output safe, it is not fast. You should consider
  [caching](caching-overview.md) the filtering result if your application requires high performance.

### Organizing Views

Like [controllers](structure-controllers.md) and [models](structure-models.md), there are conventions to organize views.

* For views rendered by a controller, they should be put under the directory `@app/views/ControllerID` by default,
  where `ControllerID` refers to the [controller ID](structure-controllers.md#routes). For example, if
  the controller class is `PostController`, the directory would be `@app/views/post`; If it is `PostCommentController`,
  the directory would be `@app/views/post-comment`. In case the controller belongs to a module, the directory
  would be `views/ControllerID` under the [[yii\base\Module::basePath|module directory]].
* For views rendered in a [widget](structure-widgets.md), they should be put under the `WidgetPath/views` directory by
  default, where `WidgetPath` stands for the directory containing the widget class file.
* For views rendered by other objects, it is recommended that you follow the similar convention as that for widgets.

You may customize these default view directories by overriding the [[yii\base\ViewContextInterface::getViewPath()]]
method of controllers or widgets.

## Rendering Views

You can render views in [controllers](structure-controllers.md), [widgets](structure-widgets.md), or any
other places by calling view rendering methods. These methods share a similar signature shown as follows,

```
/**
 * @param string $view view name or file path, depending on the actual rendering method
 * @param array $params the data to be passed to the view
 * @return string rendering result
 */
methodName($view, $params = [])
```

### Rendering in Controllers

Within [controllers](structure-controllers.md), you may call the following controller methods to render views:

* [[yii\base\Controller::render()|render()]]: renders a [named view](#named-views) and applies a [layout](#layouts)
  to the rendering result.
* [[yii\base\Controller::renderPartial()|renderPartial()]]: renders a [named view](#named-views) without any layout.
* [[yii\web\Controller::renderAjax()|renderAjax()]]: renders a [named view](#named-views) without any layout,
  and injects all registered JS/CSS scripts and files. It is usually used in response to AJAX Web requests.
* [[yii\base\Controller::renderFile()|renderFile()]]: renders a view specified in terms of a view file path or
  [alias](concept-aliases.md).
* [[yii\base\Controller::renderContent()|renderContent()]]: renders a static string by embedding it into
  the currently applicable [layout](#layouts). This method is available since version 2.0.1.

For example,

```php
namespace app\controllers;

use Yii;
use app\models\Post;
use yii\web\Controller;
use yii\web\NotFoundHttpException;

class PostController extends Controller
{
    public function actionView($id)
    {
        $model = Post::findOne($id);
        if ($model === null) {
            throw new NotFoundHttpException;
        }

        // renders a view named "view" and applies a layout to it
        return $this->render('view', [
            'model' => $model,
        ]);
    }
}
```

### Rendering in Widgets

Within [widgets](structure-widgets.md), you may call the following widget methods to render views.

* [[yii\base\Widget::render()|render()]]: renders a [named view](#named-views).
* [[yii\base\Widget::renderFile()|renderFile()]]: renders a view specified in terms of a view file path or
  [alias](concept-aliases.md).

For example,

```php
namespace app\components;

use yii\base\Widget;
use yii\helpers\Html;

class ListWidget extends Widget
{
    public $items = [];

    public function run()
    {
        // renders a view named "list"
        return $this->render('list', [
            'items' => $this->items,
        ]);
    }
}
```

### Rendering in Views

You can render a view within another view by calling one of the following methods provided by the [[yii\base\View|view component]]:

* [[yii\base\View::render()|render()]]: renders a [named view](#named-views).
* [[yii\web\View::renderAjax()|renderAjax()]]: renders a [named view](#named-views) and injects all registered
  JS/CSS scripts and files. It is usually used in response to AJAX Web requests.
* [[yii\base\View::renderFile()|renderFile()]]: renders a view specified in terms of a view file path or
  [alias](concept-aliases.md).

For example, the following code in a view renders the `_overview.php` view file which is in the same directory
as the view being currently rendered. Remember that `$this` in a view refers to the [[yii\base\View|view]] component:

```php
<?= $this->render('_overview') ?>
```

### Rendering in Other Places

In any place, you can get access to the [[yii\base\View|view]] application component by the expression
`Yii::$app->view` and then call its aforementioned methods to render a view. For example,

```php
// displays the view file "@app/views/site/license.php"
echo \Yii::$app->view->renderFile('@app/views/site/license.php');
```

### Named Views

When you render a view, you can specify the view using either a view name or a view file path/alias. In most cases,
you would use the former because it is more concise and flexible. We call views specified using names as *named views*.

A view name is resolved into the corresponding view file path according to the following rules:

* A view name may omit the file extension name. In this case, `.php` will be used as the extension. For example,
  the view name `about` corresponds to the file name `about.php`.
* If the view name starts with double slashes `//`, the corresponding view file path would be `@app/views/ViewName`.
  That is, the view is looked for under the [[yii\base\Application::viewPath|application's view path]].
  For example, `//site/about` will be resolved into `@app/views/site/about.php`.
* If the view name starts with a single slash `/`, the view file path is formed by prefixing the view name
  with the [[yii\base\Module::viewPath|view path]] of the currently active [module](structure-modules.md).
  If there is no active module, `@app/views/ViewName` will be used. For example, `/user/create` will be resolved into
  `@app/modules/user/views/user/create.php`, if the currently active module is `user`. If there is no active module,
  the view file path would be `@app/views/user/create.php`.
* If the view is rendered with a [[yii\base\View::context|context]] and the context implements [[yii\base\ViewContextInterface]],
  the view file path is formed by prefixing the [[yii\base\ViewContextInterface::getViewPath()|view path]] of the
  context to the view name. This mainly applies to the views rendered within controllers and widgets. For example,
  `about` will be resolved into `@app/views/site/about.php` if the context is the controller `SiteController`.
* If a view is rendered within another view, the directory containing the other view file will be prefixed to
  the new view name to form the actual view file path. For example, `item` will be resolved into `@app/views/post/item.php`
  if it is being rendered in the view `@app/views/post/index.php`.

According to the above rules, calling `$this->render('view')` in a controller `app\controllers\PostController` will
actually render the view file `@app/views/post/view.php`, while calling `$this->render('_overview')` in that view
will render the view file `@app/views/post/_overview.php`.

### Accessing Data in Views

There are two approaches to access data within a view: push and pull.

By passing the data as the second parameter to the view rendering methods, you are using the push approach.
The data should be represented as an array of name-value pairs. When the view is being rendered, the PHP
`extract()` function will be called on this array so that the array is extracted into variables in the view.
For example, the following view rendering code in a controller will push two variables to the `report` view:
`$foo = 1` and `$bar = 2`.

```php
echo $this->render('report', [
    'foo' => 1,
    'bar' => 2,
]);
```

The pull approach actively retrieves data from the [[yii\base\View|view component]] or other objects accessible
in views (e.g. `Yii::$app`). Using the code below as an example, within the view you can get the controller object
by the expression `$this->context`. And as a result, it is possible for you to access any properties or methods
of the controller in the `report` view, such as the controller ID shown in the following:

```php
The controller ID is: <?= $this->context->id ?>
```

The push approach is usually the preferred way of accessing data in views, because it makes views less dependent
on context objects. Its drawback is that you need to manually build the data array all the time, which could
become tedious and error prone if a view is shared and rendered in different places.

### Sharing Data among Views

The [[yii\base\View|view component]] provides the [[yii\base\View::params|params]] property that you can use
to share data among views.

For example, in an `about` view, you can have the following code which specifies the current segment of the
breadcrumbs.

```php
$this->params['breadcrumbs'][] = 'About Us';
```

Then, in the [layout](#layouts) file, which is also a view, you can display the breadcrumbs using the data
passed along [[yii\base\View::params|params]]:

```php
<?= yii\widgets\Breadcrumbs::widget([
    'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]) ?>
```

## Layouts

Layouts are a special type of views that represent the common parts of multiple views. For example, the pages
for most Web applications share the same page header and footer. While you can repeat the same page header and footer
in every view, a better way is to do this once in a layout and embed the rendering result of a content view at
an appropriate place in the layout.

### Creating Layouts

Because layouts are also views, they can be created in the similar way as normal views. By default, layouts
are stored in the directory `@app/views/layouts`. For layouts used within a [module](structure-modules.md),
they should be stored in the `views/layouts` directory under the [[yii\base\Module::basePath|module directory]].
You may customize the default layout directory by configuring the [[yii\base\Module::layoutPath]] property of
the application or modules.

The following example shows how a layout looks like. Note that for illustrative purpose, we have greatly simplified
the code in the layout. In practice, you may want to add more content to it, such as head tags, main menu, etc.

```php
<?php
use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $content string */
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <?= Html::csrfMetaTags() ?>
    <title><?= Html::encode($this->title) ?></title>
    <?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
    <header>My Company</header>
    <?= $content ?>
    <footer>© 2014 by My Company</footer>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
```

As you can see, the layout generates the HTML tags that are common to all pages. Within the `<body>` section,
the layout echoes the `$content` variable which represents the rendering result of content views and is pushed
into the layout when [[yii\base\Controller::render()]] is called.

Most layouts should call the following methods like shown in the above code. These methods mainly trigger events
about the rendering process so that scripts and tags registered in other places can be properly injected into
the places where these methods are called.

- [[yii\base\View::beginPage()|beginPage()]]: This method should be called at the very beginning of the layout.
  It triggers the [[yii\base\View::EVENT_BEGIN_PAGE|EVENT_BEGIN_PAGE]] event which indicates the beginning of a page.
- [[yii\base\View::endPage()|endPage()]]: This method should be called at the end of the layout.
  It triggers the [[yii\base\View::EVENT_END_PAGE|EVENT_END_PAGE]] event which indicates the end of a page.
- [[yii\web\View::head()|head()]]: This method should be called within the `<head>` section of an HTML page.
  It generates a placeholder which will be replaced with the registered head HTML code (e.g. link tags, meta tags)
  when a page finishes rendering.
- [[yii\web\View::beginBody()|beginBody()]]: This method should be called at the beginning of the `<body>` section.
  It triggers the [[yii\web\View::EVENT_BEGIN_BODY|EVENT_BEGIN_BODY]] event and generates a placeholder which will
  be replaced by the registered HTML code (e.g. JavaScript) targeted at the body begin position.
- [[yii\web\View::endBody()|endBody()]]: This method should be called at the end of the `<body>` section.
  It triggers the [[yii\web\View::EVENT_END_BODY|EVENT_END_BODY]] event and generates a placeholder which will
  be replaced by the registered HTML code (e.g. JavaScript) targeted at the body end position.

### Accessing Data in Layouts

Within a layout, you have access to two predefined variables: `$this` and `$content`. The former refers to
the [[yii\base\View|view]] component, like in normal views, while the latter contains the rendering result of a content
view which is rendered by calling the [[yii\base\Controller::render()|render()]] method in controllers.

If you want to access other data in layouts, you have to use the pull method as described in
the [Accessing Data in Views](#accessing-data-in-views) subsection. If you want to pass data from a content view
to a layout, you may use the method described in the [Sharing Data among Views](#sharing-data-among-views) subsection.

### Using Layouts

As described in the [Rendering in Controllers](#rendering-in-controllers) subsection, when you render a view
by calling the [[yii\base\Controller::render()|render()]] method in a controller, a layout will be applied
to the rendering result. By default, the layout `@app/views/layouts/main.php` will be used.

You may use a different layout by configuring either [[yii\base\Application::layout]] or [[yii\base\Controller::layout]].
The former governs the layout used by all controllers, while the latter overrides the former for individual controllers.
For example, the following code makes the `post` controller to use `@app/views/layouts/post.php` as the layout
when rendering its views. Other controllers, assuming their `layout` property is untouched, will still use the default
`@app/views/layouts/main.php` as the layout.

```php
namespace app\controllers;

use yii\web\Controller;

class PostController extends Controller
{
    public $layout = 'post';

    // ...
}
```

For controllers belonging to a module, you may also configure the module's [[yii\base\Module::layout|layout]] property to
use a particular layout for these controllers.

Because the `layout` property may be configured at different levels (controllers, modules, application),
behind the scene Yii takes two steps to determine what is the actual layout file being used for a particular controller.

In the first step, it determines the layout value and the context module:

- If the [[yii\base\Controller::layout]] property of the controller is not null, use it as the layout value and
  the [[yii\base\Controller::module|module]] of the controller as the context module.
- If [[yii\base\Controller::layout|layout]] is null, search through all ancestor modules (including the application itself) of the controller and
  find the first module whose [[yii\base\Module::layout|layout]] property is not null. Use that module and
  its [[yii\base\Module::layout|layout]] value as the context module and the chosen layout value.
  If such a module cannot be found, it means no layout will be applied.

In the second step, it determines the actual layout file according to the layout value and the context module
determined in the first step. The layout value can be:

- a path alias (e.g. `@app/views/layouts/main`).
- an absolute path (e.g. `/main`): the layout value starts with a slash. The actual layout file will be
  looked for under the application's [[yii\base\Application::layoutPath|layout path]] which defaults to
  `@app/views/layouts`.
- a relative path (e.g. `main`): the actual layout file will be looked for under the context module's
  [[yii\base\Module::layoutPath|layout path]] which defaults to the `views/layouts` directory under the
  [[yii\base\Module::basePath|module directory]].
- the boolean value `false`: no layout will be applied.

If the layout value does not contain a file extension, it will use the default one `.php`.

### Nested Layouts

Sometimes you may want to nest one layout in another. For example, in different sections of a Web site, you
want to use different layouts, while all these layouts share the same basic layout that generates the overall
HTML5 page structure. You can achieve this goal by calling [[yii\base\View::beginContent()|beginContent()]] and
[[yii\base\View::endContent()|endContent()]] in the child layouts like the following:

```php
<?php $this->beginContent('@app/views/layouts/base.php'); ?>

...child layout content here...

<?php $this->endContent(); ?>
```

As shown above, the child layout content should be enclosed within [[yii\base\View::beginContent()|beginContent()]] and
[[yii\base\View::endContent()|endContent()]]. The parameter passed to [[yii\base\View::beginContent()|beginContent()]]
specifies what is the parent layout. It can be either a layout file or alias.

Using the above approach, you can nest layouts in more than one levels.

### Using Blocks

Blocks allow you to specify the view content in one place while displaying it in another. They are often used together
with layouts. For example, you can define a block in a content view and display it in the layout.

You call [[yii\base\View::beginBlock()|beginBlock()]] and [[yii\base\View::endBlock()|endBlock()]] to define a block.
The block can then be accessed via `$view->blocks[$blockID]`, where `$blockID` stands for a unique ID that you assign
to the block when defining it.

The following example shows how you can use blocks to customize specific parts of a layout in a content view.

First, in a content view, define one or multiple blocks:

```php
...

<?php $this->beginBlock('block1'); ?>

...content of block1...

<?php $this->endBlock(); ?>

...

<?php $this->beginBlock('block3'); ?>

...content of block3...

<?php $this->endBlock(); ?>
```

Then, in the layout view, render the blocks if they are available, or display some default content if a block is
not defined.

```php
...
<?php if (isset($this->blocks['block1'])): ?>
    <?= $this->blocks['block1'] ?>
<?php else: ?>
    ... default content for block1 ...
<?php endif; ?>

...

<?php if (isset($this->blocks['block2'])): ?>
    <?= $this->blocks['block2'] ?>
<?php else: ?>
    ... default content for block2 ...
<?php endif; ?>

...

<?php if (isset($this->blocks['block3'])): ?>
    <?= $this->blocks['block3'] ?>
<?php else: ?>
    ... default content for block3 ...
<?php endif; ?>
...
```

## Using View Components

[[yii\base\View|View components]] provides many view-related features. While you can get view components
by creating individual instances of [[yii\base\View]] or its child class, in most cases you will mainly use
the `view` application component. You can configure this component in [application configurations](structure-applications.md#application-configurations)
like the following:

```php
[
    // ...
    'components' => [
        'view' => [
            'class' => 'app\components\View',
        ],
        // ...
    ],
]
```

View components provide the following useful view-related features, each described in more details in a separate section:

* [theming](output-theming.md): allows you to develop and change the theme for your Web site.
* [fragment caching](caching-fragment.md): allows you to cache a fragment within a Web page.
* [client script handling](output-client-scripts.md): supports CSS and JavaScript registration and rendering.
* [asset bundle handling](structure-assets.md): supports registering and rendering of [asset bundles](structure-assets.md).
* [alternative template engines](tutorial-template-engines.md): allows you to use other template engines, such as
  [Twig](http://twig.sensiolabs.org/), [Smarty](http://www.smarty.net/).

You may also frequently use the following minor yet useful features when you are developing Web pages.

### Setting Page Titles

Every Web page should have a title. Normally the title tag is being displayed in a [layout](#layouts). However, in practice
the title is often determined in content views rather than layouts. To solve this problem, [[yii\web\View]] provides
the [[yii\web\View::title|title]] property for you to pass the title information from content views to layouts.

To make use of this feature, in each content view, you can set the page title like the following:

```php
<?php
$this->title = 'My page title';
?>
```

Then in the layout, make sure you have the following code in the `<head>` section:

```php
<title><?= Html::encode($this->title) ?></title>
```

### Registering Meta Tags

Web pages usually need to generate various meta tags needed by different parties. Like page titles, meta tags
appear in the `<head>` section and are usually generated in layouts.

If you want to specify what meta tags to generate in content views, you can call [[yii\web\View::registerMetaTag()]]
in a content view, like the following:

```php
<?php
$this->registerMetaTag(['name' => 'keywords', 'content' => 'yii, framework, php']);
?>
```

The above code will register a "keywords" meta tag with the view component. The registered meta tag is
rendered after the layout finishes rendering. The following HTML code will be generated and inserted
at the place where you call [[yii\web\View::head()]] in the layout:

```php
<meta name="keywords" content="yii, framework, php">
```

Note that if you call [[yii\web\View::registerMetaTag()]] multiple times, it will register multiple meta tags,
regardless whether the meta tags are the same or not.

To make sure there is only a single instance of a meta tag type, you can specify a key as a second parameter when calling the method.
For example, the following code registers two "description" meta tags. However, only the second one will be rendered.

```html
$this->registerMetaTag(['name' => 'description', 'content' => 'This is my cool website made with Yii!'], 'description');
$this->registerMetaTag(['name' => 'description', 'content' => 'This website is about funny raccoons.'], 'description');
```

### Registering Link Tags

Like [meta tags](#registering-meta-tags), link tags are useful in many cases, such as customizing favicon, pointing to
RSS feed or delegating OpenID to another server. You can work with link tags in the similar way as meta tags
by using [[yii\web\View::registerLinkTag()]]. For example, in a content view, you can register a link tag like follows,

```php
$this->registerLinkTag([
    'title' => 'Live News for Yii',
    'rel' => 'alternate',
    'type' => 'application/rss+xml',
    'href' => 'http://www.yiiframework.com/rss.xml/',
]);
```

The code above will result in

```html
<link title="Live News for Yii" rel="alternate" type="application/rss+xml" href="http://www.yiiframework.com/rss.xml/">
```

Similar as [[yii\web\View::registerMetaTag()|registerMetaTags()]], you can specify a key when calling
[[yii\web\View::registerLinkTag()|registerLinkTag()]] to avoid generating repeated link tags.

## View Events

[[yii\base\View|View components]] trigger several events during the view rendering process. You may respond
to these events to inject content into views or process the rendering results before they are sent to end users.

- [[yii\base\View::EVENT_BEFORE_RENDER|EVENT_BEFORE_RENDER]]: triggered at the beginning of rendering a file
  in a controller. Handlers of this event may set [[yii\base\ViewEvent::isValid]] to be false to cancel the rendering process.
- [[yii\base\View::EVENT_AFTER_RENDER|EVENT_AFTER_RENDER]]: triggered after rendering a file by the call of [[yii\base\View::afterRender()]].
  Handlers of this event may obtain the rendering result through [[yii\base\ViewEvent::output]] and may modify
  this property to change the rendering result.
- [[yii\base\View::EVENT_BEGIN_PAGE|EVENT_BEGIN_PAGE]]: triggered by the call of [[yii\base\View::beginPage()]] in layouts.
- [[yii\base\View::EVENT_END_PAGE|EVENT_END_PAGE]]: triggered by the call of [[yii\base\View::endPage()]] in layouts.
- [[yii\web\View::EVENT_BEGIN_BODY|EVENT_BEGIN_BODY]]: triggered by the call of [[yii\web\View::beginBody()]] in layouts.
- [[yii\web\View::EVENT_END_BODY|EVENT_END_BODY]]: triggered by the call of [[yii\web\View::endBody()]] in layouts.

For example, the following code injects the current date at the end of the page body:

```php
\Yii::$app->view->on(View::EVENT_END_BODY, function () {
    echo date('Y-m-d');
});
```

## Rendering Static Pages

Static pages refer to those Web pages whose main content are mostly static without the need of accessing
dynamic data pushed from controllers.

You can output static pages by putting their code in the view, and then using the code like the following in a controller:

```php
public function actionAbout()
{
    return $this->render('about');
}
```

If a Web site contains many static pages, it would be very tedious repeating the similar code many times.
To solve this problem, you may introduce a [standalone action](structure-controllers.md#standalone-actions)
called [[yii\web\ViewAction]] in a controller. For example,

```php
namespace app\controllers;

use yii\web\Controller;

class SiteController extends Controller
{
    public function actions()
    {
        return [
            'page' => [
                'class' => 'yii\web\ViewAction',
            ],
        ];
    }
}
```

Now if you create a view named `about` under the directory `@app/views/site/pages`, you will be able to
display this view by the following URL:

```
http://localhost/index.php?r=site/page&view=about
```

The `GET` parameter `view` tells [[yii\web\ViewAction]] which view is requested. The action will then look
for this view under the directory `@app/views/site/pages`. You may configure [[yii\web\ViewAction::viewPrefix]]
to change the directory for searching these views.

## Best Practices

Views are responsible for presenting models in the format that end users desire. In general, views

* should mainly contain presentational code, such as HTML, and simple PHP code to traverse, format and render data.
* should not contain code that performs DB queries. Such code should be done in models.
* should avoid direct access to request data, such as `$_GET`, `$_POST`. This belongs to controllers.
  If request data is needed, they should be pushed into views by controllers.
* may read model properties, but should not modify them.

To make views more manageable, avoid creating views that are too complex or contain too much redundant code.
You may use the following techniques to achieve this goal:

* use [layouts](#layouts) to represent common presentational sections (e.g. page header, footer).
* divide a complicated view into several smaller ones. The smaller views can be rendered and assembled into a bigger
  one using the rendering methods that we have described.
* create and use [widgets](structure-widgets.md) as building blocks of views.
* create and use helper classes to transform and format data in views.


text:
require 'spec_helper'
describe CitiesController do
  render_views

  before :each do
    City.all.each { |u| u.remove }
    @city = FactoryGirl.create :sf
    @city.is_feature = true
    @city.save
    @rio = FactoryGirl.create :rio
    @rio.is_feature = true
    @rio.save
    @city_3 = FactoryGirl.create :maputo

    User.all.each { |f| f.remove }
    @user = FactoryGirl.create :user

    Report.all.each { |r| r.remove }
    @feature_pt_1 = FactoryGirl.create :feature_pt_1
    @feature_ru_1 = FactoryGirl.create :feature_ru_1
    @report = FactoryGirl.create :report

    Gallery.all.each { |g| g.remove }
    @gallery = FactoryGirl.create :gallery

    setup_photos
    @photo = Photo.all.first

    setup_cities

    verbosity = $-v
    $-v = nil
  end

  describe '#index' do
    it 'GETs english index & GLOBALS' do
      setup_sites

      get :index
      response.should be_success
      response.should render_template( 'empty' )
      assigns( :site ).should_not eql nil
      assigns( :domain ).should_not eql nil
    end

    it 'GETs json' do
      City.all.each { |c| ( c.is_feature = true ) && c.save }
      get :index, :format => :json
      response.should be_success
      results = JSON.parse(response.body)
      results.length.should >= 1
      results.each_with_index do |item, idx|
        unless results.length == idx+1
          results[idx]['name'].should <= results[idx+1]['name']
        end
      end
    end
  end

  describe '#profile (show)' do
    it 'has reports, events, galleries, current_users and videos as JSON' do
      get :profile, :cityname => @city.cityname, :format => :json
      response.should be_success
      result = JSON.parse( response.body )
      result['j_galleries'].should eql []
      result['events'].should eql []
      result['j_reports'].should eql []
      result['j_users'].should eql []
      result['videos'].should eql []
      result['venues'].should eql []
    end
  end

end

redpajama_set_name: RedPajamaGithub


text:
package uk.me.graphe.server.database;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import uk.me.graphe.server.database.dbitems.*;
import uk.me.graphe.shared.graphmanagers.OTGraphManager2d;
import uk.me.graphe.shared.graphmanagers.OTGraphManagerFactory;
import uk.me.graphe.shared.graphmanagers.OTStyleGraphManager2d;
import uk.me.graphe.shared.jsonwrapper.JSONException;
import uk.me.graphe.shared.jsonwrapper.JSONImplHolder;
import uk.me.graphe.shared.jsonwrapper.JSONObject;
import uk.me.graphe.shared.messages.Message;
import uk.me.graphe.shared.messages.MessageFactory;
import uk.me.graphe.shared.messages.operations.CompositeOperation;
import uk.me.graphe.shared.messages.operations.GraphOperation;

import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.UpdateOperations;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;

public class DatabaseImpl implements Database{

    private Mongo mMongo;
    private Morphia mMorphia = new Morphia();
    private Datastore mData;
    DBCollection mCollection;

    public DatabaseImpl () {
        try {
            mMongo = new Mongo();
        } catch (UnknownHostException e) {
            return;
        }
        mData = mMorphia.createDatastore(mMongo, "graphs");
        mCollection = mMongo.getDB("graphs").getCollection("OTGraphManager2dStore");
    }

    @Override
    public void delete(int key) {
        mData.delete(mData.createQuery(OTGraphManager2dStore.class).filter("id =", key));
    }

    @Override
    public void clean() {
        mCollection.drop();
    }

    @Override
    public int size() {
        return (int) mCollection.getCount();
    }

    @Override
    public OTStyleGraphManager2d retrieve(int key) {
        //  Extract OtGraphManagerStore from DB
        List<OTGraphManager2dStore> retrieves = mData.find(OTGraphManager2dStore.class, "id =", key).asList();
        if (retrieves == null || retrieves.size() != 1)
            return null;
        OTGraphManager2dStore retrieve = retrieves.get(0);
        List<JSONObject> objects = new LinkedList<JSONObject>();
        List<Message> messages = null;

        OTStyleGraphManager2d toReturn = OTGraphManagerFactory.newInstance(key);
        toReturn.setStateId(retrieve.getStateid());
        toReturn.setName(retrieve.getName());

        if (retrieve.getmOps() == null) {
    		return toReturn;
        }
        for (String s : retrieve.getmOps()) {
            do {
                String toStrip = s.substring(s.indexOf('{'), s.indexOf('}')+1);
                String st = "";
                for (int i=0; i < toStrip.length(); i++)
                    if (toStrip.charAt(i) != '\\')
                        st += toStrip.charAt(i);
                JSONObject item = parseItem(st);
                System.out.println("Parsing: " + st +" to " + item);
                objects.add(item);
                s = s.substring(s.indexOf('}') + 1);
            } while (s.indexOf('{') != -1);
        }
        try {
            messages = MessageFactory.makeOperationsFromJson(objects);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        for (Message item : messages) {
            // Store all operations as local, map to server in restoreState()
            System.out.println("Applying operation:" + item.toJson() +" to graph");
            toReturn.applyOperation((GraphOperation) item);
        }
        System.out.println("Returning graph: " + toReturn.getGraphId());
        return toReturn;
    }

    private JSONObject parseItem (String json) {
        JSONObject object = null;
        try {
            object = JSONImplHolder.make(json) ;
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            System.out.println("Error " + json);
            e.printStackTrace();
        }
        return object;
    }

    @Override
    public int store(OTGraphManager2d manager) {

        OTGraphManager2dStore toStore = new OTGraphManager2dStore(manager);
        CompositeOperation history;
        // Check whether the graph exists in the database already
        List<OTGraphManager2dStore> retrieves = null;
        Query<OTGraphManager2dStore> exists =  mData.find(OTGraphManager2dStore.class, "id =", manager.getGraphId());
        retrieves = exists.asList();
        if (retrieves == null || retrieves.isEmpty()) {
            history = manager.getCompleteHistory();
            return newgraph(convertOperations(history), toStore);
        }
        else if (retrieves.size() > 1)
            throw new Error("Duplicate items");
        else if (retrieves.size() == 1) {
            // Check state id of update is greater than value in database
            toStore = retrieves.get(0);
            if (manager.getStateId() <= toStore.getStateid())
                return manager.getGraphId();
            history = manager.getOperationDelta(toStore.getStateid());
            return updategraph(convertOperations(history), manager.getGraphId(), manager.getStateId());
        }
        else {
            history = manager.getCompleteHistory();
            return newgraph(convertOperations(history), toStore);
        }
    }

    private int newgraph (List<String> operations, OTGraphManager2dStore toStore) {
        toStore.setmOps(operations);
        mData.save(toStore);
        return toStore.getId();
    }

    private int updategraph (List<String> operations, int id, int newid) {
        Query<OTGraphManager2dStore> updateQuery = mData.createQuery(OTGraphManager2dStore.class).filter("id =", id);
        UpdateOperations<OTGraphManager2dStore> ops =
            mData.createUpdateOperations(OTGraphManager2dStore.class).add("mOps", operations, true).set("stateid", newid);
        mData.update(updateQuery, ops);
        return id;
    }
    private List<String> convertOperations(CompositeOperation history) {
        List<GraphOperation> operations = history.asIndividualOperations();
        List<String> storedOperations = new ArrayList<String>();
        for (GraphOperation op : operations) {
            storedOperations.add(op.toJson());
        }
        return storedOperations;
    }

	@Override
	public void rename(int id, String title) {
		Query<OTGraphManager2dStore> updateQuery = mData.createQuery(OTGraphManager2dStore.class).filter("id =", id);
        UpdateOperations<OTGraphManager2dStore> ops =
            mData.createUpdateOperations(OTGraphManager2dStore.class).set("name", title);
        mData.update(updateQuery, ops);

	}
}


text:
module Fog
  module Compute
    class Google

      class Mock

        def insert_network(network_name, ip_range, options = {})
          Fog::Mock.not_implemented
        end

      end

      class Real

        def insert_network(network_name, ip_range, options = {})
          api_method = @compute.networks.insert
          parameters = {
            'project' => @project,
          }
          body_object = {
            'name' => network_name,
            'IPv4Range' => ip_range
          }

          body_object['description'] = options[:description] if options[:description]
          body_object['gatewayIPv4'] = options[:gateway_ipv4] if options[:gateway_ipv4]

          result = self.build_result(api_method, parameters, body_object)
          response = self.build_response(result)
        end

      end

    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/drawableAnim"
            android:background="@color/anim_title_bg"
            android:text="Drawable Animation"/>

        <LinearLayout
            android:id="@+id/frameAnimLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_below="@id/drawableAnim"
            android:gravity="center_vertical"
            android:background="@color/anim_layout_bg">

            <ImageView
                android:id="@+id/foreAnim"
                android:layout_width="120dp"
                android:layout_height="150dp" />

            <ImageView
                android:id="@+id/loadingAnim"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:background="@anim/loading_anim"/>

            <ImageView
                android:layout_width="64dp"
                android:layout_height="64dp"
                android:id="@+id/googleLoadingAnim"/>

        </LinearLayout>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/viewAnim"
            android:background="@color/anim_title_bg"
            android:layout_below="@id/frameAnimLayout"
            android:text="View Animation"/>

        <HorizontalScrollView
            android:id="@+id/viewAnimLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/anim_layout_bg"
            android:layout_below="@id/viewAnim">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:gravity="center_vertical">

                <ImageView
                    android:id="@+id/scaleView"
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:src="@drawable/avator"/>

                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="A"
                    android:onClick="onClick"
                    android:id="@+id/aAnim"/>

                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="S"
                    android:onClick="onClick"
                    android:id="@+id/sAnim"/>

                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="R"
                    android:onClick="onClick"
                    android:id="@+id/rAnim"/>

                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="T"
                    android:onClick="onClick"
                    android:id="@+id/tAnim"/>

            </LinearLayout>

        </HorizontalScrollView>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/objAnim"
            android:background="@color/anim_title_bg"
            android:layout_below="@id/viewAnimLayout"
            android:text="Object Animation"/>

        <HorizontalScrollView
            android:layout_below="@id/objAnim"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/anim_layout_bg" >

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <ImageView
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:src="@drawable/avator"
                    android:id="@+id/objAnimView1"/>

                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hide"
                    android:textAllCaps="false"
                    android:onClick="onClick"
                    android:layout_below="@id/objAnimView1"
                    android:id="@+id/objAnimBtn1"/>

                <ImageView
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:background="#FFFF8080"
                    android:id="@+id/objAnimView2"
                    android:layout_toRightOf="@id/objAnimView1"/>

                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAllCaps="false"
                    android:text="Start"
                    android:onClick="onClick"
                    android:layout_alignLeft="@id/objAnimView2"
                    android:layout_below="@id/objAnimView2"
                    android:id="@+id/objAnimBtn2"/>

                <ImageView
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:src="@drawable/play_image"
                    android:layout_toRightOf="@id/objAnimView2"
                    android:id="@+id/objAnimView3"/>

                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAllCaps="false"
                    android:text="Start"
                    android:onClick="onClick"
                    android:layout_below="@id/objAnimView3"
                    android:layout_alignLeft="@id/objAnimView3"
                    android:id="@+id/objAnimBtn3"/>

                <TextView
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:text="A"
                    android:gravity="center"
                    android:textSize="50sp"
                    android:layout_toRightOf="@id/objAnimView3"
                    android:id="@+id/objAnimView4"/>

                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAllCaps="false"
                    android:text="Start"
                    android:onClick="onClick"
                    android:layout_below="@id/objAnimView4"
                    android:layout_alignLeft="@id/objAnimView4"
                    android:id="@+id/objAnimBtn4"/>

                <com.alex.androidone.view.CircleView
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:id="@+id/objAnimView5"
                    android:layout_toRightOf="@id/objAnimView4"
                    android:background="@android:color/black"/>

                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAllCaps="false"
                    android:text="Start"
                    android:onClick="onClick"
                    android:layout_below="@id/objAnimView5"
                    android:layout_alignLeft="@id/objAnimView5"
                    android:id="@+id/objAnimBtn5"/>

                <TextView
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:text="A"
                    android:gravity="center"
                    android:textSize="50sp"
                    android:layout_toRightOf="@id/objAnimView5"
                    android:id="@+id/objAnimView6"/>

                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAllCaps="false"
                    android:text="Start"
                    android:onClick="onClick"
                    android:layout_below="@id/objAnimView6"
                    android:layout_alignLeft="@id/objAnimView6"
                    android:id="@+id/objAnimBtn6"/>

                <com.alex.androidone.view.CircleView
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:id="@+id/objAnimView7"
                    android:layout_toRightOf="@id/objAnimView6"
                    android:background="@android:color/black"/>

                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAllCaps="false"
                    android:text="Start"
                    android:onClick="onClick"
                    android:layout_below="@id/objAnimView7"
                    android:layout_alignLeft="@id/objAnimView7"
                    android:id="@+id/objAnimBtn7"/>

                <ImageView
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:id="@+id/objAnimView8"
                    android:layout_toRightOf="@id/objAnimView7"
                    android:src="@drawable/phone"/>

                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAllCaps="false"
                    android:text="Start"
                    android:onClick="onClick"
                    android:layout_below="@id/objAnimView8"
                    android:layout_alignLeft="@id/objAnimView8"
                    android:id="@+id/objAnimBtn8"/>

            </RelativeLayout>

        </HorizontalScrollView>

    </RelativeLayout>
</ScrollView>


text:
package org.krysalis.barcode4j.impl;

import java.util.Collection;
import org.junit.Test;
import static org.junit.Assert.*;

import org.krysalis.barcode4j.HumanReadablePlacement;
import org.krysalis.barcode4j.output.CanvasProvider;

/**
 *
 * @author mk
 */
public class AbstractBarcodeBeanTest {

    /**
     * Test of setPattern method, of class AbstractBarcodeBean.
     */
    @Test
    public void testSetPattern() {
        System.out.println("setPattern");
        String v = "___";
        AbstractBarcodeBean instance = new AbstractBarcodeBeanImpl();
        instance.setPattern(v);
        assertEquals(v, instance.getPattern());
    }

    /**
     * Test of getHumanReadableHeight method, of class AbstractBarcodeBean.
     */
    @Test
    public void testGetHumanReadableHeight() {
        System.out.println("getHumanReadableHeight");
        AbstractBarcodeBean instance = new AbstractBarcodeBeanImpl();
        double expResult = 0.0;
        instance.setMsgPosition(HumanReadablePlacement.HRP_NONE);
        double result = instance.getHumanReadableHeight();
        assertEquals(expResult, result, 0.0);
        instance.setMsgPosition(HumanReadablePlacement.HRP_BOTTOM);
        result = instance.getHumanReadableHeight();
        assertEquals(3.67, result, 0.01);
    }

    /**
     * Test of getVerticalQuietZone method, of class AbstractBarcodeBean.
     */
    @Test
    public void testGetVerticalQuietZone() {
        System.out.println("getVerticalQuietZone");
        AbstractBarcodeBean instance = new AbstractBarcodeBeanImpl();
        double expResult = 10.0;
        instance.setQuietZone(expResult);
        double result = instance.getVerticalQuietZone();
        assertEquals(expResult, result, 0.0);
        instance.setVerticalQuietZone(expResult * 2);
        result = instance.getVerticalQuietZone();
        assertEquals(expResult * 2, result, 0.0);
    }

    /**
     * Test of setFontName method, of class AbstractBarcodeBean.
     */
    @Test
    public void testSetFontName() {
        System.out.println("setFontName");
        String name = "Tahoma";
        AbstractBarcodeBean instance = new AbstractBarcodeBeanImpl();
        instance.setFontName(name);
        assertEquals(name, instance.getFontName());
    }

    /**
     * Test of calcDimensions method, of class AbstractBarcodeBean.
     */
    @Test(expected = UnsupportedOperationException.class)
    public void testCalcDimensions() {
        System.out.println("calcDimensions");
        String msg = "";
        AbstractBarcodeBean instance = new AbstractBarcodeBeanImpl();
        instance.calcDimensions(msg);
    }

    public class AbstractBarcodeBeanImpl extends AbstractBarcodeBean {

        @Override
        protected boolean hasFontDescender() {
            return true;
        }

        @Override
        public Collection<String> getAdditionalNames() {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public double getBarWidth(int width) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void generateBarcode(CanvasProvider canvas, String msg) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public String getId() {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    }

}


text:
//  Copyright 2016 The Sawdust Open Source Project
//
// 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 subset;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @see Leetcode78Subset
 */
public class Leetcode78Subset2 {
    /**
     * running time O(N^2)
     * in loop or recursive
     */
    public List<List<Integer>> subsets(int[] arr) {
        Arrays.sort(arr);// if it require the result is in order.
        List<List<Integer>> r = new ArrayList();
        r.add(new ArrayList());
        for (int i = 0; i < arr.length; i++) {
            int cur = arr[i];

            int size = r.size();
            for (int j = 0; j < size; j++) {
                List<Integer> clone = new ArrayList( r.get(j));
                clone.add(cur);
                r.add(clone);
            }
        }
        return r;
    }
}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
using Azure.ResourceManager.Cdn;

namespace Azure.ResourceManager.Cdn.Models
{
    internal partial class CustomDomainListResult
    {
        internal static CustomDomainListResult DeserializeCustomDomainListResult(JsonElement element)
        {
            Optional<IReadOnlyList<CdnCustomDomainData>> value = default;
            Optional<string> nextLink = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("value"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<CdnCustomDomainData> array = new List<CdnCustomDomainData>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(CdnCustomDomainData.DeserializeCdnCustomDomainData(item));
                    }
                    value = array;
                    continue;
                }
                if (property.NameEquals("nextLink"))
                {
                    nextLink = property.Value.GetString();
                    continue;
                }
            }
            return new CustomDomainListResult(Optional.ToList(value), nextLink.Value);
        }
    }
}


text:
require 'serverspec'
set :backend, :exec

describe file('/poise_test') do
  it { is_expected.to be_a_file }
  its(:content) { is_expected.to eq "I'm a little teapot\n" }
end

describe file('/poise_test.json') do
  it { is_expected.to be_a_file }
  its(:content) { is_expected.to eq <<-EOH }
[
  "short and stout",
  {
    "here": "is my handle"
  }
]
EOH
end

describe file('/poise_test.yml') do
  it { is_expected.to be_a_file }
  its(:content) { is_expected.to eq <<-EOH }
---
here: is my spout
when:
- I
- get
- all
- steamed
- up
EOH
end

describe file('/poise_test_pattern') do
  it { is_expected.to be_a_file }
  its(:content) { is_expected.to eq "I must yell\ntip me over\n" }
end


text:
layout: page
title: Vision Edge Media Trade Fair
date: 2016-05-24
author: Roy Decker
tags: weekly links, java
status: published
summary: Aenean diam diam, semper id velit.
banner: images/banner/office-01.jpg
booking:
  startDate: 01/01/2016
  endDate: 01/02/2016
  ctyhocn: BALIHHX
  groupCode: VEMTF
published: true
---
Nulla quis turpis nec erat elementum rhoncus consectetur sed purus. Morbi sollicitudin libero quis eros convallis imperdiet. Phasellus aliquet, nisl ac facilisis volutpat, nisl purus venenatis nunc, interdum vehicula diam enim et quam. Donec eleifend vestibulum mauris, a consequat velit porttitor at. Cras ut accumsan enim. Integer lobortis lobortis lectus. Sed euismod mauris eu malesuada interdum. Nulla viverra sed diam eget tincidunt. In eu hendrerit elit. Ut lacinia pellentesque arcu id molestie. Nulla at leo id elit sagittis faucibus quis sit amet nisi. Donec commodo, eros mollis maximus aliquam, sem lorem rutrum ipsum, at euismod ipsum libero quis nulla. Nam eu ligula vel elit pellentesque blandit quis eget massa. Integer id ante augue. Fusce pellentesque augue vitae eros facilisis, at mattis augue sodales.

1 In id velit vestibulum, facilisis lectus eget, dapibus erat
1 Nulla volutpat arcu efficitur lacus vestibulum, ut lacinia erat tincidunt
1 Maecenas rutrum lectus euismod faucibus viverra
1 Integer et quam at neque tempor commodo ac quis purus
1 Nunc id lacus in ante dignissim molestie
1 Duis convallis tortor in lorem aliquam, a tristique metus tempor.

Fusce vel augue non ante auctor finibus at vel turpis. Donec sapien felis, consectetur sit amet luctus quis, maximus dignissim est. Ut a vulputate dolor, sed dictum turpis. Etiam lacinia sem vitae augue cursus pretium. Praesent vel nulla laoreet, convallis justo non, accumsan tellus. Phasellus egestas elit libero, eget efficitur elit laoreet nec. Vivamus sed libero sagittis lectus posuere scelerisque. Vivamus porta dictum augue, at gravida mauris mattis ac. Praesent tincidunt nisi at purus posuere, in mattis metus vehicula. Pellentesque risus enim, auctor nec enim sed, accumsan tempor dui. Vestibulum elit enim, maximus non neque ut, luctus porttitor odio. Praesent sed pretium elit, id varius quam. Pellentesque mollis metus nec dui facilisis, maximus ornare odio ornare. Ut pharetra, eros eu posuere ultricies, tellus felis maximus magna, non lobortis magna mi quis justo.


text:
module Yaqe.Rendering
{
	export class VertexArrayObject {
		private vertexBuffers: GpuVertexBuffer[];
		private vertexLayout: VertexLayout;

		constructor(vertexBuffers: GpuVertexBuffer[], vertexLayout: VertexLayout) {
			this.vertexBuffers = vertexBuffers;
			this.vertexLayout = vertexLayout;
		}

		activate(stateTracker: StateTracker) {
			var gl = stateTracker.gl;
			var lastBufferIndex = -1;
			stateTracker.disableVertexLocations();
			for(var i = 0; i < this.vertexLayout.attributes.length; ++i) {
				var attribute = this.vertexLayout.attributes[i];

				// Bind the vertex buffer
				if(attribute.buffer != lastBufferIndex) {
					var vertexBuffer = this.vertexBuffers[attribute.buffer];
					stateTracker.bindVertexBuffer(vertexBuffer);
					lastBufferIndex = attribute.buffer;
				}

				// Activate the vertex attribute
				stateTracker.enableVertexLocation(attribute.location);
				gl.vertexAttribPointer(attribute.location, attribute.components, attribute.glType(gl), attribute.normalized, this.vertexLayout.stride, attribute.offset);
			}
		}
	}
}


text:
package ev3dev.hardware.display;

import com.sun.jna.LastErrorException;
import ev3dev.hardware.display.spi.FramebufferProvider;
import ev3dev.utils.io.NativeFramebuffer;

/**
 * Creates new Linux BW framebuffer.
 */
public class BitFramebufferProvider implements FramebufferProvider {

    @Override
    public JavaFramebuffer createFramebuffer(NativeFramebuffer fb, DisplayInterface disp)
        throws LastErrorException, IllegalArgumentException {

        return new BitFramebuffer(fb, disp);
    }
}


text:
define :apache_module, :enable => true, :conf => false do
  include_recipe "apache2"

  params[:filename] = params[:filename] || "mod_#{params[:name]}.so"
  params[:module_path] = params[:module_path] || "#{node['apache']['libexecdir']}/#{params[:filename]}"

  if params[:conf]
    apache_conf params[:name]
  end

  if platform_family?("rhel", "fedora", "arch", "suse", "freebsd")
    file "#{node['apache']['dir']}/mods-available/#{params[:name]}.load" do
      content "LoadModule #{params[:name]}_module #{params[:module_path]}\n"
      mode 0644
    end
  end

  if params[:enable]
    execute "a2enmod #{params[:name]}" do
      command "/usr/sbin/a2enmod #{params[:name]}"
      notifies :restart, resources(:service => "apache2")
      not_if do (::File.symlink?("#{node['apache']['dir']}/mods-enabled/#{params[:name]}.load") and
        ((::File.exists?("#{node['apache']['dir']}/mods-available/#{params[:name]}.conf"))?
          (::File.symlink?("#{node['apache']['dir']}/mods-enabled/#{params[:name]}.conf")):(true)))
      end
    end
  else
    execute "a2dismod #{params[:name]}" do
      command "/usr/sbin/a2dismod #{params[:name]}"
      notifies :restart, resources(:service => "apache2")
      only_if do ::File.symlink?("#{node['apache']['dir']}/mods-enabled/#{params[:name]}.load") end
    end
  end
end


text:
(function () {
    'use strict';
    angular.module('app.config', ['ngResource']);
})();


text:
#region Copyright and License

#endregion

namespace NetCreditHub.Modules.Forms
{
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using Data.Entities.Auditing;
    using Extensions;

    [Table("hub_ModuleForms", Schema = "dbo")]
    public class ModuleForm : FullAuditedWithUserNamePassivableEntity
    {
        #region The maximum length of string type field values

        public const int MaxNameLength = 32;

        public const int MaxCodeLength = 32;

        public const int MaxFormJsonLength = -1;

        public const int MaxDescriptionLength = 128;

        #endregion

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public override long Id { get; set; }

        public virtual long ModuleId { get; set; }

        public virtual string Name { get; set; }

        public virtual string Code { get; set; }

        public virtual string FormJson { get; set; }

        public virtual string Description { get; set; }

        public virtual int DisplayOrder { get; set; }

        public override string ToString()
        {
            return "[ModuleForm > Id={0}, Name={1}]".FormatWith(Id, Name);
        }
    }
}


text:
import { deleteLinkedVertices } from '../deleteLinkedVertices'

beforeEach(() => {
  jest.clearAllMocks()
})

describe('cmr#deleteLinkedVerticies', () => {
  test('catches errors', async () => {
    const consoleMock = jest.spyOn(console, 'log')

    const errorMessage = await deleteLinkedVertices('C123000001-CMR', null, null, null)

    expect(errorMessage).toEqual(false)
    expect(consoleMock).toHaveBeenCalledTimes(1)
  })
})


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>EventType (gewt 1.2.0 API)</title>
<meta name="date" content="2018-10-29">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

de.esoco.ewt.event

Enum EventType

java.lang.Object

java.lang.Enum<EventType>

de.esoco.ewt.event.EventType

All Implemented Interfaces:

java.io.Serializable, java.lang.Comparable<EventType>

public enum EventType
extends java.lang.Enum<EventType>

An enumeration of all GEWT event types for which event listeners can be
 registered on components. Focus and pointer events are supported by all
 components. Which other event types are supported can be found out from the
 documentation of the respective component.

Enum Constant Summary

Enum Constants

Enum Constant and Description

ACTION

ELEMENT_CREATED

ELEMENT_DELETED

ELEMENT_OPENED

ELEMENT_SELECTED

ELEMENT_UPDATED

FOCUS_GAINED

FOCUS_LOST

KEY_PRESSED

KEY_RELEASED

KEY_TYPED

POINTER_CLICKED

POINTER_DOUBLE_CLICKED

POINTER_DRAGGED

POINTER_ENTERED

POINTER_EXITED

POINTER_HOVER

POINTER_MOVED

POINTER_PRESSED

POINTER_RELEASED

POINTER_WHEEL

SELECTION

VALUE_CHANGED

VIEW_CLOSING

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method and Description

static EventType
valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.

static EventType[]
values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

ACTION

public static final EventType ACTION

SELECTION

public static final EventType SELECTION

VALUE_CHANGED

public static final EventType VALUE_CHANGED

FOCUS_GAINED

public static final EventType FOCUS_GAINED

FOCUS_LOST

public static final EventType FOCUS_LOST

KEY_PRESSED

public static final EventType KEY_PRESSED

KEY_RELEASED

public static final EventType KEY_RELEASED

KEY_TYPED

public static final EventType KEY_TYPED

POINTER_MOVED

public static final EventType POINTER_MOVED

POINTER_DRAGGED

public static final EventType POINTER_DRAGGED

POINTER_ENTERED

public static final EventType POINTER_ENTERED

POINTER_EXITED

public static final EventType POINTER_EXITED

POINTER_HOVER

public static final EventType POINTER_HOVER

POINTER_CLICKED

public static final EventType POINTER_CLICKED

POINTER_DOUBLE_CLICKED

public static final EventType POINTER_DOUBLE_CLICKED

POINTER_PRESSED

public static final EventType POINTER_PRESSED

POINTER_RELEASED

public static final EventType POINTER_RELEASED

POINTER_WHEEL

public static final EventType POINTER_WHEEL

ELEMENT_SELECTED

public static final EventType ELEMENT_SELECTED

ELEMENT_CREATED

public static final EventType ELEMENT_CREATED

ELEMENT_DELETED

public static final EventType ELEMENT_DELETED

ELEMENT_OPENED

public static final EventType ELEMENT_OPENED

ELEMENT_UPDATED

public static final EventType ELEMENT_UPDATED

VIEW_CLOSING

public static final EventType VIEW_CLOSING

Method Detail

values

public static EventType[] values()

Returns an array containing the constants of this enum type, in
the order they are declared.  This method may be used to iterate
over the constants as follows:

for (EventType c : EventType.values())
    System.out.println(c);

Returns:

an array containing the constants of this enum type, in the order they are declared

valueOf

public static EventType valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:

name - the name of the enum constant to be returned.

Returns:

the enum constant with the specified name

Throws:

java.lang.IllegalArgumentException - if this enum type has no constant with the specified name

java.lang.NullPointerException - if the argument is null

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method


text:
The @angular/cdk/menu module provides directives to help create custom menu
interactions based on the WAI ARIA specification.

By using @angular/cdk/menu you get all of the expected behaviors for an accessible
experience, including bidi layout support, keyboard interaction, and focus management. All
directives apply their associated ARIA roles to their host element.

          Supported ARIA Roles

The directives in @angular/cdk/menu set the appropriate roles on their host element.

Directive
ARIA Role

CdkMenuBar
menubar

CdkMenu
menu

CdkMenuGroup
group

CdkMenuItem
menuitem

CdkMenuItemRadio
menuitemradio

CdkMenuItemCheckbox
menuitemcheckbox

CdkMenuTrigger
button

          CSS Styles and Classes

The @angular/cdk/menu is designed to be highly customizable to your needs. It therefore does not
make any assumptions about how elements should be styled. You are expected to apply any required
CSS styles, but the directives do apply CSS classes to make it easier for you to add custom styles.
The available CSS classes are listed below, by directive.

Directive
CSS Class
Applied...

cdkMenu
cdk-menu
Always

cdkMenu
cdk-menu-inline
If the menu is an inline menu

cdkMenuBar
cdk-menu-bar
Always

cdkMenuGroup
cdk-menu-group
Always

cdkMenuItem
cdk-menu-item
Always

cdkMenuItemCheckbox
cdk-menu-item
Always

cdkMenuItemCheckbox
cdk-menu-item-checkbox
Always

cdkMenuItemRadio
cdk-menu-item
Always

cdkMenuItemRadio
cdk-menu-item-radio
Always

cdkMenuTriggerFor
cdk-menu-trigger
Always

          Getting started

Import the CdkMenuModule into the NgModule in which you want to create menus. You can then apply
menu directives to build your custom menu. A typical menu consists of the following directives:

cdkMenuTriggerFor - links a trigger element to an ng-template containing the menu to be opened

cdkMenu - creates the menu content opened by the trigger

cdkMenuItem - added to each item in the menu

Most menu interactions consist of two parts: a trigger and a menu panel.

          Triggers

You can add cdkMenuTriggerFor to any button to make it a trigger for the given menu, or any menu
item to make it a trigger for a submenu. When adding this directive, be sure to pass a reference to
the template containing the menu it should open. Users can toggle the associated menu using a mouse
or keyboard.

When creating a submenu trigger, add both cdkMenuItem and cdkMenuTriggerFor like so,

          Menu content

There are two types of menus:

inline menus are always present on the page

pop-up menus can be toggled to hide or show by the user

You can create menus by marking their content element with the cdkMenu or cdkMenuBar
directives. You can create several types of menu interaction which are discussed below.

All type of menus should exclusively contain elements with role menuitem, menuitemcheckbox,
menuitemradio, or group. Supporting directives that automatically apply these roles are
discussed below.

Note that Angular CDK provides no styles; you must add styles as part of building your custom menu.

          Inline Menus

An inline menu is a menu that lives directly on the page rather than in a pop-up associated with a
trigger. You can use an inline menu when you want a persistent menu interaction on a page. Menu
items within an inline menus are logically grouped together, and you can navigate through them
using your keyboard. You can create an inline menu by adding the cdkMenu directive to the element
you want to serve as the menu content.

          Pop-up Menus

You can create pop-up menus using the cdkMenu directive as well. Add this directive to the
element you want to serve as the content for your pop-up menu. Then wrap the content element in an
ng-template and reference the template from the cdkMenuTriggerFor property of the trigger. This
will allow the trigger to show and hide the menu content as needed.

          Menu Bars

Menu bars are a type of inline menu that you can create using the cdkMenuBar directive. They
follow the ARIA menubar spec and behave similarly to a desktop application menubar. Each
bar consists of at least one cdkMenuItem that triggers a submenu.

          Context Menus

A context menus is a type of pop-up menu that doesn't have a traditional trigger element, instead
it is triggered when a user right-clicks within some container element. You can mark a
container element with the cdkContextMenuTriggerFor, which behaves like cdkMenuTriggerFor except
that it responds to the browser's native contextmenu event. Custom context menus appear next to
the cursor, similarly to native context menus.

You can nest context menu container elements. Upon right-click, the menu associated with the closest
container element will open.

In the example above, right-clicking on "Inner context menu" will open up the "inner" menu and
right-clicking inside "Outer context menu" will open up the "outer" menu.

          Menu Items

The cdkMenuItem directive allows users to navigate menu items via keyboard.
You can add a custom action to a menu item with the cdkMenuItemTriggered output.

You can create nested menus by using a menu item as the trigger for another menu.

          Menu Item Checkboxes

A cdkMenuItemCheckbox is a special type of menu item that behaves as a checkbox. You can use this
type of menu item to toggle items on and off. An element with the cdkMenuItemCheckbox directive
does not need the additional cdkMenuItem directive.

Checkbox items do not track their own state. You must bind the checked state using the
cdkMenuItemChecked input and listen to cdkMenuItemTriggered to know when it is toggled. If you
don't bind the state it will reset when the menu is closed and re-opened.

          Menu Item Radios

A cdkMenuItemRadio is a special type of menu item that behaves as a radio button. You can use this
type of menu item for menus with exclusively selectable items. An element with the cdkMenuItemRadio
directive does not need the additional cdkMenuItem directive.

As with checkbox items, radio items do not track their own state, but you can track it by binding
cdkMenuItemChecked and listening for cdkMenuItemTriggered. If you do not bind the state the
selection will reset when the menu is closed and reopened.

          Groups

By default cdkMenu acts as a group for cdkMenuItemRadio elements. Elements with
cdkMenuItemRadio added as children of a cdkMenu will be logically grouped and only a single item
can have the checked state.

If you would like to have unrelated groups of radio buttons within a single menu you should use the
cdkMenuGroup directive.

          Smart Menu Aim

@angular/cdk/menu is capable of intelligently predicting when a user intends to navigate to an
open submenu and preventing premature closeouts. This functionality prevents users from having to
hunt through the open menus in a maze-like fashion to reach their destination. To enable this
feature for a menu and its sub-menus, add the cdkMenuTargetAim directive to the cdkMenu or
cdkMenuBar element.

As demonstrated in the diagram above we first track the user's mouse movements within a menu. Next,
when a user mouses into a sibling menu item (e.g. Share button) the sibling item asks the Menu Aim
service if it can perform its close actions. In order to determine if the current submenu can be
closed out, the Menu Aim service calculates the slope between a selected target coordinate in the
submenu and the previous mouse point, and the slope between the target and the current mouse point.
If the slope of the current mouse point is greater than the slope of the previous that means the
user is moving towards the submenu, so we shouldn't close out. Users however may sometimes stop
short in a sibling item after moving towards the submenu. The service is intelligent enough to
detect this intention and will trigger the next menu.

          Accessibility

The set of directives defined in @angular/cdk/menu follow accessibility best practices as defined
in the ARIA spec. Specifically, the menus are aware of left-to-right and right-to-left
layouts and opened appropriately. You should however add any necessary CSS styles. Menu items should
always have meaningful labels, whether through text content, aria-label, or aria-labelledby.
Finally, keyboard interaction is supported as defined in the ARIA menubar keyboard interaction spec.


text:
package org.apache.nifi.registry.flow;

import org.junit.Before;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class TestFlowRegistryClient {

    private FlowRegistryClient flowRegistryClient;

    @Before
    public void setup() {
        flowRegistryClient = new MockFlowRegistryClient();
    }

    @Test
    public void testParamWithTrailingSlash() {
        flowRegistryClient.addFlowRegistry("1", "Registry 1", "http://localhost:1111", "NA");
        flowRegistryClient.addFlowRegistry("2", "Registry 2", "http://localhost:2222", "NA");
        flowRegistryClient.addFlowRegistry("3", "Registry 3", "http://localhost:3333", "NA");

        final String flowRegistryId = flowRegistryClient.getFlowRegistryId("http://localhost:1111/");
        assertNotNull(flowRegistryId);
        assertEquals("1", flowRegistryId);
    }

    @Test
    public void testClientWithTrailingSlash() {
        flowRegistryClient.addFlowRegistry("1", "Registry 1", "http://localhost:1111", "NA");
        flowRegistryClient.addFlowRegistry("2", "Registry 2", "http://localhost:2222/", "NA");
        flowRegistryClient.addFlowRegistry("3", "Registry 3", "http://localhost:3333", "NA");

        final String flowRegistryId = flowRegistryClient.getFlowRegistryId("http://localhost:2222");
        assertNotNull(flowRegistryId);
        assertEquals("2", flowRegistryId);
    }

    @Test
    public void testNoTrailingSlash() {
        flowRegistryClient.addFlowRegistry("1", "Registry 1", "http://localhost:1111", "NA");
        flowRegistryClient.addFlowRegistry("2", "Registry 2", "http://localhost:2222", "NA");
        flowRegistryClient.addFlowRegistry("3", "Registry 3", "http://localhost:3333", "NA");

        final String flowRegistryId = flowRegistryClient.getFlowRegistryId("http://localhost:3333");
        assertNotNull(flowRegistryId);
        assertEquals("3", flowRegistryId);
    }

    private static class MockFlowRegistryClient implements FlowRegistryClient {

        private Map<String,FlowRegistry> registryMap = new HashMap<>();

        @Override
        public FlowRegistry getFlowRegistry(String registryId) {
            return registryMap.get(registryId);
        }

        @Override
        public Set<String> getRegistryIdentifiers() {
            return registryMap.keySet();
        }

        @Override
        public void addFlowRegistry(FlowRegistry registry) {
            registryMap.put(registry.getIdentifier(), registry);
        }

        @Override
        public FlowRegistry addFlowRegistry(String registryId, String registryName, String registryUrl, String description) {
            final FlowRegistry flowRegistry = mock(FlowRegistry.class);
            when(flowRegistry.getIdentifier()).thenReturn(registryId);
            when(flowRegistry.getName()).thenReturn(registryName);
            when(flowRegistry.getURL()).thenReturn(registryUrl);
            when(flowRegistry.getDescription()).thenReturn(description);
            registryMap.put(flowRegistry.getIdentifier(), flowRegistry);
            return flowRegistry;
        }

        @Override
        public FlowRegistry removeFlowRegistry(String registryId) {
            return registryMap.remove(registryId);
        }
    }
}


text:
<!DOCTYPE html>

    <title>Browsersync</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link href="css/style.css" rel="stylesheet" />


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.dinglicom.dep.domain;

/**
 *
 * @author panzhen
 */
public class CompanyDetail {
    private String company;
    private String manager;
    private String tel;
    private String address;

    public CompanyDetail() {}
    public CompanyDetail(String name, String manager, String tel, String address) {
        this.company = name;
        this.manager = manager;
        this.tel = tel;
        this.address = address;
    }

    /**
     * @return the company
     */
    public String getCompany() {
        return company;
    }

    /**
     * @param company the company to set
     */
    public void setCompany(String company) {
        this.company = company;
    }

    /**
     * @return the manager
     */
    public String getManager() {
        return manager;
    }

    /**
     * @param manager the manager to set
     */
    public void setManager(String manager) {
        this.manager = manager;
    }

    /**
     * @return the tel
     */
    public String getTel() {
        return tel;
    }

    /**
     * @param tel the tel to set
     */
    public void setTel(String tel) {
        this.tel = tel;
    }

    /**
     * @return the address
     */
    public String getAddress() {
        return address;
    }

    /**
     * @param address the address to set
     */
    public void setAddress(String address) {
        this.address = address;
    }
}


text:
package com.netflix.spinnaker.orca.pipelinetemplate.v1schema.render.filters;

import com.hubspot.jinjava.interpret.InterpretException;
import com.hubspot.jinjava.interpret.JinjavaInterpreter;
import com.hubspot.jinjava.lib.filter.Filter;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static java.lang.String.format;

public class MaxFilter implements Filter {

  @SuppressWarnings("unchecked")
  @Override
  public Object filter(Object var, JinjavaInterpreter interpreter, String... args) {
    if (args.length != 0) {
      throw new InterpretException("max filter does not accept any arguments");
    }

    if (!(var instanceof Collection)) {
      throw new InterpretException("max filter can only be used with a list type object");
    }

    List<Double> casted = (List<Double>) ((Collection) var).stream()
      .map(v -> {
        try {
          return Double.valueOf(String.valueOf(v));
        } catch (NumberFormatException e) {
          throw new InterpretException(format("max filter requires list of numeric values, %s given", v), e);
        }
      })
      .collect(Collectors.toList());

    if (casted.isEmpty()) {
      throw new InterpretException("max filter must be provided a list of numeric values with at least one value");
    }

    Double max = Collections.max(casted);

    if (max % max.intValue() == 0) {
      return max.intValue();
    }
    return max;
  }

  @Override
  public String getName() {
    return "max";
  }
}


text:
module Fog
  module Compute
    class Cloudstack

      class Real
        # Creates a template of a virtual machine. The virtual machine must be in a STOPPED state. A template created from this command is automatically designated as a private template visible to the account that created it.
        #
        # {CloudStack API Reference}[http://cloudstack.apache.org/docs/api/apidocs-4.3/root_admin/createTemplate.html]
        def create_template(ostypeid, displaytext, name, options={})
          options.merge!(
            'command' => 'createTemplate',
            'ostypeid' => ostypeid,
            'displaytext' => displaytext,
            'name' => name
          )
          request(options)
        end
      end

    end
  end
end


text:
PATH=${WORKSPACE}/venv/bin:$PATH

PYLINT=pylint

if [ ! -d "venv" ]; then
	virtualenv venv
fi
chmod +x ./venv/bin/activate

./venv/bin/activate
pip install --trusted-host scmesos06 -i http://scmesos06:3141/simple -r requirements_dev.txt --cache-dir=/tmp/recipe

${PYLINT} -f parseable recipe | tee pylint.out


text:
using System;
#if SERIALIZABLE
using System.Runtime.Serialization;
#endif

namespace MailKit.Net.Imap {
	/// <summary>
	/// An exception that is thrown when an IMAP command returns NO or BAD.
	/// </summary>
	/// <remarks>
	/// The exception that is thrown when an IMAP command fails. Unlike a <see cref="ImapProtocolException"/>,
	/// a <see cref="ImapCommandException"/> does not require the <see cref="ImapClient"/> to be reconnected.
	/// </remarks>
#if SERIALIZABLE
	[Serializable]
#endif
	public class ImapCommandException : CommandException
	{
#if SERIALIZABLE
		/// <summary>
		/// Initializes a new instance of the <see cref="MailKit.Net.Imap.ImapCommandException"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="ImapCommandException"/> from the serialized data.
		/// </remarks>
		/// <param name="info">The serialization info.</param>
		/// <param name="context">The streaming context.</param>
		protected ImapCommandException (SerializationInfo info, StreamingContext context) : base (info, context)
		{
			var value = info.GetString ("Response");
			ImapCommandResponse response;

			Enum.TryParse (value, out response);

			Response = response;
		}
#endif

		/// <summary>
		/// Create a new <see cref="ImapCommandException"/> based on the specified command name and <see cref="ImapCommand"/> state.
		/// </summary>
		/// <remarks>
		/// Create a new <see cref="ImapCommandException"/> based on the specified command name and <see cref="ImapCommand"/> state.
		/// </remarks>
		/// <returns>A new command exception.</returns>
		/// <param name="command">The command name.</param>
		/// <param name="ic">The command state.</param>
		internal static ImapCommandException Create (string command, ImapCommand ic)
		{
			var result = ic.Response.ToString ().ToUpperInvariant ();
			string message, reason = null;

			if (string.IsNullOrEmpty (ic.ResponseText)) {
				for (int i = 0; i < ic.RespCodes.Count; i++) {
					if (ic.RespCodes[i].IsError) {
						reason = ic.RespCodes[i].Message;
						break;
					}
				}
			} else {
				reason = ic.ResponseText;
			}

			if (!string.IsNullOrEmpty (reason))
				message = string.Format ("The IMAP server replied to the '{0}' command with a '{1}' response: {2}", command, result, reason);
			else
				message = string.Format ("The IMAP server replied to the '{0}' command with a '{1}' response.", command, result);

			return ic.Exception != null ? new ImapCommandException (ic.Response, message, ic.Exception) : new ImapCommandException (ic.Response, message);
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="MailKit.Net.Imap.ImapCommandException"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="ImapCommandException"/>.
		/// </remarks>
		/// <param name="response">The IMAP command response.</param>
		/// <param name="message">The error message.</param>
		/// <param name="innerException">The inner exception.</param>
		public ImapCommandException (ImapCommandResponse response, string message, Exception innerException) : base (message, innerException)
		{
			Response = response;
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="MailKit.Net.Imap.ImapCommandException"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="ImapCommandException"/>.
		/// </remarks>
		/// <param name="response">The IMAP command response.</param>
		/// <param name="message">The error message.</param>
		public ImapCommandException (ImapCommandResponse response, string message) : base (message)
		{
			Response = response;
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="MailKit.Net.Imap.ImapCommandException"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="ImapCommandException"/>.
		/// </remarks>
		/// <param name="response">The IMAP command response.</param>
		public ImapCommandException (ImapCommandResponse response)
		{
			Response = response;
		}

		/// <summary>
		/// Gets the IMAP command response.
		/// </summary>
		/// <remarks>
		/// Gets the IMAP command response.
		/// </remarks>
		/// <value>The IMAP command response.</value>
		public ImapCommandResponse Response {
			get; private set;
		}

#if SERIALIZABLE
		/// <summary>
		/// When overridden in a derived class, sets the <see cref="System.Runtime.Serialization.SerializationInfo"/>
		/// with information about the exception.
		/// </summary>
		/// <remarks>
		/// Serializes the state of the <see cref="FolderNotFoundException"/>.
		/// </remarks>
		/// <param name="info">The serialization info.</param>
		/// <param name="context">The streaming context.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="info"/> is <c>null</c>.
		/// </exception>
		public override void GetObjectData (SerializationInfo info, StreamingContext context)
		{
			if (info == null)
				throw new ArgumentNullException ("info");

			info.AddValue ("Response", Response);

			base.GetObjectData (info, context);
		}
#endif
	}
}


text: import type { switch } from 'foo';


text:
from abc import ABCMeta
from collections import Mapping, Callable

class AtomicBlock(Mapping, Callable):
    """ This is the base class that all blocks inherit from. It simply
        indicates that it has a size (rows,cols).

        All atomic blocks are mappings from tuple indices (i,j) to values v.
        They are also callable; calling the block applies its operation.

        The "length" of a block is equal to rows*cols; it assumes the matrix
        is dense.

        A Block contains a single AtomicBlock, but offset in some global
        mapping. A StructuredMatrix consists of a list of Blocks.
    """
    __metaclass__ = ABCMeta

    def __init__(self, rows, cols, *args, **kwargs):
        self.size = (rows, cols)
        self.rows = rows
        self.cols = cols
        super(AtomicBlock, self).__init__(*args, **kwargs)

    def __iter__(self):
        for i in xrange(self.rows):
            for j in xrange(self.cols):
                v = self[i,j]
                if v != 0: yield (i, j, v)

    def __len__(self):
        return self.rows*self.cols


text:
using Assets.Scripts.CameraHandler;
using Assets.Scripts.Heat;
using Assets.Scripts.Helpers;
using Assets.Scripts.Player;
using Assets.Scripts.Player.Abilities;
using Assets.Scripts.Player.Config;
using Assets.Scripts.Player.PL;
using UnityEngine;

namespace Assets.Scripts.Player
{
	public class PlayerController : MonoBehaviour
	{
		public GameObject PilotedLight;
		public GameObject Tether;

		public float BaseStability { get; private set; }
		public float BaseIntensity { get; private set; }
		public float BaseControl { get; private set; }

		private float _currentStability = 1f;
		public float Stability { get { return _currentStability; } }
		private float _stabilityLastFrame;

		private float _currentIntensity = 1f;
		public float Intensity { get { return _currentIntensity; } }
		private float _intensityLastFrame;

		private float _currentControl = 1f;
		public float DistanceFromPlayer { get { return 10 + _currentControl / 5; } }
		private float _controlLastFrame;

		public Transform Transform { get; set; }
		public Collider2D Collider { get; set; }

		private HeatHandler[] _heatHandlers;
		private SmoothCamera2D _camera;
		private float _timeSpotted;
		private float _timeSpottedLastFrame;
		private ControlBorder _controlBorder;
		private bool _isScoutActive;

		void Awake()
		{
			Transform = transform.parent.parent;
			Collider = Transform.GetComponent<BoxCollider2D>();

			_heatHandlers = Transform.GetComponentsInChildren<HeatHandler>();
			_camera = Transform.GetComponent<AnimationScript>().CameraScript;
			_controlBorder = GetComponentInChildren<ControlBorder>();
		}

		void Start()
		{
			SetBases();
			SetStabilityToDefault();
			SetIntensityToDefault();
			SetControlToDefault();
		}

		void Update()
		{
			SetBases();
			ResetTimeIfNotSpotted();
			_currentControl = BaseControl;
			UpdateStabilityIntensity();
			UpdateControlBorder();

            CurrentClimate.Stability = _currentStability;
            CurrentClimate.Intensity = _currentIntensity;
            CurrentClimate.Control = _currentControl;

            if (KeyBindings.GetKeyUp(Controls.Ability1) && ChannelingHandler.ChannelingSet)
			{
				ChannelingHandler.IsTethered = !ChannelingHandler.IsTethered;
			}
		}

		private void SetBases()
		{
			BaseStability = PlayerPrefs.GetFloat(FloatVariable.Stability.ToString());
			BaseIntensity = PlayerPrefs.GetFloat(FloatVariable.Intensity.ToString());
			BaseControl = PlayerPrefs.GetFloat(FloatVariable.Control.ToString());
		}

		private void ResetTimeIfNotSpotted()
		{
			if (_timeSpotted == _timeSpottedLastFrame)
				_timeSpotted = 0;

			_timeSpottedLastFrame = _timeSpotted;
		}

		private void UpdateStabilityIntensity()
		{
			_currentStability = BaseStability - ChannelingHandler.ChannelPercent * BaseStability - _timeSpotted;
			_currentIntensity = BaseIntensity - ChannelingHandler.ChannelPercent * BaseIntensity - _timeSpotted;

			if (_currentStability < 0)
			{
				_currentStability = 0;
				//frozen
			}

			if (_stabilityLastFrame != _currentStability || _intensityLastFrame != _currentIntensity)
			{
				foreach (var hh in _heatHandlers)
				{
					hh.UpdateHeat(new HeatMessage(_currentIntensity, 1 + _currentStability / ConstantVariables.StabilityHeatRangeModifier));
				}
			}

			_stabilityLastFrame = _currentStability;
			_intensityLastFrame = _currentIntensity;
		}

		private void UpdateControlBorder()
		{
			if (_currentControl != _controlLastFrame || _isScoutActive != AbilityState.IsActive(Ability.Scout))
			{
				_controlBorder.SetSize(DistanceFromPlayer * (AbilityState.IsActive(Ability.Scout) ? 4 : 2));
				_isScoutActive = AbilityState.IsActive(Ability.Scout);
				_controlLastFrame = _currentControl;
			}
		}

		private void SetStabilityToDefault()
		{
			_currentStability = BaseStability;
		}

		private void SetIntensityToDefault()
		{
			_currentIntensity = BaseIntensity;
		}

		private void SetControlToDefault()
		{
			_currentControl = BaseControl;
		}

		public void CreateLight()
		{
			ChannelingHandler.PlExists = true;

			Vector3 pilotedLightPosition = Transform.localScale.x > 0f
				? transform.position + new Vector3(0.4f, 0, 0)
				: transform.position + new Vector3(-0.4f, 0, 0);

			var pl = (GameObject)Instantiate(
				PilotedLight,
				pilotedLightPosition,
				transform.rotation);

			pl.GetComponent<PilotedLightController>().Player = this;
			_camera.Pl = pl.transform;

			if (AbilityState.IsActive(Ability.Tether))
			{
				var tetherObject = Instantiate(Tether);

				var tether = tetherObject.GetComponent<Tether>();
				tether.Player = transform;
				tether.Pl = pl.transform;
			}
		}

		public void StopChanneling()
		{
			ChannelingHandler.StopChanneling();
		}

		public void Spotted()
		{
			_timeSpotted += Time.deltaTime * 3;
		}

		void OnDrawGizmos()
		{
			Gizmos.color = new Color(1, 0, 0, 0.5F);
			var box = transform.parent.parent.GetComponent<BoxCollider2D>();
			Gizmos.DrawCube(box.bounds.center, new Vector3(box.bounds.size.x, box.bounds.size.y, 1));
		}
	}
}