text:
[![Angular Style Guide](https://mgechev.github.io/angular2-style-guide/images/badge.svg)](https://angular.io/styleguide)
[![Build Status](https://travis-ci.org/mgechev/angular-seed.svg?branch=master)](https://travis-ci.org/mgechev/angular-seed)
[![Build Status](https://ci.appveyor.com/api/projects/status/jg5vg36w0klpa00e/branch/master?svg=true)](https://ci.appveyor.com/project/mgechev/angular2-seed)
[![Join the chat at https://gitter.im/mgechev/angular2-seed](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mgechev/angular2-seed?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![MIT license](http://img.shields.io/badge/license-MIT-brightgreen.svg)](http://opensource.org/licenses/MIT)
[![Dependency Status](https://david-dm.org/mgechev/angular-seed.svg)](https://david-dm.org/mgechev/angular-seed)
[![devDependency Status](https://david-dm.org/mgechev/angular-seed/dev-status.svg)](https://david-dm.org/mgechev/angular-seed#info=devDependencies)

Provides fast, reliable and extensible starter for the development of Angular projects.

`angular-seed` provides the following features:

- Allows you to painlessly update the seed tasks of your already existing project.
- Supports multiple Angular applications with shared codebase in a single instance of the seed.
- Official Angular i18n support.
- Ready to go, statically typed build system using gulp for working with TypeScript.
- Production and development builds.
- **Ahead-of-Time** compilation support.
- Sample unit tests with Jasmine and Karma including code coverage via [istanbul](https://gotwarlost.github.io/istanbul/).
- End-to-end tests with Protractor.
- Development server with Livereload.
- Following the [best practices](https://angular.io/styleguide).
- Manager of your type definitions using @types.
- Has autoprefixer and css-lint support.

This is a minor fork of mgechev's Angular-Seed with the following additions:

- Bootstrap/ng2-bootstrap
- Font support for Bootstrap
- JQuery (for the modal dialogs)
- angular2-toaster for popups
- image support in /assets/img
- a template component communicating with the VS /Server backend (/server/api/controller)
- a sample vs WebAPI configured to run /client/dist/dev at root, WebApi at /server/api/*

Setting up the VS applicationhost.config file:
the applicationhost.config file controls IISExpress directory settings in a fashion similar to an Apache Hosts file. The settings shown here will work for VS prior to 2015, but the config file is in a different location. as of 2015 Microsoft makes the config file together with the *.sln files under /.vs/config/applicationhost.config.

IIS Express Layout:
  /                     -root, pointing to /client/dist/dev
    /server             -WebApi project
      /api/{controller} -backend controllers

manually adjust the files paths prior to starting the project.

            <site name="server" id="2">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="C:\data\dev\ML\Template-Angular2-VS\client\dist\dev" />
                    <virtualDirectory path="/node_modules" physicalPath="C:\data\dev\ML\Template-Angular2-VS-VS\client\node_modules" />
                </application>
                <application path="/server" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="C:\data\dev\ML\Template-Angular2-VS\server" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="*:9000:localhost" />
                </bindings>
            </site>

When building services in Angular it is recommended in Dev to set them with the full url so that they will run correctly in both Node's webserver and IISExpress.

Resolve CORS issue:
 CORS issues
One of the challenges of using node and VS together is dealing with CORS (Cross-Origin Resource Sharing). Typically, you'll want the Angular node application to reside in its own project (an empty web project if the VS Node project extension is unavailable), and an API running as a separate MVC Web API project. This will cause CORS issues trying to connect the front end to the API.
Here are the settings to fix this (your text editor must be running in Administrator mode):
[*NOTE:  These solutions are intended for a developer's local development machine and should NOT be applied as is to production servers!! NEVER use a wildcard in a real environment!!!]
http://blog.jonathanchannon.com/2013/09/16/enabling-cors-in-iisexpress/
C:\Users\*USERNAME*\Documents\IISExpress\config\applicationhost.config
        <httpProtocol>
            <customHeaders>
                <clear />
                <add name="X-Powered-By" value="ASP.NET" />
                <add name="Access-Control-Allow-Origin" value="*" />
                <add name="Allow-Control-Allow-Origin" value="*" /><!—may need explicit valuesà
                <add name="Access-Control-Allow-Headers" value="Accept, Origin, Content-Type" />
                <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
            </customHeaders>
            <redirectHeaders>
                <clear />
            </redirectHeaders>
        </httpProtocol>

# How to start

**Note** that this seed project requires node v4.x.x or higher and npm 2.14.7 but in order to be able to take advantage of the complete functionality we **strongly recommend node >=v6.5.0 and npm >=3.10.3**.

**Here is how to [speed-up the build on Windows](https://github.com/mgechev/angular-seed/wiki/Speed-up-the-build-on-Windows)**.

In order to start the seed use:

```bash
$ git clone --depth 1 https://github.com/keslavi/Template-Angular2-VS.git
$ cd Template-Angular2-VS

# install the project's dependencies
$ npm install
# fast install (via Yarn, https://yarnpkg.com)
$ yarn install  # or yarn

# watches your files and uses livereload by default
$ npm start
# api document for the app
# npm run build.docs

# to start deving with livereload site and coverage as well as continuous testing
$ npm run start.deving

# dev build
$ npm run build.dev
# prod build
$ npm run build.prod
# prod build with AoT compilation
$ npm run build.prod.exp

# dev build of multiple applications (by default the value of --app is "app")
$ npm start -- --app baz
$ npm start -- --app foo
$ npm start -- --app bar
```

_Does not rely on any global dependencies._

# Table of Contents

- [Introduction](#introduction)
- [How to start](#how-to-start)
- [Table of Content](#table-of-content)
- [Configuration](#configuration)
- [Environment Configuration](#environment-configuration)
- [Tools documentation](#tools-documentation)
- [How to extend?](#how-to-extend)
- [Running tests](#running-tests)
- [Contributing](#contributing)
- [Advanced Seed Option](#advanced-seed-option)
- [Examples](#examples)
- [Directory Structure](#directory-structure)
- [Contributors](#contributors)
  - [Wiki Contributors](#wiki-contributors)
- [Change Log](#change-log)
- [License](#license)

# Configuration

Default application server configuration

```js
var PORT             = 5555;
var LIVE_RELOAD_PORT = 4002;
var DOCS_PORT        = 4003;
var APP_BASE         = '/';
```

Configure at runtime

```bash
$ npm start -- --port 8080 --reload-port 4000 --base /my-app/
```

## Environment configuration

If you have different environments and you need to configure them to use different end points, settings, etc. you can use the files `dev.ts` or `prod.ts` in`./tools/env/`. The name of the file is environment you want to use.

The environment can be specified by using:

```bash
$ npm start -- --config-env ENV_NAME
```

Currently the `ENV_NAME`s are `dev`, `prod`, `staging`, but you can simply add a different file `"ENV_NAME.ts".` file in order to alter extra such environments.

# Tools documentation

A documentation of the provided tools can be found in [tools/README.md](tools/README.md).

# How to extend?

Visit the [Wiki page](https://github.com/mgechev/angular-seed/wiki) of the project.

# How to update?
```
git remote add upstream https://github.com/mgechev/angular2-seed
git pull upstream master
```

# Running tests

```bash
$ npm test

# Development. Your app will be watched by karma
# on each change all your specs will be executed.
$ npm run test.watch
# NB: The command above might fail with a "EMFILE: too many open files" error.
# Some OS have a small limit of opened file descriptors (256) by default
# and will result in the EMFILE error.
# You can raise the maximum of file descriptors by running the command below:
$ ulimit -n 10480

# code coverage (istanbul)
# auto-generated at the end of `npm test`
# view coverage report:
$ npm run serve.coverage

# e2e (aka. end-to-end, integration) - In three different shell windows
# Make sure you don't have a global instance of Protractor
# Make sure you do have Java in your PATH (required for webdriver)

# npm install webdriver-manager <- Install this first for e2e testing
# npm run webdriver-update <- You will need to run this the first time
$ npm run webdriver-start
$ npm run serve.e2e
$ npm run e2e

# e2e live mode - Protractor interactive mode
# Instead of last command above, you can use:
$ npm run e2e.live
```
You can learn more about [Protractor Interactive Mode here](https://github.com/angular/protractor/blob/master/docs/debugging.md#testing-out-protractor-interactively)

# Contributing

Please see the [CONTRIBUTING](https://github.com/mgechev/angular-seed/blob/master/.github/CONTRIBUTING.md) file for guidelines.

# Advanced Seed Option

An [advanced option to this seed exists here](https://github.com/NathanWalker/angular-seed-advanced) which mirrors the latest changes here but adds core support for:

- [ngrx/store](https://github.com/ngrx/store) RxJS powered state management, inspired by **Redux**
- [ngrx/effects](https://github.com/ngrx/effects) Side effect model for @ngrx/store
- [ng2-translate](https://github.com/ocombe/ng2-translate) for i18n
  - Usage is optional but on by default
  - Up to you and your team how you want to utilize it. It can be easily removed if not needed.
- [angulartics2](https://github.com/angulartics/angulartics2) Vendor-agnostic analytics for Angular applications.
  - Out of box support for [Segment](https://segment.com/)
    - When using the seed, be sure to change your `write_key` [here](https://github.com/NathanWalker/angular-seed-advanced/blob/master/src/client/index.html#L24)
  - Can be changed to any vendor, [learn more here](https://github.com/angulartics/angulartics2#supported-providers)
- [lodash](https://lodash.com/) Helps reduce blocks of code down to single lines and enhances readability
- [NativeScript](https://www.nativescript.org/) cross platform mobile (w/ native UI) apps. [Setup instructions here](#nativescript-app).
- [Electron](http://electron.atom.io/) cross platform desktop apps (Mac, Windows and Linux). [Setup instructions here](#electron-app).

You may use it to learn how to extend this seed for your own use cases or use the advanced seed if your project needs those features.

# Examples

Forks of this project demonstrate how to extend and integrate with other libraries:

 - https://github.com/mgechev/switching-to-angular2 - code samples for the book ["Switching to Angular 2"](https://www.packtpub.com/web-development/switching-angular-2).
 - https://github.com/DeviantJS/angular2-seed-postcss - Extending PostCSS with precss / cssnext for Sass-like features.
 - https://github.com/DeviantJS/angular2-seed-material2 - integration with [Angular2-Material](https://github.com/angular/material2).
 - https://github.com/AngularShowcase/angular2-sample-app - sample Angular application.
 - https://github.com/AngularShowcase/ng2-bootstrap-sbadmin - ng2-bootstrap-sbadmin.
 - https://github.com/AngularShowcase/angular2-seed-ng2-highcharts - Simple application including a [Highcharts](http://www.highcharts.com) graph.
 - https://github.com/tarlepp/angular-sailsjs-boilerplate-frontend-angular2 - Example application for [Sails.js](http://sailsjs.org/) integration.
 - https://github.com/ludohenin/ng2-wp-blog - Angular application using Wordpress [JSON-API](http://v2.wp-api.org) backend..
 - https://github.com/AngularShowcase/angular2-seed-example-mashup - Angular application demonstrating the use of [Redux](http://redux.js.org/), [D3](https://github.com/mbostock/d3), [socket io](https://github.com/socketio), [Google Charts](https://developers.google.com/chart/), and [RxJs](https://github.com/Reactive-Extensions/RxJS).
 - https://github.com/tiagomapmarques/angular2-seed-phaser/tree/releases - integration with [Phaser](http://phaser.io/).
 - https://github.com/vyakymenko/angular2-seed-express - integration with [Express](https://expressjs.com/) full-stack development.
 - https://github.com/UIUXEngineering/angular2-jspm-typescript-seed - integration with [JSPM](http://jspm.io/).

# Directory Structure

```
.
├── LICENSE
├── README.md
├── gulpfile.ts                <- configuration of the gulp tasks
├── karma.conf.js              <- configuration of the test runner
├── package.json               <- dependencies of the project
├── protractor.conf.js         <- e2e tests configuration
├── src                        <- source code of the application
│   └── client
│       ├── app
│       │   ├── +about
│       │   │   ├── about.component.css
│       │   │   ├── about.component.e2e-spec.ts
│       │   │   ├── about.component.html
│       │   │   ├── about.component.spec.ts
│       │   │   ├── about.component.ts
│       │   │   ├── about.module.ts
│       │   │   ├── about.routes.ts
│       │   │   └── index.ts
│       │   ├── +home
│       │   │   ├── home.component.css
│       │   │   ├── home.component.e2e-spec.ts
│       │   │   ├── home.component.html
│       │   │   ├── home.component.spec.ts
│       │   │   ├── home.component.ts
│       │   │   ├── home.module.ts
│       │   │   ├── home.routes.ts
│       │   │   └── index.ts
│       │   ├── app.component.e2e-spec.ts
│       │   ├── app.component.html
│       │   ├── app.component.spec.ts
│       │   ├── app.component.ts
│       │   ├── app.module.ts
│       │   ├── app.routes.ts
│       │   ├── hot_loader_main.ts
│       │   ├── main.ts
│       │   └── shared
│       │       ├── config
│       │       │   └── env.config.ts
│       │       ├── index.ts
│       │       ├── shared.module.ts
│       │       ├── name-list
│       │       │   ├── index.ts
│       │       │   ├── name-list.service.spec.ts
│       │       │   └── name-list.service.ts
│       │       ├── navbar
│       │       │   ├── index.ts
│       │       │   ├── navbar.component.css
│       │       │   ├── navbar.component.html
│       │       │   └── navbar.component.ts
│       │       └── toolbar
│       │           ├── index.ts
│       │           ├── toolbar.component.css
│       │           ├── toolbar.component.html
│       │           └── toolbar.component.ts
│       ├── assets
│       │   ├── data.json
│       │   └── svg
│       │       └── more.svg
│       ├── css
│       │   └── main.css
│       ├── index.html
│       ├── testing
│       │   └── router
│       │       ├── mock-location-strategy.ts
│       │       └── router-testing-providers.ts
│       └── tsconfig.json
├── test-main.js               <- testing configuration
├── tools
│   ├── README.md              <- build documentation
│   ├── config
│   │   ├── project.config.ts  <- configuration of the specific project
│   │   ├── seed.config.interfaces.ts
│   │   └── seed.config.ts     <- generic configuration of the seed project
│   │   └── seed.tslint.json   <- generic tslint configuration of the seed project
│   ├── config.ts              <- exported configuration (merge both seed.config and project.config, project.config overrides seed.config)
│   ├── debug.ts
│   ├── env                    <- environment configuration
│   │   ├── base.ts
│   │   ├── dev.ts
│   │   └── prod.ts
│   ├── manual_typings
│   │   ├── project            <- manual ambient typings for the project
│   │   │   └── sample.package.d.ts
│   │   └── seed               <- seed manual ambient typings
│   │       ├── autoprefixer.d.ts
│   │       ├── colorguard.d.ts
│   │       ├── connect-livereload.d.ts
│   │       ├── cssnano.d.ts
│   │       ├── doiuse.d.ts
│   │       ├── express-history-api-fallback.d.ts
│   │       ├── istream.d.ts
│   │       ├── karma.d.ts
│   │       ├── merge-stream.d.ts
│   │       ├── open.d.ts
│   │       ├── postcss-reporter.d.ts
│   │       ├── slash.d.ts
│   │       ├── stylelint.d.ts
│   │       ├── systemjs-builder.d.ts
│   │       ├── tildify.d.ts
│   │       ├── tiny-lr.d.ts
│   │       └── walk.d.ts
│   ├── tasks                  <- gulp tasks
│   │   ├── project            <- project specific gulp tasks
│   │   │   └── sample.task.ts
│   │   └── seed               <- seed generic gulp tasks. They can be overriden by the project specific gulp tasks
│   │       ├── build.assets.dev.ts
│   │       ├── build.assets.prod.ts
│   │       ├── build.bundles.app.ts
│   │       ├── build.bundles.ts
│   │       ├── build.docs.ts
│   │       ├── build.html_css.ts
│   │       ├── build.index.dev.ts
│   │       ├── build.index.prod.ts
│   │       ├── build.js.dev.ts
│   │       ├── build.js.e2e.ts
│   │       ├── build.js.prod.ts
│   │       ├── build.js.test.ts
│   │       ├── build.js.tools.ts
│   │       ├── check.versions.ts
│   │       ├── clean.all.ts
│   │       ├── clean.coverage.ts
│   │       ├── clean.dev.ts
│   │       ├── clean.prod.ts
│   │       ├── clean.tools.ts
│   │       ├── copy.js.prod.ts
│   │       ├── css-lint.ts
│   │       ├── e2e.ts
│   │       ├── generate.manifest.ts
│   │       ├── karma.start.ts
│   │       ├── serve.coverage.ts
│   │       ├── serve.docs.ts
│   │       ├── server.prod.ts
│   │       ├── server.start.ts
│   │       ├── tslint.ts
│   │       ├── watch.dev.ts
│   │       ├── watch.e2e.ts
│   │       ├── watch.test.ts
│   │       └── webdriver.ts
│   ├── utils                  <- build utils
│   │   ├── project            <- project specific gulp utils
│   │   │   └── sample_util.ts
│   │   ├── project.utils.ts
│   │   ├── seed               <- seed specific gulp utils
│   │   │   ├── clean.ts
│   │   │   ├── code_change_tools.ts
│   │   │   ├── server.ts
│   │   │   ├── tasks_tools.ts
│   │   │   ├── template_locals.ts
│   │   │   ├── tsproject.ts
│   │   │   └── watch.ts
│   │   └── seed.utils.ts
│   └── utils.ts
├── tsconfig.json              <- configuration of the typescript project (ts-node, which runs the tasks defined in gulpfile.ts)
├── tslint.json                <- tslint configuration
├── typings                    <- typings directory. Contains all the external typing definitions defined with typings
├── typings.json
└── appveyor.yml
```

# Contributors

[](https://github.com/mgechev) |[](https://github.com/ludohenin) |[](https://github.com/d3viant0ne) |[](https://github.com/Shyam-Chen) |[](https://github.com/NathanWalker) |[](https://github.com/tarlepp) |
:---: |:---: |:---: |:---: |:---: |:---: |
[mgechev](https://github.com/mgechev) |[ludohenin](https://github.com/ludohenin) |[d3viant0ne](https://github.com/d3viant0ne) |[Shyam-Chen](https://github.com/Shyam-Chen) |[NathanWalker](https://github.com/NathanWalker) |[tarlepp](https://github.com/tarlepp) |

[](https://github.com/Nightapes) |[](https://github.com/TheDonDope) |[](https://github.com/nareshbhatia) |[](https://github.com/kiuka) |[](https://github.com/hank-ehly) |[](https://github.com/daniru) |
:---: |:---: |:---: |:---: |:---: |:---: |
[Nightapes](https://github.com/Nightapes) |[TheDonDope](https://github.com/TheDonDope) |[nareshbhatia](https://github.com/nareshbhatia) |[kiuka](https://github.com/kiuka) |[hank-ehly](https://github.com/hank-ehly) |[daniru](https://github.com/daniru) |

[](https://github.com/njs50) |[](https://github.com/vyakymenko) |[](https://github.com/jesperronn) |[](https://github.com/robstoll) |[](https://github.com/sasikumardr) |[](https://github.com/aboeglin) |
:---: |:---: |:---: |:---: |:---: |:---: |
[njs50](https://github.com/njs50) |[vyakymenko](https://github.com/vyakymenko) |[jesperronn](https://github.com/jesperronn) |[robstoll](https://github.com/robstoll) |[sasikumardr](https://github.com/sasikumardr) |[aboeglin](https://github.com/aboeglin) |

[](https://github.com/markwhitfeld) |[](https://github.com/gkalpak) |[](https://github.com/ryzy) |[](https://github.com/eppsilon) |[](https://github.com/sfabriece) |[](https://github.com/jerryorta-dev) |
:---: |:---: |:---: |:---: |:---: |:---: |
[markwhitfeld](https://github.com/markwhitfeld) |[gkalpak](https://github.com/gkalpak) |[ryzy](https://github.com/ryzy) |[eppsilon](https://github.com/eppsilon) |[sfabriece](https://github.com/sfabriece) |[jerryorta-dev](https://github.com/jerryorta-dev) |

[](https://github.com/pgrzeszczak) |[](https://github.com/e-oz) |[](https://github.com/natarajanmca11) |[](https://github.com/domfarolino) |[](https://github.com/JayKan) |[](https://github.com/larsthorup) |
:---: |:---: |:---: |:---: |:---: |:---: |
[pgrzeszczak](https://github.com/pgrzeszczak) |[e-oz](https://github.com/e-oz) |[natarajanmca11](https://github.com/natarajanmca11) |[domfarolino](https://github.com/domfarolino) |[JayKan](https://github.com/JayKan) |[larsthorup](https://github.com/larsthorup) |

[](https://github.com/JakePartusch) |[](https://github.com/LuxDie) |[](https://github.com/amedinavalencia) |[](https://github.com/tsm91) |[](https://github.com/jvitor83) |[](https://github.com/juristr) |
:---: |:---: |:---: |:---: |:---: |:---: |
[JakePartusch](https://github.com/JakePartusch) |[LuxDie](https://github.com/LuxDie) |[amedinavalencia](https://github.com/amedinavalencia) |[tsm91](https://github.com/tsm91) |[jvitor83](https://github.com/jvitor83) |[juristr](https://github.com/juristr) |

[](https://github.com/JohnCashmore) |[](https://github.com/ouq77) |[](https://github.com/devanp92) |[](https://github.com/hAWKdv) |[](https://github.com/JunaidZA) |[](https://github.com/c-ice) |
:---: |:---: |:---: |:---: |:---: |:---: |
[JohnCashmore](https://github.com/JohnCashmore) |[ouq77](https://github.com/ouq77) |[devanp92](https://github.com/devanp92) |[hAWKdv](https://github.com/hAWKdv) |[JunaidZA](https://github.com/JunaidZA) |[c-ice](https://github.com/c-ice) |

[](https://github.com/markharding) |[](https://github.com/ojacquemart) |[](https://github.com/tiagomapmarques) |[](https://github.com/TuiKiken) |[](https://github.com/evanplaice) |[](https://github.com/gotenxds) |
:---: |:---: |:---: |:---: |:---: |:---: |
[markharding](https://github.com/markharding) |[ojacquemart](https://github.com/ojacquemart) |[tiagomapmarques](https://github.com/tiagomapmarques) |[TuiKiken](https://github.com/TuiKiken) |[evanplaice](https://github.com/evanplaice) |[gotenxds](https://github.com/gotenxds) |

[](https://github.com/turbohappy) |[](https://github.com/karlhaas) |[](https://github.com/troyanskiy) |[](https://github.com/Bigous) |[](https://github.com/ip512) |[](https://github.com/Green-Cat) |
:---: |:---: |:---: |:---: |:---: |:---: |
[turbohappy](https://github.com/turbohappy) |[karlhaas](https://github.com/karlhaas) |[troyanskiy](https://github.com/troyanskiy) |[Bigous](https://github.com/Bigous) |[ip512](https://github.com/ip512) |[Green-Cat](https://github.com/Green-Cat) |

[](https://github.com/Yonet) |[](https://github.com/edud69) |[](https://github.com/daixtrose) |[](https://github.com/amaltsev) |[](https://github.com/yassirh) |[](https://github.com/bbarry) |
:---: |:---: |:---: |:---: |:---: |:---: |
[Yonet](https://github.com/Yonet) |[edud69](https://github.com/edud69) |[daixtrose](https://github.com/daixtrose) |[amaltsev](https://github.com/amaltsev) |[yassirh](https://github.com/yassirh) |[bbarry](https://github.com/bbarry) |

[](https://github.com/nulldev07) |[](https://github.com/taguan) |[](https://github.com/bbarry) |[](https://github.com/sonicparke) |[](https://github.com/brendanbenson) |[](https://github.com/brian428) |
:---: |:---: |:---: |:---: |:---: |:---: |
[nulldev07](https://github.com/nulldev07) |[taguan](https://github.com/taguan) |[bbarry](https://github.com/bbarry) |[sonicparke](https://github.com/sonicparke) |[brendanbenson](https://github.com/brendanbenson) |[brian428](https://github.com/brian428) |

[](https://github.com/briantopping) |[](https://github.com/ckapilla) |[](https://github.com/cadriel) |[](https://github.com/dszymczuk) |[](https://github.com/dmurat) |[](https://github.com/peah90) |
:---: |:---: |:---: |:---: |:---: |:---: |
[briantopping](https://github.com/briantopping) |[ckapilla](https://github.com/ckapilla) |[cadriel](https://github.com/cadriel) |[dszymczuk](https://github.com/dszymczuk) |[dmurat](https://github.com/dmurat) |[peah90](https://github.com/peah90) |

[](https://github.com/dstockhammer) |[](https://github.com/dwido) |[](https://github.com/totev) |[](https://github.com/nosachamos) |[](https://github.com/koodikindral) |[](https://github.com/hpinsley) |
:---: |:---: |:---: |:---: |:---: |:---: |
[dstockhammer](https://github.com/dstockhammer) |[dwido](https://github.com/dwido) |[totev](https://github.com/totev) |[nosachamos](https://github.com/nosachamos) |[koodikindral](https://github.com/koodikindral) |[hpinsley](https://github.com/hpinsley) |

[](https://github.com/NN77) |[](https://github.com/isidroamv) |[](https://github.com/jeffbcross) |[](https://github.com/Drane) |[](https://github.com/johnjelinek) |[](https://github.com/JunusErgin) |
:---: |:---: |:---: |:---: |:---: |:---: |
[NN77](https://github.com/NN77) |[isidroamv](https://github.com/isidroamv) |[jeffbcross](https://github.com/jeffbcross) |[Drane](https://github.com/Drane) |[johnjelinek](https://github.com/johnjelinek) |[JunusErgin](https://github.com/JunusErgin) |

[](https://github.com/justindujardin) |[](https://github.com/lihaibh) |[](https://github.com/Brooooooklyn) |[](https://github.com/tandu) |[](https://github.com/inkidotcom) |[](https://github.com/daixtrose) |
:---: |:---: |:---: |:---: |:---: |:---: |
[justindujardin](https://github.com/justindujardin) |[lihaibh](https://github.com/lihaibh) |[Brooooooklyn](https://github.com/Brooooooklyn) |[tandu](https://github.com/tandu) |[inkidotcom](https://github.com/inkidotcom) |[daixtrose](https://github.com/daixtrose) |

[](https://github.com/oferze) |[](https://github.com/ocombe) |[](https://github.com/gdi2290) |[](https://github.com/typekpb) |[](https://github.com/philipooo) |[](https://github.com/redian) |
:---: |:---: |:---: |:---: |:---: |:---: |
[oferze](https://github.com/oferze) |[ocombe](https://github.com/ocombe) |[gdi2290](https://github.com/gdi2290) |[typekpb](https://github.com/typekpb) |[philipooo](https://github.com/philipooo) |[redian](https://github.com/redian) |

[](https://github.com/alexweber) |[](https://github.com/robbatt) |[](https://github.com/robertpenner) |[](https://github.com/Sjiep) |[](https://github.com/sclausen) |[](https://github.com/heavymery) |
:---: |:---: |:---: |:---: |:---: |:---: |
[alexweber](https://github.com/alexweber) |[robbatt](https://github.com/robbatt) |[robertpenner](https://github.com/robertpenner) |[Sjiep](https://github.com/Sjiep) |[sclausen](https://github.com/sclausen) |[heavymery](https://github.com/heavymery) |

[](https://github.com/tapas4java) |[](https://github.com/valera-rozuvan) |[](https://github.com/vincentpalita) |[](https://github.com/Yalrafih) |[](https://github.com/billsworld) |[](https://github.com/blackheart01) |
:---: |:---: |:---: |:---: |:---: |:---: |
[tapas4java](https://github.com/tapas4java) |[valera-rozuvan](https://github.com/valera-rozuvan) |[vincentpalita](https://github.com/vincentpalita) |[Yalrafih](https://github.com/Yalrafih) |[billsworld](https://github.com/billsworld) |[blackheart01](https://github.com/blackheart01) |

[](https://github.com/butterfieldcons) |[](https://github.com/danielcrisp) |[](https://github.com/jgolla) |[](https://github.com/omerfarukyilmaz) |[](https://github.com/pbazurin-softheme) |[](https://github.com/rossedfort) |
:---: |:---: |:---: |:---: |:---: |:---: |
[butterfieldcons](https://github.com/butterfieldcons) |[danielcrisp](https://github.com/danielcrisp) |[jgolla](https://github.com/jgolla) |[omerfarukyilmaz](https://github.com/omerfarukyilmaz) |[pbazurin-softheme](https://github.com/pbazurin-softheme) |[rossedfort](https://github.com/rossedfort) |

[](https://github.com/savcha) |[](https://github.com/ultrasonicsoft) |[](https://github.com/taguan) |
:---: |:---: |:---: |
[savcha](https://github.com/savcha) |[ultrasonicsoft](https://github.com/ultrasonicsoft) |[taguan](https://github.com/taguan) |

## Wiki Contributors

Here are all the awesome guys who are helping to make the project's wiki even better!

```
40  Minko Gechev
22  Clayton K. N. Passos
15  Shyam-Chen
14  Vincent van Proosdij
 8  matthew harwood
 8  Christian Dobert
 8  Robert van Kints
 6  Ludovic HENIN
 5  Attila Egyed
 4  davidgfolch
 4  Chris Kapilla
 3  Stefan Schüller
 3  Patrick Hillert
 3  Ezequiel Cicala
 3  Brian Kotek
 2  Nathan Walker
 2  Dinsitro
 2  Drake Wilson
 2  Simon Hampton
 2  Yannick Koehler
 2  Giovanni Candido da Silva
 2  hhubik
 2  Joshua Wiens
 2  Cy Klassen
 1  zcsongor
 1  Ameer Nuri
 1  Ankit Kamboj
 1  BouncingBit
 1  Dang Tung
 1  Eddie Sun
 1  Enrico Secondulfo
 1  Eugene Serkin
 1  Ishara Samantha
 1  Myrmex
 1  Pol Stafford
 1  Raphael Schmitt
 1  Robert Stoll
 1  Sebastian Fuss
 1  Sebastien de Salvador
 1  The Ult
 1  Yonet
 1  graham
 1  kiuka
 1  silicakes
 1  Adam Johannesmeyer
```

# Change Log

You can follow the [Angular change log here](https://github.com/angular/angular/blob/master/CHANGELOG.md).

# License

MIT


text:
(function ($) {
  const methods = {

    init(options) {
      const defaults = {
        duration: 200, // ms
        dist: -100, // zoom scale TODO: make this more intuitive as an option
        shift: 0, // spacing for center image
        padding: 0, // Padding between non center items
        fullWidth: false, // Change to full width styles
        indicators: false, // Toggle indicators
        noWrap: false, // Don't wrap around and cycle through items.
        onCycleTo: null, // Callback for when a new slide is cycled to.
      };
      options = $.extend(defaults, options);
      const namespace = Materialize.objectSelectorString($(this));

      return this.each(function (i) {
        const uniqueNamespace = namespace + i;
        let images,
          item_width,
          item_height,
          offset,
          center,
          pressed,
          dim,
          count,
          reference,
          referenceY,
          amplitude,
          target,
          velocity,
          scrolling,
          xform,
          frame,
          timestamp,
          ticker,
          dragged,
          vertical_dragged;
        const $indicators = $('

');
        let scrollingTimeout = null;

        // Initialize
        const view = $(this);
        const showIndicators = view.attr('data-indicators') || options.indicators;

        // Options
        const setCarouselHeight = function () {
          const firstImage = view.find('.carousel-item img').first();
          if (firstImage.length) {
            if (firstImage.prop('complete')) {
              view.css('height', firstImage.height());
            } else {
              firstImage.on('load', function () {
                view.css('height', $(this).height());
              });
            }
          } else {
            const imageHeight = view.find('.carousel-item').first().height();
            view.css('height', imageHeight);
          }
        };

        if (options.fullWidth) {
          options.dist = 0;
          setCarouselHeight();

          // Offset fixed items when indicators.
          if (showIndicators) {
            view.find('.carousel-fixed-item').addClass('with-indicators');
          }
        }

        // Don't double initialize.
        if (view.hasClass('initialized')) {
          // Recalculate variables
          $(window).trigger('resize');

          // Redraw carousel.
          $(this).trigger('carouselNext', [0.000001]);
          return true;
        }

        view.addClass('initialized');
        pressed = false;
        offset = target = 0;
        images = [];
        item_width = view.find('.carousel-item').first().innerWidth();
        item_height = view.find('.carousel-item').first().innerHeight();
        dim = item_width * 2 + options.padding;

        view.find('.carousel-item').each(function (i) {
          images.push($(this)[0]);
          if (showIndicators) {
            const $indicator = $('

');

            // Add active to first by default.
            if (i === 0) {
              $indicator.addClass('active');
            }

            // Handle clicks on indicators.
            $indicator.click(function (e) {
              e.stopPropagation();

              const index = $(this).index();
              cycleTo(index);
            });
            $indicators.append($indicator);
          }
        });

        if (showIndicators) {
          view.append($indicators);
        }
        count = images.length;

        function setupEvents() {
          if (typeof window.ontouchstart !== 'undefined') {
            view[0].addEventListener('touchstart', tap);
            view[0].addEventListener('touchmove', drag);
            view[0].addEventListener('touchend', release);
          }
          view[0].addEventListener('mousedown', tap);
          view[0].addEventListener('mousemove', drag);
          view[0].addEventListener('mouseup', release);
          view[0].addEventListener('mouseleave', release);
          view[0].addEventListener('click', click);
        }

        function xpos(e) {
          // touch event
          if (e.targetTouches && (e.targetTouches.length >= 1)) {
            return e.targetTouches[0].clientX;
          }

          // mouse event
          return e.clientX;
        }

        function ypos(e) {
          // touch event
          if (e.targetTouches && (e.targetTouches.length >= 1)) {
            return e.targetTouches[0].clientY;
          }

          // mouse event
          return e.clientY;
        }

        function wrap(x) {
          return (x >= count) ? (x % count) : (x < 0) ? wrap(count + (x % count)) : x;
        }

        function scroll(x) {
          // Track scrolling state
          scrolling = true;
          if (!view.hasClass('scrolling')) {
            view.addClass('scrolling');
          }
          if (scrollingTimeout != null) {
            window.clearTimeout(scrollingTimeout);
          }
          scrollingTimeout = window.setTimeout(() => {
            scrolling = false;
            view.removeClass('scrolling');
          }, options.duration);

          // Start actual scroll
          let i,
            half,
            delta,
            dir,
            tween,
            el,
            alignment,
            xTranslation;
          const lastCenter = center;

          offset = (typeof x === 'number') ? x : offset;
          center = Math.floor((offset + dim / 2) / dim);
          delta = offset - center * dim;
          dir = (delta < 0) ? 1 : -1;
          tween = -dir * delta * 2 / dim;
          half = count >> 1;

          if (!options.fullWidth) {
            alignment = `translateX(${(view[0].clientWidth - item_width) / 2}px) `;
            alignment += `translateY(${(view[0].clientHeight - item_height) / 2}px)`;
          } else {
            alignment = 'translateX(0)';
          }

          // Set indicator active
          if (showIndicators) {
            const diff = (center % count);
            const activeIndicator = $indicators.find('.indicator-item.active');
            if (activeIndicator.index() !== diff) {
              activeIndicator.removeClass('active');
              $indicators.find('.indicator-item').eq(diff).addClass('active');
            }
          }

          // center
          // Don't show wrapped items.
          if (!options.noWrap || (center >= 0 && center < count)) {
            el = images[wrap(center)];

            // Add active class to center item.
            if (!$(el).hasClass('active')) {
              view.find('.carousel-item').removeClass('active');
              $(el).addClass('active');
            }
            el.style[xform] = `${alignment
              } translateX(${-delta / 2}px)` +
              ` translateX(${dir * options.shift * tween * i}px)` +
              ` translateZ(${options.dist * tween}px)`;
            el.style.zIndex = 0;
            if (options.fullWidth) { tweenedOpacity = 1; } else { tweenedOpacity = 1 - 0.2 * tween; }
            el.style.opacity = tweenedOpacity;
            el.style.display = 'block';
          }

          for (i = 1; i <= half; ++i) {
            // right side
            if (options.fullWidth) {
              zTranslation = options.dist;
              tweenedOpacity = (i === half && delta < 0) ? 1 - tween : 1;
            } else {
              zTranslation = options.dist * (i * 2 + tween * dir);
              tweenedOpacity = 1 - 0.2 * (i * 2 + tween * dir);
            }
            // Don't show wrapped items.
            if (!options.noWrap || center + i < count) {
              el = images[wrap(center + i)];
              el.style[xform] = `${alignment
                } translateX(${options.shift + (dim * i - delta) / 2}px)` +
                ` translateZ(${zTranslation}px)`;
              el.style.zIndex = -i;
              el.style.opacity = tweenedOpacity;
              el.style.display = 'block';
            }

            // left side
            if (options.fullWidth) {
              zTranslation = options.dist;
              tweenedOpacity = (i === half && delta > 0) ? 1 - tween : 1;
            } else {
              zTranslation = options.dist * (i * 2 - tween * dir);
              tweenedOpacity = 1 - 0.2 * (i * 2 - tween * dir);
            }
            // Don't show wrapped items.
            if (!options.noWrap || center - i >= 0) {
              el = images[wrap(center - i)];
              el.style[xform] = `${alignment
                } translateX(${-options.shift + (-dim * i - delta) / 2}px)` +
                ` translateZ(${zTranslation}px)`;
              el.style.zIndex = -i;
              el.style.opacity = tweenedOpacity;
              el.style.display = 'block';
            }
          }

          // center
          // Don't show wrapped items.
          if (!options.noWrap || (center >= 0 && center < count)) {
            el = images[wrap(center)];
            el.style[xform] = `${alignment
              } translateX(${-delta / 2}px)` +
              ` translateX(${dir * options.shift * tween}px)` +
              ` translateZ(${options.dist * tween}px)`;
            el.style.zIndex = 0;
            if (options.fullWidth) { tweenedOpacity = 1; } else { tweenedOpacity = 1 - 0.2 * tween; }
            el.style.opacity = tweenedOpacity;
            el.style.display = 'block';
          }

          // onCycleTo callback
          if (lastCenter !== center &&
              typeof (options.onCycleTo) === 'function') {
            const $curr_item = view.find('.carousel-item').eq(wrap(center));
            options.onCycleTo.call(this, $curr_item, dragged);
          }
        }

        function track() {
          let now,
            elapsed,
            delta,
            v;

          now = Date.now();
          elapsed = now - timestamp;
          timestamp = now;
          delta = offset - frame;
          frame = offset;

          v = 1000 * delta / (1 + elapsed);
          velocity = 0.8 * v + 0.2 * velocity;
        }

        function autoScroll() {
          let elapsed,
            delta;

          if (amplitude) {
            elapsed = Date.now() - timestamp;
            delta = amplitude * Math.exp(-elapsed / options.duration);
            if (delta > 2 || delta < -2) {
              scroll(target - delta);
              requestAnimationFrame(autoScroll);
            } else {
              scroll(target);
            }
          }
        }

        function click(e) {
          // Disable clicks if carousel was dragged.
          if (dragged) {
            e.preventDefault();
            e.stopPropagation();
            return false;
          } else if (!options.fullWidth) {
            const clickedIndex = $(e.target).closest('.carousel-item').index();
            const diff = (center % count) - clickedIndex;

            // Disable clicks if carousel was shifted by click
            if (diff !== 0) {
              e.preventDefault();
              e.stopPropagation();
            }
            cycleTo(clickedIndex);
          }
        }

        function cycleTo(n) {
          let diff = (center % count) - n;

          // Account for wraparound.
          if (!options.noWrap) {
            if (diff < 0) {
              if (Math.abs(diff + count) < Math.abs(diff)) { diff += count; }
            } else if (diff > 0) {
              if (Math.abs(diff - count) < diff) { diff -= count; }
            }
          }

          // Call prev or next accordingly.
          if (diff < 0) {
            view.trigger('carouselNext', [Math.abs(diff)]);
          } else if (diff > 0) {
            view.trigger('carouselPrev', [diff]);
          }
        }

        function tap(e) {
          e.preventDefault();
          pressed = true;
          dragged = false;
          vertical_dragged = false;
          reference = xpos(e);
          referenceY = ypos(e);

          velocity = amplitude = 0;
          frame = offset;
          timestamp = Date.now();
          clearInterval(ticker);
          ticker = setInterval(track, 100);
        }

        function drag(e) {
          let x,
            delta,
            deltaY;
          if (pressed) {
            x = xpos(e);
            y = ypos(e);
            delta = reference - x;
            deltaY = Math.abs(referenceY - y);
            if (deltaY < 30 && !vertical_dragged) {
              // If vertical scrolling don't allow dragging.
              if (delta > 2 || delta < -2) {
                dragged = true;
                reference = x;
                scroll(offset + delta);
              }
            } else if (dragged) {
              // If dragging don't allow vertical scroll.
              e.preventDefault();
              e.stopPropagation();
              return false;
            } else {
              // Vertical scrolling.
              vertical_dragged = true;
            }
          }

          if (dragged) {
            // If dragging don't allow vertical scroll.
            e.preventDefault();
            e.stopPropagation();
            return false;
          }
        }

        function release(e) {
          if (pressed) {
            pressed = false;
          } else {
            return;
          }

          clearInterval(ticker);
          target = offset;
          if (velocity > 10 || velocity < -10) {
            amplitude = 0.9 * velocity;
            target = offset + amplitude;
          }
          target = Math.round(target / dim) * dim;

          // No wrap of items.
          if (options.noWrap) {
            if (target >= dim * (count - 1)) {
              target = dim * (count - 1);
            } else if (target < 0) {
              target = 0;
            }
          }
          amplitude = target - offset;
          timestamp = Date.now();
          requestAnimationFrame(autoScroll);

          if (dragged) {
            e.preventDefault();
            e.stopPropagation();
          }
          return false;
        }

        xform = 'transform';
        ['webkit', 'Moz', 'O', 'ms'].every((prefix) => {
          const e = `${prefix}Transform`;
          if (typeof document.body.style[e] !== 'undefined') {
            xform = e;
            return false;
          }
          return true;
        });

        $(window).off(`resize.carousel-${uniqueNamespace}`).on(`resize.carousel-${uniqueNamespace}`, () => {
          if (options.fullWidth) {
            item_width = view.find('.carousel-item').first().innerWidth();
            item_height = view.find('.carousel-item').first().innerHeight();
            dim = item_width * 2 + options.padding;
            offset = center * 2 * item_width;
            target = offset;
          } else {
            scroll();
          }
        });

        setupEvents();
        scroll(offset);

        $(this).on('carouselNext', (e, n) => {
          if (n === undefined) {
            n = 1;
          }
          target = (dim * Math.round(offset / dim)) + (dim * n);
          if (offset !== target) {
            amplitude = target - offset;
            timestamp = Date.now();
            requestAnimationFrame(autoScroll);
          }
        });

        $(this).on('carouselPrev', (e, n) => {
          if (n === undefined) {
            n = 1;
          }
          target = (dim * Math.round(offset / dim)) - (dim * n);
          if (offset !== target) {
            amplitude = target - offset;
            timestamp = Date.now();
            requestAnimationFrame(autoScroll);
          }
        });

        $(this).on('carouselSet', (e, n) => {
          if (n === undefined) {
            n = 0;
          }
          cycleTo(n);
        });
      });
    },
    next(n) {
      $(this).trigger('carouselNext', [n]);
    },
    prev(n) {
      $(this).trigger('carouselPrev', [n]);
    },
    set(n) {
      $(this).trigger('carouselSet', [n]);
    },
  };

  $.fn.carousel = function (methodOrOptions) {
    if (methods[methodOrOptions]) {
      return methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof methodOrOptions === 'object' || !methodOrOptions) {
        // Default to "init"
      return methods.init.apply(this, arguments);
    }
    $.error(`Method ${methodOrOptions} does not exist on jQuery.carousel`);
  }; // Plugin end
}(jQuery));

redpajama_set_name: RedPajamaGithub


text:
/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 4.0 */
package org.apache.hadoop.hive.serde2.dynamic_type;

/**
 * An implementation of interface CharStream, where the stream is assumed to
 * contain only ASCII characters (without unicode processing).
 */

public class SimpleCharStream
{
  public static final boolean staticFlag = false;
  int bufsize;
  int available;
  int tokenBegin;
  public int bufpos = -1;
  protected int bufline[];
  protected int bufcolumn[];

  protected int column = 0;
  protected int line = 1;

  protected boolean prevCharIsCR = false;
  protected boolean prevCharIsLF = false;

  protected java.io.Reader inputStream;

  protected char[] buffer;
  protected int maxNextCharInd = 0;
  protected int inBuf = 0;
  protected int tabSize = 8;

  protected void setTabSize(int i) { tabSize = i; }
  protected int getTabSize(int i) { return tabSize; }

  protected void ExpandBuff(boolean wrapAround)
  {
     char[] newbuffer = new char[bufsize + 2048];
     int newbufline[] = new int[bufsize + 2048];
     int newbufcolumn[] = new int[bufsize + 2048];

     try
     {
        if (wrapAround)
        {
           System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
           System.arraycopy(buffer, 0, newbuffer,
                                             bufsize - tokenBegin, bufpos);
           buffer = newbuffer;

           System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
           System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);
           bufline = newbufline;

           System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
           System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);
           bufcolumn = newbufcolumn;

           maxNextCharInd = (bufpos += (bufsize - tokenBegin));
        }
        else
        {
           System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
           buffer = newbuffer;

           System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
           bufline = newbufline;

           System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
           bufcolumn = newbufcolumn;

           maxNextCharInd = (bufpos -= tokenBegin);
        }
     }
     catch (Throwable t)
     {
        throw new Error(t.getMessage());
     }

     bufsize += 2048;
     available = bufsize;
     tokenBegin = 0;
  }

  protected void FillBuff() throws java.io.IOException
  {
     if (maxNextCharInd == available)
     {
        if (available == bufsize)
        {
           if (tokenBegin > 2048)
           {
              bufpos = maxNextCharInd = 0;
              available = tokenBegin;
           }
           else if (tokenBegin < 0)
              bufpos = maxNextCharInd = 0;
           else
              ExpandBuff(false);
        }
        else if (available > tokenBegin)
           available = bufsize;
        else if ((tokenBegin - available) < 2048)
           ExpandBuff(true);
        else
           available = tokenBegin;
     }

     int i;
     try {
        if ((i = inputStream.read(buffer, maxNextCharInd,
                                    available - maxNextCharInd)) == -1)
        {
           inputStream.close();
           throw new java.io.IOException();
        }
        else
           maxNextCharInd += i;
        return;
     }
     catch(java.io.IOException e) {
        --bufpos;
        backup(0);
        if (tokenBegin == -1)
           tokenBegin = bufpos;
        throw e;
     }
  }

  public char BeginToken() throws java.io.IOException
  {
     tokenBegin = -1;
     char c = readChar();
     tokenBegin = bufpos;

     return c;
  }

  protected void UpdateLineColumn(char c)
  {
     column++;

     if (prevCharIsLF)
     {
        prevCharIsLF = false;
        line += (column = 1);
     }
     else if (prevCharIsCR)
     {
        prevCharIsCR = false;
        if (c == '\n')
        {
           prevCharIsLF = true;
        }
        else
           line += (column = 1);
     }

     switch (c)
     {
        case '\r' :
           prevCharIsCR = true;
           break;
        case '\n' :
           prevCharIsLF = true;
           break;
        case '\t' :
           column--;
           column += (tabSize - (column % tabSize));
           break;
        default :
           break;
     }

     bufline[bufpos] = line;
     bufcolumn[bufpos] = column;
  }

  public char readChar() throws java.io.IOException
  {
     if (inBuf > 0)
     {
        --inBuf;

        if (++bufpos == bufsize)
           bufpos = 0;

        return buffer[bufpos];
     }

     if (++bufpos >= maxNextCharInd)
        FillBuff();

     char c = buffer[bufpos];

     UpdateLineColumn(c);
     return (c);
  }

  /**
   * @deprecated
   * @see #getEndColumn
   */

  public int getColumn() {
     return bufcolumn[bufpos];
  }

  /**
   * @deprecated
   * @see #getEndLine
   */

  public int getLine() {
     return bufline[bufpos];
  }

  public int getEndColumn() {
     return bufcolumn[bufpos];
  }

  public int getEndLine() {
     return bufline[bufpos];
  }

  public int getBeginColumn() {
     return bufcolumn[tokenBegin];
  }

  public int getBeginLine() {
     return bufline[tokenBegin];
  }

  public void backup(int amount) {

    inBuf += amount;
    if ((bufpos -= amount) < 0)
       bufpos += bufsize;
  }

  public SimpleCharStream(java.io.Reader dstream, int startline,
  int startcolumn, int buffersize)
  {
    inputStream = dstream;
    line = startline;
    column = startcolumn - 1;

    available = bufsize = buffersize;
    buffer = new char[buffersize];
    bufline = new int[buffersize];
    bufcolumn = new int[buffersize];
  }

  public SimpleCharStream(java.io.Reader dstream, int startline,
                          int startcolumn)
  {
     this(dstream, startline, startcolumn, 4096);
  }

  public SimpleCharStream(java.io.Reader dstream)
  {
     this(dstream, 1, 1, 4096);
  }
  public void ReInit(java.io.Reader dstream, int startline,
  int startcolumn, int buffersize)
  {
    inputStream = dstream;
    line = startline;
    column = startcolumn - 1;

    if (buffer == null || buffersize != buffer.length)
    {
      available = bufsize = buffersize;
      buffer = new char[buffersize];
      bufline = new int[buffersize];
      bufcolumn = new int[buffersize];
    }
    prevCharIsLF = prevCharIsCR = false;
    tokenBegin = inBuf = maxNextCharInd = 0;
    bufpos = -1;
  }

  public void ReInit(java.io.Reader dstream, int startline,
                     int startcolumn)
  {
     ReInit(dstream, startline, startcolumn, 4096);
  }

  public void ReInit(java.io.Reader dstream)
  {
     ReInit(dstream, 1, 1, 4096);
  }
  public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
  int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
  {
     this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
  }

  public SimpleCharStream(java.io.InputStream dstream, int startline,
  int startcolumn, int buffersize)
  {
     this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
  }

  public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
                          int startcolumn) throws java.io.UnsupportedEncodingException
  {
     this(dstream, encoding, startline, startcolumn, 4096);
  }

  public SimpleCharStream(java.io.InputStream dstream, int startline,
                          int startcolumn)
  {
     this(dstream, startline, startcolumn, 4096);
  }

  public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
  {
     this(dstream, encoding, 1, 1, 4096);
  }

  public SimpleCharStream(java.io.InputStream dstream)
  {
     this(dstream, 1, 1, 4096);
  }

  public void ReInit(java.io.InputStream dstream, String encoding, int startline,
                          int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
  {
     ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
  }

  public void ReInit(java.io.InputStream dstream, int startline,
                          int startcolumn, int buffersize)
  {
     ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
  }

  public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
  {
     ReInit(dstream, encoding, 1, 1, 4096);
  }

  public void ReInit(java.io.InputStream dstream)
  {
     ReInit(dstream, 1, 1, 4096);
  }
  public void ReInit(java.io.InputStream dstream, String encoding, int startline,
                     int startcolumn) throws java.io.UnsupportedEncodingException
  {
     ReInit(dstream, encoding, startline, startcolumn, 4096);
  }
  public void ReInit(java.io.InputStream dstream, int startline,
                     int startcolumn)
  {
     ReInit(dstream, startline, startcolumn, 4096);
  }
  public String GetImage()
  {
     if (bufpos >= tokenBegin)
        return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);
     else
        return new String(buffer, tokenBegin, bufsize - tokenBegin) +
                              new String(buffer, 0, bufpos + 1);
  }

  public char[] GetSuffix(int len)
  {
     char[] ret = new char[len];

     if ((bufpos + 1) >= len)
        System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);
     else
     {
        System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,
                                                          len - bufpos - 1);
        System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);
     }

     return ret;
  }

  public void Done()
  {
     buffer = null;
     bufline = null;
     bufcolumn = null;
  }

  /**
   * Method to adjust line and column numbers for the start of a token.
   */
  public void adjustBeginLineColumn(int newLine, int newCol)
  {
     int start = tokenBegin;
     int len;

     if (bufpos >= tokenBegin)
     {
        len = bufpos - tokenBegin + inBuf + 1;
     }
     else
     {
        len = bufsize - tokenBegin + bufpos + 1 + inBuf;
     }

     int i = 0, j = 0, k = 0;
     int nextColDiff = 0, columnDiff = 0;

     while (i < len &&
            bufline[j = start % bufsize] == bufline[k = ++start % bufsize])
     {
        bufline[j] = newLine;
        nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];
        bufcolumn[j] = newCol + columnDiff;
        columnDiff = nextColDiff;
        i++;
     }

     if (i < len)
     {
        bufline[j] = newLine++;
        bufcolumn[j] = newCol + columnDiff;

        while (i++ < len)
        {
           if (bufline[j = start % bufsize] != bufline[++start % bufsize])
              bufline[j] = newLine++;
           else
              bufline[j] = newLine;
        }
     }

     line = bufline[j];
     column = bufcolumn[j];
  }

}


text:
"""autogenerated by genpy from emotiv_epoc/EEGFrame.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct

import std_msgs.msg

class EEGFrame(genpy.Message):
  _md5sum = "92a93661fa971fb7494f0877c88d2361"
  _type = "emotiv_epoc/EEGFrame"
  _has_header = True #flag to mark the presence of a Header object
  _full_text = """Header header
int32 accel_x
int32 accel_y

uint32 channel_count
string[] channel_names
int32[] signals
int32[] qualities

================================================================================
MSG: std_msgs/Header
# Standard metadata for higher-level stamped data types.
# This is generally used to communicate timestamped data
# in a particular coordinate frame.
#
# sequence ID: consecutively increasing ID
uint32 seq
#Two-integer timestamp that is expressed as:
# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')
# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')
# time-handling sugar is provided by the client library
time stamp
#Frame this data is associated with
# 0: no frame
# 1: global frame
string frame_id
"""
  __slots__ = ['header','accel_x','accel_y','channel_count','channel_names','signals','qualities']
  _slot_types = ['std_msgs/Header','int32','int32','uint32','string[]','int32[]','int32[]']

  def __init__(self, *args, **kwds):
    """
    Constructor. Any message fields that are implicitly/explicitly
    set to None will be assigned a default value. The recommend
    use is keyword arguments as this is more robust to future message
    changes.  You cannot mix in-order arguments and keyword arguments.

    The available fields are:
       header,accel_x,accel_y,channel_count,channel_names,signals,qualities

    :param args: complete set of field values, in .msg order
    :param kwds: use keyword arguments corresponding to message field names
    to set specific fields.
    """
    if args or kwds:
      super(EEGFrame, self).__init__(*args, **kwds)
      #message fields cannot be None, assign default values for those that are
      if self.header is None:
        self.header = std_msgs.msg.Header()
      if self.accel_x is None:
        self.accel_x = 0
      if self.accel_y is None:
        self.accel_y = 0
      if self.channel_count is None:
        self.channel_count = 0
      if self.channel_names is None:
        self.channel_names = []
      if self.signals is None:
        self.signals = []
      if self.qualities is None:
        self.qualities = []
    else:
      self.header = std_msgs.msg.Header()
      self.accel_x = 0
      self.accel_y = 0
      self.channel_count = 0
      self.channel_names = []
      self.signals = []
      self.qualities = []

  def _get_types(self):
    """
    internal API method
    """
    return self._slot_types

  def serialize(self, buff):
    """
    serialize message into buffer
    :param buff: buffer, ``StringIO``
    """
    try:
      _x = self
      buff.write(_get_struct_3I().pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs))
      _x = self.header.frame_id
      length = len(_x)
      if python3 or type(_x) == unicode:
        _x = _x.encode('utf-8')
        length = len(_x)
      buff.write(struct.pack('<I%ss'%length, length, _x))
      _x = self
      buff.write(_get_struct_2iI().pack(_x.accel_x, _x.accel_y, _x.channel_count))
      length = len(self.channel_names)
      buff.write(_struct_I.pack(length))
      for val1 in self.channel_names:
        length = len(val1)
        if python3 or type(val1) == unicode:
          val1 = val1.encode('utf-8')
          length = len(val1)
        buff.write(struct.pack('<I%ss'%length, length, val1))
      length = len(self.signals)
      buff.write(_struct_I.pack(length))
      pattern = '<%si'%length
      buff.write(struct.pack(pattern, *self.signals))
      length = len(self.qualities)
      buff.write(_struct_I.pack(length))
      pattern = '<%si'%length
      buff.write(struct.pack(pattern, *self.qualities))
    except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
    except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))

  def deserialize(self, str):
    """
    unpack serialized message in str into this message instance
    :param str: byte array of serialized message, ``str``
    """
    try:
      if self.header is None:
        self.header = std_msgs.msg.Header()
      end = 0
      _x = self
      start = end
      end += 12
      (_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs,) = _get_struct_3I().unpack(str[start:end])
      start = end
      end += 4
      (length,) = _struct_I.unpack(str[start:end])
      start = end
      end += length
      if python3:
        self.header.frame_id = str[start:end].decode('utf-8')
      else:
        self.header.frame_id = str[start:end]
      _x = self
      start = end
      end += 12
      (_x.accel_x, _x.accel_y, _x.channel_count,) = _get_struct_2iI().unpack(str[start:end])
      start = end
      end += 4
      (length,) = _struct_I.unpack(str[start:end])
      self.channel_names = []
      for i in range(0, length):
        start = end
        end += 4
        (length,) = _struct_I.unpack(str[start:end])
        start = end
        end += length
        if python3:
          val1 = str[start:end].decode('utf-8')
        else:
          val1 = str[start:end]
        self.channel_names.append(val1)
      start = end
      end += 4
      (length,) = _struct_I.unpack(str[start:end])
      pattern = '<%si'%length
      start = end
      end += struct.calcsize(pattern)
      self.signals = struct.unpack(pattern, str[start:end])
      start = end
      end += 4
      (length,) = _struct_I.unpack(str[start:end])
      pattern = '<%si'%length
      start = end
      end += struct.calcsize(pattern)
      self.qualities = struct.unpack(pattern, str[start:end])
      return self
    except struct.error as e:
      raise genpy.DeserializationError(e) #most likely buffer underfill

  def serialize_numpy(self, buff, numpy):
    """
    serialize message with numpy array types into buffer
    :param buff: buffer, ``StringIO``
    :param numpy: numpy python module
    """
    try:
      _x = self
      buff.write(_get_struct_3I().pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs))
      _x = self.header.frame_id
      length = len(_x)
      if python3 or type(_x) == unicode:
        _x = _x.encode('utf-8')
        length = len(_x)
      buff.write(struct.pack('<I%ss'%length, length, _x))
      _x = self
      buff.write(_get_struct_2iI().pack(_x.accel_x, _x.accel_y, _x.channel_count))
      length = len(self.channel_names)
      buff.write(_struct_I.pack(length))
      for val1 in self.channel_names:
        length = len(val1)
        if python3 or type(val1) == unicode:
          val1 = val1.encode('utf-8')
          length = len(val1)
        buff.write(struct.pack('<I%ss'%length, length, val1))
      length = len(self.signals)
      buff.write(_struct_I.pack(length))
      pattern = '<%si'%length
      buff.write(self.signals.tostring())
      length = len(self.qualities)
      buff.write(_struct_I.pack(length))
      pattern = '<%si'%length
      buff.write(self.qualities.tostring())
    except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
    except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))

  def deserialize_numpy(self, str, numpy):
    """
    unpack serialized message in str into this message instance using numpy for array types
    :param str: byte array of serialized message, ``str``
    :param numpy: numpy python module
    """
    try:
      if self.header is None:
        self.header = std_msgs.msg.Header()
      end = 0
      _x = self
      start = end
      end += 12
      (_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs,) = _get_struct_3I().unpack(str[start:end])
      start = end
      end += 4
      (length,) = _struct_I.unpack(str[start:end])
      start = end
      end += length
      if python3:
        self.header.frame_id = str[start:end].decode('utf-8')
      else:
        self.header.frame_id = str[start:end]
      _x = self
      start = end
      end += 12
      (_x.accel_x, _x.accel_y, _x.channel_count,) = _get_struct_2iI().unpack(str[start:end])
      start = end
      end += 4
      (length,) = _struct_I.unpack(str[start:end])
      self.channel_names = []
      for i in range(0, length):
        start = end
        end += 4
        (length,) = _struct_I.unpack(str[start:end])
        start = end
        end += length
        if python3:
          val1 = str[start:end].decode('utf-8')
        else:
          val1 = str[start:end]
        self.channel_names.append(val1)
      start = end
      end += 4
      (length,) = _struct_I.unpack(str[start:end])
      pattern = '<%si'%length
      start = end
      end += struct.calcsize(pattern)
      self.signals = numpy.frombuffer(str[start:end], dtype=numpy.int32, count=length)
      start = end
      end += 4
      (length,) = _struct_I.unpack(str[start:end])
      pattern = '<%si'%length
      start = end
      end += struct.calcsize(pattern)
      self.qualities = numpy.frombuffer(str[start:end], dtype=numpy.int32, count=length)
      return self
    except struct.error as e:
      raise genpy.DeserializationError(e) #most likely buffer underfill

_struct_I = genpy.struct_I
def _get_struct_I():
    global _struct_I
    return _struct_I
_struct_3I = None
def _get_struct_3I():
    global _struct_3I
    if _struct_3I is None:
        _struct_3I = struct.Struct("<3I")
    return _struct_3I
_struct_2iI = None
def _get_struct_2iI():
    global _struct_2iI
    if _struct_2iI is None:
        _struct_2iI = struct.Struct("<2iI")
    return _struct_2iI


text:
__author__ = 'eric'

import unittest
import os
from ckcache import new_cache

class BasicTests(unittest.TestCase):

    root = '/tmp/ckcache-test'

    def setUp(self):

        from shutil import rmtree

        try:
            rmtree(self.root)
        except OSError:
            pass

    def subpath(self,p):
        return os.path.join(self.root, p)

    def make_test_file(self):

        testfile = os.path.join(self.root, 'testfile')

        if not os.path.exists(self.root):
            os.makedirs(self.root)

        with open(testfile, 'w+') as f:
            for i in range(1024):
                f.write(str(i%10) * 1023)
                f.write('\n')

        return testfile

    def new_rand_file(self, path, size=1024):

        dir_ = os.path.dirname(path)

        if not os.path.isdir(dir_):
            os.makedirs(dir_)

        with open(path, 'w+') as f:
            for i in range(size):
                f.write(str(i % 10) * 1024)
                #f.write('\n')

        return path

    def test_basic(self):

        from ckcache.filesystem import FsCache, FsLimitedCache

        l1_repo_dir = os.path.join(self.root, 'repo-l1')
        os.makedirs(l1_repo_dir)
        l2_repo_dir = os.path.join(self.root, 'repo-l2')
        os.makedirs(l2_repo_dir)

        testfile = self.make_test_file()
        #
        # Basic operations on a cache with no upstream
        #
        l2 = FsCache(l2_repo_dir)

        p = l2.put(testfile, 'tf1')
        l2.put(testfile, 'tf2')
        g = l2.get('tf1')

        self.assertTrue(os.path.exists(p))
        self.assertTrue(os.path.exists(g))
        self.assertEqual(p, g)

        self.assertIsNone(l2.get('foobar'))

        l2.remove('tf1')

        self.assertIsNone(l2.get('tf1'))

        #
        # Now create the cache with an upstream, the first
        # cache we created

        l1 = FsLimitedCache(l1_repo_dir, upstream=l2, size=5)

        print l1
        print l2

        g = l1.get('tf2')
        self.assertTrue(g is not None)

        # Put to one and check in the other.

        l1.put(testfile, 'write-through')
        self.assertIsNotNone(l2.get('write-through'))

        l1.remove('write-through', propagate=True)
        self.assertIsNone(l2.get('write-through'))

        # Put a bunch of files in, and check that
        # l2 gets all of the files, but the size of l1 says constrained
        for i in range(0, 10):
            l1.put(testfile, 'many' + str(i))

        self.assertEquals(4194304, l1.size)

        # Check that the right files got deleted
        self.assertFalse(os.path.exists(os.path.join(l1.cache_dir, 'many1')))
        self.assertFalse(os.path.exists(os.path.join(l1.cache_dir, 'many5')))
        self.assertTrue(os.path.exists(os.path.join(l1.cache_dir, 'many6')))

        # Fetch a file that was displaced, to check that it gets loaded back
        # into the cache.
        p = l1.get('many1')
        p = l1.get('many2')
        self.assertTrue(p is not None)
        self.assertTrue(os.path.exists(os.path.join(l1.cache_dir, 'many1')))
        # Should have deleted many6
        self.assertFalse(os.path.exists(os.path.join(l1.cache_dir, 'many6')))
        self.assertTrue(os.path.exists(os.path.join(l1.cache_dir, 'many7')))

        #
        # Check that verification works
        #
        l1.verify()

        os.remove(os.path.join(l1.cache_dir, 'many8'))

        with self.assertRaises(Exception):
            l1.verify()

        l1.remove('many8')

        l1.verify()

        c = l1.database.cursor()
        c.execute("DELETE FROM  files WHERE path = ?", ('many9',))
        l1.database.commit()

        with self.assertRaises(Exception):
            l1.verify()

        l1.remove('many9')

        l1.verify()

    def test_basic_prefix(self):
        from ckcache.filesystem import FsCache, FsLimitedCache

        cache_dir = os.path.join(self.root, 'test_prefixes')

        prefix = 'prefix'

        cache1 = FsCache(cache_dir)

        cache2 = FsCache(cache_dir, prefix=prefix)

        tf = self.make_test_file()

        cache2.put(tf, 'tf')

        self.assertTrue(cache1.has('{}/{}'.format(prefix, 'tf')))

    def test_compression(self):

        from ckcache import new_cache, md5_for_file, copy_file_or_flo

        comp_cache = new_cache(os.path.join(self.root, 'compressioncache#compress'))

        print comp_cache

        test_file_name = 'test_file'

        fn = self.make_test_file()
        cf = comp_cache.put(fn, test_file_name)

        with open(cf) as stream:
            from ckcache.sgzip import GzipFile

            stream = GzipFile(stream)

            uncomp_cache = new_cache(os.path.join(self.root,'uncomp'))

            uncomp_stream = uncomp_cache.put_stream('decomp')

            copy_file_or_flo(stream, uncomp_stream)

        uncomp_stream.close()

        dcf = uncomp_cache.get('decomp')

        self.assertEquals(md5_for_file(fn), md5_for_file(dcf))

        with comp_cache.get_stream(test_file_name) as f:
            print len(f.read())

        with uncomp_cache.get_stream('decomp') as f:
            print len(f.read())

        with comp_cache.put_stream('comp2') as s:
            copy_file_or_flo(fn, s)

        self.assertTrue(comp_cache.has('comp2'))

        os.remove(fn)

    def test_md5(self):

        from ckcache import new_cache, md5_for_file
        from ckcache.filesystem import make_metadata

        fn = self.make_test_file()

        md5 = md5_for_file(fn)

        cache = new_cache(os.path.join(self.root, 'fscache'))

        cache.put(fn, 'foo1')

        abs_path = cache.path('foo1')

        self.assertEquals(md5, cache.md5('foo1'))

        cache = new_cache(os.path.join(self.root, 'compressioncache'))

        cache.put(fn, 'foo2', metadata=make_metadata(fn))

        abs_path = cache.path('foo2')

        self.assertEquals(md5, cache.md5('foo2'))

        os.remove(fn)

    def test_attachment(self):
        from ckcache import new_cache

        testfile = self.new_rand_file(os.path.join(self.root, 'testfile'))

        fs1 = new_cache(dict(dir=os.path.join(self.root, 'fs1')))

        fs3 = new_cache(dict(dir=os.path.join(self.root, 'fs3')))

        fs3.put(testfile, 'tf')
        self.assertTrue(fs3.has('tf'))
        fs3.remove('tf')
        self.assertFalse(fs3.has('tf'))

        # Show that attachment works, and that deletes propagate.
        fs3.attach(fs1)
        fs3.put(testfile, 'tf')
        self.assertTrue(fs3.has('tf'))
        self.assertTrue(fs1.has('tf'))
        fs3.remove('tf', propagate=True)
        self.assertFalse(fs3.has('tf'))
        self.assertFalse(fs1.has('tf'))
        fs3.detach()

        # Show detachment works
        fs3.attach(fs1)
        fs3.put(testfile, 'tf')
        self.assertTrue(fs3.has('tf'))
        self.assertTrue(fs1.has('tf'))
        fs3.detach()
        fs3.remove('tf', propagate=True)
        self.assertFalse(fs3.has('tf'))
        self.assertTrue(fs1.has('tf'))

    def test_multi_cache(self):
        from ckcache import new_cache
        from ckcache.multi import MultiCache

        testfile = self.new_rand_file(os.path.join(self.root, 'testfile'), size=2)

        fs1 = new_cache(dict(dir=os.path.join(self.root, 'fs1')))
        fs2 = new_cache(dict(dir=os.path.join(self.root, 'fs2')))
        fs3 = new_cache(dict(dir=os.path.join(self.root, 'fs3')))

        caches = [fs1, fs2, fs3]

        for i, cache in enumerate(caches, 1):
            cache.put(testfile, 'fs' + str(i), metadata={'i': i})
            j = (i + 1) % len(caches)

            caches[j].put(testfile, 'fs' + str(i), metadata={'i': i})

        mc = MultiCache(caches)
        ls = mc.list()

        self.assertEqual(3, len(ls))
        self.assertIn('fs1', ls)
        self.assertIn('fs3', ls)

        self.assertIn('/tmp/ckcache-test/fs1', ls['fs1']['caches'])
        self.assertIn('/tmp/ckcache-test/fs3', ls['fs1']['caches'])

        mc2 = MultiCache([fs1, fs2])
        ls = mc2.list()
        self.assertEqual(3, len(ls))
        self.assertIn('fs1', ls)
        self.assertIn('fs3', ls)

        mc.put(testfile, 'mc1')
        ls = mc.list()
        self.assertEqual(4, len(ls))
        self.assertIn('mc1', ls)

        # Put should have gone to first cache
        mc2 = MultiCache([fs2, fs3])
        ls = mc2.list()
        self.assertEqual(3, len(ls))
        self.assertNotIn('mc1', ls)
        self.assertIn('fs1', ls)
        self.assertIn('fs3', ls)

    def test_alt_cache(self):

        from ckcache.multi import AltReadCache

        testfile = self.new_rand_file(os.path.join(self.root, 'testfile'), size=2)

        fs1 = new_cache(dict(dir=os.path.join(self.root, 'fs1')))
        fs2 = new_cache(dict(dir=os.path.join(self.root, 'fs2')))

        fs2.put(testfile, 'fs2', {'foo': 'bar'})

        self.assertFalse(fs1.has('fs2'))
        self.assertTrue(fs2.has('fs2'))

        arc = AltReadCache(fs1, fs2)
        self.assertTrue(arc.has('fs2'))
        self.assertEquals(['/tmp/ckcache-test/fs2'], arc.list()['fs2']['caches'])

        self.assertEquals('/tmp/ckcache-test/fs1/fs2', arc.get('fs2'))

        # Now the fs1 cache should have the file too
        self.assertTrue(fs1.has('fs2'))
        self.assertTrue(fs2.has('fs2'))

        self.assertIn('foo', fs1.metadata('fs2'))

    def test_accounts(self):

        config = dict(
            dir = self.subpath('ta_d1'),
            upstream = dict(
                dir = self.subpath('ta_d2'),
                upstream = 's3://devtest.sandiegodata.org/test'
            )
        )

        c =  new_cache(config)

        with c.put_stream('foobar',metadata=dict(foo='bar')) as f:
            f.write("bar baz")

        self.assertTrue(c.has('foobar'))

    def test_http(self):

        http_cache = new_cache('http://devtest.sandiegodata.org/jdoc')

        self.assertTrue(bool(http_cache.has('library.json')))
        self.assertFalse(http_cache.has('missing'))

        with http_cache.get_stream('library.json') as f:
            import json
            d = json.load(f)

            self.assertIn('bundles', d.keys())

        file_cache = new_cache(os.path.join(self.root,'fc'))
        file_cache.upstream = http_cache

        self.assertTrue(bool(file_cache.has('library.json')))
        self.assertFalse(file_cache.has('missing'))

        with file_cache.get_stream('library.json') as f:
            import json

            d = json.load(f)

            self.assertIn('bundles', d.keys())

    def test_http_compressed(self):
        from ckcache import  copy_file_or_flo

        http_cache = new_cache('http://s3.sandiegodata.org/library')

        for x in  http_cache.list().keys():
            if 'example' in x:
                print x

        x  = http_cache.get_stream('example.com/random-0.0.2.db').__enter__()

        with http_cache.get_stream('example.com/random-0.0.2.db') as f:

            with open('/tmp/foo.db', 'wb') as fout:
                copy_file_or_flo(f, fout)

    def test_fallback(self):
        from ckcache import FallbackFlo
        import gzip

        o1 = new_cache(os.path.join(self.root,'o1'))
        o2 = new_cache(os.path.join(self.root, 'o2'))

        testfile = self.make_test_file()

        if not os.path.exists(o1._cache_dir):
            os.makedirs(o1._cache_dir)

        o1.put(testfile,'x')
        o2.put(testfile, 'x')

        with self.assertRaises(IOError):
            with gzip.GzipFile(fileobj=o1.get_stream('x')) as f:
                print f.read()

        ff = FallbackFlo(gzip.GzipFile(fileobj=o1.get_stream('x')), o2.get_stream('x'))

        self.assertEquals(1048576,  len(ff.read()))

        ff = FallbackFlo(gzip.GzipFile(fileobj=o1.get_stream('x')), gzip.GzipFile(fileobj=o2.get_stream('x')))

        with self.assertRaises(IOError):
            self.assertEquals(1048576, len(ff.read()))

    def test_delay(self):
        from ckcache import parse_cache_string, new_cache, copy_file_or_flo

        testfile = self.new_rand_file(os.path.join(self.root, 'testfile'), size=20)

        config = parse_cache_string('/tmp/ckcache-test/logging#log')

        cache  = new_cache(config)

        print cache

        for i in range(1,5):
            rel_path = 'async_iter/{}'.format(i)
            with cache.put_stream(rel_path) as f:
                copy_file_or_flo(testfile, f)
                print "Wrote to", rel_path

        #self.assertTrue(cache.has(rel_path))

        #print cache.path(rel_path)
        #print cache.upstream.path(rel_path)

        #cache.remove(rel_path)

        #self.assertFalse(cache.has(rel_path))

        for e in cache.list_log():
            print e.path, e.time, e.cache
            e.remove()

    def test_dict(self):
        from ckcache import parse_cache_string, new_cache, copy_file_or_flo
        from ckcache.dictionary import DictCache

        testfile = self.new_rand_file(os.path.join(self.root, 'testfile'), size=20)

        base_cache = new_cache('/tmp/ckcache-test/dict#log')

        d = DictCache(base_cache)

        d[1] = ['one', 1]
        d[2] = ['two', 2]
        d[3] = ['three', 3]

        print d[1]

        for x in d:
            print x, d[x][0]

if __name__ == '__main__':
    unittest.main()


text:
module NothsTest
  module PricingRules
    class BulkPrice

      def initialize(hash)
        @product_code = hash[:product_code]
        @qty = hash[:qty]
        @price = hash[:price]
      end

      def saving(items)
        eligible_items = items.find_all do |item| item.product_code == @product_code end

        if eligible_items.count < @qty
          0
        else
          (eligible_items.first.price-@price)*eligible_items.count
        end
      end

    end
  end
end


text:
package cgeo.contacts.permission;

import cgeo.contacts.R;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class PermissionHandler {

    private static final String contactsPermission = Manifest.permission.READ_CONTACTS;

    private PermissionHandler() {
        // Utility class should not be instantiated externally
    }

    /*
     * Check if version is marshmallow and above.
     * Used in deciding to ask runtime permission
     * */
    private static boolean notNeedAskForPermission() {
        return Build.VERSION.SDK_INT < Build.VERSION_CODES.M;
    }

    public static boolean requestContactsPermission(final Activity activity) {

        final PermissionRequestContext perm = PermissionRequestContext.ContactsActivity;
        return requestPermission(activity, contactsPermission, perm);
    }

    private static boolean requestPermission(final Activity activity, final String permission, final PermissionRequestContext perm) {

        if (notNeedAskForPermission()) {
            return true;
        }

        if (hasPermission(activity, permission)) {
            return true;
        }

        askFor(activity, permission, perm);
        return false;
    }

    private static void askFor(final Activity activity, final String permission, final PermissionRequestContext perm) {
        askFor(activity, new String[]{permission}, perm);
    }

    private static void askFor(final Activity activity, final String[] permissions, final PermissionRequestContext perm) {
        ActivityCompat.requestPermissions(activity, permissions, perm.getRequestCode());
    }

    public static void askAgainFor(final Activity activity, final int requestCode) {
        if (requestCode == PermissionRequestContext.ContactsActivity.getRequestCode()) {
            askAgainForContacts(activity);
        }
    }

    private static void askAgainForContacts(final Activity activity) {
        final boolean currShouldShowStatus = ActivityCompat.shouldShowRequestPermissionRationale(activity, contactsPermission);
        final PermissionRequestContext perm = PermissionRequestContext.ContactsActivity;
        if (currShouldShowStatus) {
            // Show permission explanation dialog...
            new AlertDialog.Builder(activity)
                    .setMessage(perm.getAskAgainResource())
                    .setCancelable(false)
                    .setNeutralButton(R.string.ask_again, (dialog, which) -> askFor(activity, new String[]{contactsPermission}, perm))
                    .create()
                    .show();
        } else {
            // Never ask again selected, or device policy prohibits the app from having that permission.
            // So, disable that feature, or fall back to another situation...
            new AlertDialog.Builder(activity)
                    .setMessage(perm.getDeniedResource())
                    .setCancelable(false)
                    .setNegativeButton(R.string.close, (dialog, which) -> activity.finish())
                    .setPositiveButton(R.string.goto_app_details, (dialog, which) -> {
                                final Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                                        Uri.fromParts("package", activity.getPackageName(), null));
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                activity.startActivity(intent);
                                activity.finish();
                            }
                    )
                    .create()
                    .show();
        }
    }

    private static boolean hasPermission(final Activity activity, final String permission) {
        return hasPermission(activity, new String[]{permission});
    }

    private static boolean hasPermission(final Activity activity, final String[] permissions) {
        boolean hasPermission = true;
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
                hasPermission = false;
            }
        }

        return hasPermission;
    }
}


text:
package monitor.resource;

/**
 * REST API model class for custom response
 *
 * @author Sugeesh Chandraweera
 */
public class ResponseResource {

    private String response;

    public ResponseResource(String message, String... args) {
        try {
            this.response = processMsg(message, args);
        } catch (Exception ex) {
            this.response = message;
        }
    }

    private String processMsg(String message, String... args) throws Exception {
        //todo need to optimize this
        int index = 0;
        while (message.contains("{}")) {
            message = message.replaceFirst("\\{\\}", args[index++]);
        }
        return message;
    }

    public String getResponse() {
        return response;
    }

    public void setResponse(String response) {
        this.response = response;
    }
}


text:
package uk.joshiejack.energy.events;

import uk.joshiejack.energy.Energy;
import uk.joshiejack.energy.EnergyConfig;
import uk.joshiejack.energy.EnergyEffects;
import uk.joshiejack.energy.EnergyFoodStats;
import net.minecraft.world.World;
import net.minecraftforge.event.entity.player.PlayerWakeUpEvent;
import net.minecraftforge.event.entity.player.SleepingTimeCheckEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.Event;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

@Mod.EventBusSubscriber(modid = Energy.MODID)
public class SleepEvents {
    @SubscribeEvent
    public static void onSleepTimeCheck(SleepingTimeCheckEvent event) {
        if (EnergyConfig.sleepAnytime)
            event.setResult(Event.Result.ALLOW);
    }

    @SubscribeEvent
    public static void onWakeup(PlayerWakeUpEvent event) {
        event.getEntityPlayer().getEntityData().setLong("LastSlept", event.getEntityPlayer().world.getWorldTime()); //Update the last sleeping timer
        EnergyUsageEvents.updatePotionEffects(event.getEntityPlayer());
        if (EnergyConfig.sleepRestoresEnergy) {
            World world = event.getEntityPlayer().world;
            if (!world.isRemote && world.getWorldTime() % 24000 == 0) {
                EnergyFoodStats stats = (EnergyFoodStats) event.getEntityPlayer().getFoodStats();
                boolean fatigued = event.getEntityPlayer().isPotionActive(EnergyEffects.FATIGUE);
                boolean exhausted = event.getEntityPlayer().isPotionActive(EnergyEffects.EXHAUSTION);
                int restored = (int) (stats.maxFoodDisplay * (fatigued ? 0.75 : exhausted ? 0.5 : 1));
                event.getEntityPlayer().getFoodStats().addStats(restored, restored * 5);
            }
        }
    }
}


text:
package org.apache.camel.impl;

import java.util.concurrent.CountDownLatch;

import org.apache.camel.ExtendedExchange;
import org.apache.camel.impl.engine.DefaultAsyncProcessorAwaitManager;
import org.apache.camel.spi.AsyncProcessorAwaitManager;
import org.apache.camel.support.DefaultExchange;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Isolated;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.nullValue;

@Isolated
public class DefaultAsyncProcessorAwaitManagerTest {

    private DefaultAsyncProcessorAwaitManager defaultAsyncProcessorAwaitManager;
    private DefaultExchange exchange;
    private CountDownLatch latch;
    private Thread thread;

    @Test
    public void testNoMessageHistory() throws Exception {
        startAsyncProcess();
        AsyncProcessorAwaitManager.AwaitThread awaitThread = defaultAsyncProcessorAwaitManager.browse().iterator().next();
        assertThat(awaitThread.getRouteId(), is(nullValue()));
        assertThat(awaitThread.getNodeId(), is(nullValue()));
        waitForEndOfAsyncProcess();
    }

    @Test
    public void testMessageHistoryWithEmptyList() throws Exception {
        startAsyncProcess();
        AsyncProcessorAwaitManager.AwaitThread awaitThread = defaultAsyncProcessorAwaitManager.browse().iterator().next();
        assertThat(awaitThread.getRouteId(), is(nullValue()));
        assertThat(awaitThread.getNodeId(), is(nullValue()));
        waitForEndOfAsyncProcess();
    }

    @Test
    public void testMessageHistoryWithNullMessageHistory() throws Exception {
        startAsyncProcess();
        AsyncProcessorAwaitManager.AwaitThread awaitThread = defaultAsyncProcessorAwaitManager.browse().iterator().next();
        assertThat(awaitThread.getRouteId(), is(nullValue()));
        assertThat(awaitThread.getNodeId(), is(nullValue()));
        waitForEndOfAsyncProcess();
    }

    @Test
    public void testMessageHistoryWithNullElements() throws Exception {
        startAsyncProcess();
        AsyncProcessorAwaitManager.AwaitThread awaitThread = defaultAsyncProcessorAwaitManager.browse().iterator().next();
        assertThat(awaitThread.getRouteId(), is(nullValue()));
        assertThat(awaitThread.getNodeId(), is(nullValue()));
        waitForEndOfAsyncProcess();
    }

    @Test
    public void testMessageHistoryWithNotNullElements() throws Exception {
        startAsyncProcess();
        exchange.adapt(ExtendedExchange.class).setHistoryNodeId("nodeId");
        AsyncProcessorAwaitManager.AwaitThread awaitThread = defaultAsyncProcessorAwaitManager.browse().iterator().next();
        assertThat(awaitThread.getNodeId(), is("nodeId"));
        waitForEndOfAsyncProcess();
    }

    private void waitForEndOfAsyncProcess() {
        latch.countDown();
        while (thread.isAlive()) {
        }
    }

    private void startAsyncProcess() throws InterruptedException {
        defaultAsyncProcessorAwaitManager = new DefaultAsyncProcessorAwaitManager();
        latch = new CountDownLatch(1);
        BackgroundAwait backgroundAwait = new BackgroundAwait();
        exchange = new DefaultExchange(new DefaultCamelContext());
        thread = new Thread(backgroundAwait);
        thread.start();
        Thread.sleep(100);
    }

    private class BackgroundAwait implements Runnable {

        @Override
        public void run() {
            defaultAsyncProcessorAwaitManager.await(exchange, latch);
        }
    }

}