text:
- [Scope](#scope)
- [Design](#design)
- [Default IdP Configuration](#default-idp-configuration)
- [Overlay IdP Configuration](#overlay-idp-configuration)

## Heroku [![](https://heroku-badge.herokuapp.com/?app=shibboleth-oidc)](https://shibboleth-oidc.herokuapp.com/idp)

An instance of this codebase is presently running on [Heroku](https://shibboleth-oidc.herokuapp.com/idp).
You may need to refresh the page twice to wake up the instance as idle timeouts may cause it to go down.

## Scope

We are working on adding support for the OpenID Connect protocol to the Shibboleth Identity Provider v3. Realistically, these
are the items we are planning to address:

* Authorization code workflow
* Dynamic discovery
* Administration and registration of OIDC RPs with the IdP.
* Ability to resolve, consume and release OIDC claims, taking advantage of IdP's machinery to release attributes.
* Ability to configure an expiration and revocation policy around OIDC access and refresh tokens from an admin perspective.

Note that no significant UI enhancements are taken into account. All configuration and changes are directly assumed to be applied to the IdP config without the presence of a web interface to facilitate. This includes administration and management of metadata, authZ codes and more.

### Resources

* [OpenID Connect Basic](http://openid.net/specs/openid-connect-basic-1_0.html)
* [OpenID Connect Implicit](http://openid.net/specs/openid-connect-implicit-1_0.html)

### Planned

The following may be considered in future versions:

* Hybrid flow
* Implicit flow
* Dynamic RP registration
* Logout
* Web UIs that facilitate managing tokens, whitelisted/blacklisted RPs, etc.

### Toolkit

- Apache Maven v3.5+
- JDK 8+
- [MITREid Connect v1.3.1](https://github.com/mitreid-connect/) handles the OIDC implementation.
- [Shibboleth Identity Provider v3.3.2](https://wiki.shibboleth.net/confluence/display/IDP30/Home)

## Design

The OIDC support is provided via the [MITREid Connect](https://github.com/mitreid-connect/) project.
It is itself based on Spring Security OAuth which itself in turn is based on Spring Security. So,
the design principal of this extension is to mostly adapt the above frameworks to what the Shibboleth
IdP framework provides in terms of authentication and attribute resolution. Also note that that MITREid
Connect is entirely Spring annotations-based when it comes to wiring up the components. Spring Security
OAuth also uses various annotations to respond to endpoint requests. Such changes also need to be accounted
for in the IdP as it does not presently use a native model for annotation-based configuration of components.

### Endpoints

The following endpoints are exposed by this extension:

- `/idp/profile/oidc/token`
- `/idp/profile/oidc/authorize`
- `/idp/profile/oidc/jwk`
- `/idp/profile/oidc/userinfo`
- `/idp/.well-known`

Each of these endpoints is protected via Spring Security, and configured in `oidc-protocol-endpoints.xml`.
Spring Security OAuth itself presents various components that respond to framework endpoints and handles
the OAuth functionality. In this extension, these endpoints are merely registered to note the new URL endpoint within the IdP framework.

### Storage

MITREid Connect ships with a JPA implementation already that is responsible for managing the persistence
of various tokens and the configuration of available/supported scopes, clients, etc. This extension
leverages that functionality and configures a by-default inmemory database instance inside `oidc-protocol-storage.xml`.
The database choice and driver are controllable via IdP settings inside `oidc.properties`.

```properties
oidc.db.schema.type=hsql
oidc.db.driver=org.hsqldb.jdbcDriver
oidc.db.url=jdbc:hsqldb:mem:oic;sql.syntax_mys=true
oidc.db.uid=sa
oidc.db.psw=
```

#### Schema

Note that the default schema provided by this extension assumes a HSQLDB database. If you wish to use a different database, you will need to provide an different schema. Additional schemas are provieded in the `conf` directory for various databases. The following databases are supported:

 1. HSQL
 2. Postgres
 3. MySQL
 4. Oracle

#### System Scopes

Systems scopes are directly provided in the IdP configuration inside the `oidc-protocol-scopes.xml`. An adopter
may choose to ignore/remove scopes that are deemed unsupported.

#### Clients

Registration of clients is now directly provided in the IdP configuration inside the `oidc-protocol.xml`.

### Issuer

The OIDC issuer is controlled via the `oidc.properties` file:

```properties
oidc.issuer=
```

### System

There are various other authentication manager/provider components registered in `oidc-protocol-system.xml`
that handle backchannel authentication requests for tokens and userinfo data. These are primarily based on
Spring Security and MITREid Connect extensions of Spring Security. Additionally, auto-registration of MITREid Connect
annotation-aware components  as well as all other components registered in this extension is handled here.

### Encryption/Signing

This extension ships with a default encryption/signing components defined in the `oidc-protocol-system.xml`.
A default JWKS is also provided which can be controlled via `oidc.properties` at:

```properties
oidc.jwtset.keystore=%{idp.home}/credentials/keystore.jwks
```

This file is presently not reloaded on changes, and its associated context is also not yet reloadable. Key
rotations for the default keystore must happen manually, and require a restart for the time being.

Note that every client registered in the IdP is also able to specify an endpoint for its JWKS.

### Clients

Client definitions are managed in the database by default. They may also be defined in `oidc-protocol.xml` and upon startup, they will be imported into the running database of choice where definitions will either be saved or updated.

```xml
<util:set id="oidcClients">
    <bean class="org.mitre.oauth2.model.ClientDetailsEntity"
            p:id="1000"
            p:clientId="client"
            p:clientSecret="secret"
            p:clientName="Sample Client">

        <property name="scope">
            <bean class="org.springframework.util.StringUtils" factory-method="commaDelimitedListToSet">
                <constructor-arg type="java.lang.String" value="openid,profile,email,address,phone,offline_access"/>
            </bean>
        </property>
        <property name="grantTypes">
            <bean class="org.springframework.util.StringUtils" factory-method="commaDelimitedListToSet">
                <constructor-arg type="java.lang.String" value="authorization_code,implicit,refresh_token"/>
            </bean>
        </property>
        <property name="redirectUris">
            <set>
                <value>http://localhost:8080/simple-web-app/openid_connect_login</value>
            </set>
        </property>
    </bean>
</util:set>
```

### Claims

Claims can be configured as normal attribute definitions in the IdP. All standard claims that are present in the specification
are supported. Here is an example of a claim:

```xml
<AttributeDefinition xsi:type="Simple" id="family_name" sourceAttributeID="family_name">
    <Dependency ref="staticAttributes" />
    <DisplayName>Family Name</DisplayName>
</AttributeDefinition>
```

Note that attribute encoders are not needed since the JSON transformation is handled directly via the underlying
frameworks. Also, claims can be filtered in turn by the IdP itself via the normal attribute filtering policy. Here is an example:

```xml
<AttributeFilterPolicy id="default">
    <PolicyRequirementRule xsi:type="Requester" value="client" />

    <AttributeRule attributeID="family_name">
        <PermitValueRule xsi:type="ANY" />
    </AttributeRule>
</AttributeFilterPolicy>
```

The requester (i.e. EntityID) is always the `clientId` of the client registered in the IdP.

Note that each client is able to specify which scopes it supports. This allows a second level of granularity where an
adopter may choose to support only specific claims within a system scope.

### Flows

#### Authorization Code Flow

This extension registered an authentication flow for OIDC inside `oidc/login/login-flow.xml` whose beans are
configured inside `oidc/login/login-beans.xml`. A typical walkthrough of the authentication flow is as such:

- The client makes a request to `/idp/.well-known` to discover endpoints for OIDC conversation.
- The IdP's `/idp/.well-known` endpoint presents a JSON envelope that contains everything the client needs to know for dynamic discovery.
- The client makes a request to `/idp/profile/oidc/authorize` endpoint which is first handled by Spring Security OAuth.
- Since the request requires an existing authentication to succeed, Spring Security OAuth throws a `InsufficientAuthenticationException`.
- The IdP is configured to ignore the this exception so that downstream Spring Security components/filters can process it later. This is done via `mvc-beans.xml`.
- `ExceptionTranslationFilter` of Spring Security kicks in and attempts to handle the request. The request is then routed to Spring Security for authentication.
- The Idp has configured Spring Security for form-based authentication, which allows the request to be routed to a `login` endpoint for authentication.
- The `login` endpoints invokes Spring Webflow to recall the OIDC login flow to start the flow.
- The `login` flow eventually reaches the authentication state allowing for end-user login.
- Once the authentication is successful, the result is then `POST`ed back to Spring Security to resume the `/idp/profile/oidc/authorize` endpoint functionality.
- The `/idp/profile/oidc/authorize` will proceed to issue a `code` for the given request does a `POST` back to the client.
- The client asks the `/idp/profile/oidc/token` endpoint for an access token, via the `code` received.
- Spring Security OAuth, having recognized an existing authentication session issues an access token back along with an `idToken` in a JWT format.
- The client validates the access token and the idToken, optionally invoking the `/idp/profile/oidc/jwk` endpoint to verify the `idToken`.
- The client will use the access token to issue a request to `/idp/profile/oidc/userinfo` to grab claims.

There are many many other permutations of this flow, and many additional extension parameters that could be passed.
To learn about all that is possible in this flow, Study [the basics of the specification](http://openid.net/specs/openid-connect-basic-1_0.html).

#### Hybrid Flow

The hybrid flow is virtually identical to the authorication code flow, except that upon authorization
requests the `response_type` parameter must be set to `id_token token`.

#### Authentication Context/Method Ref

This extension supports the `acr/amr` claims. If the client requests a specific `acr_value` in the
original request, the IdP attempts to calculate whether that value is indeed supported by any of the authentication
flows. If none is deemed viable, the authentication context weight map of the IdP is consulted to figure out the appropriate `acr`.
The result is passed onto the IdP for authentication.

Since MITREid Connect at this point does not natively support `acr/amr` claims, an implementation of a
claim service is provided by this extension to handle `acr/amr` claims for the client.

#### Max-Age, AuthN Time

This extension supports the `max_age` and `auth_time` claims. If `max_age` is provided in the original
request, the IdP attempts to calculate the authentication creation instant and may simulate a `forcedAuthN` so the end-user is actively reauthenticated.

Since MITREid Connect's support for these claims is strictly tied to an authentication that is very much
handled by Spring Security ( as a requirement for Spring Security OAuth), a custom service is provided by
this extension to handle the production of `max_age` and `auth_time`.

## Default IdP Configuration

Follow the below steps if you wish to enable this extension inside a vanilla IdP v3 deployment. Note
that synchronization of changes, as we make progress here, is entirely manual at this point.

### Build

```bash
git clone git@github.com:uchicago/shibboleth-oidc.git
```

Or download [a zip distribution](https://github.com/uchicago/shibboleth-oidc/archive/master.zip).

Build the codebase via:

```bash
./mvn[w] clean package -P new
```

### Cross Examine Changes

Unzip the `idp-webapp-overlay/target/idp.war` artifact into an `idp-temp`.
This will be used as a reference to copy configuration into your IdP deployment.

- Cross examine the `idp-temp/WEB-INF/web.xml` with your IdP and apply all differences.
- Cross examine the `idp-temp/idp/views/login.vm` and `idp-temp/idp/views/intercept/attribute-release.vm` with your IdP and apply all differences.
- Cross examine the `idp-temp/idp/system/conf/global-system.xml` with your IdP and apply all differences.
- Cross examine the `idp-temp/idp/system/conf/webflow-config.xml` with your IdP and apply all differences.
- Cross examine the `idp-temp/idp/conf/mvc-beans.xml` with your IdP and apply all differences.
- Cross examine the `idp-temp/idp/conf/idp.properties` with your IdP and apply all differences.
- Cross examine the `idp-temp/idp/conf/attribute-resolver.xml` with your IdP and apply all differences.
- Cross examine the `idp-temp/idp/conf/attribute-filter.xml` with your IdP and apply all differences.
- Cross examine the `idp-temp/idp/conf/relying-party.xml` with your IdP and apply all differences.

### Copy Configuration

- Copy `idp-temp/idp/conf/oidc.properties`, `idp-temp/idp/conf/oidc-protocol.xml` into `$IDP_HOME/conf`
- Copy the directory `idp-temp/idp/conf/schema` to `$IDP_HOME/conf/`
- Copy `idp-temp/idp/credentials/keystore.jwks` into `$IDP_HOME/credentials`
- Copy `idp-temp/idp/system/conf/oidc-protocol-*.xml` into `$IDP_HOME/system/conf`
- Copy `idp-temp/idp/system/flows/oidc` into `$IDP_HOME/system/flows`
- Copy `idp-temp/idp/system/views/oidc` into `$IDP_HOME/system/views`

### Copy JARs

Cross examine the `idp-temp/WEB-INF/lib` directory with your IdP and copy all JARs that are not present.

### Logging

The following packages may be used for log configuration:

```xml
<logger name="org.mitre" level="WARN" />
<logger name="org.hibernate" level="WARN" />

<logger name="org.springframework.web" level="WARN" />
<logger name="org.springframework.webflow" level="WARN" />
<logger name="org.springframework.security" level="WARN" />
<logger name="org.springframework.security.oauth2" level="WARN" />
<logger name="net.shibboleth.idp.oidc" level="WARN" />
```

## Overlay IdP Configuration

The project itself follows an overlay-module where the IdP is configured to embed all of its configuration
inside the final war artifact. In doing so, the following changes are then overlaid into the IdP context and
need to be accounted for during IdP upgrades.

* `login.vm` and `attribute-release.vm` are overlaid to account for CSRF changes
* `password-authn-config.xml` is overlaid to indicate JAAS is used for authN.
* `global-system.xml` registers the `oidc-protocol-system` file
* `webflow-config.xml` is overlaid to add the OIDC flow configuration.
* `mvc-beans.xml` is used in the overlay `conf` directory to override the default beans and config.
 - This is used to define a new view resolver based on Spring bean names and remaps the excluded exceptions from the view resolver.
* A custom JAR is dropped into the overlay's `WEB-INF/lib` that mocks authentication. This is configured via the `jaas.config` file.
* `oidc.properties` controls the OIDC module configuration. This is appended to the list of property files loaded by
the IdP via `idp.properties`.
* `web.xml` is modified to register the `.well-known` endpoint and also registers the spring security filters.

### Build [![Build Status](https://travis-ci.org/uchicago/shibboleth-oidc.svg?branch=master)](https://travis-ci.org/uchicago/shibboleth-oidc)
In order to run the overlay build, examine the `/conf/idp.properties` inside the `idp-webapp-overlay` module,
and adjust the values of hostname, entityId, passwords, etc. Then from the command prompt, execute:

#### Initial installs

```bash
./mvn[w] clean install -P new
```

This will wipe out any previous files inside `credentials` and `metadata` directories and start anew.

#### Subsequent installs

```bash
./mvn[w] clean install
```

### Run IdP

#### Prepare HTTPS

You will also need to set up a keystore under `/etc/jetty` and name it `thekeystore`. The keystore password and the
key password should both be `changeit`.

A sample keystore is provided under the `idp-webapp-overlay/etc/jetty` directory that is empty, and can be used to set up the environment.

#### Run Jetty

From the root directory, run the following command:

```bash
./mvn[w] clean package verify -Dhost=jetty
```

This will spin up an embedded Jetty server to load the IdP context. Remote debugging is available under port 5000 from your IDE.

If you want a somewhat faster build, run:

```bash
./mvn[w] clean package verify -Dhost=jetty --projects idp-oidc-impl,idp-webapp-overlay
```

Scripted as:

```bash
./runidp.[sh|cmd]
```

### Run Client Application

```bash
./runclient.[sh|cmd]
```

The client is automatically and by default pre=registered with IdP under `https://mmoayyed.unicon.net:9443/simple-web-app`.
It runs inside a Jetty instance that is configured to use port `9443` and the same keystore the IdP uses for simplicity.

## Dockerized IdP Configuration

The Shibboleth IdP along with a sample PHP application protected by the Shibboleth SP and a sample OpenID Connect enabled application are all put together inside docker containers, controlled mostly via the `docker-compose.yml` file.

The Shibboleth IdP that runs inside the docker container is itself an overlay of the `idp-webapp-overlay` project that only overrides what is needed for the docker build to run successfully.

### Build

```bash
git clone git@github.com:uchicago/shibboleth-oidc.git
```

Build the codebase via:

```bash
./mvn[w] clean package -P new
```

### Configure

- Copy and overwrite the generated `idp-metadata.xml` from the `idp-webapp-overlay` project over to then `idp-webapp-overlay-docker` project.
- Adjust the newly copied `idp-metadata.xml` file, changing entityId and endpoint references to `idptestbed`.
- Exchange the newly adjusted `idp-metadata.xml` file with the `sp`.
- Add `127.0.0.1 idptestbed` to your hosts file.

### Run

The run the container:

```bash
./rundocker.sh
```


text:
/**
 * ParticipatingStudent.js
 *
 * @description :: TODO: You might write a short summary of how this model works and what it represents here.
 * @docs        :: http://sailsjs.org/documentation/concepts/models-and-orm/models
 */

module.exports = {

  attributes: {
    login: {
      type: 'string',
      required: true,
      unique: true
    },
    firstName: {
      type: 'string',
      required: true
    },
    lastName: {
      type: 'string',
      required: true
    },
    studentId: {
      type: 'string',
      required: true
    }
  }
};

redpajama_set_name: RedPajamaGithub


text:
package com.xn.dao;

import java.util.List;

import com.xn.model.PageBean;
import com.xn.model.URLModel;

public interface URLDao {

	public int usefullCount();
	public int unusefullCount();

	public List<URLModel> getUseFullData(PageBean pageBean);

	public List<URLModel> getunUseFullData(PageBean pageBean);
}


text:
package primitives

import (
	"encoding/xml"
	"github.com/plandem/ooxml/ml"
)

//FontCharsetType is a type to encode charset of font
type FontCharsetType ml.PropertyInt

//MarshalXML marshal FontCharsetType
func (t *FontCharsetType) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
	return (*ml.PropertyInt)(t).MarshalXML(e, start)
}

//UnmarshalXML unmarshal FontCharsetType
func (t *FontCharsetType) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
	return (*ml.PropertyInt)(t).UnmarshalXML(d, start)
}


text:
import App from 'components/App';
import { Provider } from 'mobx-react';
import promiseFinally from 'promise.prototype.finally';
import React from 'react';
import ReactDOM from 'react-dom';
import registerServiceWorker from 'registerServiceWorker';
import { toolboxStore } from 'stores';

import './index.css';

promiseFinally.shim();

const stores = {
  toolboxStore
};

ReactDOM.render(
  <Provider {...stores}>
    <App />
  </Provider>,
  document.getElementById('root') as HTMLElement
);
registerServiceWorker();


text:
package :postgres_db do
  description 'Install Postgres'
  defaults postgres_version: '9.6'

  requires :postgres_apt
  requires :postgresql_server, postgres_version: opts[:postgres_version]
  requires :update_pg_hba, postgres_version: opts[:postgres_version]
  requires :update_postgresql_conf, postgres_version: opts[:postgres_version]
  requires :postgres_encoding_utf8
end

package :postgres_apt do
  apt_list    = '/etc/apt/sources.list.d/pgdg.list'
  apt_source  = "deb http://apt.postgresql.org/pub/repos/apt/ `lsb_release -c -s`-pgdg main\n"

  runner "echo \"#{apt_source}\" | sudo tee #{apt_list}" do
    pre :install, 'true && wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -'
    post :install, 'sudo apt-get update'
  end

  verify do
    file_contains apt_list, 'pgdg'
  end
end

package :postgresql_server do
  requires :postgres_apt

  apt "postgresql-#{opts[:postgres_version]} postgresql-contrib-#{opts[:postgres_version]}"

  verify do
    has_apt "postgresql-#{opts[:postgres_version]}"
    has_apt "postgresql-contrib-#{opts[:postgres_version]}"
  end
end

package :update_pg_hba do
  config_file_path = "/etc/postgresql/#{opts[:postgres_version]}/main/pg_hba.conf"
  config_template = File.join(File.dirname(__FILE__), 'configs', 'pg_hba.conf')

  file config_file_path, contents: File.read(config_template), sudo: true

  runner "chown postgres:postgres #{config_file_path}"
  runner "chmod 755 #{config_file_path}"
  runner 'service postgresql restart'

  verify do
    has_file config_file_path
    has_permission config_file_path, '755'
    belongs_to_user config_file_path, 'postgres'
    belongs_to_group config_file_path, 'postgres'
  end
end

package :postgres_encoding_utf8 do
  runner %{echo "
  update pg_database set datistemplate=false where datname='template1';
  drop database Template1;
  create database template1 with owner=postgres encoding='UTF-8' lc_collate='en_US.utf8' lc_ctype='en_US.utf8' template template0;
  update pg_database set datistemplate=true where datname='template1';" | sudo -u postgres psql}

  verify do
    @commands << "echo \"select datcollate from pg_database where datname='template1'\" | sudo -u postgres psql | grep en_US.utf8"
  end
end

package :update_postgresql_conf do
  runner "sed -i 's/max_connections = 100/max_connections = 300/g' /etc/postgresql/#{opts[:postgres_version]}/main/postgresql.conf"

  verify do
    file_contains "/etc/postgresql/#{opts[:postgres_version]}/main/postgresql.conf", 'max_connections = 300'
  end
end

# TODO: auto restart after reboot, https://github.com/grimen/sprinkle-stack/blob/master/packages/database/postgresql.rb


text:
<?php

$installer = $this;
/* @var $installer Mage_Core_Model_Resource_Setup */

$installer->startSetup();

$installer->run("

-- DROP TABLE IF EXISTS `{$this->getTable('dataflow_session')}`;
CREATE TABLE `{$this->getTable('dataflow_session')}` (
  `session_id` int(11) NOT NULL auto_increment,
  `user_id` int(11) NOT NULL,
  `created_date` datetime default NULL,
  `file` varchar(255) character set utf8 default NULL,
  `type` varchar(32) character set utf8 default NULL,
  `direction` varchar(32) character set utf8 default NULL,
  `comment` varchar(255) character set utf8 default NULL,
  PRIMARY KEY  (`session_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- DROP TABLE IF EXISTS `{$this->getTable('dataflow_import_data')}`;
CREATE TABLE `{$this->getTable('dataflow_import_data')}` (
  `import_id` int(11) NOT NULL auto_increment,
  `session_id` int(11) default NULL,
  `serial_number` int(11) NOT NULL default '0',
  `value` text character set utf8,
  `status` int(1) NOT NULL default '0',
  PRIMARY KEY  (`import_id`),
  KEY `FK_dataflow_import_data` (`session_id`),
  CONSTRAINT `FK_dataflow_import_data` FOREIGN KEY (`session_id`) REFERENCES `{$this->getTable('dataflow_session')}` (`session_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
");

$installer->endSetup();


text:
var $holderOfertyProdukty;
    var $holderOfertyDodatki;

    var $addTableLink = $('Dodaj produkt');
    var $addTableDodatekLink = $('Dodaj produkt');
    var $newTableLinkLi = $('').append($addTableLink);
    var $newTableDodatekLinkLi = $('').append($addTableDodatekLink);

$(document).ready(function()
{
    $holderOfertyProdukty = $('#oferty-produkty-container');
    $holderOfertyDodatki = $('#oferty-dodatki-container');

    $addTableLink.on('click',function(e) {
        e.preventDefault();
        $newTableLinkLi = $(this);
        $holderOfertyProdukty.data('index', $holderOfertyProdukty.find('tr.produkt').length);
        addTableForm($holderOfertyProdukty);
        $('.selectpicker').selectpicker();
    });

    $addTableDodatekLink.on('click',function(e) {
        e.preventDefault();
        $newTableDodatekLinkLi = $(this);
        $holderOfertyDodatki.data('index', $holderOfertyDodatki.find('tr.produkt').length);
        addTableDodatkiForm($holderOfertyDodatki);
        $('.selectpicker').selectpicker();
    });

    $holderOfertyProdukty.closest('table').after($addTableLink);
    $holderOfertyDodatki.closest('table').after($addTableDodatekLink);

    $holderOfertyProdukty.on('click','.produkt-del',function(e)
    {
        e.preventDefault();
        $holderProdukt = $(this).closest('tr.produkt');
        $holderProduktInfo = $holderProdukt.next('tr');
        $holderProduktInfo.remove();
        $holderProdukt.remove();
    });

    $holderOfertyDodatki.on('click','.produkt-del',function(e)
    {
        e.preventDefault();
        $holderProdukt = $(this).closest('tr.produkt');
//        $holderProduktInfo = $holderProdukt.next('tr');
//        $holderProduktInfo.remove();
        $holderProdukt.remove();
    });

    $holderOfertyProdukty.on('click','.cena-add',function(e)
    {
        e.preventDefault();
        $holderCeny = $(this).closest('tbody');
        var prototype = $holderCeny.data('prototype');
        $holderCeny.data('index',$holderCeny.find('tr.cena').length);
        var indeks = $holderCeny.data('index');
        var nowaCena = prototype.replace(/__cena_name__/g, indeks);
        $holderCeny.data('index', indeks + 1);
        $holderCeny.append(nowaCena);
    });

    $holderOfertyProdukty.on('click','.cena-del',function(e) {
        e.preventDefault();

        $formLi = $(this).closest('tr.cena');
        $formLi.remove();
    });

    function addTableForm($collectionHolder)
    {
        var prototype = $collectionHolder.data('prototype');
        var index = $collectionHolder.data('index');
        var newForm = prototype.replace(/__name__/g, index);
        $collectionHolder.data('index', index + 1);
        $collectionHolder.append(newForm);
    }

    function addTableDodatkiForm($collectionHolder)
    {
        var prototype = $collectionHolder.data('prototype');
        var index = $collectionHolder.data('index');
        var newForm = prototype.replace(/__name__/g, index);
        $collectionHolder.data('index', index + 1);
        $collectionHolder.append(newForm);
    }

    $('.sidebar-listek').click(function() {
        var sidebar = $(".left-toggle-sidebar");
        var pozycja = sidebar.css("left");
        sidebar.animate({left: parseInt(pozycja,10) == -512 ? "-1px" : "-512px"}, 1500, "easeInOutQuart" );
    });

    //    Confirm-Dialog
    $('#btn-anuluj').click(function(e){
        e.preventDefault();
        $('#dialog-delete-confirm')
            .dialog("open");
    });

    $('#dialog-delete-confirm').dialog({
        autoOpen: false,
        resizable: false,
        height: 300,
        width: 500,
        modal: true,
        buttons: {
            Ok: {
                text: 'Tak, anuluj zamówienie',
                class: 'btn btn-xs btn-danger',
                click: function() {
                    $('#form_anuluj').click();
                }
            },
            Cancel: {
                text: 'Tak, anuluj zamówienie',
                class: 'btn btn-xs btn-primary',
                click: function() {
                    $( this ).dialog( "close" );
                }
            }
        },
        show: {
            effect: "blind",
            duration: 500
        },
        hide: {
            effect: "blind",
            duration: 500
        },
        closeOnEscape: true
    });
});


text:
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace NuGetGallery
{
    public class CreateCuratedPackageRequest
    {
        [Required]
        [DisplayName("Package ID")]
        public string PackageId { get; set; }

        [DataType(DataType.MultilineText)]
        public string Notes { get; set; }
    }
}


text:
--------------------------------
--
-- @function [parent=#FadeOutTRTiles] turnOffTile
-- @param self
-- @param #vec2_table pos

--------------------------------
--
-- @function [parent=#FadeOutTRTiles] transformTile
-- @param self
-- @param #vec2_table pos
-- @param #float distance

--------------------------------
--
-- @function [parent=#FadeOutTRTiles] testFunc
-- @param self
-- @param #size_table pos
-- @param #float time
-- @return float#float ret (return value: float)

--------------------------------
--  creates the action with the grid size and the duration
-- @function [parent=#FadeOutTRTiles] create
-- @param self
-- @param #float duration
-- @param #size_table gridSize
-- @return FadeOutTRTiles#FadeOutTRTiles ret (return value: cc.FadeOutTRTiles)

--------------------------------
--
-- @function [parent=#FadeOutTRTiles] clone
-- @param self
-- @return FadeOutTRTiles#FadeOutTRTiles ret (return value: cc.FadeOutTRTiles)

--------------------------------
--
-- @function [parent=#FadeOutTRTiles] update
-- @param self
-- @param #float time

return nil


text:
<Record>
<Term>Erythromycin-sulfisoxazole</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<SemanticType>Organic Chemical</SemanticType>
<Synonym>Erythromycin ethylsuccinate and sulfisoxazole</Synonym>
<Synonym>Erythromycin-sulfisoxazole</Synonym>
<Synonym>Erythromycin estolate;sulfisoxazole acetyl</Synonym>
<Synonym>Ilosone Sulfa</Synonym>
<Synonym>Erythromycin ethylsuccinate;sulfisoxazole acetyl</Synonym>
<Synonym>Pediazole</Synonym>
<Synonym>Erythromycin ethylsuccinate and sulfisoxazole acetyl</Synonym>
<Synonym>Eryzole</Synonym>
<Source>FDA Registry</Source>
</Record>


text:
function show_test_data(test_data_values) {
    $('#data_list').html('');
    localStorage.setItem('test_data', test_data_values);
    for (i = 0; i < test_data_values.length; i++) {
        $('#data_list').append('<li>' + test_data_values[i] + '</li>');
    }
}

function get_test_data() {
    $('#online_status').removeClass('offline').removeClass('online').html('pending...');
    if(localStorage.test_data !== 'undefined') {
        test_data_values = localStorage.test_data;
    } else {
        test_data_values = [];
    }
    $.ajax({
        url : "/get_data",
        type: "GET",
        dataType: "json",
        data: {'test_data_values': test_data_values},
        success: function(data) {
            $('#online_status').removeClass('offline');
            $('#online_status').addClass('online');
            $('#online_status').html('online');
            show_test_data(data.test_data_values);
        },
        error: function () {
            $('#online_status').addClass('offline');
            $('#online_status').removeClass('online');
            $('#online_status').html('offline');
            show_test_data(test_data_values.split(','));
        }
    });
}

$(document).ready(function() {
    if(typeof(Storage) !== "undefined") {
        $('#clear_localstorage_button').on('click', function() {
            localStorage.removeItem('test_data');
            $('#data_list').html('');
            test_data_values = [];
        });
        $('#load_data_button').on('click', get_test_data);
        get_test_data();
    } else {
        alert('Sorry, your Browser does not support localStorage.');
    }
});


text:
#include "cef_dark_window.h"

#include "appshell/browser/resource.h"
#include <minmax.h>
#include <objidl.h>
#include <Uxtheme.h>
#include <Shlwapi.h>

#include "config.h"

// With VS2015 including the gdiplus.h header results in many C4458 warnings.
// Disable them.
#ifdef _MSC_VER
    #pragma warning(push)
    #pragma warning(disable:4458) // declaration of 'xxx' hides class member
#endif
#include <GdiPlus.h>
#ifdef _MSC_VER
    #pragma warning(pop)
#endif

//win HiDPI - Macro for loading button resources for scale factors start
#define BUTTON_RESOURCES(scale)\
    if (mSysCloseButton == NULL) {\
	mSysCloseButton = ResourceImage::FromResource(MAKEINTRESOURCE(IDB_CLOSE_BUTTON_ ## scale));\
    }\
    if (mSysMaximizeButton == NULL) {\
        mSysMaximizeButton = ResourceImage::FromResource(MAKEINTRESOURCE(IDB_MAX_BUTTON_ ## scale));\
    }\
    if (mSysMinimizeButton == NULL) {\
        mSysMinimizeButton = ResourceImage::FromResource(MAKEINTRESOURCE(IDB_MIN_BUTTON_ ## scale));\
    }\
    if (mSysRestoreButton == NULL) {\
        mSysRestoreButton = ResourceImage::FromResource(MAKEINTRESOURCE(IDB_RESTORE_BUTTON_ ## scale));\
    }\
    if (mHoverSysCloseButton == NULL) {\
        mHoverSysCloseButton = ResourceImage::FromResource(MAKEINTRESOURCE(IDB_CLOSE_HOVER_BUTTON_ ## scale));\
    }\
    if (mHoverSysRestoreButton == NULL) {\
        mHoverSysRestoreButton = ResourceImage::FromResource(MAKEINTRESOURCE(IDB_RESTORE_HOVER_BUTTON_ ## scale));\
    }\
    if (mHoverSysMinimizeButton == NULL) {\
        mHoverSysMinimizeButton = ResourceImage::FromResource(MAKEINTRESOURCE(IDB_MIN_HOVER_BUTTON_ ## scale));\
    }\
    if (mHoverSysMaximizeButton == NULL) {\
        mHoverSysMaximizeButton = ResourceImage::FromResource(MAKEINTRESOURCE(IDB_MAX_HOVER_BUTTON_ ## scale));\
    }\
    if (mPressedSysCloseButton == NULL) {\
        mPressedSysCloseButton = ResourceImage::FromResource(MAKEINTRESOURCE(IDB_CLOSE_PRESSED_BUTTON_ ## scale));\
    }\
    if (mPressedSysRestoreButton == NULL) {\
        mPressedSysRestoreButton = ResourceImage::FromResource(MAKEINTRESOURCE(IDB_RESTORE_PRESSED_BUTTON_ ## scale));\
    }\
    if (mPressedSysMinimizeButton == NULL) {\
        mPressedSysMinimizeButton = ResourceImage::FromResource(MAKEINTRESOURCE(IDB_MIN_PRESSED_BUTTON_ ## scale));\
    }\
    if (mPressedSysMaximizeButton == NULL) {\
        mPressedSysMaximizeButton = ResourceImage::FromResource(MAKEINTRESOURCE(IDB_MAX_PRESSED_BUTTON_ ## scale));\
    }
//Macro for loading button resources end

// Libraries
#pragma comment(lib, "gdiplus")
#pragma comment(lib, "UxTheme")

// Externals
extern HINSTANCE hInst;

// Module Globals (Not exported)
static ULONG_PTR gdiplusToken = NULL;

// Constants
static const int kMenuPadding = 4;
static const int kWindowFrameZoomFactorCY = 4;
static const int kSystemIconZoomFactorCY = 4;
static const int kSystemIconZoomFactorCX = 2;

// GDI+ Helpers
static void RECT2Rect(Gdiplus::Rect& dest, const RECT& src) {
    dest.X = src.left;
    dest.Y = src.top;
    dest.Width = ::RectWidth(src);
    dest.Height = ::RectHeight(src);
}

namespace ResourceImage
{
    // Loads an Image from an application's resource section
    //  and returns a GDI+ Image object or NULL on failure
    Gdiplus::Image* FromResource(LPCWSTR lpResourceName)
    {
        // We're only loading PNG images at the present time
        HRSRC hResource = ::FindResource(::hInst, lpResourceName, L"PNG");
        if (!hResource)
            return NULL;

        HGLOBAL hData = ::LoadResource(::hInst, hResource);
        if (!hData)
            return NULL;

        void* data = ::LockResource(hData);
        ULONG size = ::SizeofResource(::hInst, hResource);

        IStream* pStream = ::SHCreateMemStream((BYTE*)data, (UINT)size);

        if (!pStream)
            return NULL;

        Gdiplus::Image* image = Gdiplus::Image::FromStream(pStream);
        pStream->Release();
        return image;
    }

}

/*
 * cef_dark_window
 */
cef_dark_window::cef_dark_window() :
    mSysCloseButton(NULL),
    mSysRestoreButton(NULL),
    mSysMinimizeButton(NULL),
    mSysMaximizeButton(NULL),
    mHoverSysCloseButton(NULL),
    mHoverSysRestoreButton(NULL),
    mHoverSysMinimizeButton(NULL),
    mHoverSysMaximizeButton(NULL),
    mPressedSysCloseButton(NULL),
    mPressedSysRestoreButton(NULL),
    mPressedSysMinimizeButton(NULL),
    mPressedSysMaximizeButton(NULL),
    mWindowIcon(NULL),
    mBackgroundActiveBrush(NULL),
    mBackgroundInactiveBrush(NULL),
    mFrameOutlineActivePen(NULL),
    mFrameOutlineInactivePen(NULL),
    mCaptionFont(NULL),
    mMenuFont(NULL),
    mHighlightBrush(NULL),
    mHoverBrush(NULL),
    mIsActive(TRUE)
{
    ::ZeroMemory(&mNcMetrics, sizeof(mNcMetrics));
}

cef_dark_window::~cef_dark_window()
{
}

/*
 * DoFinalCleanup -- Called when the app is shutting down so we can shut down GDI+
 */
void cef_dark_window::DoFinalCleanup()
{
    if (gdiplusToken != NULL) {
        Gdiplus::GdiplusShutdown(gdiplusToken);
    }
}

void cef_dark_window::InitializeWindowForDarkUI()
{
    // Make sure that the window theme is set
    //  to no theme so we get the right metrics
    ::SetWindowTheme(mWnd, L"", L"");
}

/*
 * InitDrawingResources -- Loads Pens, Brushes and Images used for drawing
 */
void cef_dark_window::InitDrawingResources()
{
    // Fetch Non Client Metric Data
    //  NOTE: Windows XP chokes if the size include Windows Version 6 members so
    //          subtract off the size of the new data members
    mNcMetrics.cbSize = sizeof (mNcMetrics) - sizeof (mNcMetrics.iPaddedBorderWidth);
    ::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, &mNcMetrics, 0);

    // Startup GDI+
    if (gdiplusToken == NULL) {
        Gdiplus::GdiplusStartupInput gdiplusStartupInput;
        Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
    }
    LoadSysButtonImages();

    // Create Brushes and Pens
    if (mBackgroundActiveBrush == NULL) {
        mBackgroundActiveBrush = ::CreateSolidBrush(CEF_COLOR_BACKGROUND_ACTIVE);
    }
    if (mBackgroundInactiveBrush == NULL) {
        mBackgroundInactiveBrush = ::CreateSolidBrush(CEF_COLOR_BACKGROUND_INACTIVE);
    }
    if (mHighlightBrush == NULL) {
        mHighlightBrush = ::CreateSolidBrush(CEF_COLOR_MENU_HILITE_BACKGROUND);
    }
    if (mHoverBrush == NULL) {
        mHoverBrush = ::CreateSolidBrush(CEF_COLOR_MENU_HOVER_BACKGROUND);
    }
    if (mFrameOutlineActivePen == NULL) {
        mFrameOutlineActivePen = ::CreatePen(PS_SOLID, 1, CEF_COLOR_FRAME_OUTLINE_ACTIVE);
    }
    if (mFrameOutlineInactivePen == NULL) {
        mFrameOutlineInactivePen = ::CreatePen(PS_SOLID, 1, CEF_COLOR_FRAME_OUTLINE_INACTIVE);
    }
}

/*
 * InitMenuFont -- Creates a Font object for drawing menu items
 */
void cef_dark_window::InitMenuFont()
{
    if (mMenuFont == NULL) {
        mMenuFont = ::CreateFontIndirect(&mNcMetrics.lfMenuFont);
    }
}

/*
 * LoadSysButtonImages -- Loads the images used for system buttons (close, min, max, restore)
 */
void cef_dark_window::LoadSysButtonImages()
{
	UINT scaleFactor = GetDPIScalingX();

    if(scaleFactor>=250)
    {
        BUTTON_RESOURCES(2_5X)
    }
    else if(scaleFactor>=200)
    {
        BUTTON_RESOURCES(2X)
    }
    else if(scaleFactor>=150)
    {
        BUTTON_RESOURCES(1_5X)
    }
    else if(scaleFactor>=125)
    {
        BUTTON_RESOURCES(1_25X)
    }
    else
    {
        BUTTON_RESOURCES(1X)
    }
}

// WM_NCCREATE handler
BOOL cef_dark_window::HandleNcCreate()
{
    InitDrawingResources();
    InitializeWindowForDarkUI();
    return FALSE;
}

bool cef_dark_window::SubclassWindow(HWND hWnd)
{
    InitDrawingResources();
    if (cef_window::SubclassWindow(hWnd)) {
        InitializeWindowForDarkUI();
        return true;
    }
    return false;
}

// WM_NCCREATE handler
BOOL cef_dark_window::HandleNcDestroy()
{
    TrackNonClientMouseEvents(false);

    delete mSysCloseButton;
    delete mSysRestoreButton;
    delete mSysMinimizeButton;
    delete mSysMaximizeButton;

    delete mHoverSysCloseButton;
    delete mHoverSysRestoreButton;
    delete mHoverSysMinimizeButton;
    delete mHoverSysMaximizeButton;

    delete mPressedSysCloseButton;
    delete mPressedSysRestoreButton;
    delete mPressedSysMinimizeButton;
    delete mPressedSysMaximizeButton;

    ::DeleteObject(mBackgroundActiveBrush);
    ::DeleteObject(mBackgroundInactiveBrush);
    ::DeleteObject(mCaptionFont);
    ::DeleteObject(mMenuFont);
    ::DeleteObject(mHighlightBrush);
    ::DeleteObject(mHoverBrush);
    ::DeleteObject(mFrameOutlineActivePen);
    ::DeleteObject(mFrameOutlineInactivePen);

    return cef_window::HandleNcDestroy();
}

// WM_SETTINGCHANGE handler
BOOL cef_dark_window::HandleSettingChange(UINT uFlags, LPCWSTR lpszSection)
{
    switch (uFlags)
    {
    case SPI_SETICONTITLELOGFONT:
    case SPI_SETHIGHCONTRAST:
    case SPI_SETNONCLIENTMETRICS:
    case SPI_SETFONTSMOOTHING:
    case SPI_SETFONTSMOOTHINGTYPE:
    case SPI_SETFONTSMOOTHINGCONTRAST:
    case SPI_SETFONTSMOOTHINGORIENTATION:
        // Reset our state
        mNonClientData.Reset();

        // Reset Fonts -- they will be recreated when needed
        ::DeleteObject(mCaptionFont);
        mCaptionFont = NULL;

        ::DeleteObject(mMenuFont);
        mMenuFont = NULL;

        // Reload Non Client Metrics
        ::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, &mNcMetrics, 0);
        break;
    }
    return FALSE;
}

// Computes the Rect where the System Icon is drawn in window coordinates
void cef_dark_window::ComputeWindowIconRect(RECT& rect) const
{
    int top = ::GetSystemMetrics (SM_CYFRAME);
    int left = ::GetSystemMetrics (SM_CXFRAME);

    if (IsZoomed()) {
        top += ::kSystemIconZoomFactorCY;
        left += ::kSystemIconZoomFactorCX;
    }
    ::SetRectEmpty(&rect);
    rect.top =  top;
    rect.left = left;
    rect.bottom = rect.top + ::GetSystemMetrics(SM_CYSMICON);
    rect.right = rect.left + ::GetSystemMetrics(SM_CXSMICON);
}

// Computes the Rect where the window caption is drawn in window coordinates
void cef_dark_window::ComputeWindowCaptionRect(RECT& rect) const
{
    RECT wr;
    GetWindowRect(&wr);

    int top = mNcMetrics.iBorderWidth;

    if (IsZoomed()) {
        top = ::kWindowFrameZoomFactorCY;
    }

    rect.top = top;
    rect.bottom = rect.top + mNcMetrics.iCaptionHeight;

    RECT ir;
    ComputeWindowIconRect(ir);

    RECT mr;
    ComputeMinimizeButtonRect(mr);

    rect.left = ir.right + ::GetSystemMetrics (SM_CXFRAME);
    rect.right = mr.left - ::GetSystemMetrics (SM_CXFRAME);
}

// Computes the Rect where the minimize button is drawn in window coordinates
void cef_dark_window::ComputeMinimizeButtonRect(RECT& rect) const
{
    ComputeMaximizeButtonRect(rect);

    rect.left -= (mSysMinimizeButton->GetWidth() + 1);
    rect.right = rect.left + mSysMinimizeButton->GetWidth();
    rect.bottom = rect.top + mSysMinimizeButton->GetHeight();
}

// Computes the Rect where the maximize button is drawn in window coordinates
void cef_dark_window::ComputeMaximizeButtonRect(RECT& rect) const
{
    ComputeCloseButtonRect(rect);

    rect.left -= (mSysMaximizeButton->GetWidth() + 1);
    rect.right = rect.left + mSysMaximizeButton->GetWidth();
    rect.bottom = rect.top + mSysMaximizeButton->GetHeight();
}

// Computes the Rect where the close button is drawn in window coordinates
void cef_dark_window::ComputeCloseButtonRect(RECT& rect) const
{
    int top = mNcMetrics.iBorderWidth;
    int right = mNcMetrics.iBorderWidth;

    if (IsZoomed()) {
        top = ::GetSystemMetrics (SM_CYFRAME);
        right = ::GetSystemMetrics (SM_CXFRAME);
    }

    RECT wr;
    GetWindowRect(&wr);

    rect.left = ::RectWidth(wr) - right - mSysCloseButton->GetWidth();
    rect.top = top;
    rect.right = rect.left + mSysCloseButton->GetWidth();
    rect.bottom = rect.top + mSysCloseButton->GetHeight();
}

void cef_dark_window::ComputeRequiredMenuRect(RECT& rect) const
{
    HMENU menu = GetMenu();
    int items = ::GetMenuItemCount(menu);

    ::SetRectEmpty(&rect);

    for (int i = 0; i < items; i++) {
        RECT itemRect;
        ::SetRectEmpty(&itemRect);
        if (::GetMenuItemRect(mWnd, menu, (UINT)i, &itemRect)) {
            itemRect.bottom += ::kMenuPadding;
            AdjustMenuItemRect(itemRect);

            RECT dest;
            if (::UnionRect(&dest, &rect, &itemRect)) {
                ::CopyRect(&rect, &dest);
            }
        }
    }
}

// Computes the Rect where the menu bar is drawn in window coordinates
void cef_dark_window::ComputeMenuBarRect(RECT& rect) const
{
    RECT rectClient;
    RECT rectCaption;

    ComputeWindowCaptionRect(rectCaption);
    ComputeLogicalClientRect(rectClient);

    rect.top = rectCaption.bottom + 1;
    rect.bottom = rectClient.top - 1;

    rect.left = rectClient.left;
    rect.right = rectClient.right;
}

// Draw the background for the non-client area
void cef_dark_window::DoDrawFrame(HDC hdc)
{
    RECT rectWindow;
    GetWindowRect(&rectWindow);

    RECT rectFrame;
    ::SetRectEmpty(&rectFrame);

    rectFrame.bottom = ::RectHeight(rectWindow);
    rectFrame.right = ::RectWidth(rectWindow);

    // Paint the entire thing with the background brush
    ::FillRect(hdc, &rectFrame, (mIsActive) ? mBackgroundActiveBrush : mBackgroundInactiveBrush);

    HGDIOBJ oldPen = (mIsActive) ? ::SelectObject(hdc, mFrameOutlineActivePen) : ::SelectObject(hdc, mFrameOutlineInactivePen);
    HGDIOBJ oldbRush = ::SelectObject(hdc, ::GetStockObject(NULL_BRUSH));

    // Now draw a PX tuxedo border around the edge
    ::Rectangle(hdc, 0, 0, rectFrame.right, rectFrame.bottom);

    ::SelectObject(hdc, oldPen);
    ::SelectObject(hdc, oldbRush);
}

// Draw the System Icon
void cef_dark_window::DoDrawSystemMenuIcon(HDC hdc)
{
    if (mWindowIcon == 0) {
        // We haven't cached the icon yet so figure out
        //  which one we need.

        // First try to load the small icon
        mWindowIcon = (HICON)SendMessage(WM_GETICON, ICON_SMALL, 0);

        // Otherwise try to use the big icon
        if (!mWindowIcon)
            mWindowIcon = (HICON)SendMessage(WM_GETICON, ICON_BIG, 0);

        // If that doesn't work check the window class for an icon

        // Start with the small
        if (!mWindowIcon)
            mWindowIcon = reinterpret_cast<HICON>(GetClassLongPtr(GCLP_HICONSM));

        // Then try to load the big icon
        if (!mWindowIcon)
            mWindowIcon = reinterpret_cast<HICON>(GetClassLongPtr(GCLP_HICON));

        // Otherwise we need an icon, so just use the standard Windows default
        //  application Icon which may very between versions
        if (!mWindowIcon)
            mWindowIcon = ::LoadIcon(NULL, IDI_APPLICATION);
    }

    RECT rectIcon;
    ComputeWindowIconRect(rectIcon);
    ::DrawIconEx(hdc, rectIcon.left, rectIcon.top, mWindowIcon, ::RectWidth(rectIcon), ::RectHeight(rectIcon), 0, NULL, DI_NORMAL);
}

// Draw the Caption Bar
void cef_dark_window::DoDrawTitlebarText(HDC hdc)
{
    if (mCaptionFont == 0) {
        mCaptionFont = ::CreateFontIndirect(&mNcMetrics.lfCaptionFont);
    }

    RECT textRect;
    ComputeWindowCaptionRect(textRect);

    HGDIOBJ hPreviousFont = ::SelectObject(hdc, mCaptionFont);
    int oldBkMode = ::SetBkMode(hdc, TRANSPARENT);
    COLORREF oldRGB = ::SetTextColor(hdc, CEF_COLOR_NORMALTEXT);

    // Setup the rect to use to calculate the position
    RECT windowRect;
    GetWindowRect(&windowRect);
    ScreenToNonClient(&windowRect);

    // Get the title and the length
    int textLength = GetWindowTextLength() + 1;
    LPWSTR szCaption = new wchar_t [textLength + 1];
    ::ZeroMemory(szCaption, textLength + 1);
    int cchCaption = GetWindowText(szCaption, textLength);

    // Figure out how much space we need to draw ethe whole thing
    RECT rectTemp;
    ::SetRectEmpty(&rectTemp);
    ::DrawText(hdc, szCaption, ::wcslen(szCaption), &rectTemp, DT_SINGLELINE|DT_CALCRECT|DT_NOPREFIX);

    // Can it be centered within the window?
    if (((::RectWidth(windowRect) / 2) + (::RectWidth(rectTemp) / 2) + 1) < textRect.right) {
        windowRect.bottom = textRect.bottom;
        windowRect.top += textRect.top;
        ::DrawText(hdc, szCaption, cchCaption, &windowRect, DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX);
    } else {
        // Can't be centered so LEFT justify and add ellipsis when truncated
        ::DrawText(hdc, szCaption, cchCaption, &textRect, DT_LEFT|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX);
    }

    delete []szCaption;
    ::SetTextColor(hdc, oldRGB);
    ::SetBkMode(hdc, oldBkMode);
    ::SelectObject(hdc, hPreviousFont);
}

// Draw the System Icons (close/min/max/restore)
void cef_dark_window::DoDrawSystemIcons(HDC hdc)
{
    Gdiplus::Image* CloseButton = mSysCloseButton;
    Gdiplus::Image* RestoreButton = mSysRestoreButton;
    Gdiplus::Image* MinimizeButton = mSysMinimizeButton;
    Gdiplus::Image* MaximizeButton = mSysMaximizeButton;

    if (mNonClientData.mButtonOver) {
        // If the mouse is over or down on a button then
        //  we need to pick the correct image for that button's state
        switch (mNonClientData.mActiveButton)
        {
        case HTCLOSE:
            CloseButton = (mNonClientData.mButtonDown) ? mPressedSysCloseButton : mHoverSysCloseButton;
            break;

        case HTMAXBUTTON:
            RestoreButton = (mNonClientData.mButtonDown) ? mPressedSysRestoreButton : mHoverSysRestoreButton;
            MaximizeButton = (mNonClientData.mButtonDown) ? mPressedSysMaximizeButton : mHoverSysMaximizeButton;
            break;

        case HTMINBUTTON:
            MinimizeButton = (mNonClientData.mButtonDown) ? mPressedSysMinimizeButton : mHoverSysMinimizeButton;
            break ;
        }
    }

    RECT rcButton;
    Gdiplus::Rect rect;
    Gdiplus::Graphics grpx(hdc);

    ComputeCloseButtonRect(rcButton);
    ::RECT2Rect(rect, rcButton);

    grpx.DrawImage(CloseButton, rect);

    ComputeMaximizeButtonRect(rcButton);
    ::RECT2Rect(rect, rcButton);

    if (IsZoomed()) {
        grpx.DrawImage(RestoreButton, rect);
    } else {
        grpx.DrawImage(MaximizeButton, rect);
    }

    ComputeMinimizeButtonRect(rcButton);
    ::RECT2Rect(rect, rcButton);

    grpx.DrawImage(MinimizeButton, rect);
}

// Enforce that the menu has our background color otherwise it
//  uses the system default color for the menu bar which looks funny
void cef_dark_window::EnforceMenuBackground()
{
    MENUBARINFO mbi = {0};
    mbi.cbSize = sizeof(mbi);

    GetMenuBarInfo(OBJID_MENU, 0, &mbi);

    MENUINFO mi = {0};
    mi.cbSize = sizeof(mi);
    mi.fMask = MIM_BACKGROUND;

    ::GetMenuInfo(mbi.hMenu, &mi);

    if (mIsActive) {
        if (mi.hbrBack != mBackgroundActiveBrush) {
            mi.hbrBack = mBackgroundActiveBrush;
            ::SetMenuInfo(mbi.hMenu, &mi);
        }
    } else {
        if (mi.hbrBack != mBackgroundInactiveBrush) {
            mi.hbrBack = mBackgroundInactiveBrush;
            ::SetMenuInfo(mbi.hMenu, &mi);
        }
    }
}

// Setup the device context for drawing
void cef_dark_window::InitDeviceContext(HDC hdc)
{
    RECT rectClipClient;
    SetRectEmpty(&rectClipClient);
    ComputeLogicalClientRect(rectClipClient);

    // exclude the client area to reduce flicker
    ::ExcludeClipRect(hdc, rectClipClient.left, rectClipClient.top, rectClipClient.right, rectClipClient.bottom);
}

void cef_dark_window::AdjustMenuItemRect(RECT &itemRect) const
{
    if (CanUseAeroGlass() && IsZoomed()) {
        ScreenToClient(&itemRect);
    } else {
        ScreenToNonClient(&itemRect);
    }
}

// This Really just Draws the menu bar items since it assumes
//  that the background has already been drawn using DoDrawFrame
void cef_dark_window::DoDrawMenuBar(HDC hdc)
{
    HMENU menu = GetMenu();
    int items = ::GetMenuItemCount(menu);

    RECT menuBarRect;
    ComputeMenuBarRect(menuBarRect);

    for (int i = 0; i < items; i++) {
        // Determine the menu item state and ID
        MENUITEMINFO mmi = {0};
        mmi.cbSize = sizeof (mmi);
        mmi.fMask = MIIM_STATE|MIIM_ID;
        ::GetMenuItemInfo (menu, i, TRUE, &mmi);

        RECT itemRect;
        ::SetRectEmpty(&itemRect);

        if (::GetMenuItemRect(mWnd, menu, (UINT)i, &itemRect)) {
            AdjustMenuItemRect(itemRect);

            POINT ptTopLeftItem = {itemRect.left, itemRect.top};

            if (CanUseAeroGlass() && !::PtInRect(&menuBarRect, ptTopLeftItem)) {
                // Check to make sure it's actually in the
                //  the correct location (fixes aero drawing issue)
                int itemHeight = ::RectHeight(itemRect);
                itemRect.top = menuBarRect.top;
                itemRect.bottom = itemRect.top + itemHeight;
            }

            // Draw the menu item
            DRAWITEMSTRUCT dis = {0};
            dis.CtlType = ODT_MENU;
            dis.itemID = mmi.wID;
            dis.hwndItem = (HWND)menu;
            dis.itemAction = ODA_DRAWENTIRE;
            dis.hDC = hdc;
            ::CopyRect(&dis.rcItem, &itemRect);

            if (mmi.fState & MFS_HILITE) {
                dis.itemState |= ODS_SELECTED;
            }
            if (mmi.fState & MFS_GRAYED) {
                dis.itemState |= ODS_GRAYED;
            }

            dis.itemState |= ODS_NOACCEL;

            HandleDrawItem(&dis);
        }
    }
}

// Paints the entire non-client area.
//  Creates an in-memory DC to draw on to reduce flicker
void cef_dark_window::DoPaintNonClientArea(HDC hdc)
{
    EnforceMenuBackground();
    cef_buffered_dc dc(this, hdc);

    InitDeviceContext(dc);
    InitDeviceContext(dc.GetWindowDC());

    DoDrawFrame(dc);
    DoDrawSystemMenuIcon(dc);
    DoDrawTitlebarText(dc);
    DoDrawSystemIcons(dc);
    DoDrawMenuBar(dc);
}

// Special case for derived classes to implement
//  in order to repaint the client area when we've
//  turned off redraw and turn it back on.
void cef_dark_window::DoRepaintClientArea()
{
}

// Force Drawing the non-client area.
//  Normally WM_NCPAINT is used but there are times when you
//  need to force drawing the entire non-client area when
//  legacy windows message handlers start drawing non-client
//  artifacts over top of us
void cef_dark_window::UpdateNonClientArea()
{
    HDC hdc;
    if (CanUseAeroGlass()) {
        hdc = GetDC();
    } else {
        hdc = GetWindowDC();
    }

    DoPaintNonClientArea(hdc);
    ReleaseDC(hdc);
}

// WM_NCPAINT handler
BOOL cef_dark_window::HandleNcPaint(HRGN hUpdateRegion)
{
    HDC hdc = GetDCEx(hUpdateRegion, DCX_WINDOW|DCX_INTERSECTRGN|DCX_USESTYLE);
    DoPaintNonClientArea(hdc);
    ReleaseDC(hdc);

    return TRUE;
}

// WM_NCHITTEST handler
int cef_dark_window::HandleNcHitTest(LPPOINT ptHit)
{
    RECT rectWindow;
    GetWindowRect(&rectWindow);

    if (!::PtInRect(&rectWindow, *ptHit))
        return HTNOWHERE;

    RECT rectClient;
    GetClientRect(&rectClient);
    ClientToScreen(&rectClient);

    if (::PtInRect(&rectClient, *ptHit))
        return HTCLIENT;

    RECT rectCaption;
    ComputeWindowCaptionRect(rectCaption);
    NonClientToScreen(&rectCaption);

    if (::PtInRect(&rectCaption, *ptHit))
        return HTCAPTION;

    RECT rectCloseButton;
    ComputeCloseButtonRect(rectCloseButton);
    NonClientToScreen(&rectCloseButton);

    if (::PtInRect(&rectCloseButton, *ptHit))
        return HTCLOSE;

    RECT rectMaximizeButton;
    ComputeMaximizeButtonRect(rectMaximizeButton);
    NonClientToScreen(&rectMaximizeButton);

    if (::PtInRect(&rectMaximizeButton, *ptHit))
        return HTMAXBUTTON;

    RECT rectMinimizeButton;
    ComputeMinimizeButtonRect(rectMinimizeButton);
    NonClientToScreen(&rectMinimizeButton);

    if (::PtInRect(&rectMinimizeButton, *ptHit))
        return HTMINBUTTON;

    RECT rectSysIcon;
    ComputeWindowIconRect(rectSysIcon);
    NonClientToScreen(&rectSysIcon);

    if (::PtInRect(&rectSysIcon, *ptHit))
        return HTSYSMENU;

    if (!IsZoomed()) {

        // Left Border
        if (ptHit->x >= rectWindow.left && ptHit->x <= rectWindow.left + ::GetSystemMetrics (SM_CYFRAME))
        {
            // it's important that we know if the mouse is on a corner so that
            //    the right mouse cursor is displayed
            if (ptHit->y <= rectWindow.top + ::GetSystemMetrics (SM_CYFRAME))
                 return HTTOPLEFT;

            if (ptHit->y >= rectWindow.bottom - ::GetSystemMetrics (SM_CYFRAME))
                 return HTBOTTOMLEFT;

            return HTLEFT;
        }

        // Right Border
        if (ptHit->x <= rectWindow.right && ptHit->x >= rectWindow.right - ::GetSystemMetrics (SM_CYFRAME))
        {
            // it's important that we know if the mouse is on a corner so that
            //    the right mouse cursor is displayed
            if (ptHit->y <= rectWindow.top + ::GetSystemMetrics (SM_CYFRAME))
                return HTTOPRIGHT;

            if (ptHit->y >= rectWindow.bottom - ::GetSystemMetrics (SM_CYFRAME))
                return HTBOTTOMRIGHT;

            return HTRIGHT;
        }

        // Top and Bottom Borders
        if (ptHit->y <= rectWindow.top + ::GetSystemMetrics (SM_CYFRAME))
             return HTTOP;

        if (ptHit->y >= rectWindow.bottom - ::GetSystemMetrics (SM_CYFRAME))
             return HTBOTTOM;
    }

    // If it's not in the menu, it's in the caption
    RECT rectMenu;
    ComputeRequiredMenuRect(rectMenu);
    NonClientToScreen(&rectMenu);

    if (::PtInRect(&rectMenu, *ptHit))
        return HTMENU;

    return HTCAPTION;
}

// Like UpdateNonClientArea, but sets up a clipping region to just update the system buttons
void cef_dark_window::UpdateNonClientButtons ()
{
    // create a simple clipping region
    //  that only includes the system buttons (min/max/restore/close)
    HDC hdc;

    if (CanUseAeroGlass()) {
        hdc = GetDC();
    } else {
        hdc = GetWindowDC();
    }

    RECT rectCloseButton ;
    ComputeCloseButtonRect (rectCloseButton) ;

    RECT rectMaximizeButton ;
    ComputeMaximizeButtonRect (rectMaximizeButton) ;

    RECT rectMinimizeButton ;
    ComputeMinimizeButtonRect (rectMinimizeButton) ;

    RECT rectWindow ;
    ComputeLogicalWindowRect (rectWindow) ;
    ::ExcludeClipRect (hdc, rectWindow.left, rectWindow.top, rectWindow.right, rectWindow.bottom);

    RECT rectButtons;
    rectButtons.top = rectCloseButton.top;
    rectButtons.right = rectCloseButton.right;
    rectButtons.bottom = rectCloseButton.bottom;
    rectButtons.left = rectMinimizeButton.left;

    HRGN hrgnUpdate = ::CreateRectRgnIndirect(&rectButtons);

    if (::SelectClipRgn(hdc, hrgnUpdate) != NULLREGION) {
        DoPaintNonClientArea(hdc);
    }

    ::DeleteObject(hrgnUpdate);
    ReleaseDC(hdc);
}

// WM_MEASUREITEM handler
// Since we have owner drawn menus, we need to provide information about
//  the menus back to Windows so it can layout the menubar appropriately.
BOOL cef_dark_window::HandleMeasureItem(LPMEASUREITEMSTRUCT lpMIS)
{
    static wchar_t szMenuString[256] = L"";

    if (lpMIS->CtlType == ODT_MENU) {
        HDC dc      = GetWindowDC();
        HMENU menu  = GetMenu();
        int items   = ::GetMenuItemCount(menu);

        InitMenuFont();

        HGDIOBJ fontOld = ::SelectObject(dc, mMenuFont);

        ::GetMenuString(menu, lpMIS->itemID, szMenuString, _countof(szMenuString), MF_BYCOMMAND);

        RECT rectTemp;
        SetRectEmpty(&rectTemp);

        // Calc the size of this menu item
        ::DrawText(dc, szMenuString, ::wcslen(szMenuString), &rectTemp, DT_SINGLELINE|DT_CALCRECT);

        lpMIS->itemHeight = ::RectHeight(rectTemp);
        lpMIS->itemWidth = ::RectWidth(rectTemp);

        ::SelectObject(dc, fontOld);
        ReleaseDC(dc);
        return TRUE;
    }

    return FALSE;
}

// WM_DRAWITEM handler
// Handles drawing the menu bar items with a dark background
BOOL cef_dark_window::HandleDrawItem(LPDRAWITEMSTRUCT lpDIS)
{
    static wchar_t szMenuString[256] = L"";

    if (lpDIS->CtlType == ODT_MENU) {

        InitMenuFont();

        HGDIOBJ fontOld = ::SelectObject(lpDIS->hDC, mMenuFont);
        COLORREF rgbMenuText =  CEF_COLOR_NORMALTEXT;
        HMENU hMenu = (HMENU)lpDIS->hwndItem;

        ::GetMenuString(hMenu, lpDIS->itemID, szMenuString, _countof(szMenuString), MF_BYCOMMAND);

        RECT rectBG;
        // Add a little more room to the top fixes highlight issue
        ::CopyRect(&rectBG, &lpDIS->rcItem);
        rectBG.top -= 2;

        if (lpDIS->itemState & ODS_SELECTED || lpDIS->itemState & ODS_HOTLIGHT) {
            ::FillRect(lpDIS->hDC, &rectBG, mHoverBrush);
        } else {
            ::FillRect(lpDIS->hDC, &rectBG, (mIsActive) ? mBackgroundActiveBrush : mBackgroundInactiveBrush);
        }

        if (lpDIS->itemState & ODS_GRAYED) {
            rgbMenuText = CEF_COLOR_MENU_DISABLED_TEXT;
        }

        COLORREF oldRGB = ::SetTextColor(lpDIS->hDC, rgbMenuText);

        UINT format = DT_CENTER|DT_SINGLELINE;

        if (lpDIS->itemState & ODS_NOACCEL) {
            format  |= DT_HIDEPREFIX;
        }

        int oldBkMode   = ::SetBkMode(lpDIS->hDC, TRANSPARENT);

        ::DrawText(lpDIS->hDC, szMenuString, ::wcslen(szMenuString), &lpDIS->rcItem, format);

        ::SelectObject(lpDIS->hDC, fontOld);
        ::SetBkMode(lpDIS->hDC, oldBkMode);
        ::SetTextColor(lpDIS->hDC, oldRGB);

        return TRUE;
    }

    return FALSE;
}

/*
 * The mouse handlers below will track the state of
 *  the mouse and the system buttons so the drawing code
 *  can show the correct state and fire the correct command.
 *
 * NonClientData.mActiveButton  HitTest for the button the mouse is over/pushed
 * NonClientData.mButtonDown    Indicates whether the mouse button is down or not
 *                                  The button down state is only an indicator that the
 *                                  action performed by the mouse *could* result in
 *                                  execution of the SysCommand.
 * NonClientData.mButtonOver    Indicates whether the mouse is over mActiveButton
 *                                  Once the mouse button has been pressed -- mActiveButton
 *                                  will not update on mouse moves until the mouse button
 *                                  is released.  mButtonOver, however, will change during
 *                                  mouse moves to indicate that the mouse is indeed over
 *                                  the button that was pressed.
 *                              This prevents misfires when the button is pressed and
 *                                  held and moved to another button and released.
 */

// WM_NCMOUSELEAVE handler
void cef_dark_window::HandleNcMouseLeave()
{
    // When the mouse leaves the non-client area
    //  we just need to reset our button state and
    //  redraw the system buttons
    mNonClientData.Reset();
    UpdateNonClientButtons();
}

// WM_NCMOUSEMOVE handler
BOOL cef_dark_window::HandleNcMouseMove(UINT uHitTest)
{
    bool needUpdate = false;

    if (mNonClientData.mActiveButton != uHitTest)
    {
        needUpdate = true;
        if (mNonClientData.mButtonDown) {
            // If the mouse button was down, we just want
            //  to indicate that we're no longer over the system button
            mNonClientData.mButtonOver = false;
        } else {
            switch (uHitTest)
            {
            case HTCLOSE:
            case HTMAXBUTTON:
            case HTMINBUTTON:
                // Otherwise, we're just mousing over stuff
                //  so we need to show the visual feedback
                mNonClientData.mButtonOver = true;
                mNonClientData.mActiveButton = uHitTest;
                TrackNonClientMouseEvents();
                break;
            default:
                // User isn't hovering over anything that
                //  we care about so just reset and redraw
                mNonClientData.Reset();
                UpdateNonClientButtons();
                // let the DefaultWindowProc handle this
                return FALSE;
            }
        }
    } else {
        // Check to see if the user moved the mouse back over
        //  the button that they originally click and held and
        //  redraw the button in the correct state if they did
        if (mNonClientData.mButtonDown && !mNonClientData.mButtonOver) {
            mNonClientData.mButtonOver = true;
            needUpdate = true;
        }
    }

    if (needUpdate) {
        UpdateNonClientButtons();
    }
    return TRUE;
}

// WM_NCLBUTTONDOWN handler
BOOL cef_dark_window::HandleNcLeftButtonDown(UINT uHitTest)
{
    switch (uHitTest)
    {
    case HTCLOSE:
    case HTMAXBUTTON:
    case HTMINBUTTON:
        // we only care about these guys
        mNonClientData.mActiveButton = uHitTest;
        mNonClientData.mButtonOver = true;
        mNonClientData.mButtonDown = true;
        UpdateNonClientButtons();
        TrackNonClientMouseEvents();
        return TRUE;
    default:
        mNonClientData.Reset();
        UpdateNonClientButtons();
        return FALSE;
    }
}

// WM_NCLBUTTONUP handler
BOOL cef_dark_window::HandleNcLeftButtonUp(UINT uHitTest, LPPOINT point)
{
    NonClientButtonStateData oldData(mNonClientData);

    mNonClientData.Reset();

    UpdateNonClientButtons();

    switch (oldData.mActiveButton)
    {
    case HTCLOSE:
        if (oldData.mButtonOver) {
            SendMessage (WM_SYSCOMMAND, SC_CLOSE, (LPARAM)POINTTOPOINTS(*point));
            TrackNonClientMouseEvents(false);
        }
        return TRUE;
    case HTMAXBUTTON:
        if (oldData.mButtonOver) {
            if (IsZoomed())
                SendMessage (WM_SYSCOMMAND, SC_RESTORE, (LPARAM)POINTTOPOINTS(*point));
            else
                SendMessage (WM_SYSCOMMAND, SC_MAXIMIZE, (LPARAM)POINTTOPOINTS(*point));
            TrackNonClientMouseEvents(false);
        }
        return TRUE;
    case HTMINBUTTON:
        if (oldData.mButtonOver) {
            SendMessage (WM_SYSCOMMAND, SC_MINIMIZE, (LPARAM)POINTTOPOINTS(*point));
            TrackNonClientMouseEvents(false);
        }
        return TRUE;
    }

    return FALSE;
}

void cef_dark_window::DoPaintClientArea(HDC hdc)
{

}

// WindowProc handles dispatching of messages and routing back to the base class or to Windows
LRESULT cef_dark_window::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
    LRESULT lr = 0;

    switch (message)
    {
    case WM_SETTINGCHANGE:
        // NOTE: We want anyone else interested in this message
        //          to be notified of a setting change even if we handle
        //          the message.  Otherwise the default implementation
        //          may be in the wrong state
        HandleSettingChange((UINT)wParam, (LPCWSTR)lParam);
        break;
    case WM_NCMOUSELEAVE:
        // NOTE: We want anyone else interested in this message
        //          to be notified. Otherwise the default implementation
        //          may be in the wrong state
        HandleNcMouseLeave();
        break;
    case WM_NCMOUSEMOVE:
        if (HandleNcMouseMove((UINT)wParam))
            return 0L;
        break;

    case WM_NCLBUTTONDOWN:
        if (HandleNcLeftButtonDown((UINT)wParam))
            return 0L;
        break;
    case WM_NCLBUTTONUP:
        {
            POINT pt;
            POINTSTOPOINT(pt, lParam);
            if (HandleNcLeftButtonUp((UINT)wParam, &pt))
                return 0L;
        }
        break;
    case WM_NCCREATE:
        if (HandleNcCreate())
            return 0L;
        break;
    case WM_NCPAINT:
        if (HandleNcPaint((HRGN)wParam))
            return 0L;
        break;
    case WM_NCDESTROY:
        if (HandleNcDestroy())
            return 0L;
        break;
    case WM_NCHITTEST:
        {
            POINT pt;
            POINTSTOPOINT(pt, lParam);
            return HandleNcHitTest(&pt);
        }
        break;
    case WM_MEASUREITEM:
        if (HandleMeasureItem((LPMEASUREITEMSTRUCT)lParam))
            return TRUE;
        break;
    case WM_DRAWITEM:
        if (HandleDrawItem((LPDRAWITEMSTRUCT)lParam))
            return TRUE;
        break;
    case WM_SETICON:
        mWindowIcon = 0;
        break;
    case WM_SETTEXT:
    case WM_ACTIVATE:
    case WM_NCACTIVATE:
        // Turn off redraw because the
        //  DefaultWindowProc will paint over top of
        //  our frame and cause the title bar to flicker
        if (!IsIconic()){
            SetRedraw(FALSE);
        }
        break;
    }
    lr = cef_window::WindowProc(message, wParam, lParam);
    // post default message processing
    switch (message)
    {
    case WM_WINDOWPOSCHANGING:
    case WM_WINDOWPOSCHANGED:
    case WM_MOVE:
    case WM_SIZE:
    case WM_SIZING:
    case WM_EXITSIZEMOVE:
        UpdateNonClientArea();
        break;
    }

    // special case -- since we turned off redraw for these
    //  messages to reduce flicker, we need to turn redraw
    //  on now and force updating the non-client area
    switch (message)
    {
    case WM_SETTEXT:
    case WM_ACTIVATE:
    case WM_NCACTIVATE:
        if (!IsIconic()){
            SetRedraw(TRUE);
            UpdateNonClientArea();
            if (message != WM_SETTEXT) {
                DoRepaintClientArea();
            }
        }
        break;
    case WM_ACTIVATEAPP:
        mIsActive = (BOOL)wParam;
        UpdateNonClientArea();
        break;
    }
    return lr;
}


text:
package gcbatch.utils.json;

import gcbatch.TestBase;
import gcbatch.base.data.model.Entry;
import gcbatch.utils.JsonUtil;
import gcbatch.utils.MapUtil;
import gcbatch.utils.resource.model.Field;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class JsonSerializeTest extends TestBase {
    @Override
    public void execute() throws Throwable {
        String json1 = JsonUtil.toJson("12345", false);
        System.out.println(json1);
        assert json1.equals("\"12345\"");

        String json2 = JsonUtil.toJson(123, false);
        System.out.println(json2);
        assert json2.equals("123");

        String json3 = JsonUtil.toJson(null, false);
        System.out.println(json3);
        assert json3.equals("null");

        String json4 = JsonUtil.toJson(new Entry<>("234234", 12345), false);
        System.out.println(json4);
        assert json4.equals("{\"234234\":12345}");

        Date date = new Date();
        String json5 = JsonUtil.toJson(new Object [] {"234234", 12345, date}, false);
        System.out.println(json5);
        assert json5.equals("[\"234234\",12345," + date.getTime() + "]");

        List<Object[]> dataList = new ArrayList<>();
        dataList.add( new Object[] {"item1", 100,134,54444,1133});
        dataList.add( new Object[] {"item2", 244,544,1133,76});
        dataList.add( new Object[] {"item3", 314,5444,133,76});
        dataList.add( new Object[] {"item4", 124,5444,133,76});
        dataList.add( new Object[] {"item5", 324,5414,133,76});
        dataList.add( new Object[] {"item6", 324,4144,133,76});
        dataList.add( new Object[] {"item7", 324,5414,133,76});
        dataList.add( new Object[] {"item8", 324,541,133,76});
        dataList.add( new Object[] {"item9", 324,54,133,76});
        dataList.add( new Object[] {"item10", 324,544,133,76});
        dataList.add( new Object[] {"item11", 324,5444,133,76});
        dataList.add( new Object[] {"item23", 324,5414,133,76});
        dataList.add( new Object[] {"item134", 324,5414,133,76});

        List<Object[]> dataList2 = new ArrayList<>();
        dataList2.add( new Integer[] {32234,5444,1133,7676,4554,12312,76011,2343,344});
        dataList2.add( new Integer[] {3423,544,1133,7676,454,12312,7611,233,4});
        dataList2.add( new Integer[] {324,54444,133,76,654,12,7611,23,2343});

        System.out.println(JsonUtil.toJson(MapUtil.of("data1", dataList, "data2", dataList2), false));
        System.out.println(JsonUtil.toJson(MapUtil.of("data1", dataList, "data2", dataList2, "data3", dataList, "data4", dataList2), false));

        System.out.println(JsonUtil.jsonToBean(Field.class, "{\"padRule\": \"padLeft\"}").toJsonString());
        // TODO err System.out.println(JsonUtil.jsonToJSONObj("{\"padRule\": \"padLeft\"}").toJavaObject(Field.class).toJsonString());
        System.out.println(JsonUtil.jsonToBean(Field.class, JsonUtil.jsonToJSONObj("{\"padRule\": \"padLeft\"}").toJSONString()).toJsonString());
    }
}


text:
package com.amazonaws.services.cognitoidentity.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.cognitoidentity.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * DescribeIdentityPoolResult JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeIdentityPoolResultJsonUnmarshaller implements Unmarshaller<DescribeIdentityPoolResult, JsonUnmarshallerContext> {

    public DescribeIdentityPoolResult unmarshall(JsonUnmarshallerContext context) throws Exception {
        DescribeIdentityPoolResult describeIdentityPoolResult = new DescribeIdentityPoolResult();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return describeIdentityPoolResult;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("IdentityPoolId", targetDepth)) {
                    context.nextToken();
                    describeIdentityPoolResult.setIdentityPoolId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("IdentityPoolName", targetDepth)) {
                    context.nextToken();
                    describeIdentityPoolResult.setIdentityPoolName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("AllowUnauthenticatedIdentities", targetDepth)) {
                    context.nextToken();
                    describeIdentityPoolResult.setAllowUnauthenticatedIdentities(context.getUnmarshaller(Boolean.class).unmarshall(context));
                }
                if (context.testExpression("SupportedLoginProviders", targetDepth)) {
                    context.nextToken();
                    describeIdentityPoolResult.setSupportedLoginProviders(new MapUnmarshaller<String, String>(context.getUnmarshaller(String.class), context
                            .getUnmarshaller(String.class)).unmarshall(context));
                }
                if (context.testExpression("DeveloperProviderName", targetDepth)) {
                    context.nextToken();
                    describeIdentityPoolResult.setDeveloperProviderName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("OpenIdConnectProviderARNs", targetDepth)) {
                    context.nextToken();
                    describeIdentityPoolResult.setOpenIdConnectProviderARNs(new ListUnmarshaller<String>(context.getUnmarshaller(String.class))
                            .unmarshall(context));
                }
                if (context.testExpression("CognitoIdentityProviders", targetDepth)) {
                    context.nextToken();
                    describeIdentityPoolResult.setCognitoIdentityProviders(new ListUnmarshaller<CognitoIdentityProvider>(
                            CognitoIdentityProviderJsonUnmarshaller.getInstance()).unmarshall(context));
                }
                if (context.testExpression("SamlProviderARNs", targetDepth)) {
                    context.nextToken();
                    describeIdentityPoolResult.setSamlProviderARNs(new ListUnmarshaller<String>(context.getUnmarshaller(String.class)).unmarshall(context));
                }
                if (context.testExpression("IdentityPoolTags", targetDepth)) {
                    context.nextToken();
                    describeIdentityPoolResult.setIdentityPoolTags(new MapUnmarshaller<String, String>(context.getUnmarshaller(String.class), context
                            .getUnmarshaller(String.class)).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return describeIdentityPoolResult;
    }

    private static DescribeIdentityPoolResultJsonUnmarshaller instance;

    public static DescribeIdentityPoolResultJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new DescribeIdentityPoolResultJsonUnmarshaller();
        return instance;
    }
}


text:
from django.core.urlresolvers import reverse
from django.test import Client
from django.test import TestCase

from . import views

class TestTasks(TestCase):

    def setUp(self):
        self.client = Client()

    def test_task_index_is_ok(self):
        response = self.client.get(reverse(views.index))
        self.assertEqual(response.status_code, 200)

    def test_task_list_is_ok(self):
        # This URL's regex requires a single numeric argument
        response = self.client.get(reverse(views.detail, args=[0]))
        self.assertEqual(response.status_code, 200)


text:
set -e
set -v

while [[ $# -gt 0 ]]
do
key="$1"
case $key in
    --job_server_jar)
        JOB_SERVER_JAR="$2"
        shift # past argument
        shift # past value
        ;;
    --runner)
        RUNNER="$2"
        shift # past argument
        shift # past value
        ;;
    --env_dir)
        ENV_DIR="$2"
        shift # past argument
        shift # past value
        ;;
    --python_root_dir)
        PYTHON_ROOT_DIR="$2"
        shift # past argument
        shift # past value
        ;;
    --python_version)
        PYTHON_VERSION="$2"
        shift # past argument
        shift # past value
        ;;
    --python_container_image)
        PYTHON_CONTAINER_IMAGE="$2"
        shift # past argument
        shift # past value
        ;;
    *)    # unknown option
        echo "Unknown option: $1"
        exit 1
        ;;
esac
done

# Go to the root of the repository
cd $(git rev-parse --show-toplevel)

# Verify docker command exists
command -v docker
docker -v

# Verify container has already been built
echo "Checking for Docker image ${PYTHON_CONTAINER_IMAGE}"
docker images --format "{{.Repository}}:{{.Tag}}" | grep $PYTHON_CONTAINER_IMAGE

# Set up Python environment
python$PYTHON_VERSION -m venv $ENV_DIR
. $ENV_DIR/bin/activate
pip install --retries 10 -e $PYTHON_ROOT_DIR

PIPELINE_PY="
import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import SetupOptions
from apache_beam.testing.util import assert_that
from apache_beam.testing.util import equal_to
from apache_beam.transforms import Create
from apache_beam.transforms import Map

# To test that our main session is getting plumbed through artifact staging
# correctly, create a global variable. If the main session is not plumbed
# through properly, global_var will be undefined and the pipeline will fail.
global_var = 1

pipeline_options = PipelineOptions()
pipeline_options.view_as(SetupOptions).save_main_session = True
pipeline = beam.Pipeline(options=pipeline_options)
pcoll = (pipeline
         | Create([0, 1, 2])
         | Map(lambda x: x + global_var))
assert_that(pcoll, equal_to([1, 2, 3]))

result = pipeline.run()
result.wait_until_finish()
"

if [[ "$RUNNER" = "FlinkRunner" ]]; then
  INPUT_JAR_ARG="flink_job_server_jar"
else
  INPUT_JAR_ARG="spark_job_server_jar"
fi

# Create the jar
OUTPUT_JAR="test-pipeline-${RUNNER}-$(date +%Y%m%d-%H%M%S).jar"
(python -c "$PIPELINE_PY" \
  --runner "$RUNNER" \
  --"$INPUT_JAR_ARG" "$JOB_SERVER_JAR" \
  --output_executable_path $OUTPUT_JAR \
  --parallelism 1 \
  --sdk_worker_parallelism 1 \
  --environment_type DOCKER \
  --environment_options "docker_container_image=$PYTHON_CONTAINER_IMAGE" \
) || TEST_EXIT_CODE=$? # don't fail fast here; clean up before exiting

if [[ "$TEST_EXIT_CODE" -eq 0 ]]; then
  # Execute the jar
  java -jar $OUTPUT_JAR || TEST_EXIT_CODE=$?
fi

rm -rf $ENV_DIR
rm -f $OUTPUT_JAR

if [[ "$TEST_EXIT_CODE" -eq 0 ]]; then
  echo ">>> SUCCESS"
else
  echo ">>> FAILURE"
fi
exit $TEST_EXIT_CODE


text:
module.exports = function hello (msg) {
  console.log(msg);
};

if (require.main === module) {
  module.exports('Hello, world!');
}


text:
require 'sidekiq/web'

Catarse::Application.routes.draw do
  def ssl_options
    if Rails.env.production? && CatarseSettings[:secure_host]
      {protocol: 'https', host: CatarseSettings[:secure_host]}
    else
      {}
    end
  end

  mount JasmineRails::Engine => '/specs' if defined?(JasmineRails)
  devise_for(
    :users,
    {
      path: '',
      path_names:   { sign_in: :login, sign_out: :logout, sign_up: :sign_up },
      controllers:  { omniauth_callbacks: :omniauth_callbacks, passwords: :passwords },
      defaults: ssl_options
    }
  )

  devise_scope :user do
    post '/sign_up', {to: 'devise/registrations#create', as: :sign_up}.merge(ssl_options)
  end

  get '/thank_you' => "static#thank_you"

  check_user_admin = lambda { |request| request.env["warden"].authenticate? and request.env['warden'].user.admin }

  filter :locale, exclude: /\/auth\//

  # Mountable engines
  constraints check_user_admin do
    mount Sidekiq::Web => '/sidekiq'
  end

  mount CatarsePaypalExpress::Engine => "/", as: :catarse_paypal_express
  mount CatarseMoip::Engine => "/", as: :catarse_moip
#  mount CatarseWepay::Engine => "/", as: :catarse_wepay

  # Channels
  constraints subdomain: /^(?!www|secure|test|local)(\w+)/ do
    namespace :channels, path: '' do
      namespace :admin do
        namespace :reports do
          resources :subscriber_reports, only: [ :index ]
        end
        resources :posts
        resources :partners
        resources :followers, only: [ :index ]
        resources :projects, only: [ :index, :update] do
          member do
            put 'approve'
            put 'reject'
            put 'push_to_draft'
            put 'push_to_trash'
          end
        end
      end

      resources :posts
      get '/', to: 'profiles#show', as: :profile
      get '/how-it-works', to: 'profiles#how_it_works', as: :about
      resource :profile
      resources :projects, only: [:new, :create, :show] do
        collection do
          get 'video'
        end
      end
      # NOTE We use index instead of create to subscribe comming back from auth via GET
      resource :channels_subscriber, only: [:show, :destroy], as: :subscriber
    end
  end

  # Root path should be after channel constraints
  root to: 'projects#index'

  get "/explore" => "explore#index", as: :explore

  namespace :reports do
    resources :contribution_reports_for_project_owners, only: [:index]
  end

  resources :projects, only: [:index, :create, :update, :new, :show] do
    resources :updates, controller: 'projects/updates', only: [ :index, :create, :destroy ]
    resources :rewards, only: [ :index, :create, :update, :destroy, :new, :edit ] do
      member do
        post 'sort'
      end
    end
    resources :contributions, {controller: 'projects/contributions'}.merge(ssl_options) do
      member do
        put 'credits_checkout'
      end
    end
    collection do
      get 'video'
    end
    member do
      put 'pay'
      get 'embed'
      get 'video_embed'
      get 'embed_panel'
      get 'send_to_analysis'
    end
  end
  resources :users do
    resources :projects, controller: 'users/projects', only: [ :index ]
    member do
      get :unsubscribe_notifications
      get :credits
    end
    collection do
      get :uservoice_gadget
    end
    resources :contributions, controller: 'users/contributions', only: [:index] do
      member do
        get :request_refund
      end
    end

    resources :unsubscribes, only: [:create]
    member do
      get 'projects'
      put 'unsubscribe_update'
      put 'update_email'
      put 'update_password', ssl_options
    end
  end

  namespace :admin do
    resources :projects, only: [ :index, :update, :destroy ] do
      member do
        put 'approve'
        put 'reject'
        put 'push_to_draft'
        put 'push_to_trash'
      end
    end

    resources :statistics, only: [ :index ]
    resources :financials, only: [ :index ]

    resources :contributions, only: [ :index, :update, :show ] do
      member do
        put 'confirm'
        put 'pendent'
        put 'change_reward'
        put 'refund'
        put 'hide'
        put 'cancel'
        put 'push_to_trash'
      end
    end
    resources :users, only: [ :index ]

    namespace :reports do
      resources :contribution_reports, only: [ :index ]
    end
  end

  get "/terms-of-use" => 'high_voltage/pages#show', id: 'terms_of_use'
  get "/privacy-policy" => 'high_voltage/pages#show', id: 'privacy_policy'

  get "/:permalink" => "projects#show", as: :project_by_slug

end


text:
namespace
    #line 1 "_config.weave"
           Weave.Compiler
    #line default
{
    using System;
    using System.IO;
    using
        #line 2 "_config.weave"
       Weave.Expressions
        #line default
        ;

    partial class
    Templates
    {
        [System.CodeDom.Compiler.GeneratedCode("Weave", "1.2.1.0")]
        public
        void
        RenderEchoTag
            (
            #line 1 "EchoTag.weave"
       EchoTag
            #line default
            model, TextWriter writer, string indentation = null)
        {
            var __encode = new Func<object, string>(
                #line 4 "_config.weave"
        ToLiteral
                #line default
                );
            var __originalIndentation = indentation = indentation ?? string.Empty;
            if (
                #line 3 "EchoTag.weave"
     model.Encoded
                #line default
                )
            {
                writer.Write(indentation);
                writer.Write("writer.Write(__encode(");
                writer.WriteLine();
                indentation = __originalIndentation + "    ";
                var __model0 =
                    #line 5 "EchoTag.weave"
                      model.Expression
                    #line default
                    ;
                RenderCode(__model0, writer, indentation);
                writer.Write(indentation);
                writer.Write("));");
                writer.WriteLine();
            }
            else
            {
                writer.Write(indentation);
                writer.Write("writer.Write(");
                writer.WriteLine();
                indentation = __originalIndentation + "    ";
                var __model1 =
                    #line 9 "EchoTag.weave"
                      model.Expression
                    #line default
                    ;
                RenderCode(__model1, writer, indentation);
                writer.Write(indentation);
                writer.Write(");");
                writer.WriteLine();
            }
        }
    }
}


text:
package org.jtb.icongen;

import android.app.IntentService;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.util.DisplayMetrics;

import java.io.File;
import java.io.FileOutputStream;

public class IconGenService extends IntentService {
  private enum Size {
    MDPI(24, 24, "drawable-mdpi", DisplayMetrics.DENSITY_MEDIUM / DisplayMetrics.DENSITY_DEFAULT),
    HDPI(36, 36, "drawable-hdpi", DisplayMetrics.DENSITY_HIGH / DisplayMetrics.DENSITY_DEFAULT),
    XHDPI(48, 48, "drawable-xhdpi", DisplayMetrics.DENSITY_XHIGH / DisplayMetrics.DENSITY_DEFAULT),
    XXHDPI(72, 72, "drawable-xxhdpi", DisplayMetrics.DENSITY_XXHIGH / DisplayMetrics.DENSITY_DEFAULT);

    private final int w;
    private final int h;
    private final String folder;
    private final float scale;

    private Size(int w, int h, String folder, float scale) {
      this.w = w;
      this.h = h;
      this.folder = folder;
      this.scale = scale;
    }
  }

  private final Paint textPaint;

  public IconGenService() {
    super(IconGenService.class.getName());

    textPaint = new Paint();
    textPaint.setColor(Color.WHITE);
    textPaint.setAntiAlias(true);
    textPaint.setStyle(Paint.Style.FILL_AND_STROKE);
    textPaint.setTextAlign(Paint.Align.CENTER);
    textPaint.setTypeface(Typeface.create("sans-serif-condensed", Typeface.NORMAL));
    textPaint.setFakeBoldText(true);

  }

  @Override
  protected void onHandleIntent(Intent intent) {
    for (Size size : Size.values()) {
      for (int i = -99; i < 100; i++) {
        String resName;
        if (i < 0) {
          resName = String.format("ic_stat_minus_%d.png", i * -1);
        } else {
          resName = String.format("ic_stat_%d.png", i);
        }
        write(String.format("%d\u00B0", i), resName, size);
      }
    }

    for (Size size : Size.values()) {
      write("?\u00B0", "undefined.png", size);
    }
  }

  private void write(String text, String resName, Size size) {
    Bitmap b = Bitmap.createBitmap(size.w, size.h, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);

    textPaint.setTextSize(14 * size.scale);

    Rect bounds = new Rect();
    textPaint.getTextBounds(text, 0, text.length(), bounds);

    float x = c.getWidth() / 2f;
    float y = (c.getHeight() + bounds.height()) / 2f;

    c.drawText(text, x, y, textPaint);

    try {
      File dir = new File("/sdcard/res/" + size.folder);
      dir.mkdirs();

      FileOutputStream out = new FileOutputStream(new File(dir, resName));
      b.compress(Bitmap.CompressFormat.PNG, 90, out);
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}


text:
package com.github.werpu.scalaelresolver.scalaelresolvertest;

import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
import java.io.Serializable;

@Named
@RequestScoped
public class Bean4 implements Serializable {
    private String test4 = "hello world from bean4";

    public String getTest4() {
        return test4;
    }

    public void setTest4(String test4) {
        this.test4 = test4;
    }
}


text:
function processColor(){
// TODO(lmr): seems like a good example of something we should pull directly from RN.
return 0;
}

module.exports=processColor;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace FirstProject.Exceptions
{
    /// <summary>
    /// Custom exception when age less than 0 has been encountered
    /// </summary>
    /// <remarks>
    /// For example purposes - in real application exception for such situation may not be the best solution
    /// </remarks>
    [Serializable]
    public class InvalidAgeException : Exception, ISerializable
    {
        public int Age { get; set; }

        public InvalidAgeException()
        {

        }

        public InvalidAgeException(string message) : base(message)
        {

        }

        public InvalidAgeException(string message, Exception innerException) : base(message, innerException)
        {

        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        /// <remarks>This constructor is used for deserialization when no custom properties used.
        /// Commenting out this constructor will throw an exception during deserialization attempt.
        /// Handling required in case of custom properties used.
        /// </remarks>
        protected InvalidAgeException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            if (info != null)
                Age = info.GetInt32("Age");
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        /// <remarks>Required for correct custom property serialization</remarks>
        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            base.GetObjectData(info, context);

            if (info != null)
                info.AddValue("Age", Age);
        }

    }
}


text:
import React, { PureComponent } from 'react'
import { connect } from 'react-redux'

import Button from 'material-ui/Button'
import Dialog, {
  DialogActions,
  DialogContent,
  DialogTitle
} from 'material-ui/Dialog'
import TextField from 'material-ui/TextField'

import onSubmit from './onSubmit'

export default connect(mapStateToProps)(class extends PureComponent {
  constructor () {
    super()
    this.state = {
      name: ''
    }
  }

  componentWillReceiveProps (nextProps) {
    const {
      createOpen
    } = this.props

    if (!createOpen && nextProps.createOpen) {
      this.setState({ name: '' })
    }
  }

  render () {
    const {
      createOpen,
      toggle,
      dispatch,
      tournament
    } = this.props

    const {
      name
    } = this.state

    return (
      <Dialog
        open={createOpen}
        onClose={toggle}
        fullWidth
      >
        <DialogTitle>
          {'Create break category'}
        </DialogTitle>
        <DialogContent>
          <TextField
            label={'Category name'}
            fullWidth
            value={name}
            onChange={(e) => this.setState({ name: e.target.value })}
            margin={'normal'}
          />
        </DialogContent>
        <DialogActions>
          <Button
            onClick={toggle}
            color={'secondary'}
          >
            {'CANCEL'}
          </Button>
          <Button
            onClick={() => onSubmit(
              dispatch,
              tournament,
              name,
              toggle
            )}
            color={'primary'}
          >
            {'SUBMIT'}
          </Button>
        </DialogActions>
      </Dialog>
    )
  }
})

function mapStateToProps (state, ownProps) {
  return {
    tournament: state.tournaments.current.data
  }
}


text:
Describe "Parallel foreach syntax" -Tags "CI" {

   Context 'Should be able to retrieve AST of parallel foreach, error in regular case' {
        $errors = @()
        $ast = [System.Management.Automation.Language.Parser]::ParseInput(
            'foreach -parallel ($foo in $bar) {}', [ref] $null, [ref] $errors)
        It '$errors.Count' { $errors.Count | Should -Be 1 }
        It '$ast.EndBlock.Statements[0].Flags' { $ast.EndBlock.Statements[0].Flags | Should -BeExactly 'Parallel' }
    }

    It 'Should be able to retrieve AST of parallel foreach, works in JobDefinition case' -Skip:$IsCoreCLR {
        . .\TestsOnWinFullOnly.ps1
        Run-TestOnWinFull "ForeachParallel:ASTOfParallelForeachOnWorkflow"
    }

    Context 'Supports newlines before and after' {
        $errors = @()
        $ast = [System.Management.Automation.Language.Parser]::ParseInput(
            "foreach `n-parallel `n(`$foo in `$bar) {}", [ref] $null, [ref] $null)
        It '$errors.Count' { $errors.Count | Should -Be 0 }
        It '$ast.EndBlock.Statements[0].Flags' { $ast.EndBlock.Statements[0].Flags | Should -BeExactly 'Parallel' }
    }

    Context 'Generates an error on invalid parameter' {
        $errors = @()
        $ast = [System.Management.Automation.Language.Parser]::ParseInput(
            'foreach -bogus ($input in $bar) { }', [ref]$null, [ref]$errors)
        It '$errors.Count' { $errors.Count | Should -Be 1 }
        It '$errors[0].ErrorId' { $errors[0].ErrorId | Should -BeExactly 'InvalidForeachFlag' }
    }

    Context 'Generate an error on -parallel that is not a workflow' {
        $errors = @()
        $ast = [System.Management.Automation.Language.Parser]::ParseInput(
            'foreach -parallel ($input in $bar) { }', [ref]$null, [ref]$errors)
        It '$errors.Count' { $errors.Count | Should -Be 1 }
        It '$errors[0].ErrorId' { $errors[0].ErrorId | Should -BeExactly 'ParallelNotSupported' }
    }
}


text:
PROJECT = cn
JS_OUTPUT = cargo-not-min.js
CSS_OUTPUT = cargo-not-min.css
JS_MAP_OUTPUT = cargo-not-map.js
INDEX_OUTPUT = index.html

# Closure Library variables.
LIB_URL = https://github.com/google/closure-library.git
LIB_PATH = closure/library

# Closure Compiler variables.
CC_URL = http://dl.google.com/closure-compiler/compiler-latest.zip
CC_PATH = closure/compiler
CC_JAR = $(CC_PATH)/compiler.jar

# Closure closurebuilder.py arguments.
CC = python $(LIB_PATH)/closure/bin/build/closurebuilder.py \
		--root $(LIB_PATH) \
		--root $(PROJECT)/ \
		--namespace "$(PROJECT)" \
		--compiler_jar $(CC_JAR) \
		--compiler_flags "--jscomp_error=const" \
		--compiler_flags "--jscomp_error=visibility" \
		--compiler_flags "--warning_level=VERBOSE" \
		--compiler_flags "--js=$(JS_MAP_OUTPUT)" \
		--compiler_flags "--js=$(LIB_PATH)/closure/goog/deps.js"

# Closure Stylesheets variables.
CSS_URL = https://closure-stylesheets.googlecode.com/files/closure-stylesheets-20111230.jar
CSS_JAR = closure/closure-stylesheets.jar

# Closure Stylesheets arguments.
CSS = java -jar $(CSS_JAR) `find gss -name *.gss` \
		--output-file $(CSS_OUTPUT)

debug: css-debug
	py/index.py $(CSS_OUTPUT) $(JS_MAP_OUTPUT) `$(CC) --output_mode list` > \
		$(INDEX_OUTPUT)

release: css-release
	$(CC) \
		--compiler_flags "--compilation_level=ADVANCED_OPTIMIZATIONS" \
		--output_mode compiled > $(JS_OUTPUT)
	py/index.py $(CSS_OUTPUT) $(JS_OUTPUT) > $(INDEX_OUTPUT)

css-release:
	$(CSS) \
		--rename DEBUG \
		--output-renaming-map-format CLOSURE_COMPILED \
		--output-renaming-map $(JS_MAP_OUTPUT) \

css-debug:
	$(CSS) \
		--pretty-print \
		--rename DEBUG \
		--output-renaming-map-format CLOSURE_UNCOMPILED \
		--output-renaming-map $(JS_MAP_OUTPUT) \

dry-run: css-release
	$(CC) --output_mode compiled > /dev/null

lint:
	gjslint --strict --unix_mode -r $(PROJECT)

clean:
	rm -f $(JS_OUTPUT) $(CSS_OUTPUT) $(JS_MAP_OUTPUT) $(INDEX_OUTPUT)

server:
	python -m SimpleHTTPServer

closure: closure-library closure-compiler closure-stylesheets

closure-library:
	@test -d $(LIB_PATH)/.git || rm -rf $(LIB_PATH) # Delete any non-git version.
	@test -d $(LIB_PATH) || git clone $(LIB_URL) $(LIB_PATH)
	@cd $(LIB_PATH) && git pull

closure-compiler:
	wget $(CC_URL) -O /tmp/cc.zip
	unzip -o /tmp/cc.zip -d $(CC_PATH)

closure-stylesheets:
	wget $(CSS_URL) -O $(CSS_JAR)