text:
/**
 * Talisman metrics/prefix
 * ========================
 *
 * Function computing the Prefix distance/similarity. This is basically the
 * ratio of the length of the common prefix to the length of the shortest
 * sequence.
 *
 * [Tags]: metric, string metric.
 */

/**
 * Prefix similarity.
 *
 * @param  {array|string} a - First sequence.
 * @param  {array|string} b - Second sequence.
 * @param  {number}         - Similarity between 0 & 1.
 */
export function similarity(a, b) {
  if (a === b)
    return 1;

  if (!a.length || !b.length)
    return 0;

  if (a.length > b.length)
    [a, b] = [b, a];

  let i = 0;

  const l = a.length;

  for (; i < l; i++) {
    if (a[i] !== b[i])
      break;
  }

  return i / l;
}

/**
 * Prefix distance.
 *
 * @param  {array|string} a - First sequence.
 * @param  {array|string} b - Second sequence.
 * @param  {number}         - Distance between 0 & 1.
 */
export function distance(a, b) {
  return 1 - similarity(a, b);
}


text:
TEST_DIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))

LOAD_FILES = core/core-load-paths.el
UNIT_TEST_FILES = \
  core-configuration-layer-utest.el \
  core-funcs-utest.el
FUNC_TEST_FILES = \
  core-spacemacs-ftest.el \
  core-spacemacs-buffer-ftest.el \
  core-configuration-layer-ftest.el \
  core-release-management-ftest.el

include ../../spacemacs.mk

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE topic
  PUBLIC "-//OASIS//DTD DITA Topic//EN" "topic.dtd">
<topic id="front-cover" outputclass="front-cover">
   <title>A Midsummer Night's Dream</title>

         A MIDSUMMER NIGHT'S DREAM

SCENE  Athens, and a wood near it.

      <fig frame="all" outputclass="cover-picture">

            <image href="images/cover-graphic.jpg" placement="break" align="center" width="200">
               <alt>Cover Graphic</alt>
            </image>

      </fig>

By agreement with Jon Bosak (2009), this edition is
      published under the <xref href="http://creativecommons.org/licenses/by-nc-sa/3.0/us/" format="html"
                  scope="external">Creative Commons Attribution-Noncommercial-Share Alike</xref> license. Jon's original
      license and attributions also apply (see below).

            <xref href="http://creativecommons.org/licenses/by-nc-sa/3.0/us/" format="html"
                  scope="external">
               <image href="images/cc-logo-88x31.png">
                  <alt>Creative Commons License</alt>
               </image>
            </xref>

ASCII text placed in the public domain by Moby Lexical Tools, 1992.

SGML markup by Jon Bosak, 1992-1994.

XML version by Jon Bosak, 1996-1999.

The XML markup in this version is Copyright © 1999 Jon Bosak.
This work may freely be distributed on condition that it not be
modified or altered in any way.

</topic>


text:
from __future__ import print_function
import argparse
import sys
import metadata
import io_file
import scanner
import charts

def parse_input(argv):

    arg_parser = argparse.ArgumentParser(
        prog=argv[0],
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description=metadata.description)

    arg_parser.add_argument(
        '-V', '--version',
        action='version',
        version='{0} {1}'.format(metadata.project, metadata.version))

    arg_parser.add_argument('PROJECTPATH',
                            help='Path of the project to be scanned')

    args = arg_parser.parse_args()

    project_path = args.PROJECTPATH
    return project_path

def main(argv):
    path = parse_input(argv)
    file_list = io_file.scan_path(path)
    total_files = len(file_list)
    print('{0} java files'.format(total_files))
    occurrencies = scanner.scan_annotation(file_list)
    print('{0} java files containing annotation'.format(occurrencies))
    charts.generate_chart(total_files, occurrencies)

if __name__ == '__main__':
    main(sys.argv)


text:
html5-gamedev-haxe-externs
==========================

Haxe externovi za Miroslavljev HTML5 endžin


text:
{% extends "layout.html" %}
{% block content %}

User search for: "{{ query }}"

{% if users|length > 0 %}

      User

    {% for user in users %}

        {{ user.username }}

        Follow

    {% endfor %}

{% include "_flash_success.html" %}

{% else %}

No results found...

{% endif %}
{% endblock %}


text:
import Ember from 'ember';

const { Controller } = Ember;

export default Controller.extend({
  actions: {
    updateContactInfo() {
      this.set('isLoading', true);
      let currentUser = this.get('model');
      currentUser.save()
        .then(() => {
          this.get('notify').success(this.l10n.t('Your Contact Info has been updated'));
        })
        .catch(() => {
          this.get('notify').error(this.l10n.t('An unexpected error occurred'));
        })
        .finally(() => {
          this.set('isLoading', false);
        });
    }
  }
});


text:
package me.mervin.core;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import me.mervin.core.Global.AttributeType;

import me.mervin.util.D;

 /**
 *   Attribute.java
 *
 *  @author Mervin.Wong  DateTime 2013-10-14 下午9:42:45
 *  @version 0.4.0
 *  *********************************************************
 *  ChangeLog:
 *  == 2013/10/19
 * + method: public boolean containsKey(String key)
 * + method: public boolean containsValue(String value)
 */
public class Attribute {

	/*
	 * 属性内容
	 */
	private Map<String, String> attrValueMap = null;
	/*
	 * 对应key值的value类型
	 */
	private Map<String, AttributeType> attrTypeMap = null;

	/*
	 * 构造函数
	 */
	public Attribute(){
		if(this.attrValueMap == null){
			this.attrValueMap = new HashMap<String, String>();
			this.attrTypeMap = new HashMap<String, AttributeType>();
		}
	}

	public Attribute(String k, String v, AttributeType type){
		if(this.attrValueMap == null){
			this.attrValueMap = new HashMap<String, String>();
			this.attrTypeMap = new HashMap<String, AttributeType>();
		}

		this.attrValueMap.put(k, v);
		this.attrTypeMap.put(k, type);
	}

	public void set(String k, String v){
		this.attrValueMap.put(k, v);
		this.attrTypeMap.put(k, AttributeType.STRING);
	}
	public void set(String k, String v, AttributeType type){
		this.attrValueMap.put(k, v);
		this.attrTypeMap.put(k, type);
	}
	public void set(Map<String, String> attrs){
		this.attrValueMap.putAll(attrs);
	}

	public String get(String key){
		return this.attrValueMap.get(key);

	}

	public boolean containsKey(String key){
		if(this.attrValueMap != null){
			return this.attrValueMap.containsKey(key);
		}else{
			return false;
		}
	}

	public boolean containsValue(String value){
		return this.attrValueMap.containsValue(value);
	}
}


text:
package com.tc.websocket.valueobjects;

// TODO: Auto-generated Javadoc
/**
 * The Interface IPrompt.
 */
public interface IPrompt {

	/** The Constant EXCEPTION. */
	public static final String EXCEPTION="EXCEPTION";

	/**
	 * Gets the message.
	 *
	 * @return the message
	 */
	public abstract String getMessage();

	/**
	 * Gets the title.
	 *
	 * @return the title
	 */
	public abstract String getTitle();

	/**
	 * Sets the message.
	 *
	 * @param title the title
	 * @param message the message
	 */
	public abstract void setMessage(String title, String message);

}


text:
|Where is your change?|You changed|To test your changes|
|---|---|---|
|`./roles`| Playbook content |[Build and push a new mig-operator image](#building-and-pushing-the-mig-operator-container-image) |
|`./deploy/non-olm`| OpenShift 3 manifests | [Apply updated manifests directly](#using-a-new-mig-operator-container-image) |
|`./deploy/olm-catalog`| OpenShift 4 metadata | [Build and push a new OperatorHub metadata, update OperatorSource](#pushing-operator-metadata-openshift-4x)|

**Note**: if you build a new mig-operator image, you must reference it in `./deploy/non-olm/[...]` and `./deploy/olm-catalog/[...]`.

## Building and pushing the mig-operator container image

1. Pull the latest `operator-sdk` base image before building.

```
docker pull quay.io/operator-framework/ansible-operator:latest
```

2. Set quay org and tag

```
export ORG=your-quay-org
export TAG=latest
```

2. Run the build from the root of the mig-operator repo:

```
docker build -f build/Dockerfile -t quay.io/$ORG/mig-operator-container:$TAG .
docker push quay.io/$ORG/mig-operator-container:$TAG
```

### Using a new mig-operator container image

#### OpenShift 3

1. Update the deploy manifest in `./deploy/non-olm`

   ```
   # from ./deploy/non-olm/latest/operator.yml
   [...]
      containers:
      - name: operator
        image: quay.io/$ORG/mig-operator-container:$TAG
   ```

2. Apply the updated manifest to your cluster
   ```
   oc apply -f ./deploy/non-olm/latest/operator.yml
   ```

#### OpenShift 4

1. Update the ClusterServiceVersion in `./deploy/olm-catalog`

   ```
   # from ./deploy/olm-catalog/[...]/crane-operator.v99.0.0.clusterserviceversion.yaml
   [...]
      containers:
      - name: operator
        image: quay.io/$ORG/mig-operator-container:$TAG
   ```

2. Follow steps to [push operator metadata](#pushing-operator-metadata-openshift-4x)

3. Follow steps to [install mig-operator after pushing metadata](#installing-mig-operator-after-pushing-metadata)

## Pushing Operator Metadata (OpenShift 4.x)

The tooling and steps for pushing metadata depend on the OpenShift version.
|OpenShift Versions|Operator Metadata Tooling|
|---|---|
|4.5+|[opm](https://github.com/operator-framework/operator-registry)|
|4.1 - 4.5|[operator-courier](https://github.com/operator-framework/operator-courier)|
|3.x| n/a |

---

### Pushing operator metadata with `opm` (OpenShift 4.5+)

#### Prerequisities

- Install `opm` from [operator-registry](https://github.com/operator-framework/operator-registry)

#### Build bundle and index images, update CatalogSource

1. Set quay org and image tag

   ```
   export ORG=your-quay-org
   export TAG=latest
   ```

2. Build and push the _bundle image_

   ```
   docker build -f build/Dockerfile.bundle -t quay.io/$ORG/mig-operator-bundle:$TAG .
   docker push quay.io/$ORG/mig-operator-bundle:$TAG
   ```
   *Note*: visit quay.io and make `mig-operator-bundle` public before continuing

3. Build and push the _index image_

   ```
   opm index add --container-tool docker --bundles quay.io/$ORG/mig-operator-bundle:$TAG --tag quay.io/$ORG/mig-operator-index:$TAG
   docker push quay.io/$ORG/mig-operator-index:$TAG
   ```
   *Note*: visit quay.io and make `mig-operator-index` public before continuing

4. Create a new _CatalogSource_ referencing the _index image_
   ```
   cat << EOF > catalogsource.yml
   apiVersion: operators.coreos.com/v1alpha1
   kind: CatalogSource
   metadata:
     name: migration-operator
     namespace: openshift-marketplace
   spec:
     sourceType: grpc
     image: quay.io/$ORG/mig-operator-index:$TAG
   EOF

   oc create -f catalogsource.yml
   ```

   *Note*: CatalogSources will not pull updated images.
   https://github.com/operator-framework/operator-lifecycle-manager/issues/903

   As a workaround, use the commands below to modify your CatalogSource with the latest index image SHA
   ```bash
   export BUNDLEDIGEST=$(docker pull quay.io/$ORG/mig-operator-index:latest | grep Digest | awk '{ print $2 }')
   sed "s/:latest/@$BUNDLEDIGEST/" catalogsource.yml | oc create -f -
   ```

---

### Pushing operator metadata with `operator-courier` (OpenShift 4.1-4.5)

#### Prerequisities

 - Install `opm` from [operator-registry](https://github.com/operator-framework/operator-registry)
 - Install `operator-courier`

    ```
    dnf -y install python3-operator-courier
    ```

 - Set the `QUAY_TOKEN` basic auth token
    - To interact with the quay API using operator courier you will need to obtain a  basic auth token. The example script below can be used to retrieve a token and then to more easily follow examples here it is suggested you export it in your .bashrc or somewhere else that makes sense for you, `export QUAY_TOKEN="basic ..."`.

   ```
   export QUAY_USERNAME
   export QUAY_PASSWORD
   echo $(curl -sH "Content-Type: application/json" -XPOST https://quay.io/cnr/api/v1/users/login -d '
   {
   "user": {
   "username": "'"${QUAY_USERNAME}"'",
   "password": "'"${QUAY_PASSWORD}"'"
   }
   }')
   ```

#### Pushing metadata and updating the CatalogSource

1. Set quay org and tag

   ```
   export ORG=your-quay-org
   export TAG=latest
   ```

2. Follow steps 1-3 from [build bundle and index images](#pushing-operator-metadata-with-opm-openshift-45) to build an index image.

3. Use `opm` to export metadata from your index image in _appregistry format_

   ```
   opm index export --container-tool docker -i quay.io/$ORG/mig-operator-index:$TAG mtc-operator
   ```
   *Note*: This will produce a directory called `downloaded` with _appregistry format_ metadata.

4. Use `operator-courier` to push updated metadata, making sure to increment the version

    ```
    operator-courier --verbose push downloaded/mtc-operator $ORG mtc-operator 2.0.0 "$QUAY_TOKEN"
    ```
    *Note*: visit quay.io and make the app `$ORG/mtc-operator` public before continuing

5. Create a new _OperatorSource_ referencing the pushed metadata
    ```
    cat << EOF > mig-operator-source.yaml
    apiVersion: operators.coreos.com/v1
    kind: OperatorSource
    metadata:
      name: migration-operator
      namespace: openshift-marketplace
    spec:
      type: appregistry
      endpoint: https://quay.io/cnr
      registryNamespace: $ORG
      displayName: "Migration Operator"
      publisher: "ocp-migrate-team@redhat.com"
    EOF

    oc create -f mig-operator-source.yaml
    ```

---

## Installing mig-operator after pushing metadata

### Disabling default OperatorSources

If you are working on an operator such as crane, that exists in community-operators or elsewhere you may see duplicate operators in the UI. It can be difficult to discern which copy comes from which source. To alleviate this problem you may disable the default operator sources.

```
oc patch OperatorHub cluster --type json -p '[{"op": "add", "path": "/spec/disableAllDefaultSources", "value": true}]'
```

To reverse this change simply update the value again.
```
oc patch OperatorHub cluster --type json -p '[{"op": "add", "path": "/spec/disableAllDefaultSources", "value": false}]'
```

### Creating the OperatorGroup
Before creating a subscription from the CLI, you must create an OperatorGroup.

```
cat << EOF > operatorgroup.yml
apiVersion: operators.coreos.com/v1
kind: OperatorGroup
metadata:
  namespace: openshift-migration
  generateName: openshift-migration-
spec:
  targetNamespaces:
  - openshift-migration
EOF

oc create -f operatorgroup.yml
```

### Creating the Operator Subscription

You may _Subscribe_ to an Operator via OperatorHub or from the CLI.

To _Subscribe_ to an Operator from the CLI:

1. Ensure the namespace exists,
2. Select an update channel
3. Write a subscription.yml, and create the resource.

```
oc create namespace openshift-migration ||:

export CHANNEL=latest

cat << EOF > subscription.yml
apiVersion: operators.coreos.com/v1alpha1
kind: Subscription
metadata:
  name: crane-operator
  namespace: openshift-migration
spec:
  channel: $CHANNEL
  installPlanApproval: Automatic
  name: crane-operator
  source: migration-operator
  sourceNamespace: openshift-marketplace
EOF

oc create -f subscription.yml
```

### Making iterative changes to mig-operator
If you have made a change, deployed the operator, spotted an error and need to test another update:

1. Update operator playbook and metadata
   1. Make changes to _playbook contents_
   1. Build and push updated _mig-operator image_
   1. Make changes to _operator metadata_
   1. Build and push updated _operator metadata_

1. Clean up
   1. Delete the Operator Subscription `oc delete -f subscription.yml`
   1. Delete the OperatorSource `oc delete -f mig-operator-source.yaml`

1. Re-deploy
   1. Recreate the OperatorSource `oc create -f mig-operator-source.yaml`
   1. Recreate the Operator Subscription  `oc create -f subscription.yml`


text:
"""
A script which removes spam comments from the database.

The determination of which comments are spam is based on two pieces of
information:

1. The comment's ``is_public`` field, and

2. The comment's age.

If the ``is_public`` field is set to ``False`` and the comment is
older than a specified threshold (see below), it will be considered
spam and will be deleted.

**Arguments:**

``-a``, ``--age=AGE``
    The age threshold, in days, past which a non-public comment will
    be considered spam, and thus deleted. Defaults to 14 if not
    supplied (and thus will delete non-public comments which are at
    least two weeks old).

``-d``, ``--dry-run``
    Does not delete any comments, but merely prints the number of
    comments which would have been deleted.

``-s``, ``--settings=SETTINGS``
    Django settings module to use. This argument is required.

``-t``, ``--type=TYPE``
    The type of comment to perform deletion on; ``free`` will use the
    ``FreeComment`` model, and ``registered`` will use the ``Comment``
    model. Defaults to ``free`` if not specified.

``-v``, ``--verbose``
    Run verbosely, printing information to standard output about each
    comment as it is deleted.

Regardless of the ``verbose``flag, this script will print the total
number of deleted comments to standard output when finished.

This script is intended to be run as a cron job; for example, to have
it run at midnight each Sunday, with default values::

    0 0 * sun python /path/to/comment_utils/bin/delete_spam_comments.py --settings=yoursite.settings

"""

import datetime, os
from optparse import OptionParser

def delete_spam_comments(age, dry_run, type, verbose):
    from django.contrib.comments import models
    comment_model = { 'free': models.FreeComment,
                      'registered': models.Comment }[type]
    age_cutoff = datetime.datetime.now() - datetime.timedelta(days=age)
    comments_to_delete = comment_model.objects.filter(is_public__exact=False,
                                                      submit_date__lt=age_cutoff)
    deleted_count = comments_to_delete.count()
    if not dry_run:
        for comment in comments_to_delete:
            if verbose:
                print "Deleting spam comment '%s' on '%s', from %s" % (comment,
                                                                       comment.get_content_object(),
                                                                       comment.submit_date.strftime("%Y-%m-%d"))
            comment.delete()
    print "Deleted %s spam comments" % deleted_count

if __name__ == '__main__':
    usage = "usage: %prog --settings=settings [options]"
    parser = OptionParser(usage)
    parser.add_option('-a', '--age', dest='age', metavar='AGE', type='int',
                      help="The age threshold, in days, past which a non-public comment will be considered spam, and thus be deleted. Defaults to 14 if not supplied.")
    parser.add_option('-d', '--dry-run', action="store_true", dest="dry_run",
                      help="Does not delete any comments, but merely outputs the number of comments which would have been deleted.")
    parser.add_option('-s', '--settings', dest='settings', metavar='SETTINGS',
                      help="Django settings module to use. This argument is required.")
    parser.add_option('-t', '--type', dest='type', metavar='TYPE', type='choice', choices=('free', 'registered'),
                      help="The type of comment to perform deletion on; 'free' will use the 'FreeComment' model, and 'registered' will use the 'Comment' model. Defaults to 'free' if not specified.")
    parser.add_option('-v', '--verbose', dest='verbose', metavar='VERBOSE', action='store_true',
                      help="Run verbosely, printing information to standard output about each comment as it is deleted.")
    (options, args) = parser.parse_args()
    if not options.settings:
        parser.error("You must specify a settings module.")
    os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
    age = options.age or 14
    dry_run = options.dry_run or False
    comment_type = options.type or 'free'
    verbose = options.verbose or False
    delete_spam_comments(age=age, dry_run=dry_run,
                         type=comment_type, verbose=verbose)


text:
package org.apache.spark.sql.execution.command.v2

import org.apache.spark.sql.Row
import org.apache.spark.sql.execution.command

/**
 * The class contains tests for the `ALTER TABLE .. RENAME PARTITION` command
 * to check V2 table catalogs.
 */
class AlterTableRenamePartitionSuite
  extends command.AlterTableRenamePartitionSuiteBase
  with CommandSuiteBase {

  test("with location") {
    withNamespaceAndTable("ns", "tbl") { t =>
      createSinglePartTable(t)
      val loc = "location1"
      sql(s"ALTER TABLE $t ADD PARTITION (id = 2) LOCATION '$loc'")
      sql(s"INSERT INTO $t PARTITION (id = 2) SELECT 'def'")
      checkPartitions(t, Map("id" -> "1"), Map("id" -> "2"))
      checkLocation(t, Map("id" -> "2"), loc)

      sql(s"ALTER TABLE $t PARTITION (id = 2) RENAME TO PARTITION (id = 3)")
      checkPartitions(t, Map("id" -> "1"), Map("id" -> "3"))
      // `InMemoryPartitionTableCatalog` should keep the original location
      checkLocation(t, Map("id" -> "3"), loc)
      checkAnswer(sql(s"SELECT id, data FROM $t WHERE id = 3"), Row(3, "def"))
    }
  }
}


text:
package org.apache.sshd.util.test;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.security.Key;
import java.security.KeyPair;
import java.security.interfaces.DSAParams;
import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.DSAPublicKey;
import java.security.interfaces.ECKey;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.ECField;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.EllipticCurve;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.sshd.client.SshClient;
import org.apache.sshd.common.SshdSocketAddress;
import org.apache.sshd.common.keyprovider.KeyPairProvider;
import org.apache.sshd.common.util.GenericUtils;
import org.apache.sshd.common.util.ValidateUtils;
import org.apache.sshd.server.SshServer;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;

/**
 * TODO Add javadoc
 *
 * @author Apache MINA SSHD Project
 */
public abstract class BaseTestSupport extends Assert {
    public static final String TEMP_SUBFOLDER_NAME = "temp";
    // can be used to override the 'localhost' with an address other than 127.0.0.1 in case it is required
    public static final String TEST_LOCALHOST = System.getProperty("org.apache.sshd.test.localhost", SshdSocketAddress.LOCALHOST_IP);

    // useful test sizes for keys
    @SuppressWarnings("boxing")
    public static final List<Integer> DSS_SIZES =
            Collections.unmodifiableList(Arrays.asList(512, 768, 1024));
    @SuppressWarnings("boxing")
    public static final List<Integer> RSA_SIZES =
            Collections.unmodifiableList(Arrays.asList(1024, 2048, 3072, 4096));

    @Rule
    public final TestWatcher rule = new TestWatcher() {
        // TODO consider using a ThreadLocal storage for the start time - provided
        //      the code is assured to call starting/finished on the same thread
        private long startTime;

        @Override
        protected void starting(Description description) {
            System.out.println("\nStarting " + description.getClassName() + ":" + description.getMethodName() + "...\n");
            startTime = System.currentTimeMillis();
        }

        @Override
        protected void finished(Description description) {
            long duration = System.currentTimeMillis() - startTime;
            System.out.println("\nFinished " + description.getClassName() + ":" + description.getMethodName() + " in " + duration + " ms\n");
        }
    };

    @Rule
    public final TestName TEST_NAME_HOLDER = new TestName();
    private Path targetFolder;
    private Path tempFolder;

    protected BaseTestSupport() {
        super();
    }

    public final String getCurrentTestName() {
        return TEST_NAME_HOLDER.getMethodName();
    }

    protected SshServer setupTestServer() {
        return Utils.setupTestServer(getClass());
    }

    protected SshClient setupTestClient() {
        return Utils.setupTestClient(getClass());
    }

    protected KeyPairProvider createTestHostKeyProvider() {
        return Utils.createTestHostKeyProvider(getClass());
    }

    /**
     * Attempts to build a relative path whose root is the location
     * of the TEMP sub-folder of the Maven "target" folder associated
     * with the project
     *
     * @param comps The path components - ignored if {@code null}/empty
     * @return The {@link Path} representing the result - same as target folder if no components
     * @see #TEMP_SUBFOLDER_NAME
     * @see #getTargetRelativeFile(Collection)
     */
    protected Path getTempTargetRelativeFile(String ... comps) {
        return getTempTargetRelativeFile(GenericUtils.isEmpty(comps) ? Collections.<String>emptyList() : Arrays.asList(comps));
    }

    /**
     * Attempts to build a relative path whose root is the location
     * of the TEMP sub-folder of the Maven "target" folder associated
     * with the project
     *
     * @param comps The path components - ignored if {@code null}/empty
     * @return The {@link Path} representing the result - same as target folder if no components
     * @see #TEMP_SUBFOLDER_NAME
     * @see #getTempTargetFolder();
     */
    protected Path getTempTargetRelativeFile(Collection<String> comps) {
        return Utils.resolve(getTempTargetFolder(), comps);
    }

    /**
     * @return The TEMP sub-folder {@link Path} of the Maven "target" folder
     * associated with the project - never {@code null}
     */
    protected Path getTempTargetFolder() {
        synchronized(TEMP_SUBFOLDER_NAME) {
            if (tempFolder == null) {
                tempFolder = ValidateUtils.checkNotNull(detectTargetFolder(), "No target folder detected").resolve(TEMP_SUBFOLDER_NAME);
            }
        }

        return tempFolder;
    }

    /**
     * Attempts to build a relative path whose root is the location
     * of the Maven "target" folder associated with the project
     *
     * @param comps The path components - ignored if {@code null}/empty
     * @return The {@link Path} representing the result - same as target folder if no components
     */
    protected Path getTargetRelativeFile(String ... comps) {
        return getTargetRelativeFile(GenericUtils.isEmpty(comps) ? Collections.<String>emptyList() : Arrays.asList(comps));
    }

    /**
     * Attempts to build a relative path whose root is the location
     * of the Maven "target" folder associated with the project
     *
     * @param comps The path components - ignored if {@code null}/empty
     * @return The {@link Path} representing the result - same as target folder if no components
     * @see #detectTargetFolder()
     */
    protected Path getTargetRelativeFile(Collection<String> comps) {
        return Utils.resolve(detectTargetFolder(), comps);
    }

    /**
     * Attempts to detect the location of the Maven "target" folder
     * associated with the project that contains the actual class extending this
     * base class
     *
     * @return The {@link File} representing the location of the "target" folder
     * @throws IllegalArgumentException If failed to detect the folder
     */
    protected Path detectTargetFolder() throws IllegalStateException {
        synchronized (TEMP_SUBFOLDER_NAME) {
            if (targetFolder == null) {
                targetFolder = ValidateUtils.checkNotNull(Utils.detectTargetFolder(getClass()), "Failed to detect target folder").toPath();
            }
        }

        return targetFolder;
    }

    protected Path detectSourcesFolder() throws IllegalStateException {
        Path target = detectTargetFolder();
        Path parent = target.getParent();
        return parent.resolve("src");
    }

    public static final String MAIN_SUBFOLDER = "main", TEST_SUBFOLDER = "test";
    public static final String RESOURCES_SUBFOLDER = "resources";

    protected Path getClassResourcesFolder(String resType /* test or main */) {
        return getClassResourcesFolder(resType, getClass());
    }

    protected Path getClassResourcesFolder(String resType /* test or main */, Class<?> clazz) {
        return getPackageResourcesFolder(resType, clazz.getPackage());
    }

    protected Path getPackageResourcesFolder(String resType /* test or main */, Package pkg) {
        return getPackageResourcesFolder(resType, pkg.getName());
    }

    protected Path getPackageResourcesFolder(String resType /* test or main */, String pkgName) {
        Path src = detectSourcesFolder();
        Path root = src.resolve(resType);
        Path resources = root.resolve(RESOURCES_SUBFOLDER);
        return resources.resolve(pkgName.replace('.', File.separatorChar));
    }

    /* ------------------- Useful extra test helpers ---------------------- */

    public static String shuffleCase(CharSequence cs) {
        if (GenericUtils.isEmpty(cs)) {
            return "";
        }

        StringBuilder sb = new StringBuilder(cs.length());
        for (int index = 0; index < cs.length(); index++) {
            char ch = cs.charAt(index);
            double v = Math.random();
            if (Double.compare(v, 0.3d) < 0) {
                ch = Character.toUpperCase(ch);
            } else if ((Double.compare(v, 0.3d) >= 0) && (Double.compare(v, 0.6d) < 0)) {
                ch = Character.toLowerCase(ch);
            }
            sb.append(ch);
        }

        return sb.toString();
    }

    public static List<Object[]> parameterize(Collection<?> params) {
        if (GenericUtils.isEmpty(params)) {
            return Collections.emptyList();
        }

        List<Object[]> result = new ArrayList<Object[]>(params.size());
        for (Object p : params) {
            result.add(new Object[]{p});
        }

        return result;
    }
    /* ----------------------- Useful extra assertions --------------------- */

    public static void assertEquals(String message, boolean expected, boolean actual) {
        assertEquals(message, Boolean.valueOf(expected), Boolean.valueOf(actual));
    }

    public static <T> void assertEquals(String message, Iterable<? extends T> expected, Iterable<? extends T> actual) {
        if (expected != actual) {
            assertEquals(message, expected.iterator(), actual.iterator());
        }
    }

    public static <T> void assertEquals(String message, Iterator<? extends T> expected, Iterator<? extends T> actual) {
        if (expected == actual) {
            return;
        }

        for (int index = 0; expected.hasNext(); index++) {
            assertTrue(message + "[next actual index=" + index + "]", actual.hasNext());

            T expValue = expected.next(), actValue = actual.next();
            assertEquals(message + "[iterator index=" + index + "]", expValue, actValue);
        }

        // once expected is exhausted make sure no more actual items left
        assertFalse(message + "[non-empty-actual]", actual.hasNext());
    }

    public static Path assertHierarchyTargetFolderExists(Path folder, LinkOption... options) throws IOException {
        if (Files.exists(folder, options)) {
            assertTrue("Target is an existing file instead of a folder: " + folder, Files.isDirectory(folder, options));
        } else {
            Files.createDirectories(folder);
        }

        return folder;
    }

    public static File assertHierarchyTargetFolderExists(File folder) {
        if (folder.exists()) {
            assertTrue("Target is an existing file instead of a folder: " + folder.getAbsolutePath(), folder.isDirectory());
        } else {
            assertTrue("Failed to create hierarchy of " + folder.getAbsolutePath(), folder.mkdirs());
        }

        return folder;
    }

    public static void assertObjectInstanceOf(String message, Class<?> expected, Object obj) {
        assertNotNull(message + " - no actual object", obj);

        Class<?> actual = obj.getClass();
        if (!expected.isAssignableFrom(actual)) {
            fail(message + " - actual object type (" + actual.getName() + ") incompatible with expected (" + expected.getName() + ")");
        }
    }

    public static <E> void assertListEquals(String message, List<? extends E> expected, List<? extends E> actual) {
        int expSize = GenericUtils.size(expected), actSize = GenericUtils.size(actual);
        assertEquals(message + "[size]", expSize, actSize);

        for (int index = 0; index < expSize; index++) {
            E expValue = expected.get(index), actValue = actual.get(index);
            assertEquals(message + "[" + index + "]", expValue, actValue);
        }
    }

    public static void assertKeyPairEquals(String message, KeyPair expected, KeyPair actual) {
        assertKeyEquals(message + "[public]", expected.getPublic(), actual.getPublic());
        assertKeyEquals(message + "[private]", expected.getPrivate(), actual.getPrivate());
    }

    public static final <T extends Key> void assertKeyEquals(String message, T expected, T actual) {
        if (expected == actual) {
            return;
        }

        assertEquals(message + "[algorithm]", expected.getAlgorithm(), actual.getAlgorithm());

        if (expected instanceof RSAPublicKey) {
            assertRSAPublicKeyEquals(message, RSAPublicKey.class.cast(expected), RSAPublicKey.class.cast(actual));
        } else if (expected instanceof DSAPublicKey) {
            assertDSAPublicKeyEquals(message, DSAPublicKey.class.cast(expected), DSAPublicKey.class.cast(actual));
        } else if (expected instanceof ECPublicKey) {
            assertECPublicKeyEquals(message, ECPublicKey.class.cast(expected), ECPublicKey.class.cast(actual));
        } else if (expected instanceof RSAPrivateKey) {
            assertRSAPrivateKeyEquals(message, RSAPrivateKey.class.cast(expected), RSAPrivateKey.class.cast(actual));
        } else if (expected instanceof ECPrivateKey) {
            assertECPrivateKeyEquals(message, ECPrivateKey.class.cast(expected), ECPrivateKey.class.cast(actual));
        }
        assertArrayEquals(message + "[encdoded-data]", expected.getEncoded(), actual.getEncoded());
    }

    public static final void assertRSAPublicKeyEquals(String message, RSAPublicKey expected, RSAPublicKey actual) {
        if (expected == actual) {
            return;
        }

        assertEquals(message + "[e]", expected.getPublicExponent(), actual.getPublicExponent());
        assertEquals(message + "[n]", expected.getModulus(), actual.getModulus());
    }

    public static final void assertDSAPublicKeyEquals(String message, DSAPublicKey expected, DSAPublicKey actual) {
        if (expected == actual) {
            return;
        }

        assertEquals(message + "[y]", expected.getY(), actual.getY());
        assertDSAParamsEquals(message + "[params]", expected.getParams(), actual.getParams());
    }

    public static final void assertECPublicKeyEquals(String message, ECPublicKey expected, ECPublicKey actual) {
        if (expected == actual) {
            return;
        }

        assertECPointEquals(message + "[W]", expected.getW(), actual.getW());
        assertECParameterSpecEquals(message, expected, actual);
    }

    public static final void assertRSAPrivateKeyEquals(String message, RSAPrivateKey expected, RSAPrivateKey actual) {
        if (expected == actual) {
            return;
        }

        assertEquals(message + "[d]", expected.getPrivateExponent(), actual.getPrivateExponent());
        assertEquals(message + "[n]", expected.getModulus(), actual.getModulus());
    }

    public static final void assertDSAPrivateKeyEquals(String message, DSAPrivateKey expected, DSAPrivateKey actual) {
        if (expected == actual) {
            return;
        }

        assertEquals(message + "[x]", expected.getX(), actual.getX());
        assertDSAParamsEquals(message + "[params]", expected.getParams(), actual.getParams());
    }

    public static final void assertDSAParamsEquals(String message, DSAParams expected, DSAParams actual) {
        if (expected == actual) {
            return;
        }

        assertEquals(message + "[g]", expected.getG(), actual.getG());
        assertEquals(message + "[p]", expected.getP(), actual.getP());
        assertEquals(message + "[q]", expected.getQ(), actual.getQ());
    }

    public static final void assertECPrivateKeyEquals(String message, ECPrivateKey expected, ECPrivateKey actual) {
        if (expected == actual) {
            return;
        }

        assertEquals(message + "[S]", expected.getS(), actual.getS());
        assertECParameterSpecEquals(message, expected, actual);
    }

    public static final void assertECParameterSpecEquals(String message, ECKey expected, ECKey actual) {
        if (expected == actual) {
            return;
        }
        assertECParameterSpecEquals(message, expected.getParams(), actual.getParams());
    }

    public static final void assertECParameterSpecEquals(String message, ECParameterSpec expected, ECParameterSpec actual) {
        if (expected == actual) {
            return;
        }

        assertEquals(message + "[order]", expected.getOrder(), actual.getOrder());
        assertEquals(message + "[cofactor]", expected.getCofactor(), actual.getCofactor());
        assertECPointEquals(message + "[generator]", expected.getGenerator(), actual.getGenerator());
        assertCurveEquals(message + "[curve]", expected.getCurve(), actual.getCurve());
    }

    public static final void assertCurveEquals(String message, EllipticCurve expected, EllipticCurve actual) {
        if (expected == actual) {
            return;
        }

        assertEquals(message + "[A]", expected.getA(), actual.getA());
        assertEquals(message + "[B]", expected.getB(), actual.getB());
        assertArrayEquals(message + "[seed]", expected.getSeed(), actual.getSeed());
        assertECFieldEquals(message + "[field]", expected.getField(), actual.getField());
    }

    public static final void assertECFieldEquals(String message, ECField expected, ECField actual) {
        if (expected == actual) {
            return;
        }

        assertEquals(message + "[size]", expected.getFieldSize(), actual.getFieldSize());
    }

    public static final void assertECPointEquals(String message, ECPoint expected, ECPoint actual) {
        if (expected == actual) {
            return;
        }

        assertEquals(message + "[x]", expected.getAffineX(), actual.getAffineX());
        assertEquals(message + "[y]", expected.getAffineY(), actual.getAffineY());
    }

    public static void assertFileLength(File file, long length, long timeout) throws Exception {
        assertFileLength(file.toPath(), length, timeout);
    }

    /**
     * Waits the specified timeout for the file to exist and have the required length
     *
     * @param file    The file {@link Path} to check
     * @param length  Expected length
     * @param timeout Timeout (msec.) to wait for satisfying the requirements
     * @throws Exception If failed to access the file
     */
    public static void assertFileLength(Path file, long length, long timeout) throws Exception {
        if (waitForFile(file, length, timeout)) {
            return;
        }
        assertTrue("File not found: " + file, Files.exists(file));
        assertEquals("Mismatched file size for " + file, length, Files.size(file));
    }

    public static boolean waitForFile(Path file, long length, long timeout) throws Exception {
        while (timeout > 0L) {
            long sleepTime = Math.min(timeout, 100L);
            if (Files.exists(file) && (Files.size(file) == length)) {
                return true;
            }

            long sleepStart = System.nanoTime();
            Thread.sleep(sleepTime);
            long sleepEnd = System.nanoTime(), nanoSleep = sleepEnd - sleepStart;

            sleepTime = TimeUnit.NANOSECONDS.toMillis(nanoSleep);
            timeout -= sleepTime;
        }

        return false;
    }
}


text:
from __future__ import absolute_import

import responses
from mock import patch
from time import time

from sentry.testutils import APITestCase
from sentry.models import Activity, ExternalIssue, Group, GroupLink, GroupStatus, Identity, IdentityProvider, Integration
from sentry.integrations.vsts.integration import VstsIntegration
from sentry.utils.http import absolute_uri
from .testutils import (
    WORK_ITEM_UPDATED,
    WORK_ITEM_UNASSIGNED,
    WORK_ITEM_UPDATED_STATUS,
    WORK_ITEM_STATES,
)

class VstsWebhookWorkItemTest(APITestCase):
    def setUp(self):
        self.organization = self.create_organization()
        self.project = self.create_project(organization=self.organization)
        self.access_token = '1234567890'
        self.account_id = u'80ded3e8-3cd3-43b1-9f96-52032624aa3a'
        self.instance = 'instance.visualstudio.com'
        self.shared_secret = '1234567890'
        self.model = Integration.objects.create(
            provider='vsts',
            external_id=self.account_id,
            name='vsts_name',
            metadata={
                 'domain_name': 'instance.visualstudio.com',
                 'subscription': {
                     'id': 1234,
                     'secret': self.shared_secret,
                 }
            }
        )
        self.identity_provider = IdentityProvider.objects.create(type='vsts')
        self.identity = Identity.objects.create(
            idp=self.identity_provider,
            user=self.user,
            external_id='vsts_id',
            data={
                'access_token': self.access_token,
                'refresh_token': 'qwertyuiop',
                'expires': int(time()) + int(1234567890),
            }
        )
        self.org_integration = self.model.add_organization(self.organization.id, self.identity.id)
        self.org_integration.config = {
            'sync_status_reverse': True,
            'sync_status_forward': True,
            'sync_comments': True,
            'sync_forward_assignment': True,
            'sync_reverse_assignment': True,
        }
        self.org_integration.save()
        self.integration = VstsIntegration(self.model, self.organization.id)

        self.user_to_assign = self.create_user('sentryuseremail@email.com')

    def create_linked_group(self, external_issue, project, status):
        group = self.create_group(project=project, status=status)
        GroupLink.objects.create(
            group_id=group.id,
            project_id=project.id,
            linked_type=GroupLink.LinkedType.issue,
            linked_id=external_issue.id,
            data={}
        )
        return group

    @responses.activate
    def test_workitem_change_assignee(self):
        work_item_id = 31

        external_issue = ExternalIssue.objects.create(
            organization_id=self.organization.id,
            integration_id=self.model.id,
            key=work_item_id,
        )
        with patch('sentry.integrations.vsts.webhooks.sync_group_assignee_inbound') as mock:
            resp = self.client.post(
                absolute_uri('/extensions/vsts/issue-updated/'),
                data=WORK_ITEM_UPDATED,
                HTTP_SHARED_SECRET=self.shared_secret,
            )

            assert resp.status_code == 200
            external_issue = ExternalIssue.objects.get(id=external_issue.id)
            assert mock.call_count == 1
            args = mock.call_args[1]

            assert args['integration'].__class__ == Integration
            assert args['email'] == 'lauryn@sentry.io'
            assert args['external_issue_key'] == work_item_id
            assert args['assign'] is True

    @responses.activate
    def test_workitem_unassign(self):
        work_item_id = 33
        external_issue = ExternalIssue.objects.create(
            organization_id=self.organization.id,
            integration_id=self.model.id,
            key=work_item_id,
        )
        with patch('sentry.integrations.vsts.webhooks.sync_group_assignee_inbound') as mock:
            resp = self.client.post(
                absolute_uri('/extensions/vsts/issue-updated/'),
                data=WORK_ITEM_UNASSIGNED,
                HTTP_SHARED_SECRET=self.shared_secret,
            )

            assert resp.status_code == 200
            external_issue = ExternalIssue.objects.get(id=external_issue.id)
            assert mock.call_count == 1
            args = mock.call_args[1]

            assert args['integration'].__class__ == Integration
            assert args['email'] is None
            assert args['external_issue_key'] == work_item_id
            assert args['assign'] is False

    @responses.activate
    def test_inbound_status_sync_resolve(self):
        responses.add(
            responses.GET,
            'https://instance.visualstudio.com/c0bf429a-c03c-4a99-9336-d45be74db5a6/_apis/wit/workitemtypes/Bug/states',
            json=WORK_ITEM_STATES,
        )
        work_item_id = 33
        num_groups = 5
        external_issue = ExternalIssue.objects.create(
            organization_id=self.organization.id,
            integration_id=self.model.id,
            key=work_item_id,
        )
        groups = [
            self.create_linked_group(
                external_issue,
                self.project,
                GroupStatus.UNRESOLVED) for _ in range(num_groups)]

        with self.feature('organizations:integrations-issue-sync'):
            resp = self.client.post(
                absolute_uri('/extensions/vsts/issue-updated/'),
                data=WORK_ITEM_UPDATED_STATUS,
                HTTP_SHARED_SECRET=self.shared_secret,
            )
            assert resp.status_code == 200
            group_ids = [g.id for g in groups]
            assert len(
                Group.objects.filter(
                    id__in=group_ids,
                    status=GroupStatus.RESOLVED)) == num_groups
            assert len(Activity.objects.filter(group_id__in=group_ids)) == num_groups

    @responses.activate
    def test_inbound_status_sync_unresolve(self):
        responses.add(
            responses.GET,
            'https://instance.visualstudio.com/c0bf429a-c03c-4a99-9336-d45be74db5a6/_apis/wit/workitemtypes/Bug/states',
            json=WORK_ITEM_STATES,
        )
        work_item_id = 33
        num_groups = 5
        external_issue = ExternalIssue.objects.create(
            organization_id=self.organization.id,
            integration_id=self.model.id,
            key=work_item_id,
        )
        groups = [
            self.create_linked_group(
                external_issue,
                self.project,
                GroupStatus.RESOLVED) for _ in range(num_groups)]

        # Change so that state is changing from resolved to unresolved
        state = WORK_ITEM_UPDATED_STATUS['resource']['fields']['System.State']
        state['oldValue'] = 'Resolved'
        state['newValue'] = 'Active'

        with self.feature('organizations:integrations-issue-sync'):
            resp = self.client.post(
                absolute_uri('/extensions/vsts/issue-updated/'),
                data=WORK_ITEM_UPDATED_STATUS,
                HTTP_SHARED_SECRET=self.shared_secret,
            )
            assert resp.status_code == 200
            group_ids = [g.id for g in groups]
            assert len(
                Group.objects.filter(
                    id__in=group_ids,
                    status=GroupStatus.UNRESOLVED)) == num_groups
            assert len(Activity.objects.filter(group_id__in=group_ids)) == num_groups


text:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// create a schema
var placeSchema = new Schema({
    street: String,
    number: Number,
    city: String,
    postalCode: String,
    country: String
});

// the schema is useless so far
// we need to create a model using it
var Place = mongoose.model('place', placeSchema, 'place');

// make this available to our users in our Node applications
module.exports = Place;


text:
package io.undertow.protocols.http2;

import java.nio.ByteBuffer;

import io.undertow.UndertowMessages;
import io.undertow.util.HttpString;

/**
 * @author Stuart Douglas
 */
final class Hpack {

    private static final byte LOWER_DIFF = 'a' - 'A';
    static final int DEFAULT_TABLE_SIZE = 4096;
    private static final int MAX_INTEGER_OCTETS = 8; //not sure what a good value for this is, but the spec says we need to provide an upper bound

    /**
     * table that contains powers of two,
     * used as both bitmask and to quickly calculate 2^n
     */
    private static final int[] PREFIX_TABLE;

    static final HeaderField[] STATIC_TABLE;
    static final int STATIC_TABLE_LENGTH;

    static {
        PREFIX_TABLE = new int[32];
        for (int i = 0; i < 32; ++i) {
            int n = 0;
            for (int j = 0; j < i; ++j) {
                n = n << 1;
                n |= 1;
            }
            PREFIX_TABLE[i] = n;
        }

        HeaderField[] fields = new HeaderField[62];
        //note that zero is not used
        fields[1] = new HeaderField(new HttpString(":authority"), null);
        fields[2] = new HeaderField(new HttpString(":method"), "GET");
        fields[3] = new HeaderField(new HttpString(":method"), "POST");
        fields[4] = new HeaderField(new HttpString(":path"), "/");
        fields[5] = new HeaderField(new HttpString(":path"), "/index.html");
        fields[6] = new HeaderField(new HttpString(":scheme"), "http");
        fields[7] = new HeaderField(new HttpString(":scheme"), "https");
        fields[8] = new HeaderField(new HttpString(":status"), "200");
        fields[9] = new HeaderField(new HttpString(":status"), "204");
        fields[10] = new HeaderField(new HttpString(":status"), "206");
        fields[11] = new HeaderField(new HttpString(":status"), "304");
        fields[12] = new HeaderField(new HttpString(":status"), "400");
        fields[13] = new HeaderField(new HttpString(":status"), "404");
        fields[14] = new HeaderField(new HttpString(":status"), "500");
        fields[15] = new HeaderField(new HttpString("accept-charset"), null);
        fields[16] = new HeaderField(new HttpString("accept-encoding"), "gzip, deflate");
        fields[17] = new HeaderField(new HttpString("accept-language"), null);
        fields[18] = new HeaderField(new HttpString("accept-ranges"), null);
        fields[19] = new HeaderField(new HttpString("accept"), null);
        fields[20] = new HeaderField(new HttpString("access-control-allow-origin"), null);
        fields[21] = new HeaderField(new HttpString("age"), null);
        fields[22] = new HeaderField(new HttpString("allow"), null);
        fields[23] = new HeaderField(new HttpString("authorization"), null);
        fields[24] = new HeaderField(new HttpString("cache-control"), null);
        fields[25] = new HeaderField(new HttpString("content-disposition"), null);
        fields[26] = new HeaderField(new HttpString("content-encoding"), null);
        fields[27] = new HeaderField(new HttpString("content-language"), null);
        fields[28] = new HeaderField(new HttpString("content-length"), null);
        fields[29] = new HeaderField(new HttpString("content-location"), null);
        fields[30] = new HeaderField(new HttpString("content-range"), null);
        fields[31] = new HeaderField(new HttpString("content-type"), null);
        fields[32] = new HeaderField(new HttpString("cookie"), null);
        fields[33] = new HeaderField(new HttpString("date"), null);
        fields[34] = new HeaderField(new HttpString("etag"), null);
        fields[35] = new HeaderField(new HttpString("expect"), null);
        fields[36] = new HeaderField(new HttpString("expires"), null);
        fields[37] = new HeaderField(new HttpString("from"), null);
        fields[38] = new HeaderField(new HttpString("host"), null);
        fields[39] = new HeaderField(new HttpString("if-match"), null);
        fields[40] = new HeaderField(new HttpString("if-modified-since"), null);
        fields[41] = new HeaderField(new HttpString("if-none-match"), null);
        fields[42] = new HeaderField(new HttpString("if-range"), null);
        fields[43] = new HeaderField(new HttpString("if-unmodified-since"), null);
        fields[44] = new HeaderField(new HttpString("last-modified"), null);
        fields[45] = new HeaderField(new HttpString("link"), null);
        fields[46] = new HeaderField(new HttpString("location"), null);
        fields[47] = new HeaderField(new HttpString("max-forwards"), null);
        fields[48] = new HeaderField(new HttpString("proxy-authenticate"), null);
        fields[49] = new HeaderField(new HttpString("proxy-authorization"), null);
        fields[50] = new HeaderField(new HttpString("range"), null);
        fields[51] = new HeaderField(new HttpString("referer"), null);
        fields[52] = new HeaderField(new HttpString("refresh"), null);
        fields[53] = new HeaderField(new HttpString("retry-after"), null);
        fields[54] = new HeaderField(new HttpString("server"), null);
        fields[55] = new HeaderField(new HttpString("set-cookie"), null);
        fields[56] = new HeaderField(new HttpString("strict-transport-security"), null);
        fields[57] = new HeaderField(new HttpString("transfer-encoding"), null);
        fields[58] = new HeaderField(new HttpString("user-agent"), null);
        fields[59] = new HeaderField(new HttpString("vary"), null);
        fields[60] = new HeaderField(new HttpString("via"), null);
        fields[61] = new HeaderField(new HttpString("www-authenticate"), null);
        STATIC_TABLE = fields;
        STATIC_TABLE_LENGTH = STATIC_TABLE.length - 1;
    }

    static class HeaderField {
        final HttpString name;
        final String value;
        final int size;

        HeaderField(HttpString name, String value) {
            this.name = name;
            this.value = value;
            if (value != null) {
                this.size = 32 + name.length() + value.length();
            } else {
                this.size = -1;
            }
        }
    }

    /**
     * Decodes an integer in the HPACK prefex format. If the return value is -1
     * it means that there was not enough data in the buffer to complete the decoding
     * sequence.
     *

     * If this method returns -1 then the source buffer will not have been modified.
     *
     * @param source The buffer that contains the integer
     * @param n      The encoding prefix length
     * @return The encoded integer, or -1 if there was not enough data
     */
    static int decodeInteger(ByteBuffer source, int n) throws HpackException {
        if (source.remaining() == 0) {
            return -1;
        }
        if(n >= PREFIX_TABLE.length) {
            throw UndertowMessages.MESSAGES.integerEncodedOverTooManyOctets(MAX_INTEGER_OCTETS);
        }
        int count = 1;
        int sp = source.position();
        int mask = PREFIX_TABLE[n];

        int i = mask & source.get();
        int b;
        if (i < PREFIX_TABLE[n]) {
            return i;
        } else {
            int m = 0;
            do {
                if(count++ > MAX_INTEGER_OCTETS) {
                    throw UndertowMessages.MESSAGES.integerEncodedOverTooManyOctets(MAX_INTEGER_OCTETS);
                }
                if (source.remaining() == 0) {
                    //we have run out of data
                    //reset
                    source.position(sp);
                    return -1;
                }

                if(m >= PREFIX_TABLE.length) {
                    throw UndertowMessages.MESSAGES.integerEncodedOverTooManyOctets(MAX_INTEGER_OCTETS);
                }
                b = source.get();
                i = i + (b & 127) * (PREFIX_TABLE[m] + 1);
                m += 7;
            } while ((b & 128) == 128);
        }
        return i;
    }

    /**
     * Encodes an integer in the HPACK prefix format.
     *

     * This method assumes that the buffer has already had the first 8-n bits filled.
     * As such it will modify the last byte that is already present in the buffer, and
     * potentially add more if required
     *
     * @param source The buffer that contains the integer
     * @param value  The integer to encode
     * @param n      The encoding prefix length
     */
    static void encodeInteger(ByteBuffer source, int value, int n) {
        int twoNminus1 = PREFIX_TABLE[n];
        int pos = source.position() - 1;
        if (value < twoNminus1) {
            source.put(pos, (byte) (source.get(pos) | value));
        } else {
            source.put(pos, (byte) (source.get(pos) | twoNminus1));
            value = value - twoNminus1;
            while (value >= 128) {
                source.put((byte) (value % 128 + 128));
                value = value / 128;
            }
            source.put((byte) value);
        }
    }

    static byte toLower(byte b) {
        if (b >= 'A' && b <= 'Z') {
            return (byte) (b + LOWER_DIFF);
        }
        return b;
    }

    private Hpack() {}

}


text:
from redbot.message import headers
from redbot.syntax import rfc7230

class connection(headers.HttpHeader):
    canonical_name = "Connection"
    description = """\
The `Connection` header allows senders to specify which headers are hop-by-hop; that is, those that
are not forwarded by intermediaries.

It also indicates options that are desired for this particular connection; e.g., `close` means that
it should not be reused."""
    reference = f"{rfc7230.SPEC_URL}#header.connection"
    syntax = rfc7230.Connection
    list_header = True
    deprecated = False
    valid_in_requests = True
    valid_in_responses = True

class ConnectionTest(headers.HeaderTest):
    name = "Connection"
    inputs = [b"close"]
    expected_out = ["close"]


text:
package com.resgain.base.entity.pdm;

import javax.persistence.Entity;

import com.resgain.base.abs.AbstractPersistentObject;
import com.resgain.base.annotation.Desc;
import com.resgain.base.annotation.Label;
import com.resgain.sparrow.pdm.bean.Column;

@Entity
@javax.persistence.Table(name = "PDM_COLUMN")
@Desc("表字段信息")
public class PdmColumn extends AbstractPersistentObject
{
	private static final long serialVersionUID = 1L;

	@javax.persistence.Column(name = "TABLE_ID")
	@Label(name = "TABLE_ID", nullFlag = false)
	private String tableId;

	@javax.persistence.Column(name = "CODE")
	@Label(name = "代码", nullFlag = false)
	private String code;

	@javax.persistence.Column(name = "NAME")
	@Label(name = "含义", nullFlag = false)
    private String name;

	@javax.persistence.Column(name = "DOMAIN_ID")
	@Label(name = "DOMAIN_ID", nullFlag = true)
    private String domainId; //定义的数据域ID

	@javax.persistence.Column(name = "TYPE")
	@Label(name = "类型", nullFlag = false)
    private String type;

	@javax.persistence.Column(name = "LENGTH")
	@Label(name = "长度", nullFlag = true)
    private int length;

	@javax.persistence.Column(name = "PK_FLAG")
	@Label(name = "是否为主键", nullFlag = false)
    private boolean pkFlag; //

	@javax.persistence.Column(name = "NULL_FLAG")
	@Label(name = "是否可以为空", nullFlag = false)
    private boolean nullFlag; //是否可以为空

	@javax.persistence.Column(name = "UNIQUE_FLAG")
	@Label(name = "是否唯一", nullFlag = false)
    private boolean uniqueFlag;

	@javax.persistence.Column(name = "REF_TABLE_ID")
	@Label(name = "关联表ID", nullFlag = true)
    private String refTableId;

	@javax.persistence.Column(name = "REF_COLUMN_ID")
	@Label(name = "关联表字段ID", nullFlag = true)
    private String refColumnId;

	@javax.persistence.Column(name = "COMMENT")
	@Label(name = "注释", nullFlag = true)
    private String comment;

	public PdmColumn() {
		super();
	}

	public PdmColumn(String tableId, Column column) {
		super();
		this.tableId = tableId;
		this.code = column.getCode();
		this.name = column.getName();
		this.domainId = column.getDomainId();
		this.type = column.getType().replaceAll("\\([0-9\\.]+\\)", "");
		this.length = column.getLength();
		this.pkFlag = column.isPkFlag();
		this.nullFlag = column.isNullFlag();
		this.uniqueFlag = column.isUniqueFlag();
		this.refTableId = column.getRef()==null?null:column.getRef().getId();
		this.refColumnId = column.getRefId();
		this.comment = column.getComment();
	}

	public String getTableId() {
		return tableId;
	}

	public void setTableId(String tableId) {
		this.tableId = tableId;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDomainId() {
		return domainId;
	}

	public void setDomainId(String domainId) {
		this.domainId = domainId;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public int getLength() {
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}

	public boolean isPkFlag() {
		return pkFlag;
	}

	public void setPkFlag(boolean pkFlag) {
		this.pkFlag = pkFlag;
	}

	public boolean isNullFlag() {
		return nullFlag;
	}

	public void setNullFlag(boolean nullFlag) {
		this.nullFlag = nullFlag;
	}

	public boolean isUniqueFlag() {
		return uniqueFlag;
	}

	public void setUniqueFlag(boolean uniqueFlag) {
		this.uniqueFlag = uniqueFlag;
	}

	public String getRefTableId() {
		return refTableId;
	}

	public void setRefTableId(String refTableId) {
		this.refTableId = refTableId;
	}

	public String getRefColumnId() {
		return refColumnId;
	}

	public void setRefColumnId(String refColumnId) {
		this.refColumnId = refColumnId;
	}

	public String getComment() {
		return comment;
	}

	public void setComment(String comment) {
		this.comment = comment;
	}
}


text:
package websql

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
)

func test() {
	key := "a very very very" // 16 bytes
	plaintext := "some really really really long plaintext"
	fmt.Println(plaintext)

	ciphertext, err := EncryptStr(key, plaintext)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(ciphertext)

	result, err := DecryptStr(key, ciphertext)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(result)
}

func EncryptStr(key, text string) (string, error) {
	cipherBin, err := Encrypt([]byte(key), []byte(text))
	return hex.EncodeToString(cipherBin), err
}
func DecryptStr(key, text string) (string, error) {
	ciphyBin, err := hex.DecodeString(text)
	if err != nil {
		return "", err
	}
	plainBin, err := Decrypt([]byte(key), ciphyBin)
	return string(plainBin), err

}

func Encrypt(key, text []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	b := base64.StdEncoding.EncodeToString(text)
	ciphertext := make([]byte, aes.BlockSize+len(b))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return nil, err
	}
	cfb := cipher.NewCFBEncrypter(block, iv)
	cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))
	return ciphertext, nil
}

func Decrypt(key, text []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	if len(text) < aes.BlockSize {
		return nil, errors.New("ciphertext too short")
	}
	iv := text[:aes.BlockSize]
	text = text[aes.BlockSize:]
	cfb := cipher.NewCFBDecrypter(block, iv)
	cfb.XORKeyStream(text, text)
	data, err := base64.StdEncoding.DecodeString(string(text))
	if err != nil {
		return nil, err
	}
	return data, nil
}


text:
package kalang.compiler.compile.semantic;

/**
 *
 * @author Kason Yang
 */
public class FieldNotFoundException extends RuntimeException{

    public FieldNotFoundException(String message) {
        super(message);
    }

}


text:
layout: single
elementName: hgroup
---

          Type: block

        Self-closing:

            No

      Permalink
      Share
      MDN

        #
        hgroup

        Experimental

Defines the heading of a section. It can only contain heading levels: <h1> <h2> <h3> <h4> <h5> <h6>

          Example:
          Copy

<hgroup>

{{site.title}}

{{site.description}}

</hgroup>

{% highlight html %}<hgroup>

{{site.title}}

{{site.description}}

</hgroup>{% endhighlight %}


text:
namespace GitDiffMargin
{
    using System.ComponentModel.Composition;
    using Microsoft.VisualStudio.Editor;
    using Microsoft.VisualStudio.Shell;
    using Microsoft.VisualStudio.Text.Editor;
    using Microsoft.VisualStudio.TextManager.Interop;
    using Microsoft.VisualStudio.Utilities;

    [Export(typeof(IVsTextViewCreationListener))]
    [ContentType("text")]
    [TextViewRole(PredefinedTextViewRoles.Editable)]
    internal class GitDiffMarginTextViewCreationListener : IVsTextViewCreationListener
    {
        private readonly SVsServiceProvider _serviceProvider;
        private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService;

        [ImportingConstructor]
        public GitDiffMarginTextViewCreationListener(SVsServiceProvider serviceProvider, IVsEditorAdaptersFactoryService editorAdaptersFactoryService)
        {
            _serviceProvider = serviceProvider;
            _editorAdaptersFactoryService = editorAdaptersFactoryService;
        }

        public void VsTextViewCreated(IVsTextView textViewAdapter)
        {
            ITextView textView = _editorAdaptersFactoryService.GetWpfTextView(textViewAdapter);
            if (textView == null)
                return;

            GitDiffMarginCommandHandler filter = new GitDiffMarginCommandHandler(textViewAdapter, _editorAdaptersFactoryService, textView);
            filter.Enabled = true;
            textView.Properties.AddProperty(typeof(GitDiffMarginCommandHandler), filter);
        }
    }
}


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

namespace dk.nita.saml20.Schema.Core
{
    /// <summary>
    /// The <SubjectLocality> element specifies the DNS domain name and IP address for the system from
    /// which the assertion subject was authenticated. It has the following attributes:
    /// </summary>
    [Serializable]
    [XmlType(Namespace=Saml20Constants.ASSERTION)]
    [XmlRoot(ELEMENT_NAME, Namespace = Saml20Constants.ASSERTION, IsNullable = false)]
    public class SubjectLocality
    {
        /// <summary>
        /// The XML Element name of this class
        /// </summary>
        public const string ELEMENT_NAME = "SubjectLocality";

        private string addressField;

        private string dNSNameField;

        /// <summary>
        /// Gets or sets the address.
        /// The network address of the system from which the principal identified by the subject was
        /// authenticated. IPv4 addresses SHOULD be represented in dotted-decimal format (e.g., "1.2.3.4").
        /// IPv6 addresses SHOULD be represented as defined by Section 2.2 of IETF RFC 3513 [RFC 3513]
        /// (e.g., "FEDC:BA98:7654:3210:FEDC:BA98:7654:3210").
        /// </summary>
        /// <value>The address.</value>
        [XmlAttributeAttribute]
        public string Address
        {
            get { return addressField; }
            set { addressField = value; }
        }

        /// <summary>
        /// Gets or sets the name of the DNS.
        /// The DNS name of the system from which the principal identified by the subject was authenticated.
        /// </summary>
        /// <value>The name of the DNS.</value>
        [XmlAttributeAttribute]
        public string DNSName
        {
            get { return dNSNameField; }
            set { dNSNameField = value; }
        }
    }
}


text:
package com.example.anvil.databinding;

import android.content.Context;
import android.widget.LinearLayout;
import android.widget.SeekBar;

import static trikita.anvil.DSL.*;
import trikita.anvil.RenderableView;

public class SeekBarLayout extends RenderableView {

    int value = 0;

    public SeekBarLayout(Context c) {
        super(c);
    }

    @Override
    public void view() {
        linearLayout(() -> {
            size(FILL, FILL);
            orientation(LinearLayout.VERTICAL);

            seekBarLayout();
            seekBarLayout();
        });
    }

    private void seekBarLayout() {
        seekBar(() -> {
            size(FILL, WRAP);
            margin(dip(40));
            progress(value);
            onSeekBarChange((sb, progress, fromUser) -> {
                if (fromUser) {
                    value = progress;
                }
            });
        });
    }
}


text:
import React, { Component } from 'react';
import {NativeModules, AsyncStorage} from 'react-native';
import {StackNavigator} from 'react-navigation';
import styles from './styles';
import TabNav from './TabNav';

import init from './modules/init';
import listener from './modules/listener';
import message from './modules/message';
import subscriptions from './modules/subscription';

listener();

const AppNavigator = StackNavigator(
    {
        'AppTabs': {
            screen: TabNav
        }
    },
    {
        initialRouteName: 'AppTabs'
    }
);

export default class App extends Component {
    constructor(){
        super();
        message.clearOldMessages();
    }

    componentDidMount(){
        AsyncStorage.getItem('initialized', (err, result) => {
            if(!result){
                init(); //set up permissions and subs if first time app is run
            }
        });
    }

    render() {
        return (
            <AppNavigator />
        );
    }
}


text:
package com.yattatech.util;

import java.util.Comparator;
import com.yattatech.domain.Couple;

/**
 * Comparator that orders a list of couple by husband name
 * in ascending order
 *
 * @author Adriano Braga Alencar (adrianobragaalencar@gmail.com)
 *
 */
public final class CoupleNameComparator implements Comparator<Couple> {

    @Override
    public int compare(Couple lh, Couple rh) {
        if (lh == null) {
            return rh == null ? 0 : 1;
        } else if (rh == null) {
            return -1;
        }
        return lh.getName().compareTo(rh.getName());
    }
}


text:
from pandac.PandaModules import *
from toontown.toonbase.ToontownBattleGlobals import *
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.PyDatagram import PyDatagram
from direct.distributed.PyDatagramIterator import PyDatagramIterator
from otp.otpbase import OTPGlobals

class Experience:
    notify = DirectNotifyGlobal.directNotify.newCategory('Experience')

    def __init__(self, expStr = None, owner = None):
        self.owner = owner
        if expStr == None:
            self.experience = []
            for track in range(0, len(Tracks)):
                self.experience.append(StartingLevel)

        else:
            self.experience = self.makeFromNetString(expStr)
        return

    def __str__(self):
        return str(self.experience)

    def makeNetString(self):
        dataList = self.experience
        datagram = PyDatagram()
        for track in range(0, len(Tracks)):
            datagram.addUint16(dataList[track])

        dgi = PyDatagramIterator(datagram)
        return dgi.getRemainingBytes()

    def makeFromNetString(self, netString):
        dataList = []
        dg = PyDatagram(netString)
        dgi = PyDatagramIterator(dg)
        for track in range(0, len(Tracks)):
            dataList.append(dgi.getUint16())

        return dataList

    def addExp(self, track, amount = 1):
        if type(track) == type(''):
            track = Tracks.index(track)
        self.notify.debug('adding %d exp to track %d' % (amount, track))
        if self.owner.getGameAccess() == OTPGlobals.AccessFull:
            if self.experience[track] + amount <= MaxSkill:
                self.experience[track] += amount
            else:
                self.experience[track] = MaxSkill
        elif self.experience[track] + amount <= UnpaidMaxSkills[track]:
            self.experience[track] += amount
        elif self.experience[track] > UnpaidMaxSkills[track]:
            self.experience[track] += 0
        else:
            self.experience[track] = UnpaidMaxSkills[track]

    def maxOutExp(self):
        for track in range(0, len(Tracks)):
            self.experience[track] = MaxSkill - UberSkill

    def maxOutExpMinusOne(self):
        for track in range(0, len(Tracks)):
            self.experience[track] = MaxSkill - 1

    def makeExpHigh(self):
        for track in range(0, len(Tracks)):
            self.experience[track] = Levels[track][len(Levels[track]) - 1] - 1

    def makeExpRegular(self):
        import random
        for track in range(0, len(Tracks)):
            rank = random.choice((0, int(random.random() * 1500.0), int(random.random() * 2000.0)))
            self.experience[track] = Levels[track][len(Levels[track]) - 1] - rank

    def zeroOutExp(self):
        for track in range(0, len(Tracks)):
            self.experience[track] = StartingLevel

    def setAllExp(self, num):
        for track in range(0, len(Tracks)):
            self.experience[track] = num

    def getExp(self, track):
        if type(track) == type(''):
            track = Tracks.index(track)
        return self.experience[track]

    def setExp(self, track, exp):
        if type(track) == type(''):
            track = Tracks.index(track)
        self.experience[track] = exp

    def getExpLevel(self, track):
        if type(track) == type(''):
            track = Tracks.index(track)
        level = 0
        for amount in Levels[track]:
            if self.experience[track] >= amount:
                level = Levels[track].index(amount)

        return level

    def getTotalExp(self):
        total = 0
        for level in self.experience:
            total += level

        return total

    def getNextExpValue(self, track, curSkill = None):
        if curSkill == None:
            curSkill = self.experience[track]
        retVal = Levels[track][len(Levels[track]) - 1]
        for amount in Levels[track]:
            if curSkill < amount:
                retVal = amount
                return retVal

        return retVal

    def getNewGagIndexList(self, track, extraSkill):
        retList = []
        curSkill = self.experience[track]
        nextExpValue = self.getNextExpValue(track, curSkill)
        finalGagFlag = 0
        while curSkill + extraSkill >= nextExpValue and curSkill < nextExpValue and not finalGagFlag:
            retList.append(Levels[track].index(nextExpValue))
            newNextExpValue = self.getNextExpValue(track, nextExpValue)
            if newNextExpValue == nextExpValue:
                finalGagFlag = 1
            else:
                nextExpValue = newNextExpValue

        return retList


text:
{% for p in points %}
<area shape="circle" coords="{{p.0}},{{p.1}},5" href="{{url_for('frontend.experiment_results_by_instance', database=database, experiment_id=experiment.idExperiment)}}?instance={{p.4.idInstance}}" title="{{sc}}: {{p.3|round(2)}}<br/>{{p.4.name}}" />
{% endfor %}


text:
from itty import post, Response

# Used to validate the values passed into the base url and raise errors.
from publisher.utils import check_base_url, raise_error

# Used to decode and encode post bodies that contain json encoded data.
# Note that in python 2.5 and 2.6 the json module is called simplejson.
# In Python 2.7 and onwards, json is used.
try:
    from json import loads, dumps
except ImportError:
    from simplejson import loads, dumps

# Used to authenticate a user to the data model.
from publisher.model import model

# Used to match URLs.
from constants import (AUTH, AUTH_AUTHORIZATION_HEADER)

def check_authorization_header(url, environment):
    '''
    Checks for the existence of the auth-scheme token. Note that the validate
    API entry point has a different auth-scheme token.

    Server Errors:

        This section documents errors that are persisted on the server and not
        sent to the client. Note that the publisher is free to modify the
        content of these messages as they please.

        InvalidAuthScheme:

            Returned when the publisher does not recognize the requested
            format.

            Code: InvalidAuthScheme
            Message: An error occurred. Please contact support.
            Debug: Varies with the error.
            HTTP Error Code: 400.
            Required: No
    '''
    # All of the errors in this function share a common code and status.
    code = 'InvalidAuthScheme'
    status = 400
    message = 'An error occurred. Please contact support.'

    # Make sure the token is provided.
    if 'HTTP_AUTHORIZATION' not in environment:
        debug = 'The authorization token has not been provided.'
        raise_error(url, code, message, status, debug)

    # Make sure the token's value is correct. The auth-scheme token isn't
    # important for this part of the API, but it is for others.
    if environment['HTTP_AUTHORIZATION'] != AUTH_AUTHORIZATION_HEADER:
        debug = 'The authorization token is incorrect.'
        raise_error(url, code, message, status, debug)

def decode_body(url, body):
    '''
    This function checks the validity of the body parameter. It takes the
    request body and returns python objects by decoding the body using
    json.

    Server Errors:

        This section documents errors that are persisted on the server and not
        sent to the client. Note that the publisher is free to modify the
        content of these messages as they please.

        InvalidFormat:

            Returned when the publisher does not recognize the requested
            format.

            Code: InvalidFormat
            Message: The requested article could not be found.
            Debug: Varies with the error.
            HTTP Error Code: 400.
            Required: No
    '''
    # All of the errors in this function share a common code and status.
    code = 'InvalidFormat'
    status = 400
    message = 'An error occurred. Please contact support.'

    # If the body cannot be decoded, a proper error response must be made.
    # This try except block intercepts the default exception and raises
    # a json encoded exception using the raise_error function.
    try:
        json_body = loads(body, encoding='utf-8')

    except ValueError:
        # If a ValueError occurred, the json decoder could not decode the
        # body of the request. We need to return an error to the client.
        # Note that we do not return the body of the request as it could
        # contain access credentials.
        debug = 'Could not decode post body. json is expected.'
        raise_error(url, code, message, status, debug)

    # Make sure a valid number of parameters have been provided.
    if len(json_body) < 1 or len(json_body) > 2:
        debug = 'Post body has an invalid number of parameters.'
        raise_error(url, code, message, status, debug)

    return json_body

def check_device(url, body):
    '''
    This function checks the validity of the device parameter. It takes the
    decoded json body of the request and raises an error if a problem is
    found.

    Server Errors:

        This section documents errors that are persisted on the server and not
        sent to the client. Note that the publisher is free to modify the
        content of these messages as they please.

        InvalidDevice:

            Returned when the request does not specify the device parameters
            properly.

            Code: InvalidDevice
            Message: The requested article could not be found.
            Debug: Varies with the error.
            HTTP Error Code: 400
            Required: No
    '''
    # All of the errors in this function share a common code and status.
    code = 'InvalidDevice'
    status = 400
    message = 'An error occurred. Please contact support.'

    # Validate that the device is provided as a parameter to the body. This
    # sample publisher does not store the device, but a production system
    # could store these values in order to perform analysis on the types of
    # devices that access products.
    if 'device' not in body:
        debug = 'The device has not been provided.'
        raise_error(url, code, message, status, debug)

    # Make sure the device is a dictionary.
    if not isinstance(body['device'], dict):
        debug = 'The device is not a map.'
        raise_error(url, code, message, status, debug)

    # Check to make sure that the manufacturer of the device has been
    # provided.
    if 'manufacturer' not in body['device']:
        debug = 'The manufacturer has not been provided.'
        raise_error(url, code, message, status, debug)

    # Check to make sure the manufacturer is of the right type.
    manufacturer = body['device']['manufacturer']
    if not isinstance(manufacturer, unicode) and \
       not isinstance(manufacturer, str):
        debug = 'The manufacturer is not a string.'
        raise_error(url, code, message, status, debug)

    # Check to make sure that the model of the device has been provided.
    if 'model' not in body['device']:
        debug = 'The model has not been provided.'
        raise_error(url, code, message, status, debug)

    # Check to make sure the model is of the right type.
    model = body['device']['model']
    if not isinstance(model, unicode) and \
       not isinstance(model, str):
        debug = 'The model is not a string.'
        raise_error(url, code, message, status, debug)

    # Check to make sure that the os_version of the device has been provided.
    if 'os_version' not in body['device']:
        debug = 'The os_version has not been provided.'
        raise_error(url, code, message, status, debug)

    # Check to make sure the os_version is of the right type.
    os_version = body['device']['os_version']
    if not isinstance(os_version, unicode) and \
       not isinstance(os_version, str):
        debug = 'The os_version is not a string.'
        raise_error(url, code, message, status, debug)

def check_auth_params(url, body):
    '''
    This function checks the validity of the authParams parameter as per the
    API. It takes the decoded json body of the request and raises an exception
    if a problem is found.

    The difference between check_auth_params and check_publisher_auth_params
    is that check_auth_params enforces validity to the API. In contrast,
    check_publisher_auth_params enforces validity as to this implementation.
    It checks specifically for the existence of the "username" and "password"
    fields.

    Server Errors:

        This section documents errors that are persisted on the server and not
        sent to the client. Note that the publisher is free to modify the
        content of these messages as they please.

        InvalidAuthParams:

            Returned when the request does not specify the authParams parameter
            properly.

            Code: InvalidAuthParams
            Message: An error occurred. Please contact support.
            Debug: Varies with the error.
            HTTP Error Code: 400
            Required: No
    '''
    # All of the errors in this function share a common code and status.
    code = 'InvalidAuthParams'
    status = 400
    message = 'An error occurred. Please contact support.'

    # Note that not having an authParams key is valid.
    if 'authParams' not in body:
        return

    # When authParams is provided, the type must be a dictionary.
    if not isinstance(body['authParams'], dict):
        debug = 'The authParams is not a map.'
        raise_error(url, code, message, status, debug)

    # Make sure that all the values in the dictionary are strings.
    for key in body['authParams']:
        value = body['authParams'][key]
        if not isinstance(value, unicode) and not isinstance(value, str):
            debug = 'This authParams value is not a string: ' + unicode(key)
            raise_error(url, code, message, status, debug)

def check_publisher_auth_params(url, body):
    '''
    This function checks for the existence of the authParams dictionary and
    the exiistence of the "username" and "password" keys in the authParams
    dictionary.

    The difference between check_auth_params and check_publisher_auth_params
    is that check_auth_params enforces validity to the API. In contrast,
    check_publisher_auth_params enforces validity as to this implementation.
    It checks specifically for the existence of the "username" and "password"
    fields.

    Server Errors:

        This section documents errors that are persisted on the server and not
        sent to the client. Note that the publisher is free to modify the
        content of these messages as they please.

        InvalidAuthParams:

            Returned when the request does not specify the authParams parameter
            properly.

            Code: InvalidAuthParams
            Message: An error occurred. Please contact support.
            Debug: Varies with the error.
            HTTP Error Code: 400
            Required: No
    '''
    # All of the errors in this function share a common code and status.
    code = 'InvalidAuthParams'
    status = 400
    message = 'An error occurred. Please contact support.'

    # In this implementation, authParams is required. The check for authParams
    # being a dictionary has already been carried out by check_auth_params.
    if 'authParams' not in body:
        debug = 'The authParams has not been provided.'
        raise_error(url, code, message, status, debug)

    # Make sure username is provided. The check_auth_params has already
    # checked the type of the username.
    if 'username' not in body['authParams']:
        debug = 'The username has not been provided.'
        raise_error(url, code, message, status, debug)

    # Make sure password is provided. The check_auth_params has already
    # checked the type of the password.
    if 'password' not in body['authParams']:
        debug = 'The password has not been provided.'
        raise_error(url, code, message, status, debug)

@post(AUTH)
def auth(request, api, version, format, product_code):
    '''
    Overview:

        Attempt an authentication for a product using supplied credentials. If
        successful, a session key is obtained that can be used for requests to
        protected resources/content. The base URL scheme for this entry point
        is:

            /:api/:version/:format/auth/:productcode

        In this particular case, the api is "paywallproxy" and the version is
        v1.0.0. Currently, the only supported format is "json". The URL for
        this entry point therefore looks like:

            /paywallproxy/v1.0.0/json/auth/:productcode

        If the product cannot be found, an "InvalidProduct" error should be
        returned. This error will be returned to the client. A full list of
        errors that this entry point returns is available below. Client errors
        are proxied to the client. Server errors remain on Polar's server.

        An auth-scheme token is expected when a call is made to this API end
        point. It must conform to RFC 2617 specifications. The authorization
        header has the following form:

            Authorization: PolarPaywallProxyAuthv1.0.0

    Parameters:

        There are two sets of parameters that this API entry point requires.
        The first set consists of the product code, which is specified in the
        URL and the post body, which contains formatted json. Technical details
        will follow after a description of the parameters and an example will
        follow after that.

        The product code is part of the URL. It is a publisher-assigned unique
        identifier for this product. The product code is required.

        The post body is a json map with two keys. The first key is "device",
        which is a json map describing the device requesting authorization.
        This key is required. The second key is "authParams", which is
        optional.

        The "device" map contains three keys. "manufacturer" is the full name
        of the device manufacturer. "model" is the device's model number and
        name. "os_version" is a string that describes the version of the
        device's operating system.

        The contents of the "authParams" map will vary based on the settings
        on the Polar server. The keys of the map is the name of the parameter
        set on the server. The values of the map is the value entered by the
        user.

        Details regarding the various parameters are described below.

        Product Code:

            A publisher-assigned unique identifier for this product.

            Availability: >= v1.0.0
            Required: Yes
            Location: URL
            Format: URL
            Type: String
            Max Length: 256

        device:

            A json map describing the device requesting authorization.

            Availability: >= v1.0.0
            Required: Yes
            Location: POST Body
            Format: json
            Type: json map
            Max Length: N/A

        manufacturer:

            The full name of the device manufacturer. Contained in the "device"
            map.

            Availability: >= v1.0.0
            Required: Yes
            Location: POST Body
            Format: json
            Type: string
            Max Length: 256

        model:

            The device's model number and name. Contained in the "device" map.

            Availability: >= v1.0.0
            Required: Yes
            Location: POST Body
            Format: json
            Type: string
            Max Length: 256

        os_version:

            The version of the device's operating system. Contained in the
            "device" map.

            Availability: >= v1.0.0
            Required: Yes
            Location: POST Body
            Format: json
            Type: string
            Max Length: 256

        authParams:

            A map of the authentication parameters and their values.

            Availability: >= v1.0.0
            Required: Yes
            Location: POST Body
            Format: json
            Type: map
            Max Length: N/A

        authParams key:

            The name of the authentication parameter. Contained in the
            "authParams" map.

            Availability: >= v1.0.0
            Required: Yes
            Location: POST Body
            Format: json
            Type: string
            Max Length: 256

        authParams value:

            The user entered value of the authentication parameter. Contained
            in the "authParams" map.

            Availability: >= v1.0.0
            Required: Yes
            Location: POST Body
            Format: json
            Type: string
            Max Length: 512

    Response:

        The following parameters are returned by this API end point. The
        resposne is json encoded. It has two keys; "sessionKey" and "products".
        "sessionKey" is a key that allows the client to re-authenticate without
        the supplied authentication parameters. "products" is a list of product
        identifiers that the user has access to.

        sessionKey:

            A key that allows the client to re-authenticate without the
            supplied authentication parameters.

            Availability: >= v1.0.0
            Required: Yes
            Location: POST Body
            Format: json
            Type: string
            Max Length: 512

        products:

            A list of product identifiers that the user has access to.

            Availability: >= v1.0.0
            Required: Yes
            Location: POST Body
            Format: json
            Type: list
            Max Length: N/A

        product:

            A publisher-assigned unique identifier for this product that the
            user has access to. Contained in the "products" list.

            Availability: >= v1.0.0
            Required: Yes
            Location: POST Body
            Format: json
            Type: string
            Max Length: 256

    Example:

        Example Request:

            POST /paywallproxy/v1.0.0/json/auth/gold-level HTTP/1.1
            Authorization: PolarPaywallAuthv1.0.0 123:x
            Content-Type: application/json

            {
                "device": {
                    "manufacturer": "Phake Phones Inc.",
                    "model": "90",
                    "os_version": "1.1.1"
                },

                "authParams": {
                    "username": "polar",
                    "password": "mobile"
                }
            }

        Example Response:

            HTTP/1.1 200 OK
            Content-Type: application/json

            {
                "sessionKey": "9c4a51cc08d1879570c",

                "products": [
                    "gold-level",
                    "silver-level"
                ]
            }

    Errors:

        Some of the following errors are marked optional. They are included in
        this example for completeness and testing purposes. Implementing them
        makes testing the connection between Polar's server and the publishers
        server easier.

        InvalidPaywallCredentials:

            Thrown when the authentication parameters are invalid.

            Code: InvalidPaywallCredentials
            Message: Varies with the error.
            HTTP Error Code: 401
            Required: Yes

        AccountProblem:

            There is a problem with the user's account. The user is
            prompted to contact technical support.

            Code: AccountProblem
            Message: Your account is not valid. Please contact support.
            HTTP Error Code: 403
            Required: Yes

        InvalidProduct:

            Thrown when the product code indicated is invalid.

            Code: InvalidProduct
            Message: The requested article could not be found.
            HTTP Error Code: 404
            Required: Yes

        InvalidAPI:

            Returned when the publisher does not recognize the requested api.

            Code: InvalidAPI
            Message: An error occurred. Please contact support.
            Debug: The requested api is not implemented: <api>
            HTTP Error Code: 404
            Required: No

        InvalidVersion:

            Returned when the publisher does not recognize the requested
            version.

            Code: InvalidVersion
            Message: An error occurred. Please contact support.
            Debug: The requested version is not implemented: <version>
            HTTP Error Code: 404
            Required: No

        InvalidFormat:

            Returned when the publisher does not recognize the requested
            format.

            Code: InvalidFormat
            Message: An error occurred. Please contact support.
            Debug: The requested format is not implemented: <format>
            HTTP Error Code: 404
            Required: No

        InvalidDevice:

            Returned when the request does not specify the device parameters
            properly.

            Code: InvalidDevice
            Message: An error occurred. Please contact support.
            Debug: Varies with the error.
            HTTP Error Code: 400
            Required: No

        InvalidAuthParams:

            Returned when the request does not specify the authParams parameter
            properly.

            Code: InvalidAuthParams
            Message: An error occurred. Please contact support.
            Debug: Varies with the error.
            HTTP Error Code: 400
            Required: No

        InvalidAuthScheme:

            Returned when the publisher does not recognize the requested
            format.

            Code: InvalidAuthScheme
            Message: An error occurred. Please contact support.
            Debug: Varies with the error.
            HTTP Error Code: 400.
            Required: No
    '''
    # Store the full URL string so that it can be used to report errors.
    url = request.path

    # Validate the request and its headers.
    check_base_url(url, api, version, format)
    check_authorization_header(url, request._environ)

    # Validate the request body.
    body = decode_body(url, request.body)
    check_device(url, body)
    check_auth_params(url, body)

    # Note that the authentication parameters that will be passed into this
    # service are configurable through Polar's server. The function
    # check_publisher_auth_params ensures that the authentication parameters
    # specific to this publisher's implementation (username, password) exist
    # and are strings.
    check_publisher_auth_params(url, body)
    username = body['authParams']['username']
    password = body['authParams']['password']

    # Authenticate the user to get the session id and the products.
    (session_id, products) = model().authenticate_user(url, username, password,
                                                                  product_code)

    # Create the response body.
    result = {}
    result['sessionKey'] = session_id
    result['products'] = products
    content = dumps(result)

    status = 200
    headers = []
    content_type = 'application/json'
    return Response(content, headers, status, content_type)