text:
___

[![taylor swift](https://img.shields.io/badge/secured%20by-taylor%20swift-brightgreen.svg)](https://twitter.com/SwiftOnSecurity)
[![volkswagen status](https://auchenberg.github.io/volkswagen/volkswargen_ci.svg?v=1)](https://github.com/auchenberg/volkswagen)
[![Build Status](https://travis-ci.org/AngularClass/angular2-webpack-starter.svg?branch=master)](https://travis-ci.org/AngularClass/angular2-webpack-starter)
[![GitHub version](https://badge.fury.io/gh/angularclass%2Fangular2-webpack-starter.svg)](https://badge.fury.io/gh/angularclass%2Fangular2-webpack-starter)
[![Dependency Status](https://david-dm.org/angularclass/angular2-webpack-starter.svg)](https://david-dm.org/angularclass/angular2-webpack-starter)
[![Stack Share](http://img.shields.io/badge/tech-stack-0690fa.svg?style=flat)](http://stackshare.io/angularclass/angular-2-webpack-starter)

# Angular2 Webpack Starter [![Join Slack](https://img.shields.io/badge/slack-join-brightgreen.svg)](https://angularclass.com/slack-join) [![Join the chat at https://gitter.im/angularclass/angular2-webpack-starter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/angularclass/angular2-webpack-starter?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

> An Angular starter kit featuring [Angular 4](https://angular.io), [Ahead of Time Compile](https://angular.io/docs/ts/latest/cookbook/aot-compiler.html), [Router](https://angular.io/docs/ts/latest/guide/router.html), [Forms](https://angular.io/docs/ts/latest/guide/forms.html),
[Http](https://angular.io/docs/ts/latest/guide/server-communication.html),
[Services](https://gist.github.com/gdi2290/634101fec1671ee12b3e#_follow_@AngularClass_on_twitter),
[Tests](https://angular.io/docs/ts/latest/guide/testing.html), [E2E](https://angular.github.io/protractor/#/faq#what-s-the-difference-between-karma-and-protractor-when-do-i-use-which-)), [Karma](https://karma-runner.github.io/), [Protractor](https://angular.github.io/protractor/), [Jasmine](https://github.com/jasmine/jasmine), [Istanbul](https://github.com/gotwarlost/istanbul), [TypeScript](http://www.typescriptlang.org/), [@types](https://www.npmjs.com/~types), [TsLint](http://palantir.github.io/tslint/), [Codelyzer](https://github.com/mgechev/codelyzer), [Hot Module Replacement](https://webpack.github.io/docs/hot-module-replacement-with-webpack.html), and [Webpack 2](http://webpack.github.io/) by [AngularClass](https://angularclass.com).

> If you're looking for Angular 1.x please use [NG6-starter](https://github.com/angularclass/NG6-starter)
> If you're looking to learn about Webpack and ES6 Build Tools check out [ES6-build-tools](https://github.com/AngularClass/ES6-build-tools)
> If you're looking to learn TypeScript see [TypeStrong/learn-typescript](https://github.com/TypeStrong/learn-typescript)
> If you're looking for something easier to get started with then see the angular2-seed that I also maintain [angular/angular2-seed](https://github.com/AngularClass/angular2-seed)

This seed repo serves as an Angular starter for anyone looking to get up and running with Angular and TypeScript fast. Using a [Webpack 2](http://webpack.github.io/) for building our files and assisting with boilerplate. We're also using Protractor for our end-to-end story and Karma for our unit tests.
* Best practices in file and application organization for Angular.
* Ready to go build system using Webpack for working with TypeScript.
* Angular examples that are ready to go when experimenting with Angular.
* A great Angular seed repo for anyone who wants to start their project.
* Ahead of Time (AoT) compile for rapid page loads of your production builds.
* Tree shaking to automatically remove unused code from your production bundle.
* [Webpack DLLs](https://robertknight.github.io/posts/webpack-dll-plugins/) dramatically speed your development builds.
* Testing Angular code with Jasmine and Karma.
* Coverage with Istanbul and Karma
* End-to-end Angular code using Protractor.
* Type manager with @types
* Hot Module Replacement with Webpack and [@angularclass/hmr](https://github.com/angularclass/angular2-hmr) and [@angularclass/hmr-loader](https://github.com/angularclass/angular2-hmr-loader)
* Material Design with [angular/material2](https://github.com/angular/material2)
* Angular 4 support via changing package.json and any future Angular versions

### Quick start
**Make sure you have Node version >= 6.0 and NPM >= 3**
> Clone/Download the repo then edit `app.component.ts` inside [`/src/app/app.component.ts`](/src/app/app.component.ts)

```bash
# clone our repo
# --depth 1 removes all but one .git commit history
git clone --depth 1 https://github.com/angularclass/angular2-webpack-starter.git

# change directory to our repo
cd angular2-webpack-starter

# install the repo with npm
npm install

# start the server
npm start

# use Hot Module Replacement
npm run server:dev:hmr

# if you're in China use cnpm
# https://github.com/cnpm/cnpm
```
go to [http://0.0.0.0:3000](http://0.0.0.0:3000) or [http://localhost:3000](http://localhost:3000) in your browser

# Table of Contents
* [File Structure](#file-structure)
* [Getting Started](#getting-started)
    * [Dependencies](#dependencies)
    * [Installing](#installing)
    * [Running the app](#running-the-app)
* [Configuration](#configuration)
* [AoT Don'ts](#aot-donts)
* [External Stylesheets](#external-stylesheets)
* [Contributing](#contributing)
* [TypeScript](#typescript)
* [@Types](#types)
* [Frequently asked questions](#frequently-asked-questions)
* [Support, Questions, or Feedback](#support-questions-or-feedback)
* [License](#license)

## File Structure
We use the component approach in our starter. This is the new standard for developing Angular apps and a great way to ensure maintainable code by encapsulation of our behavior logic. A component is basically a self contained app usually in a single file or a folder with each concern as a file: style, template, specs, e2e, and component class. Here's how it looks:
```
angular2-webpack-starter/
 ├──config/                        * our configuration
 |   ├──helpers.js                 * helper functions for our configuration files
 |   ├──spec-bundle.js             * ignore this magic that sets up our Angular testing environment
 |   ├──karma.conf.js              * karma config for our unit tests
 |   ├──protractor.conf.js         * protractor config for our end-to-end tests
 │   ├──webpack.dev.js             * our development webpack config
 │   ├──webpack.prod.js            * our production webpack config
 │   └──webpack.test.js            * our testing webpack config
 │
 ├──src/                           * our source files that will be compiled to javascript
 |   ├──main.browser.ts            * our entry file for our browser environment
 │   │
 |   ├──index.html                 * Index.html: where we generate our index page
 │   │
 |   ├──polyfills.ts               * our polyfills file
 │   │
 │   ├──app/                       * WebApp: folder
 │   │   ├──app.component.spec.ts  * a simple test of components in app.component.ts
 │   │   ├──app.e2e.ts             * a simple end-to-end test for /
 │   │   └──app.component.ts       * a simple version of our App component components
 │   │
 │   └──assets/                    * static assets are served here
 │       ├──icon/                  * our list of icons from www.favicon-generator.org
 │       ├──service-worker.js      * ignore this. Web App service worker that's not complete yet
 │       ├──robots.txt             * for search engines to crawl your website
 │       └──humans.txt             * for humans to know who the developers are
 │
 │
 ├──tslint.json                    * typescript lint config
 ├──typedoc.json                   * typescript documentation generator
 ├──tsconfig.json                  * typescript config used outside webpack
 ├──tsconfig.webpack.json          * config that webpack uses for typescript
 ├──package.json                   * what npm uses to manage it's dependencies
 └──webpack.config.js              * webpack main configuration file

```

# Getting Started
## Dependencies
What you need to run this app:
* `node` and `npm` (`brew install node`)
* Ensure you're running the latest versions Node `v6.x.x`+ (or `v7.x.x`) and NPM `3.x.x`+

> If you have `nvm` installed, which is highly recommended (`brew install nvm`) you can do a `nvm install --lts && nvm use` in `$` to run with the latest Node LTS. You can also have this `zsh` done for you [automatically](https://github.com/creationix/nvm#calling-nvm-use-automatically-in-a-directory-with-a-nvmrc-file)

Once you have those, you should install these globals with `npm install --global`:
* `webpack` (`npm install --global webpack`)
* `webpack-dev-server` (`npm install --global webpack-dev-server`)
* `karma` (`npm install --global karma-cli`)
* `protractor` (`npm install --global protractor`)
* `typescript` (`npm install --global typescript`)

## Installing
* `fork` this repo
* `clone` your fork
* `npm install webpack-dev-server rimraf webpack -g` to install required global dependencies
* `npm install` to install all dependencies or `yarn`
* `npm run server` to start the dev server in another tab

## Running the app
After you have installed all dependencies you can now run the app. Run `npm run server` to start a local server using `webpack-dev-server` which will watch, build (in-memory), and reload for you. The port will be displayed to you as `http://0.0.0.0:3000` (or if you prefer IPv6, if you're using `express` server, then it's `http://[::1]:3000/`).

### server
```bash
# development
npm run server
# production
npm run build:prod
npm run server:prod
```

## Other commands

### build files
```bash
# development
npm run build:dev
# production (jit)
npm run build:prod
# AoT
npm run build:aot
```

### hot module replacement
```bash
npm run server:dev:hmr
```

### watch and build files
```bash
npm run watch
```

### run unit tests
```bash
npm run test
```

### watch and run our tests
```bash
npm run watch:test
```

### run end-to-end tests
```bash
# update Webdriver (optional, done automatically by postinstall script)
npm run webdriver:update
# this will start a test server and launch Protractor
npm run e2e
```

### continuous integration (run unit tests and e2e tests together)
```bash
# this will test both your JIT and AoT builds
npm run ci
```

### run Protractor's elementExplorer (for end-to-end)
```bash
npm run e2e:live
```

### build Docker
```bash
npm run build:docker
```

# Configuration
Configuration files live in `config/` we are currently using webpack, karma, and protractor for different stages of your application

# AoT Don'ts
The following are some things that will make AoT compile fail.

- Don't use require statements for your templates or styles, use styleUrls and templateUrls, the angular2-template-loader plugin will change it to require at build time.
- Don't use default exports.
- Don't use `form.controls.controlName`, use `form.get('controlName')`
- Don't use `control.errors?.someError`, use `control.hasError('someError')`
- Don't use functions in your providers, routes or declarations, export a function and then reference that function name
- @Inputs, @Outputs, View or Content Child(ren), Hostbindings, and any field you use from the template or annotate for Angular should be public

# External Stylesheets
Any stylesheets (Sass or CSS) placed in the `src/styles` directory and imported into your project will automatically be compiled into an external `.css` and embedded in your production builds.

For example to use Bootstrap as an external stylesheet:
1) Create a `styles.scss` file (name doesn't matter) in the `src/styles` directory.
2) `npm install` the version of Boostrap you want.
3) In `styles.scss` add `@import 'bootstrap/scss/bootstrap.scss';`
4) In `src/app/app.module.ts` add underneath the other import statements: `import '../styles/styles.scss';`

# Contributing
You can include more examples as components but they must introduce a new concept such as `Home` component (separate folders), and Todo (services). I'll accept pretty much everything so feel free to open a Pull-Request

# TypeScript
> To take full advantage of TypeScript with autocomplete you would have to install it globally and use an editor with the correct TypeScript plugins.

## Use latest TypeScript compiler
TypeScript 2.1.x includes everything you need. Make sure to upgrade, even if you installed TypeScript previously.

```
npm install --global typescript
```

## Use a TypeScript-aware editor
We have good experience using these editors:

* [Visual Studio Code](https://code.visualstudio.com/)
* [Webstorm 10](https://www.jetbrains.com/webstorm/download/)
* [Atom](https://atom.io/) with [TypeScript plugin](https://atom.io/packages/atom-typescript)
* [Sublime Text](http://www.sublimetext.com/3) with [Typescript-Sublime-Plugin](https://github.com/Microsoft/Typescript-Sublime-plugin#installation)

### Visual Studio Code + Debugger for Chrome
> Install [Debugger for Chrome](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) and see docs for instructions to launch Chrome

The included `.vscode` automatically connects to the webpack development server on port `3000`.

# Types
> When you include a module that doesn't include Type Definitions inside of the module you can include external Type Definitions with @types

i.e, to have youtube api support, run this command in terminal:
```shell
npm i @types/youtube @types/gapi @types/gapi.youtube
```
In some cases where your code editor doesn't support Typescript 2 yet or these types weren't listed in ```tsconfig.json```, add these to **"src/custom-typings.d.ts"** to make peace with the compile check:
```es6
import '@types/gapi.youtube';
import '@types/gapi';
import '@types/youtube';
```

## Custom Type Definitions
When including 3rd party modules you also need to include the type definition for the module
if they don't provide one within the module. You can try to install it with @types

```
npm install @types/node
npm install @types/lodash
```

If you can't find the type definition in the registry we can make an ambient definition in
this file for now. For example

```typescript
declare module "my-module" {
  export function doesSomething(value: string): string;
}
```

If you're prototyping and you will fix the types later you can also declare it as type any

```typescript
declare var assert: any;
declare var _: any;
declare var $: any;
```

If you're importing a module that uses Node.js modules which are CommonJS you need to import as

```typescript
import * as _ from 'lodash';
```

# Frequently asked questions
* What's the current browser support for Angular?
  * Please view the updated list of [browser support for Angular 2](https://github.com/angularclass/awesome-angular2#current-browser-support-for-angular-2)
* Why is my service, aka provider, is not injecting parameter correctly?
  * Please use `@Injectable()` for your service for typescript to correctly attach the metadata (this is a TypeScript problem)
* Where do I write my tests?
  * You can write your tests next to your component files. See [`/src/app/home/home.component.spec.ts`](/src/app/home/home.component.spec.ts)
* How do I start the app when I get `EACCES` and `EADDRINUSE` errors?
  * The `EADDRINUSE` error means the port `3000` is currently being used and `EACCES` is lack of permission for webpack to build files to `./dist/`
* How to use `sass` for css?
 *  * `loaders: ['raw-loader','sass-loader']` and `@Component({ styleUrls: ['./filename.scss'] })` see Wiki page [How to include SCSS in components](https://github.com/AngularClass/angular2-webpack-starter/wiki/How-to-include-SCSS-in-components), or issue [#136](https://github.com/AngularClass/angular2-webpack-starter/issues/136) for more information.
* How do I test a Service?
 * See issue [#130](https://github.com/AngularClass/angular2-webpack-starter/issues/130#issuecomment-158872648)
* How do I add `vscode-chrome-debug` support?
 * The VS Code chrome debug extension support can be done via `launch.json` see issue [#144](https://github.com/AngularClass/angular2-webpack-starter/issues/144#issuecomment-164063790)
* How do I make the repo work in a virtual machine?
 * You need to use `0.0.0.0` so revert these changes [#205](https://github.com/AngularClass/angular2-webpack-starter/pull/205/files)
* What are the naming conventions for Angular?
 * please see issue [#185](https://github.com/AngularClass/angular2-webpack-starter/issues/185) and PR [196](https://github.com/AngularClass/angular2-webpack-starter/pull/196)
* How do I include bootstrap or jQuery?
 * please see issue [#215](https://github.com/AngularClass/angular2-webpack-starter/issues/215) and [#214](https://github.com/AngularClass/angular2-webpack-starter/issues/214#event-511768416)
* How do I async load a component?
 * see wiki [How-do-I-async-load-a-component-with-AsyncRoute](https://github.com/AngularClass/angular2-webpack-starter/wiki/How-do-I-async-load-a-component-with-AsyncRoute)
* Error: Cannot find module 'tapable'
 * Remove `node_modules/` and run `npm cache clean` then `npm install`
* How do I turn on Hot Module Replacement
 * Run `npm run server:dev:hmr`
* `RangeError: Maximum call stack size exceeded`
 * This is a problem with minifying Angular and it's recent JIT templates. If you set `mangle` to `false` then you should be good.
* Why is the size of my app larger in development?
 * We are using inline source-maps and hot module replacement which will increase the bundle size.
* If you're in China
 * check out https://github.com/cnpm/cnpm
* If you're looking to add Angular 2 Material Design
 * check out the [material2](https://github.com/AngularClass/angular2-webpack-starter/tree/material2) branch
* node-pre-gyp ERR in npm install (Windows)
 * install Python x86 version between 2.5 and 3.0 on windows see issue [#626](https://github.com/AngularClass/angular2-webpack-starter/issues/626)
* `Error:Error: Parse tsconfig error [{"messageText":"Unknown compiler option 'lib'.","category":1,"code":5023},{"messageText":"Unknown compiler option 'strictNullChecks'.","category":1,"code":5023},{"messageText":"Unknown compiler option 'baseUrl'.","category":1,"code":5023},{"messageText":"Unknown compiler option 'paths'.","category":1,"code":5023},{"messageText":"Unknown compiler option 'types'.","category":1,"code":5023}]`
 * remove `node_modules/typescript` and run `npm install typescript@beta`. This repo now uses ts 2.0
* "There are multiple modules with names that only differ in casing"
 * change `c:\[path to angular2-webpack-starter]` to `C:\[path to angular2-webpack-starter]` see [926#issuecomment-245223547](https://github.com/AngularClass/angular2-webpack-starter/issues/926#issuecomment-245223547)

# Support, Questions, or Feedback
> Contact us anytime for anything about this repo or Angular

* [Chat: AngularClass.slack](http://angularclass.com/member-join/)
* [Twitter: @AngularClass](https://twitter.com/AngularClass)
* [Gitter: AngularClass/angular2-webpack-starter](https://gitter.im/angularclass/angular2-webpack-starter)

# Deployment

## Netlify

You can quickly create a free site to get started using this
starter kit in production on [Netlify](https://www.netlify.com/):

[![Deploy to Netlify](https://www.netlify.com/img/deploy/button.svg)](https://app.netlify.com/start/deploy?repository=https://github.com/AngularClass/angular2-webpack-starter)

___

enjoy — **AngularClass**

[![AngularClass](https://cloud.githubusercontent.com/assets/1016365/9863770/cb0620fc-5af7-11e5-89df-d4b0b2cdfc43.png  "Angular Class")](https://angularclass.com)
##[AngularClass](https://angularclass.com)
> Learn AngularJS, Angular, and Modern Web Development from the best.
> Looking for corporate Angular training, want to host us, or Angular consulting? patrick@angularclass.com

___

# License
 [MIT](/LICENSE)


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="net.inno.modules.dao.AreaMapper">
<insert id="insert" parameterType="Area">
INSERT INTO sys_area
	(
	areaId,
	parentId,
	`name`,
	`key`
	)
VALUES
	(
	#{areaId},
	#{parentId},
	#{name},
	#{key}
	)
</insert>

<delete id="delete" parameterType="long">
DELETE FROM sys_area WHERE areaId = #{areaId}
</delete>

<update id="update" parameterType="Area">
UPDATE sys_area SET
	parentId = #{parentId},
	`name` = #{name},
	`key` = #{key}
WHERE
	areaId = #{areaId}
</update>

<select id="get" resultType="Area" parameterType="long">
	SELECT * FROM sys_area WHERE areaId = #{areaId}
</select>

<select id="find" resultType="Area" parameterType="Area">
	SELECT * FROM sys_area where 1=1
	<if test="areaId != -1">
		 AND areaId = #{areaId}
	</if>
	<if test="parentId != -1">
		 AND parentId = #{parentId}
	</if>
	<if test="name != null">
		 AND `name` like #{name}
	</if>
	<if test="key != null">
		 AND `key` like #{key}
	</if>
</select>

<select id="search" resultType="Area" parameterType="ListCondition">
	SELECT <if test="distinct">distinct</if> * FROM sys_area
	<if test="_parameter != null">
		<include refid="Where_ListCondition"/>
	</if>
	<if test="orderSql != null">order by ${orderSql}</if>
</select>

<select id="count" resultType="java.lang.Integer" parameterType="ListCondition">
	SELECT count(*) FROM sys_area
	<if test="_parameter != null">
		<include refid="Where_ListCondition"/>
	</if>
</select>

<sql id="Where_ListCondition">
	<where>
		<foreach collection="listSql" item="value">
			${value}
		</foreach>
	</where>
</sql>

<!-- 通过父节点来找下一级的全部节点 -->
<select id="getAreaByParentId" resultType="Area" parameterType="java.lang.Integer">
	SELECT
		areaId,
		parentId,
		`name`,
		`key`
	FROM
		sys_area
	WHERE
		parentId = #{parentId}
</select>

</mapper>

redpajama_set_name: RedPajamaGithub


text:
package com.arpnetworking.metrics.mad.model.statistics;

import com.arpnetworking.logback.annotations.Loggable;

/**
 * Top 99.9th percentile statistic. Use {@link StatisticFactory} for construction.
 *
 * @author Brandon Arp (brandon dot arp at inscopemetrics dot io)
 */
@Loggable
public final class TP99p9Statistic extends TPStatistic {

    private TP99p9Statistic() {
        super(99.9d);
    }

    private static final long serialVersionUID = 1L;
}


text:
'use strict';

var assert = require('chai').assert;
var expect = require('chai').expect;
var should = require('should');
var Hook = require('../lib/').Hook;
var TallyHook = require('../test/common.js').TallyHook;

describe('Tests in ' + __filename, function () {
  describe('Hook functionality test', function () {
    it('Hook methods all fire', function () {
      var obj = {
        preTally: 0,
        exeTally: 0,
        postTally: 0
      };
      var hook = new TallyHook({ name: 'tallyHook' });
      var hookA = new TallyHook({ name: 'tallyHookA' });
      var hookB = new TallyHook({ name: 'tallyHookB' });
      hook.setHook(hookA).setHook(hookB);
      return hook.process(obj).then(function (obj) {
        obj.should.have.property('preTally', 3);
        obj.should.have.property('exeTally', 3);
        obj.should.have.property('postTally', 3);
      }).catch(function (reason) {
        console.dir(reason);
      });
    });
  });
});


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;

public class DNAMarker
{
	private static readonly string[] DNACHARS = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" };
	private static readonly string[] JUNKCHARS = { "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V" };
	public string Sequence { get; private set; } // Hex String

	private int _minChunks = 3; // number of chunks that uniquely ID this sequence. Does not include Start/End chunks, which are mandatory
	private int _maxChunks = 10;

	private int _minChunkSize = 4; // number of characters per chunk
	private int _maxChunkSize = 10;

	private int _minJunkSize = 0; // Number of Junk characters to separate IDS chunks
	private int _maxJunkSize = 10;

	private StringBuilder _builder;
	public List<DNAChunk> Chunks;
	public string IndexName { get; private set; }

	public DNAMarker(string index)
	{
		IndexName = index;
		Chunks = new List<DNAChunk>();
		_builder = new StringBuilder();
		generateAllChunks();
		Sequence = _builder.ToString();
	}

	private void generateAllChunks()
	{
		clearBuilder();

		generateJunkChunk();
		generateIDChunk(); // Starting Chunk
		int numChunks = Random.Range(_minChunks, _maxChunks);

		for (int i = 0; i < numChunks; i++)
		{
			generateJunkChunk();
			generateIDChunk();
			generateJunkChunk();
		}

		generateIDChunk(); // EndingChunk
		generateJunkChunk();
	}

	private void generateIDChunk()
	{
		int chunkSize = Random.Range(_minChunkSize, _maxChunkSize);
		generateChunk(chunkSize);
		AddChunkToList(false);

	}

	private void generateJunkChunk()
	{
		int chunkSize = Random.Range(_minJunkSize, _maxJunkSize);
		generateJunk(chunkSize);
		AddChunkToList(true);
	}

	private void generateChunk(int chunkSize)
	{
		for (int i = 0; i < chunkSize; i++)
		{
			_builder.Append(GetDNAChar());
		}
	}

	private void generateJunk(int chunkSize)
	{

		for (int i = 0; i < chunkSize; i++)
		{
			_builder.Append(GetJunkChar());
		}
	}

	private void AddChunkToList(bool isJunk)
	{
		DNAChunk newChunk = new DNAChunk(_builder.ToString(), IndexName, isJunk);
		//Debug.Log("Adding Chunk Sequence: " + _builder.ToString());
		Chunks.Add(newChunk);
		clearBuilder();
	}

	private void clearBuilder()
	{
		_builder.Remove(0, _builder.Length);
	}

	private static string GetDNAChar()
	{
		int charIndex = Random.Range(0, DNACHARS.Length);
		return DNACHARS[charIndex];
	}

	private static string GetJunkChar()
	{
		int charIndex = Random.Range(0, JUNKCHARS.Length);
		return JUNKCHARS[charIndex];
	}
}


text:
![PowerHour](raw/banner.png)

Master [![Build Status](https://ci.hoogit.ca/job/PowerHour.master/badge/icon)](https://ci.hoogit.ca/job/PowerHour.master/)

Develop [![Build Status](https://ci.hoogit.ca/job/PowerHour.develop/badge/icon)](https://ci.hoogit.ca/job/PowerHour.develop/)

An application to aid in the playing of a classic drinking game called Power Hour, or Century club.
With the goal being consume a shot of beer every minute for an hour, or one hundred minutes.

Official website [Power Hour App](https://powerhourapp.ca)

## Get It

Or grab the apk [here](https://ci.hoogit.ca/job/PowerHour.master/), or better yet clone and build yourself.

## Changelog
```
Version 2.0.1
- Fatal bug when exiting and resuming active game
- Display bug on android wear on game finish
- Made Android wear less annoying on game finish
- Fix some Wear display issues, and vibrating issues
Version 2.0
- BIG update
- Added Android Wear support
- Permission Changes
  - None? I don't think Wear requires anymore permissions
- Bug fixes
  - Incorrect time remaining is now displayed properly
  - Fix centering of some items in tablet mode
  - Fix some fatal crashes that occurred during configuring game
  - Rate app button actually opens Play Store properly
- Tweaked about page
Version 1.1
 - Initial release to play store
```

## Features
- Beautiful Material Design elements
- Completely customizable game modes
- Use of foreground services and wake locks to keep the game active with the screen off
- Change background and accent colors
- Choose a notification sound or record your own
- Android Wear support!
- **FREE & AD FREE**

## TODO
- Before & After shots, stitched together at end of game
- Sharing said photos to facebook/instagram/tweeeeter etc.
- Add camera button to game controls, take picture any time you want? Stitch together at end
- Add music playlist, options:
  - Play 60 seconds of random song, and switch songs when its shot time
  - Just choose from a list of music to play in the background
- Proper settings menu
  - Enable/disable wear feature
- Update TargetSDK to Marshmallow aka implement new permissions "feature"

## Android Wear
**It just Works™**

In theory as long as a Wear device is paired it should receive updates and information.
I have tried my best to make it work with many Wear devices, but I only have the emulator to work with.
If there is anyone out there using that feature and something looks wrong let me know!

## Permissions Breakdown
- Record Audio - For recording your own sound to be played at the end of each round
- Vibrate - Used with the audio to alert you the round has finished
- Internet - Used for the crash reporting analytics
- Wake Lock - So the countdown will continue to be active if the screen is turned off

## Libraries used
```groovy
compile 'de.psdev.licensesdialog:licensesdialog:1.7.0'
compile 'com.jakewharton:butterknife:7.0.1'
compile 'com.squareup:otto:1.3.8'
compile 'com.github.paolorotolo:appintro:3.4.0'
compile 'com.crashlytics.sdk.android:crashlytics:2.4.0@aar'
compile 'com.daimajia.easing:library:1.0.1@aar'
compile 'com.daimajia.androidanimations:library:1.1.3@aar'
compile 'com.github.markushi:circlebutton:1.1'
compile 'info.hoang8f:fbutton:1.0.5'
compile 'com.github.afollestad.material-dialogs:core:0.8.5.6@aar'

// personal repo
compile 'ca.hoogit:circularprogressbar:2.0.1'
compile 'ca.hoogit:MaterialDesign:1.0.2'
compile 'ca.hoogit:fabbutton:1.2.0'
compile 'ca.hoogit:soundchooser:1.1.0'
compile 'com.nineoldandroids:library:2.4.0'
```

## License

Power Hour
Copyright (C) 2015  Jordon de Hoog

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


text:
/*
 * lesson_trajectory_points.cpp
 *
 *  Created on: Apr 21, 2015
 *      Author: Jorge Nicho
 */

#ifdef __i386__
#pragma message("i386 Architecture detected, disabling EIGEN VECTORIZATION")
#define EIGEN_DONT_VECTORIZE
#define EIGEN_DISABLE_UNALIGNED_ARRAY_ASSERT
#else
#pragma message("64bit Architecture detected, enabling EIGEN VECTORIZATION")
#endif

#include <ros/ros.h>
#include <descartes_moveit/moveit_state_adapter.h>
#include <descartes_trajectory/cart_trajectory_pt.h>
#include <descartes_trajectory/joint_trajectory_pt.h>
#include <descartes_trajectory/axial_symmetric_pt.h>
#include <eigen_conversions/eigen_msg.h>

int main(int argc, char** argv)
{
  ros::init(argc,argv,"lesson_trajectory_points");
  ros::AsyncSpinner spinner(2);
  spinner.start();

  // Create a Descartes robot model
  descartes_core::RobotModelPtr robot_model_ptr(new descartes_moveit::MoveitStateAdapter());
  if(robot_model_ptr->initialize("robot_description","manipulator","world","tool"))
  {
    ROS_INFO_STREAM("Robot Model initialized");
  }
  else
  {
    ROS_ERROR_STREAM("Failed to initialized Robot Model");
    return 1;
  }

  // Create Descartes cartesian point
  Eigen::Affine3d tool_pose = descartes_core::utils::toFrame(0.4f,0.2f,0.1f,0,M_PI/2,0);

  // Getting nominal cartesian pose
  Eigen::Affine3d ik_pose;
  std::vector<double> seed(robot_model_ptr->getDOF(),0);
  seed[0] = 0;
  seed[1] = -M_PI/6;
  seed[2] = M_PI/8;
  seed[3] = -M_PI/6;
  seed[4] = 0;
  seed[5] = M_PI/2;

  // Getting joint pose from cartesian point
  std::vector<double> joint_pose;

  // Create Cartesian point with rotational freedom about the z axis

  // Getting all the cartesian poses with discretized rotation about z
  EigenSTL::vector_Affine3d poses;

  // Getting all joint solutions
  std::vector< std::vector<double> > solutions;

  // Getting closest joint pose
  std::vector<double> closest_joint_pose;
  joint_pose[1] = joint_pose[1] + M_PI/20;
  joint_pose[2] = joint_pose[2] + M_PI/20;
  joint_pose[4] = joint_pose[4] + M_PI/20;
  joint_pose[5] = joint_pose[5] - M_PI/20;

  return 0;
}


text:
<?php

/*
 *
 * User Role Editor plugin: user capabilities editor page
 *
 */

if (!defined('URE_PLUGIN_URL')) {
  die;  // Silence is golden, direct call is prohibited
}

?>

<?php
	if (!is_multisite() || current_user_can('manage_network_users')) {
		$anchor_start = 'user_to_edit->ID}",
          "ure_user_{$this->user_to_edit->ID}") .'" >';
		$anchor_end = '';
	} else {
		$anchor_start = '';
		$anchor_end = '';
	}
  $user_info = ' '.$anchor_start. $this->user_to_edit->user_login;
  if ($this->user_to_edit->display_name!==$this->user_to_edit->user_login) {
    $user_info .= ' ('.$this->user_to_edit->display_name.')';
  }
  $user_info .= $anchor_end.'';
 if (is_multisite() && is_super_admin($this->user_to_edit->ID)) {
   $user_info .= '  '. esc_html__('Network Super Admin', 'ure') .'';
 }

	 $this->display_box_start(esc_html__('Change capabilities for user', 'ure').$user_info, 'min-width:1100px;');

?>

  <?php
    $caps_access_restrict_for_simple_admin = $this->get_option('caps_access_restrict_for_simple_admin', 0);
    if (is_super_admin() || !$this->multisite || !class_exists('User_Role_Editor_Pro') || !$caps_access_restrict_for_simple_admin) {
        if ($this->caps_readable) {
            $checked = 'checked="checked"';
        } else {
            $checked = '';
        }
?>

		<input type="checkbox" name="ure_caps_readable" id="ure_caps_readable" value="1"
      <?php echo $checked; ?> onclick="ure_turn_caps_readable(<?php echo $this->user_to_edit->ID; ?>);"  />
    <?php esc_html_e('Show capabilities in human readable form', 'ure'); ?>
<?php
    if ($this->show_deprecated_caps) {
      $checked = 'checked="checked"';
    } else {
      $checked = '';
    }
?>
    <input type="checkbox" name="ure_show_deprecated_caps" id="ure_show_deprecated_caps" value="1"
        <?php echo $checked; ?> onclick="ure_turn_deprecated_caps(<?php echo $this->user_to_edit->ID; ?>);"/>
    <?php esc_html_e('Show deprecated capabilities', 'ure'); ?>
<?php
    }
?>

<?php esc_html_e('Primary Role:', 'ure'); ?>

<?php
$show_admin_role = $this->show_admin_role_allowed();
// output primary role selection dropdown list
$this->user_primary_role_dropdown_list($this->user_to_edit->roles);

$values = array_values($this->user_to_edit->roles);
$primary_role = array_shift($values);  // get 1st element from roles array
if (function_exists('bbp_filter_blog_editable_roles') ) {  // bbPress plugin is active
?>

<?php esc_html_e('bbPress Role:', 'ure'); ?>

<?php
	// Get the roles
	$dynamic_roles = bbp_get_dynamic_roles();
	$bbp_user_role = bbp_get_user_role($this->user_to_edit->ID);
	if (!empty($bbp_user_role)) {
		echo $dynamic_roles[$bbp_user_role]['name'];
	}
}
?>

<?php esc_html_e('Other Roles:', 'ure'); ?>

<?php

	foreach ($this->roles as $role_id => $role) {
		if ( ($show_admin_role || $role_id!='administrator') && ($role_id!==$primary_role) ) {
			if ( $this->user_can( $role_id ) ) {
				$checked = 'checked="checked"';
			} else {
				$checked = '';
			}
			echo '<input type="checkbox"	id="wp_role_' . $role_id .
        '" name="wp_role_' . $role_id . '" value="' . $role_id . '"' . $checked .' /> ' .
        esc_html__($role['name'], 'ure') . '
';
		}
	}
 ?>

	<?php esc_html_e('Core capabilities:', 'ure'); ?>

		<?php esc_html_e('Quick filter:', 'ure'); ?>
		<input type="text" id="quick_filter" name="quick_filter" value="" size="20" onkeyup="ure_filter_capabilities(this.value);" />

				<?php $this->show_capabilities( true, false ); ?>

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

<?php
	$quant = count( $this->full_capabilities ) - count( $this->get_built_in_wp_caps() );
	if ($quant>0) {
     echo '
';
?>
	<?php esc_html_e('Custom capabilities:', 'ure'); ?>

				<?php $this->show_capabilities( false, false ); ?>

<?php
	}  // if ($quant>0)
?>

  <input type="hidden" name="object" value="user" />
  <input type="hidden" name="user_id" value="<?php echo $this->user_to_edit->ID; ?>" />
<?php
  $this->display_box_end();
?>


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Brgy extends CI_Controller {

    var $data;

    function __construct() {
        parent::__construct(); // needed when adding a constructor to a controller
        //page_specific
        $this->data = array(
            'head_content' => 'layouts/page_specific/blank',
            'foot_content' => 'layouts/page_specific/blank'
        );
        // $this->data can be accessed from anywhere in the controller.

        $this->load->model('brgy_m', 'brgy_m');
    }

    public function index() {
        $data = $this->data;
        $data['main_content'] = 'brgy_profile';
        $data['pagename'] = 'Barangay Profile';
        $data['pagesubname'] = '';

        $data['lists'] = $this->brgy_m->get_brgy_m();

        $this->load->view('layouts/main', $data);
    }

    public function edit_brgy() {
        if ($_FILES['bp_logo']['size'] < 528385) {

            $filename = time() . '_brgy_logo';
            $logourl = './resident-photo/' . $filename . '.jpg';

            $tmp_name = $_FILES['bp_logo']['tmp_name'];
            move_uploaded_file($tmp_name, "$logourl");
        } else {
            redirect('brgy');
        }

        $this->brgy_m->edit_brgy_m($logourl);
        $this->session->set_flashdata('msg', "Barangay Profile updated!");
        redirect('brgy');
    }

    public function edit_brgy_logo() {
        if ($_FILES['bp_logo']['size'] < 528385) {

            $filename = time() . '_brgy_logo';
            $logourl = './resident-photo/' . $filename . '.jpg';

            $tmp_name = $_FILES['bp_logo']['tmp_name'];
            move_uploaded_file($tmp_name, "$logourl");
        } else {
            redirect('brgy');
        }

        $this->brgy_m->edit_brgy_logo_m($logourl);
        $this->session->set_flashdata('msg', "Barangay Profile updated!");
        redirect('brgy');
    }

}


text:
var localStorageSpace = {};

var chrome = {
    storage: {
        local: {
            set: function(data, callback) {
                for (var key in data) {
                    localStorageSpace[key] = data[key];
                }

                callback();
            },

            get: function(data, callback) {
                var datas = [];
                for (var key in data) {
                    datas[key] = localStorageSpace[key];
                }

                callback(datas);
            },

            remove: function(data, callback) {
                for (var key in data) {
                    delete localStorageSpace[data[key]];
                }

                callback();
            }
        },
        sync: this.local
    },

    runtime: {
        lastError: null
    }
};


text:
package com.google.template.soy.passes;

import com.google.common.base.Preconditions;
import com.google.template.soy.data.SanitizedContent.ContentKind;
import com.google.template.soy.error.ErrorReporter;
import com.google.template.soy.error.SoyErrorKind;
import com.google.template.soy.shared.internal.DelTemplateSelector;
import com.google.template.soy.soytree.AbstractSoyNodeVisitor;
import com.google.template.soy.soytree.CallBasicNode;
import com.google.template.soy.soytree.CallDelegateNode;
import com.google.template.soy.soytree.SoyFileSetNode;
import com.google.template.soy.soytree.SoyNode;
import com.google.template.soy.soytree.SoyNode.ParentSoyNode;
import com.google.template.soy.soytree.TemplateBasicNode;
import com.google.template.soy.soytree.TemplateDelegateNode;
import com.google.template.soy.soytree.TemplateNode;
import com.google.template.soy.soytree.TemplateRegistry;
import com.google.template.soy.soytree.defn.TemplateParam;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * Checks various rules regarding the use of delegates (including delegate packages, delegate
 * templates, and delegate calls).
 *
 * <p>Important: Do not use outside of Soy code (treat as superpackage-private).
 *
 * <p> {@link #exec} should be called on a full parse tree. There is no return value. A
 * {@code SoySyntaxException} is thrown if an error is found.
 *
 */
final class CheckDelegatesVisitor extends AbstractSoyNodeVisitor<Void> {

  private static final SoyErrorKind CALL_TO_DELTEMPLATE =
      SoyErrorKind.of("''call'' to delegate template ''{0}'' (expected ''delcall'').");
  private static final SoyErrorKind CROSS_PACKAGE_DELCALL =
      SoyErrorKind.of(
          "Found illegal call from ''{0}'' to ''{1}'', which is in a different delegate package.");
  private static final SoyErrorKind DELCALL_TO_BASIC_TEMPLATE =
      SoyErrorKind.of("''delcall'' to basic template ''{0}'' (expected ''call'').");
  private static final SoyErrorKind DELTEMPLATES_WITH_DIFFERENT_PARAM_DECLARATIONS =
      SoyErrorKind.of(
          "Found delegate template with same name ''{0}'' but different param declarations "
              + "compared to the definition at {1}.");
  private static final SoyErrorKind STRICT_DELTEMPLATES_WITH_DIFFERENT_CONTENT_KIND =
      SoyErrorKind.of(
          "If one deltemplate has strict autoescaping, all its peers must also be strictly"
              + " autoescaped with the same content kind: {0} != {1}. Conflicting definition at"
              + " {2}.");

  /** A template registry built from the Soy tree. */
  private final TemplateRegistry templateRegistry;

  /** The current enclosing template's name, as suitable for user messages (during pass). */
  private String currTemplateNameForUserMsgs;

  /** Current delegate package name, or null if none (during pass). */
  private String currDelPackageName;
  private final ErrorReporter errorReporter;

  CheckDelegatesVisitor(TemplateRegistry templateRegistry, ErrorReporter errorReporter) {
    this.templateRegistry = templateRegistry;
    this.errorReporter = errorReporter;
  }

  @Override public Void exec(SoyNode soyNode) {

    Preconditions.checkArgument(soyNode instanceof SoyFileSetNode);
    // Perform checks that only involve templates (uses templateRegistry only, no traversal).
    checkTemplates();

    // Perform checks that involve calls (uses traversal).
    super.exec(soyNode);

    return null;
  }

  /**
   * Performs checks that only involve templates (uses templateRegistry only).
   */
  private void checkTemplates() {

    DelTemplateSelector<TemplateDelegateNode> selector = templateRegistry.getDelTemplateSelector();

    // Check that all delegate templates with the same name have the same declared params and
    // content kind.
    for (Collection<TemplateDelegateNode> delTemplateGroup :
        selector.delTemplateNameToValues().asMap().values()) {
      TemplateDelegateNode firstDelTemplate = null;
      Set<TemplateParam> firstRequiredParamSet = null;
      ContentKind firstContentKind = null;

      // loop over all members of the deltemplate group.
      for (TemplateDelegateNode delTemplate : delTemplateGroup) {
        if (firstDelTemplate == null) {
          // First template encountered.
          firstDelTemplate = delTemplate;
          firstRequiredParamSet = getRequiredParamSet(delTemplate);
          firstContentKind = delTemplate.getContentKind();
        } else {
          // Not first template encountered.
          Set<TemplateParam> currRequiredParamSet = getRequiredParamSet(delTemplate);
          if (!currRequiredParamSet.equals(firstRequiredParamSet)) {
            errorReporter.report(
                delTemplate.getSourceLocation(),
                DELTEMPLATES_WITH_DIFFERENT_PARAM_DECLARATIONS,
                firstDelTemplate.getDelTemplateName(),
                firstDelTemplate.getSourceLocation().toString());
          }
          if (delTemplate.getContentKind() != firstContentKind) {
            // TODO: This is only *truly* a requirement if the strict mode deltemplates are
            // being called by contextual templates. For a strict-to-strict call, everything
            // is escaped at runtime at the call sites. You could imagine delegating between
            // either a plain-text or rich-html template. However, most developers will write
            // their deltemplates in a parallel manner, and will want to know when the
            // templates differ. Plus, requiring them all to be the same early-on will allow
            // future optimizations to avoid the run-time checks, so it's better to start out
            // as strict as possible and only open up if needed.
            errorReporter.report(
                delTemplate.getSourceLocation(),
                STRICT_DELTEMPLATES_WITH_DIFFERENT_CONTENT_KIND,
                String.valueOf(firstContentKind),
                String.valueOf(delTemplate.getContentKind()),
                firstDelTemplate.getSourceLocation().toString());
          }
        }
      }
    }
  }

  private static Set<TemplateParam> getRequiredParamSet(TemplateDelegateNode delTemplate) {
    Set<TemplateParam> paramSet = new HashSet<>();
    for (TemplateParam param : delTemplate.getParams()) {
      if (param.isRequired()) {
        paramSet.add(param);
      }
    }
    return paramSet;
  }

  // -----------------------------------------------------------------------------------------------
  // Implementations for specific nodes.

  @Override protected void visitTemplateNode(TemplateNode node) {
    this.currTemplateNameForUserMsgs = node.getTemplateNameForUserMsgs();
    this.currDelPackageName = node.getDelPackageName();
    visitChildren(node);
  }

  @Override protected void visitCallBasicNode(CallBasicNode node) {

    String calleeName = node.getCalleeName();

    // Check that the callee name is not a delegate template name.
    if (templateRegistry.getDelTemplateSelector().hasDelTemplateNamed(calleeName)) {
      errorReporter.report(node.getSourceLocation(), CALL_TO_DELTEMPLATE, calleeName);
    }

    // Check that the callee is either not in a delegate package or in the same delegate package.
    TemplateBasicNode callee = templateRegistry.getBasicTemplate(calleeName);
    if (callee != null) {
      String calleeDelPackageName = callee.getDelPackageName();
      if (calleeDelPackageName != null && ! calleeDelPackageName.equals(currDelPackageName)) {
        errorReporter.report(
            node.getSourceLocation(),
            CROSS_PACKAGE_DELCALL,
            currTemplateNameForUserMsgs,
            callee.getTemplateName());
      }
    }
  }

  @Override protected void visitCallDelegateNode(CallDelegateNode node) {

    String delCalleeName = node.getDelCalleeName();

    // Check that the callee name is not a basic template name.
    if (templateRegistry.getBasicTemplate(delCalleeName) != null) {
      errorReporter.report(node.getSourceLocation(), DELCALL_TO_BASIC_TEMPLATE, delCalleeName);
    }
  }

  // -----------------------------------------------------------------------------------------------
  // Fallback implementation.

  @Override protected void visitSoyNode(SoyNode node) {
    if (node instanceof ParentSoyNode<?>) {
      visitChildren((ParentSoyNode<?>) node);
    }
  }

}


text:
module Spree
  module Admin
    class MailMethodsController < BaseController
      def update
        params[:smtp_password] = nil if params[:smtp_username].blank?

        params.each do |name, value|
          next unless Spree::Config.has_preference? name
          Spree::Config[name] = value
        end

        flash[:success] = Spree.t(:successfully_updated, resource: Spree.t(:mail_method_settings))
        redirect_to edit_admin_mail_method_url
      end

      def testmail
        if TestMailer.test_email(try_spree_current_user.email).deliver_now
          flash[:success] = Spree.t('mail_methods.testmail.delivery_success')
        else
          flash[:error] = Spree.t('mail_methods.testmail.delivery_error')
        end
      rescue => e
        flash[:error] = Spree.t('mail_methods.testmail.error', e: e)
      ensure
        redirect_to edit_admin_mail_method_url
      end
    end
  end
end


text: from .statistics_recorder import StatisticsRecorder


text:
package org.nd4j.linalg.api.buffer;

import org.bytedeco.javacpp.DoublePointer;
import org.bytedeco.javacpp.indexer.DoubleIndexer;
import org.bytedeco.javacpp.indexer.Indexer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.nd4j.linalg.BaseNd4jTest;
import org.nd4j.linalg.api.buffer.util.DataTypeUtil;
import org.nd4j.linalg.api.memory.MemoryWorkspace;
import org.nd4j.linalg.api.memory.conf.WorkspaceConfiguration;
import org.nd4j.linalg.api.memory.enums.AllocationPolicy;
import org.nd4j.linalg.api.memory.enums.LearningPolicy;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.factory.Nd4jBackend;
import org.nd4j.linalg.util.SerializationUtils;

import java.io.*;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * Double data buffer tests
 *
 * This tests the double buffer data opType
 * Put all buffer related tests here
 *
 * @author Adam Gibson
 */
@RunWith(Parameterized.class)
public class DoubleDataBufferTest extends BaseNd4jTest {
    DataBuffer.Type initialType;

    public DoubleDataBufferTest(Nd4jBackend backend) {
        super(backend);
        initialType = Nd4j.dataType();
    }

    @Before
    public void before() {

        DataTypeUtil.setDTypeForContext(DataBuffer.Type.DOUBLE);
    }

    @After
    public void after() {
        DataTypeUtil.setDTypeForContext(initialType);
    }

    @Test
    public void testPointerCreation() {
        DoublePointer floatPointer = new DoublePointer(1, 2, 3, 4);
        Indexer indexer = DoubleIndexer.create(floatPointer);
        DataBuffer buffer = Nd4j.createBuffer(floatPointer, DataBuffer.Type.DOUBLE, 4, indexer);
        DataBuffer other = Nd4j.createBuffer(new double[] {1, 2, 3, 4});
        assertArrayEquals(other.asDouble(), buffer.asDouble(), 0.001);
    }

    @Test
    public void testGetSet() throws Exception {
        double[] d1 = new double[] {1, 2, 3, 4};
        DataBuffer d = Nd4j.createBuffer(d1);
        double[] d2 = d.asDouble();
        assertArrayEquals(d1, d2, 1e-1f);

    }

    @Test
    public void testSerialization2() throws Exception {
        INDArray[] arr = new INDArray[] {Nd4j.ones(1, 10),
                        //      Nd4j.ones(5,10).getRow(2)
        };

        for (INDArray a : arr) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
                oos.writeObject(a);
                oos.flush();
            }

            byte[] bytes = baos.toByteArray();

            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);

            INDArray aDeserialized = (INDArray) ois.readObject();

            System.out.println(aDeserialized);
            assertEquals(Nd4j.ones(1, 10), aDeserialized);
        }
    }

    @Test
    public void testSerialization() {
        DataBuffer buf = Nd4j.createBuffer(5);
        String fileName = "buf.ser";
        File file = new File(fileName);
        file.deleteOnExit();
        SerializationUtils.saveObject(buf, file);
        DataBuffer buf2 = SerializationUtils.readObject(file);
        //assertEquals(buf, buf2);
        assertArrayEquals(buf.asDouble(), buf2.asDouble(), 0.001);

        Nd4j.alloc = DataBuffer.AllocationMode.DIRECT;
        buf = Nd4j.createBuffer(5);
        file.deleteOnExit();
        SerializationUtils.saveObject(buf, file);
        buf2 = SerializationUtils.readObject(file);
        //        assertEquals(buf, buf2);
        assertArrayEquals(buf.asDouble(), buf2.asDouble(), 0.001);
    }

    @Test
    public void testDup() throws Exception {
        double[] d1 = new double[] {1, 2, 3, 4};
        DataBuffer d = Nd4j.createBuffer(d1);
        DataBuffer d2 = d.dup();
        assertArrayEquals(d.asDouble(), d2.asDouble(), 0.0001f);
    }

    @Test
    public void testPut() throws Exception {
        double[] d1 = new double[] {1, 2, 3, 4};
        DataBuffer d = Nd4j.createBuffer(d1);
        d.put(0, 0.0);
        double[] result = new double[] {0, 2, 3, 4};
        d1 = d.asDouble();
        assertArrayEquals(d1, result, 1e-1f);
    }

    @Test
    public void testGetRange() throws Exception {
        DataBuffer buffer = Nd4j.linspace(1, 5, 5).data();
        double[] get = buffer.getDoublesAt(0, 3);
        double[] data = new double[] {1, 2, 3};
        assertArrayEquals(get, data, 1e-1f);

        double[] get2 = buffer.asDouble();
        double[] allData = buffer.getDoublesAt(0, (int) buffer.length());
        assertArrayEquals(get2, allData, 1e-1f);

    }

    @Test
    public void testGetOffsetRange() throws Exception {
        DataBuffer buffer = Nd4j.linspace(1, 5, 5).data();
        double[] get = buffer.getDoublesAt(1, 3);
        double[] data = new double[] {2, 3, 4};
        assertArrayEquals(get, data, 1e-1f);

        double[] allButLast = new double[] {2, 3, 4, 5};

        double[] allData = buffer.getDoublesAt(1, (int) buffer.length());
        assertArrayEquals(allButLast, allData, 1e-1f);

    }

    @Test
    public void testAssign() {
        DataBuffer assertion = Nd4j.createBuffer(new double[] {1, 2, 3});
        DataBuffer one = Nd4j.createBuffer(new double[] {1});
        DataBuffer twoThree = Nd4j.createBuffer(new double[] {2, 3});
        DataBuffer blank = Nd4j.createBuffer(new double[] {0, 0, 0});
        blank.assign(one, twoThree);
        assertArrayEquals(assertion.asDouble(), blank.asDouble(), 0.0001);
    }

    @Test
    public void testOffset() {
        DataBuffer create = Nd4j.createBuffer(new double[] {1, 2, 3, 4}, 2);
        assertEquals(2, create.length());
        assertEquals(4, create.underlyingLength());
        assertEquals(2, create.offset());
        assertEquals(3, create.getDouble(0), 1e-1);
        assertEquals(4, create.getDouble(1), 1e-1);

    }

    @Test
    public void testReallocation() {
        DataBuffer buffer = Nd4j.createBuffer(new double[] {1, 2, 3, 4});
        assertEquals(4, buffer.capacity());
        double[] old = buffer.asDouble();
        buffer.reallocate(6);
        assertEquals(6, buffer.capacity());
        assertArrayEquals(old, buffer.asDouble(), 1e-1);
    }

    @Test
    public void testReallocationWorkspace() {
        WorkspaceConfiguration initialConfig = WorkspaceConfiguration.builder().initialSize(10 * 1024L * 1024L)
                        .policyAllocation(AllocationPolicy.STRICT).policyLearning(LearningPolicy.NONE).build();
        MemoryWorkspace workspace = Nd4j.getWorkspaceManager().getAndActivateWorkspace(initialConfig, "SOME_ID");

        DataBuffer buffer = Nd4j.createBuffer(new double[] {1, 2, 3, 4});
        double[] old = buffer.asDouble();
        assertTrue(buffer.isAttached());
        assertEquals(4, buffer.capacity());
        buffer.reallocate(6);
        assertEquals(6, buffer.capacity());
        assertArrayEquals(old, buffer.asDouble(), 1e-1);
        workspace.close();

    }

    @Override
    public char ordering() {
        return 'c';
    }
}


text:
module.exports = {
    create(context) {
        return {
            ForOfStatement(node) {
                context.report(node, 'Unexpected use of "for...of".');
            },
        };
    },
    meta: {
        deprecated: true,
        docs: {
            category: 'Stylistic Issues',
            description: 'Disallow "for...of"',
            recommended: false,
        },
        schema: [],
    },
};


text:
sample code from joint meetup with Casey West

# Concourse Deployments

## In Cloud Foundry

You need to specify two user-provided services. First, hosted graphite. You need the `apikey`, `host`, and `port`. Create a JSON file to store them which looks like this:

```json
{
    "apikey": "API-KEY",
    "url": "http://CUSTOM-URL.hostedgraphite.com",
    "port": 12345
}
```

Then create the service in the correct org and space:

```sh
$ cf cups hostedgraphite -p "$(cat hosted-graphite.json)"
```

Next, create a papertrail account and get the `syslog-tls` URL that works for Cloud Foundry integration:

```sh
$ cf cups my-logs -l syslog-tls://HOST.papertrailapp.com:PORT
```

## Setting Your Pipeline

You need to specify hosted graphite variables so the build and basic tests can run for maven install. You need the following environment variables:

* `hostedgraphite-apikey`
* `hostedgraphite-url`
* `hostedgraphite-port`

Make sure they match what you used to configure the user provided service in Cloud Foundry.

You need to specify PWS (or another cloud foundry) credentials and target details with the folloing variables:

* `pws-username`
* `pws-password`
* `pws-organization`
* `pws-space`

Now, set your pipeline. If you want to use the official Concourse v1.1.0 `cf-resource` integration, which may not work due to CF CLI v6.13 from October 2015, do the following:

```sh
$ fly -t lite set-pipeline -p op-apps -c ci/pipeline.yml -l ~/.pws-operationalized.yml
$ fly -t lite unpause-pipeline -p op-apps
$ fly -t lite trigger-job -j op-apps/make-jar-not-war
```

If you want to set a pipeline using an up-to-date CF CLI in the docker container [caseywest/cf-release](https://hub.docker.com/r/caseywest/cf-release/) which packages CF CLI v6.17 from April 2016, do the following:

```sh
$ fly -t lite set-pipeline -p op-apps-working -c ci/working-pipeline.yml -l ~/.pws-operationalized.yml
$ fly -t lite unpause-pipeline -p op-apps-working
$ fly -t lite trigger-job -j op-apps-working/make-jar-not-war
```

Take luck!


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>at.rocklogic.kafka</groupId>
    <artifactId>object-support-example</artifactId>
    <version>0.1-SNAPSHOT</version>

    <properties>
    <spring-kafka.version>1.1.0.RELEASE</spring-kafka.version>
        <lombok.version>1.16.4</lombok.version>
        <kafka.version>0.10.0.1</kafka.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
    </parent>

    <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.kafka</groupId>
        <artifactId>spring-kafka</artifactId>
        <version>${spring-kafka.version}</version>
    </dependency>

        <dependency>
            <groupId>at.rocklogic.kafka</groupId>
            <artifactId>object-support</artifactId>
            <version>0.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka-clients</artifactId>
            <version>${kafka.version}</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

</project>


text:
package com.yahoo.sql4d.insert.nodes;

import java.util.LinkedHashMap;
import java.util.Map;
import org.json.JSONObject;

/**
 * Ex: Used in batch data ingestion.
 * "partitionsSpec" : {
      "type" : "dimension",
      "partitionDimension" : null,
      "targetPartitionSize" : 5000000,
      "maxPartitionSize" : 7500000,
      "assumeGrouped" : false,
      "numShards" : -1
    }
 *
 * @author srikalyan
 */
public class PartitionsSpec {
    public long targetPartitionSize = 5000000;
    public String type = "hashed";// dimension/hashed

    @Override
    public String toString() {
        return String.format(getJson().toString(2));
    }

    public JSONObject getJson() {
        return new JSONObject(getDataMap());
    }

    public Map<String, Object> getDataMap() {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("type", type);
        map.put("targetPartitionSize", targetPartitionSize);
        return map;
    }
}


text:
using System.Collections;
using UnityEngine;
using UnityTools;
using UnityTools.SceneManagement;

public class GameManager : AGameManager<GameManager, GameManager.State>
{
    public enum State
    {
        Menu,
        Play,
        Loading,
        Pause,
        GameOver
    }

    private void Start()
    {
        Invoke("LoadNextLevel", 2);
    }

    private void LoadNextLevel()
    {
        SceneManager.Instance.LoadNextLevel();
    }
}


text:
"""Cluster restaurants on map"""
import Clustering
import Map
import DataImporter

def create_gaussian_clusters_and_map(restaurants, restaurant_ids_to_topics, my_map, lda, use_human_labels=True):
    data = Clustering.create_data_array(restaurants, restaurant_ids_to_topics, my_map)
    Clustering.plot_gaussian_clusters(my_map, restaurants, restaurant_ids_to_topics, data, lda)

def run(my_map, reviews, restaurants):
    restaurants = Clustering.filter_restaurants(restaurants)
    normalized_restaurant_ids_to_topics, lda = Clustering.get_predictions(my_map, reviews, restaurants)
    create_gaussian_clusters_and_map(restaurants, normalized_restaurant_ids_to_topics, my_map, lda)

def main():
    my_map = Map.Map.vegas()
    reviews = DataImporter.get_vegas_reviews()
    restaurants = DataImporter.get_vegas_restaurants()
    run(my_map, reviews, restaurants)

if __name__ == '__main__':
    main()


text:
using System.Collections.Generic;
using Village.Model;

namespace Village.DataAccess.Repository
{
    public interface IInvoiceRepository
    {
        List<Invoice> GetAllInvoice();

        List<Invoice> GetInvoiceByOwner(int ownerId);
    }
}


text:
Info 0    [00:00:25.000] Provided types map file "/a/lib/typesMap.json" doesn't exist
Info 1    [00:00:26.000] request:
    {
      "seq": 0,
      "type": "request",
      "command": "open",
      "arguments": {
        "file": "/user/username/projects/myproject/src/test.ts"
      }
    }
Before request
//// [/user/username/projects/myproject/src/test.ts]
import * as blabla from "./blabla.json";
declare var console: any;
console.log(blabla);

//// [/user/username/projects/myproject/src/blabla.json]
{}

//// [/a/lib/lib.d.ts]
/// <reference no-default-lib="true"/>
interface Boolean {}
interface Function {}
interface CallableFunction {}
interface NewableFunction {}
interface IArguments {}
interface Number { toExponential: any; }
interface Object {}
interface RegExp {}
interface String { charAt: any; }
interface Array<T> { length: number; [n: number]: T; }

//// [/user/username/projects/myproject/tsconfig.json]
{"compilerOptions":{"resolveJsonModule":true,"composite":true},"include":["./src/*.ts","./src/*.json"]}

PolledWatches::

FsWatches::

FsWatchesRecursive::

Info 2    [00:00:27.000] Search path: /user/username/projects/myproject/src
Info 3    [00:00:28.000] For info: /user/username/projects/myproject/src/test.ts :: Config file name: /user/username/projects/myproject/tsconfig.json
Info 4    [00:00:29.000] Creating configuration project /user/username/projects/myproject/tsconfig.json
Info 5    [00:00:30.000] FileWatcher:: Added:: WatchInfo: /user/username/projects/myproject/tsconfig.json 2000 undefined Project: /user/username/projects/myproject/tsconfig.json WatchType: Config file
Info 6    [00:00:31.000] event:
    {"seq":0,"type":"event","event":"projectLoadingStart","body":{"projectName":"/user/username/projects/myproject/tsconfig.json","reason":"Creating possible configured project for /user/username/projects/myproject/src/test.ts to open"}}
Info 7    [00:00:32.000] Config: /user/username/projects/myproject/tsconfig.json : {
 "rootNames": [
  "/user/username/projects/myproject/src/test.ts",
  "/user/username/projects/myproject/src/blabla.json"
 ],
 "options": {
  "resolveJsonModule": true,
  "composite": true,
  "configFilePath": "/user/username/projects/myproject/tsconfig.json"
 }
}
Info 8    [00:00:33.000] DirectoryWatcher:: Added:: WatchInfo: /user/username/projects/myproject/src 0 undefined Config: /user/username/projects/myproject/tsconfig.json WatchType: Wild card directory
Info 9    [00:00:34.000] Elapsed:: *ms DirectoryWatcher:: Added:: WatchInfo: /user/username/projects/myproject/src 0 undefined Config: /user/username/projects/myproject/tsconfig.json WatchType: Wild card directory
Info 10   [00:00:35.000] FileWatcher:: Added:: WatchInfo: /user/username/projects/myproject/src/blabla.json 500 undefined WatchType: Closed Script info
Info 11   [00:00:36.000] Starting updateGraphWorker: Project: /user/username/projects/myproject/tsconfig.json
Info 12   [00:00:37.000] DirectoryWatcher:: Added:: WatchInfo: /user/username/projects/myproject/src 1 undefined Project: /user/username/projects/myproject/tsconfig.json WatchType: Failed Lookup Locations
Info 13   [00:00:38.000] Elapsed:: *ms DirectoryWatcher:: Added:: WatchInfo: /user/username/projects/myproject/src 1 undefined Project: /user/username/projects/myproject/tsconfig.json WatchType: Failed Lookup Locations
Info 14   [00:00:39.000] FileWatcher:: Added:: WatchInfo: /a/lib/lib.d.ts 500 undefined WatchType: Closed Script info
Info 15   [00:00:40.000] DirectoryWatcher:: Added:: WatchInfo: /user/username/projects/myproject/node_modules/@types 1 undefined Project: /user/username/projects/myproject/tsconfig.json WatchType: Type roots
Info 16   [00:00:41.000] Elapsed:: *ms DirectoryWatcher:: Added:: WatchInfo: /user/username/projects/myproject/node_modules/@types 1 undefined Project: /user/username/projects/myproject/tsconfig.json WatchType: Type roots
Info 17   [00:00:42.000] Finishing updateGraphWorker: Project: /user/username/projects/myproject/tsconfig.json Version: 1 structureChanged: true structureIsReused:: Not Elapsed:: *ms
Info 18   [00:00:43.000] Project '/user/username/projects/myproject/tsconfig.json' (Configured)
Info 19   [00:00:44.000] 	Files (3)
	/a/lib/lib.d.ts
	/user/username/projects/myproject/src/blabla.json
	/user/username/projects/myproject/src/test.ts

	../../../../a/lib/lib.d.ts
	  Default library for target 'es3'
	src/blabla.json
	  Imported via "./blabla.json" from file 'src/test.ts'
	  Matched by include pattern './src/*.json' in 'tsconfig.json'
	src/test.ts
	  Matched by include pattern './src/*.ts' in 'tsconfig.json'

Info 20   [00:00:45.000] -----------------------------------------------
Info 21   [00:00:46.000] event:
    {"seq":0,"type":"event","event":"projectLoadingFinish","body":{"projectName":"/user/username/projects/myproject/tsconfig.json"}}
Info 22   [00:00:47.000] event:
    {"seq":0,"type":"event","event":"telemetry","body":{"telemetryEventName":"projectInfo","payload":{"projectId":"4a33d78ee40d836c4f4e64c59aed976628aea0013be9585c5ff171dfc41baf98","fileStats":{"js":0,"jsSize":0,"jsx":0,"jsxSize":0,"ts":1,"tsSize":87,"tsx":0,"tsxSize":0,"dts":1,"dtsSize":334,"deferred":0,"deferredSize":0},"compilerOptions":{"resolveJsonModule":true,"composite":true},"typeAcquisition":{"enable":false,"include":false,"exclude":false},"extends":false,"files":false,"include":true,"exclude":false,"compileOnSave":false,"configFileName":"tsconfig.json","projectType":"configured","languageServiceEnabled":true,"version":"FakeVersion"}}}
Info 23   [00:00:48.000] event:
    {"seq":0,"type":"event","event":"configFileDiag","body":{"triggerFile":"/user/username/projects/myproject/src/test.ts","configFile":"/user/username/projects/myproject/tsconfig.json","diagnostics":[]}}
Info 24   [00:00:49.000] Search path: /user/username/projects/myproject
Info 25   [00:00:50.000] For info: /user/username/projects/myproject/tsconfig.json :: No config files found.
Info 26   [00:00:51.000] Project '/user/username/projects/myproject/tsconfig.json' (Configured)
Info 26   [00:00:52.000] 	Files (3)

Info 26   [00:00:53.000] -----------------------------------------------
Info 26   [00:00:54.000] Open files:
Info 26   [00:00:55.000] 	FileName: /user/username/projects/myproject/src/test.ts ProjectRootPath: undefined
Info 26   [00:00:56.000] 		Projects: /user/username/projects/myproject/tsconfig.json
After request

PolledWatches::
/user/username/projects/myproject/node_modules/@types:
  {"pollingInterval":500}

FsWatches::
/user/username/projects/myproject/tsconfig.json:
  {}
/user/username/projects/myproject/src:
  {}
/user/username/projects/myproject/src/blabla.json:
  {}
/a/lib/lib.d.ts:
  {}

FsWatchesRecursive::
/user/username/projects/myproject/src:
  {}

Info 26   [00:00:57.000] response:
    {
      "responseRequired": false
    }
Info 27   [00:00:58.000] request:
    {
      "command": "geterr",
      "arguments": {
        "delay": 0,
        "files": [
          "/user/username/projects/myproject/src/test.ts"
        ]
      },
      "seq": 1,
      "type": "request"
    }
Before request

PolledWatches::
/user/username/projects/myproject/node_modules/@types:
  {"pollingInterval":500}

FsWatches::
/user/username/projects/myproject/tsconfig.json:
  {}
/user/username/projects/myproject/src:
  {}
/user/username/projects/myproject/src/blabla.json:
  {}
/a/lib/lib.d.ts:
  {}

FsWatchesRecursive::
/user/username/projects/myproject/src:
  {}

After request

PolledWatches::
/user/username/projects/myproject/node_modules/@types:
  {"pollingInterval":500}

FsWatches::
/user/username/projects/myproject/tsconfig.json:
  {}
/user/username/projects/myproject/src:
  {}
/user/username/projects/myproject/src/blabla.json:
  {}
/a/lib/lib.d.ts:
  {}

FsWatchesRecursive::
/user/username/projects/myproject/src:
  {}

Info 28   [00:00:59.000] response:
    {
      "responseRequired": false
    }
Before checking timeout queue length (1) and running

PolledWatches::
/user/username/projects/myproject/node_modules/@types:
  {"pollingInterval":500}

FsWatches::
/user/username/projects/myproject/tsconfig.json:
  {}
/user/username/projects/myproject/src:
  {}
/user/username/projects/myproject/src/blabla.json:
  {}
/a/lib/lib.d.ts:
  {}

FsWatchesRecursive::
/user/username/projects/myproject/src:
  {}

Info 29   [00:01:00.000] event:
    {"seq":0,"type":"event","event":"syntaxDiag","body":{"file":"/user/username/projects/myproject/src/test.ts","diagnostics":[]}}
After checking timeout queue length (1) and running

PolledWatches::
/user/username/projects/myproject/node_modules/@types:
  {"pollingInterval":500}

FsWatches::
/user/username/projects/myproject/tsconfig.json:
  {}
/user/username/projects/myproject/src:
  {}
/user/username/projects/myproject/src/blabla.json:
  {}
/a/lib/lib.d.ts:
  {}

FsWatchesRecursive::
/user/username/projects/myproject/src:
  {}

Before running immediate callbacks and checking length (1)

PolledWatches::
/user/username/projects/myproject/node_modules/@types:
  {"pollingInterval":500}

FsWatches::
/user/username/projects/myproject/tsconfig.json:
  {}
/user/username/projects/myproject/src:
  {}
/user/username/projects/myproject/src/blabla.json:
  {}
/a/lib/lib.d.ts:
  {}

FsWatchesRecursive::
/user/username/projects/myproject/src:
  {}

Info 30   [00:01:01.000] event:
    {"seq":0,"type":"event","event":"semanticDiag","body":{"file":"/user/username/projects/myproject/src/test.ts","diagnostics":[]}}
Before running immediate callbacks and checking length (1)

PolledWatches::
/user/username/projects/myproject/node_modules/@types:
  {"pollingInterval":500}

FsWatches::
/user/username/projects/myproject/tsconfig.json:
  {}
/user/username/projects/myproject/src:
  {}
/user/username/projects/myproject/src/blabla.json:
  {}
/a/lib/lib.d.ts:
  {}

FsWatchesRecursive::
/user/username/projects/myproject/src:
  {}

Before running immediate callbacks and checking length (1)

PolledWatches::
/user/username/projects/myproject/node_modules/@types:
  {"pollingInterval":500}

FsWatches::
/user/username/projects/myproject/tsconfig.json:
  {}
/user/username/projects/myproject/src:
  {}
/user/username/projects/myproject/src/blabla.json:
  {}
/a/lib/lib.d.ts:
  {}

FsWatchesRecursive::
/user/username/projects/myproject/src:
  {}

Info 31   [00:01:02.000] event:
    {"seq":0,"type":"event","event":"suggestionDiag","body":{"file":"/user/username/projects/myproject/src/test.ts","diagnostics":[]}}
Info 32   [00:01:03.000] event:
    {"seq":0,"type":"event","event":"requestCompleted","body":{"request_seq":1}}
Before running immediate callbacks and checking length (1)

PolledWatches::
/user/username/projects/myproject/node_modules/@types:
  {"pollingInterval":500}

FsWatches::
/user/username/projects/myproject/tsconfig.json:
  {}
/user/username/projects/myproject/src:
  {}
/user/username/projects/myproject/src/blabla.json:
  {}
/a/lib/lib.d.ts:
  {}

FsWatchesRecursive::
/user/username/projects/myproject/src:
  {}


text:
A Set of graded Kubernetes tutorials to document self-progress and help peers

### Credits
  - Borrowed unabashedly from [janakiramm/kubernetes-101](https://github.com/janakiramm/kubernetes-101/tree/master/Docker)
    - Not forked as I intend to create a step by step guide for myself and others in a single repo
  - [github/rmenn](https://github.com/rmenn) for the mentorship

### Build a Docker image
Replace `DOCKER_HUB_USER` with your Docker Hub username.

```
cd Docker
docker build -t <DOCKER_HUB_USER>/web .
docker push <DOCKER_HUB_USER>/web
```

### Launch the app with Docker Compose
```
docker-compose up -d
```

### Test the app
```
curl localhost:5000
```

### Setup Minikube
[macOS / OS X: Minikube](minikube.md)

### 101: Pods exposed as Services
```
cd ../101-pod-service
kubectl create -f db-pod.yml
kubectl create -f db-svc.yml
kubectl create -f web-pod.yml
kubectl create -f web-svc.yml
```

### 102: Pods with ReplicaSet exposed as Services
WIP

### 103: Deployments exposed as Services
```
cd ../103-deployment-replicas-service
kubectl create -f db-dpl.yml
kubectl create -f db-svc.yml
kubectl create -f web-dpl.yml
kubectl create -f web-svc.yml
```

### Check that the Pods and Services are created
```
kubectl get pods
kubectl get svc
```

### Get the NodePort for the web Service. Make a note of the port.
```
kubectl describe svc web
```

### Test the app by using minkube service url

```
minikube service web --url
```


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace InitialRound.Models.Schema.dbo
{
    [Table("TestResult", Schema = "dbo")]
    public class TestResult
    {
        [Key]
        public Guid ID { get; set; }
        public Guid AttemptID { get; set; }
        public Guid? TestID { get; set; }
        public bool Passed { get; set; }
        public string TestName { get; set; }
        public string InputString { get; set; }
        public string ExpectedOutputString { get; set; }
        public string OutputString { get; set; }
        public DateTime CreatedDate { get; set; }
        public string CreatedBy { get; set; }
        public DateTime LastUpdatedDate { get; set; }
        public string LastUpdatedBy { get; set; }

        public virtual Attempt Attempt { get; set; }
    }
}


text:
module Volt
  class CLI
    desc 'precompile', 'precompile all application assets'

    def precompile
      compile
    end

    private

    def compile
      puts 'compiling project...'
      require 'fileutils'
      ENV['SERVER'] = 'true'

      require 'opal'
      require 'rack'
      require 'volt'
      require 'volt/volt/core'
      require 'volt/boot'

      @root_path ||= Dir.pwd
      Volt.root  = @root_path

      volt_app = Volt.boot(@root_path)

      require 'volt/server/rack/component_paths'
      require 'volt/server/rack/component_code'
      require 'volt/server/component_handler'

      @app_path = File.expand_path(File.join(@root_path, 'app'))

      @component_paths   = ComponentPaths.new(@root_path)
      @app               = Rack::Builder.new
      @opal_files        = OpalFiles.new(@app, @app_path, @component_paths)
      @index_files       = IndexFiles.new(@app, volt_app, @component_paths, @opal_files)
      @component_handler = ComponentHandler.new(@component_paths)

      puts 'Compile Opal for components'
      write_component_js
      puts 'Copy assets'
      write_sprockets
      puts 'Compile JS/CSS'
      write_js_and_css
      puts 'Write index files'
      write_index

      puts "compiled"
    end

    def logical_paths_and_full_paths
      @opal_files.environment.each_file do |full_path|
        logical_path = @opal_files.environment.send(:logical_path_for_filename, full_path, []).to_s

        yield(logical_path, full_path.to_s)
      end

    end

    def write_sprockets
      # Serve the opal files
      logical_paths_and_full_paths do |logical_path, full_path|
        # Only include files that aren't compiled elsewhere, like fonts
        if !logical_path[/[.](y|css|js|html|erb)$/] &&
          File.extname(logical_path) != '' &&
          # opal includes some node modules in the standard lib that we don't need to compile in
          (full_path !~ /\/opal/ && full_path !~ /\/stdlib\// && logical_path !~ /^node_js\//)
          write_sprocket_file(logical_path)
        end
      end
    end

    def write_js_and_css
      (@index_files.javascript_files + @index_files.css_files).each do |logical_path|
        if logical_path =~ /^\/assets\//
          logical_path = logical_path.gsub(/^\/assets\//, '')
          write_sprocket_file(logical_path)
        end
      end
    end

    def write_sprocket_file(logical_path)
      path = "#{@root_path}/public/assets/#{logical_path}"

      begin
        # Only write out the assets
        # if logical_path =~ /\/assets\//
          content = @opal_files.environment[logical_path].to_s
          write_file(path, content)
        # end
      rescue Sprockets::FileNotFound, SyntaxError => e
        # ignore
      end
    end

    def write_component_js
      javascript_code = @component_handler.compile_for_component('main', true)

      path = File.join(Volt.root, '/public/components/main.js')
      write_file(path, javascript_code)
    end

    def write_index
      path = "#{@root_path}/public/index.html"

      write_file(path, @index_files.html)
    end

    def write_file(path, data)
      FileUtils.mkdir_p(File.dirname(path))

      File.open(path, 'wb') do |file|
        file.write(data)
      end
    end
  end
end


text:
require 'spec_helper'
require 'net/ssh/test'

describe ElectricSheep::Interactors::SshInteractor do
  include Net::SSH::Test

  module Net ; module SSH ; module Test

    # Avoid Net::SSH::Test::Extensions to collide with Coveralls
    class << self
      def remove_io_aliases
        ::IO.class_eval <<-EOF
          class << self
            alias_method :select, :select_for_real
          end
        EOF
      end

      def create_io_aliases
        ::IO.class_eval <<-EOF
          class << self
            alias_method :select_for_real, :select
            alias_method :select, :select_for_test
          end
        EOF
      end
    end

    remove_io_aliases

    class Kex
      def exchange_keys
        result = Net::SSH::Buffer.from(:byte, NEWKEYS)
        @connection.send_message(result)

        buffer = @connection.next_message
        raise Net::SSH::Exception, "expected NEWKEYS" unless buffer.type == NEWKEYS

        { :session_id        => "abc-xyz",
          # :server_key        => OpenSSL::PKey::RSA.new(512),
          :shared_secret     => OpenSSL::BN.new("1234567890", 10),
          :hashing_algorithm => OpenSSL::Digest::SHA1 }
      end
    end
  end ; end ; end

  before do
    Net::SSH::Test.create_io_aliases
  end

  let(:logger){ mock }

  let(:interactor) do
    subject.new( host, job, 'johndoe', logger )
  end

  let(:host) do
    ElectricSheep::Metadata::Host.new(hostname: 'host.tld')
  end

  let(:job) do
    mock.tap do |job|
      job.stubs(:id).returns('my-job')
    end
  end

  after do
    Net::SSH::Test.remove_io_aliases
  end

  describe 'selecting the private key' do

    let(:host){ mock }
    let(:job){ mock }

    it 'uses the host key if specified' do
      host.expects(:private_key).returns('key_rsa')
      subject.new(host, job, 'user').send(:private_key).
        must_equal File.expand_path('key_rsa')
    end

    it 'falls back to the job key' do
      host.expects(:private_key).returns(nil)
      job.expects(:private_key).returns('key_rsa')
      subject.new(host, job, 'user').send(:private_key).
      must_equal File.expand_path('key_rsa')
    end

    it 'falls back to the default key' do
      host.expects(:private_key).returns(nil)
      job.expects(:private_key).returns(nil)
      subject.new(host, job, 'user').send(:private_key).
      must_equal File.expand_path('~/.ssh/id_rsa')
    end

  end

  describe "with a session" do

    def build_ssh_story(cmd, replies={}, exit_status=0)
      story do |session|
        channel = session.opens_channel
        channel.sends_exec cmd
        replies.each do |type, reply|
          channel.send "gets_#{type}", reply
        end
        yield if block_given?
        channel.gets_exit_status(exit_status)
        channel.gets_close
        channel.sends_close
      end
    end

    before do
      ElectricSheep::Crypto.open_ssl.expects(:get_key).
        with('/path/to/private/key', :private).
        returns(pk = mock)
      pk.expects(:export).returns('SECRET')
      Net::SSH.expects(:start).
        with('host.tld', 'johndoe', port: 22, key_data: 'SECRET', keys_only: true).
        returns( connection )
      user = 'johndoe'
      job.expects(:private_key).returns('/path/to/private/key')
      ElectricSheep::Helpers::Directories.any_instance.expects(:mk_job_directory!)
    end

    it 'logs to stderr on failing exec' do
      story do |session|
        channel = session.opens_channel
        channel.sends_exec 'whatever', true, false
        channel.gets_close
        channel.sends_close
      end
      logger.expects(:debug).with('whatever')
      assert_scripted do
        interactor.in_session do
          proc{ interactor.exec 'whatever' }.must_raise RuntimeError
        end
      end
    end

    it 'should return stdout output' do
      build_ssh_story 'echo "Hello World"', {data: 'Hello World'}
      logger.expects(:debug).with('echo "Hello World"')
      logger.expects(:debug).with('Hello World')
      assert_scripted do
        interactor.in_session do
          result = interactor.exec 'echo "Hello World"'
          result.must_equal({:out=>"Hello World", :err=>"", :exit_status=>0})
        end
      end
    end

    it 'should return stderr output' do
      build_ssh_story 'echo "Goodbye Cruel World" >&2', {extended_data: 'Goodbye Cruel World'}
      logger.expects(:debug).with('echo "Goodbye Cruel World" >&2')
      assert_scripted do
        interactor.in_session do
          result = interactor.exec 'echo "Goodbye Cruel World" >&2'
          result.must_equal({:out=>"", :err=>"Goodbye Cruel World", :exit_status=>0})
        end
      end
    end

    it 'should return both stdout and stderr' do
      build_ssh_story 'echo "Hello World" ; echo "Goodbye Cruel World" >&2',
      {data: 'Hello World', extended_data: 'Goodbye Cruel World'}
      logger.expects(:debug).with('echo "Hello World" ; echo "Goodbye Cruel World" >&2')
      logger.expects(:debug).with('Hello World')
      assert_scripted do
        interactor.in_session do
          result = interactor.exec 'echo "Hello World" ; echo "Goodbye Cruel World" >&2'
          result.must_equal({:out=>"Hello World", :err=>"Goodbye Cruel World", :exit_status=>0})
        end
      end
    end

    describe 'on returning status' do
      it 'should succeed' do
        build_ssh_story 'echo "Hello World"', {data: 'Hello World'}
        logger.expects(:debug).with('echo "Hello World"')
        logger.expects(:debug).with('Hello World')
        assert_scripted do
          result=nil
          interactor.in_session do
            result = interactor.exec('echo "Hello World"')
          end
          result[:exit_status].must_equal 0
          result[:out].must_equal 'Hello World'
        end
      end

      it 'should fail gracefully' do
        build_ssh_story 'ls --wtf', {extended_data: 'An error'}, 2
        logger.expects(:debug).with('ls --wtf')
        assert_scripted do
          interactor.in_session do
            proc{ interactor.exec('ls --wtf') }.must_raise RuntimeError
          end
        end
      end

      it 'should be able to delete resources' do
        resource=mock(path: 'resource')
        cmd='rm -rf /path/to/resource'
        build_ssh_story cmd, {}
        logger.expects(:debug).with(cmd)
        interactor.expects(:expand_path).with('resource').
          returns('/path/to/resource')
        assert_scripted do
          interactor.in_session do
            result = interactor.delete!(resource)
            result[:exit_status].must_equal 0
          end
        end
      end
    end

  end

  it 'uses the SCP from SSH session' do
    interactor.expects(:session).returns(mock(scp: scp=mock))
    interactor.scp.must_equal scp
  end

  describe 'transfering resources' do

    [:input, :output].each do |m|

      let(m) do
        mock.tap do |r|
          r.stubs(:path).returns(m.to_s)
        end
      end

      let("#{m}_path"){ "/path/to/#{m}" }

    end

    let(:local_interactor){ mock }

    let(:scp){ mock }

    let(:seq){ sequence('transfer') }

    before do
      interactor.stubs(:scp).returns(scp)
    end

    def expects_paths_expansion(input_expander, output_expander)
      input_expander.expects(:expand_path).with(input.path).
        returns(input_path)
      output_expander.expects(:expand_path).with(output.path).
        returns(output_path)
    end

    def expects_file_op(action, interactor)
      scp.expects(action).in_sequence(seq).
        with(input_path, output_path, recursive: input.directory?)
    end

    def expects_directory_op(action, interactor)
      path_regexp=/\/path\/to\/tmp\d{8}/
      interactor.expects(:exec).in_sequence(seq).
        with(regexp_matches(/^mkdir #{path_regexp}/))
      scp.expects(action).in_sequence(seq).
        with(input_path, regexp_matches(path_regexp), recursive: input.directory?)
      interactor.expects(:exec).in_sequence(seq).
        with(regexp_matches(/^mv #{path_regexp}.* #{output_path}/))
      interactor.expects(:exec).in_sequence(seq).
        with(regexp_matches(/^rm -rf #{path_regexp}/))
    end

    def self.ensure_scp(type, action)

      it "#{action}s a #{type}" do
        [:input, :output].each do |m|
          send(m).stubs(:directory?).returns(type==:directory)
        end
        expanders=[local_interactor, interactor]
        expanders.reverse! if action == :download
        expects_paths_expansion(*expanders)
        send "expects_#{type}_op", "#{action}!", expanders.last
        interactor.send "#{action}!", input, output, local_interactor
      end

    end

    ensure_scp :file, :download
    ensure_scp :file, :upload
    ensure_scp :directory, :download
    ensure_scp :directory, :upload

  end
end


text:
#ifndef GKCHESS_IBOOKREADER_H
#define GKCHESS_IBOOKREADER_H

#include "gkchess_movedata.h"
#include <gutil/string.h>
#include <QObject>

namespace GKChess
{

/** An interface to access an opening book. */
class IBookReader
{
public:

    class IValidationProgressObserver;

    /** Opens a book with the given file name. If a book was already open, it will be closed
     *  and the new one will be opened.
     *
     *  Throws an exception if the book could not be opened.
    */
    virtual void OpenBook(const char *) = 0;

    /** Returns true if the book is open. */
    virtual bool IsBookOpen() const = 0;

    /** Returns the filename for the book that is currently open, or 0 if there is no book open. */
    virtual const char *GetBookFilename() const = 0;

    /** Validates the book. This may be a time-expensive operation, so you can provide a callback function
     *  to track its progress.
     *  Throws an exception if validation fails
    */
    virtual void ValidateBook(IValidationProgressObserver * = 0) = 0;

    /** Looks up the given position in the book, and returns all the moves it found.
     *  If the position was not in the database, an empty vector is returned.
    */
    virtual QList<BookMove> LookupMoves(const char *fen) = 0;

    /** Closes the book, or does nothing if it's already closed. */
    virtual void CloseBook() = 0;

    virtual ~IBookReader(){}

    /** Used to catch progress updates during book validation. */
    class IValidationProgressObserver
    {
    public:
        virtual void OnValidationProgressUpdate(int) = 0;
    };

};

}

Q_DECLARE_INTERFACE(GKChess::IBookReader, "GKChess.IBookReader")

#endif // GKCHESS_IBOOKREADER_H


text:
package org.jmxtrans.embedded.util.pool;

import org.apache.commons.pool.BaseKeyedPoolableObjectFactory;
import org.junit.Test;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

/**
 * @author Cyrille Le Clerc
 */
public class ManagedGenericKeyedObjectPoolTest {

    @Test
    public void testMbeanAttributeAccess() throws Exception {
        BaseKeyedPoolableObjectFactory<String, String> factory = new BaseKeyedPoolableObjectFactory<String, String>() {
            @Override
            public String makeObject(String key) throws Exception {
                return key;
            }
        };
        ManagedGenericKeyedObjectPool<String, String> objectPool = new ManagedGenericKeyedObjectPool<String, String>(factory);

        ObjectName objectName = new ObjectName("org.jmxtrans.embedded:Type=TestPool,Name=TestPool@" + System.identityHashCode(this));
        MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
        objectName = mbeanServer.registerMBean(objectPool, objectName).getObjectName();
        try {
            Object numIdle = mbeanServer.getAttribute(objectName, "NumIdle");
            assertThat(numIdle, instanceOf(Number.class));

        } finally {
            mbeanServer.unregisterMBean(objectName);
        }

    }
}


text:
package org.terasology.logic.commands;

public interface CommandProvider {

}


text:
package ru.lotnyk.todo_list.controller;

import ru.lotnyk.todo_list.model.Item;
import ru.lotnyk.todo_list.repository.ItemRepository;
import ru.lotnyk.todo_list.uttil.ItemUttil;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;

/**
 * Class AddUser.
 * @author Roman Lotnyk(romanlotnik@yandex.ru)
 * @version 1
 * @since 16.09.2017
 */
public class AddUser extends HttpServlet {

    /**
     * itemRepository.
     */
    private ItemRepository itemRepository;

    /**
     * doPost.
     * @param req req
     * @param resp resp
     * @throws ServletException "ServletException"
     * @throws IOException "IOException"
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.itemRepository = new ItemUttil();
        Item item = new Item();
        item.setDescription(req.getParameter("description"));
        item.setCreate(new Timestamp(System.currentTimeMillis()));
        this.itemRepository.add(item);
        resp.sendRedirect(String.format("%s/index.html", req.getContextPath()));
    }

}


text:
using System;
using System.Collections.ObjectModel;
using System.Xml.Serialization;

namespace NGin.Core.Configuration.Serialization
{
    [Serializable, XmlRoot( "pluginconfig" ),
        ConfigDataType( typeof( PluginsConfigXml ) )]
    public class PluginsConfigXml
    {
        [XmlArray( "plugins" ), XmlArrayItem( "file" )]
        public Collection<FileXml> PlugIns { get; set; }

        public bool IsInitialized
        {
            get
            {
                if ( this.PlugIns == null )
                {
                    return false;
                }

                return true;
            }
        }

        public override int GetHashCode()
        {
            if ( this.PlugIns != null && this.PlugIns.Count > 0 )
            {
                int hashCode = PlugIns.Count.GetHashCode();

                foreach ( FileXml file in this.PlugIns )
                {
                    hashCode = hashCode ^ file.GetHashCode();
                }

                return hashCode;
            }

            return base.GetHashCode();
        }

        public override bool Equals( object obj )
        {
            PluginsConfigXml other = obj as PluginsConfigXml;
            // check type
            if ( other == null )
            {
                return false;
            }

            if ( this.PlugIns != null )
            {
                // check amount of dependencies
                if ( this.PlugIns.Count != other.PlugIns.Count )
                {
                    return false;
                }

                // check each dependency
                for ( int i = 0; i < this.PlugIns.Count; i++ )
                {
                    if ( !this.PlugIns[ i ].Equals( other.PlugIns[ i ] ) )
                    {
                        return false;
                    }
                }
            }

            return true;
        }
    }
}