text:
package org.springframework.orm.jpa.vendor;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;

import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.NonUniqueObjectException;
import org.hibernate.NonUniqueResultException;
import org.hibernate.ObjectDeletedException;
import org.hibernate.OptimisticLockException;
import org.hibernate.PersistentObjectException;
import org.hibernate.PessimisticLockException;
import org.hibernate.PropertyValueException;
import org.hibernate.QueryException;
import org.hibernate.QueryTimeoutException;
import org.hibernate.Session;
import org.hibernate.StaleObjectStateException;
import org.hibernate.StaleStateException;
import org.hibernate.TransientObjectException;
import org.hibernate.UnresolvableObjectException;
import org.hibernate.WrongClassException;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.DataException;
import org.hibernate.exception.JDBCConnectionException;
import org.hibernate.exception.LockAcquisitionException;
import org.hibernate.exception.SQLGrammarException;

import org.springframework.dao.CannotAcquireLockException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.dao.InvalidDataAccessResourceUsageException;
import org.springframework.dao.PessimisticLockingFailureException;
import org.springframework.jdbc.datasource.ConnectionHandle;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.jpa.DefaultJpaDialect;
import org.springframework.orm.jpa.EntityManagerFactoryUtils;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.transaction.InvalidIsolationLevelException;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;

/**
 * {@link org.springframework.orm.jpa.JpaDialect} implementation for
 * Hibernate EntityManager. Developed against Hibernate 3.6 and 4.2/4.3.
 *
 * @author Juergen Hoeller
 * @author Costin Leau
 * @since 2.0
 */
@SuppressWarnings({"serial", "deprecation"})
public class HibernateJpaDialect extends DefaultJpaDialect {

	private static Class<?> optimisticLockExceptionClass;

	private static Class<?> pessimisticLockExceptionClass;

	static {
		// Checking for Hibernate 4.x's Optimistic/PessimisticEntityLockException
		ClassLoader cl = HibernateJpaDialect.class.getClassLoader();
		try {
			optimisticLockExceptionClass = cl.loadClass("org.hibernate.dialect.lock.OptimisticEntityLockException");
		}
		catch (ClassNotFoundException ex) {
			// OptimisticLockException is deprecated on Hibernate 4.x; we're just using it on 3.x anyway
			optimisticLockExceptionClass = OptimisticLockException.class;
		}
		try {
			pessimisticLockExceptionClass = cl.loadClass("org.hibernate.dialect.lock.PessimisticEntityLockException");
		}
		catch (ClassNotFoundException ex) {
			pessimisticLockExceptionClass = null;
		}
	}

	private boolean prepareConnection = (HibernateConnectionHandle.sessionConnectionMethod == null);

	/**
	 * Set whether to prepare the underlying JDBC Connection of a transactional
	 * Hibernate Session, that is, whether to apply a transaction-specific
	 * isolation level and/or the transaction's read-only flag to the underlying
	 * JDBC Connection.
	 *
Default is "true" on Hibernate EntityManager 4.x (with its 'on-close'
	 * connection release mode, and "false" on Hibernate EntityManager 3.6 (due to
	 * the 'after-transaction' release mode there). Note that Hibernate 4.2+ is
	 * strongly recommended in order to make isolation levels work efficiently.
	 *
If you turn this flag off, JPA transaction management will not support
	 * per-transaction isolation levels anymore. It will not call
	 * {@code Connection.setReadOnly(true)} for read-only transactions anymore either.
	 * If this flag is turned off, no cleanup of a JDBC Connection is required after
	 * a transaction, since no Connection settings will get modified.
	 *
NOTE: The default behavior in terms of read-only handling changed
	 * in Spring 4.1, propagating the read-only status to the JDBC Connection now,
	 * analogous to other Spring transaction managers. This may have the effect
	 * that you're running into read-only enforcement now where previously write
	 * access has accidentally been tolerated: Please revise your transaction
	 * declarations accordingly, removing invalid read-only markers if necessary.
	 * @since 4.1
	 * @see java.sql.Connection#setTransactionIsolation
	 * @see java.sql.Connection#setReadOnly
	 */
	public void setPrepareConnection(boolean prepareConnection) {
		this.prepareConnection = prepareConnection;
	}

	@Override
	public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
			throws PersistenceException, SQLException, TransactionException {

		Session session = getSession(entityManager);

		if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
			session.getTransaction().setTimeout(definition.getTimeout());
		}

		boolean isolationLevelNeeded = (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT);
		Integer previousIsolationLevel = null;
		boolean resetConnection = false;

		if (isolationLevelNeeded || definition.isReadOnly()) {
			if (this.prepareConnection) {
				Connection con = HibernateConnectionHandle.doGetConnection(session);
				previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
				resetConnection = true;
			}
			else if (isolationLevelNeeded) {
				throw new InvalidIsolationLevelException(getClass().getSimpleName() +
						" does not support custom isolation levels since the 'prepareConnection' flag is off. " +
						"This is the case on Hibernate 3.6 by default; either switch that flag at your own risk " +
						"or upgrade to Hibernate 4.x, with 4.2+ recommended.");
			}
		}

		// Standard JPA transaction begin call for full JPA context setup...
		entityManager.getTransaction().begin();

		// Adapt flush mode and store previous isolation level, if any.
		FlushMode previousFlushMode = prepareFlushMode(session, definition.isReadOnly());
		return new SessionTransactionData(session, previousFlushMode, resetConnection, previousIsolationLevel);
	}

	@Override
	public Object prepareTransaction(EntityManager entityManager, boolean readOnly, String name)
			throws PersistenceException {

		Session session = getSession(entityManager);
		FlushMode previousFlushMode = prepareFlushMode(session, readOnly);
		return new SessionTransactionData(session, previousFlushMode, false, null);
	}

	protected FlushMode prepareFlushMode(Session session, boolean readOnly) throws PersistenceException {
		FlushMode flushMode = session.getFlushMode();
		if (readOnly) {
			// We should suppress flushing for a read-only transaction.
			if (!flushMode.equals(FlushMode.MANUAL)) {
				session.setFlushMode(FlushMode.MANUAL);
				return flushMode;
			}
		}
		else {
			// We need AUTO or COMMIT for a non-read-only transaction.
			if (flushMode.lessThan(FlushMode.COMMIT)) {
				session.setFlushMode(FlushMode.AUTO);
				return flushMode;
			}
		}
		// No FlushMode change needed...
		return null;
	}

	@Override
	public void cleanupTransaction(Object transactionData) {
		((SessionTransactionData) transactionData).resetSessionState();
	}

	@Override
	public ConnectionHandle getJdbcConnection(EntityManager entityManager, boolean readOnly)
			throws PersistenceException, SQLException {

		Session session = getSession(entityManager);
		return new HibernateConnectionHandle(session);
	}

	@Override
	public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
		if (ex instanceof HibernateException) {
			return convertHibernateAccessException((HibernateException) ex);
		}
		if (ex instanceof PersistenceException && ex.getCause() instanceof HibernateException) {
			return convertHibernateAccessException((HibernateException) ex.getCause());
		}
		return EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ex);
	}

	/**
	 * Convert the given HibernateException to an appropriate exception
	 * from the {@code org.springframework.dao} hierarchy.
	 * @param ex HibernateException that occurred
	 * @return the corresponding DataAccessException instance
	 */
	protected DataAccessException convertHibernateAccessException(HibernateException ex) {
		if (ex instanceof JDBCConnectionException) {
			return new DataAccessResourceFailureException(ex.getMessage(), ex);
		}
		if (ex instanceof SQLGrammarException) {
			SQLGrammarException jdbcEx = (SQLGrammarException) ex;
			return new InvalidDataAccessResourceUsageException(ex.getMessage() + "; SQL [" + jdbcEx.getSQL() + "]", ex);
		}
		if (ex instanceof QueryTimeoutException) {
			QueryTimeoutException jdbcEx = (QueryTimeoutException) ex;
			return new org.springframework.dao.QueryTimeoutException(ex.getMessage() + "; SQL [" + jdbcEx.getSQL() + "]", ex);
		}
		if (ex instanceof LockAcquisitionException) {
			LockAcquisitionException jdbcEx = (LockAcquisitionException) ex;
			return new CannotAcquireLockException(ex.getMessage() + "; SQL [" + jdbcEx.getSQL() + "]", ex);
		}
		if (ex instanceof PessimisticLockException) {
			PessimisticLockException jdbcEx = (PessimisticLockException) ex;
			return new PessimisticLockingFailureException(ex.getMessage() + "; SQL [" + jdbcEx.getSQL() + "]", ex);
		}
		if (ex instanceof ConstraintViolationException) {
			ConstraintViolationException jdbcEx = (ConstraintViolationException) ex;
			return new DataIntegrityViolationException(ex.getMessage()  + "; SQL [" + jdbcEx.getSQL() +
					"]; constraint [" + jdbcEx.getConstraintName() + "]", ex);
		}
		if (ex instanceof DataException) {
			DataException jdbcEx = (DataException) ex;
			return new DataIntegrityViolationException(ex.getMessage() + "; SQL [" + jdbcEx.getSQL() + "]", ex);
		}
		// end of JDBCException subclass handling

		if (ex instanceof QueryException) {
			return new InvalidDataAccessResourceUsageException(ex.getMessage(), ex);
		}
		if (ex instanceof NonUniqueResultException) {
			return new IncorrectResultSizeDataAccessException(ex.getMessage(), 1, ex);
		}
		if (ex instanceof NonUniqueObjectException) {
			return new DuplicateKeyException(ex.getMessage(), ex);
		}
		if (ex instanceof PropertyValueException) {
			return new DataIntegrityViolationException(ex.getMessage(), ex);
		}
		if (ex instanceof PersistentObjectException) {
			return new InvalidDataAccessApiUsageException(ex.getMessage(), ex);
		}
		if (ex instanceof TransientObjectException) {
			return new InvalidDataAccessApiUsageException(ex.getMessage(), ex);
		}
		if (ex instanceof ObjectDeletedException) {
			return new InvalidDataAccessApiUsageException(ex.getMessage(), ex);
		}
		if (ex instanceof UnresolvableObjectException) {
			UnresolvableObjectException hibEx = (UnresolvableObjectException) ex;
			return new ObjectRetrievalFailureException(hibEx.getEntityName(), hibEx.getIdentifier(), ex.getMessage(), ex);
		}
		if (ex instanceof WrongClassException) {
			WrongClassException hibEx = (WrongClassException) ex;
			return new ObjectRetrievalFailureException(hibEx.getEntityName(), hibEx.getIdentifier(), ex.getMessage(), ex);
		}
		if (ex instanceof StaleObjectStateException) {
			StaleObjectStateException hibEx = (StaleObjectStateException) ex;
			return new ObjectOptimisticLockingFailureException(hibEx.getEntityName(), hibEx.getIdentifier(), ex);
		}
		if (ex instanceof StaleStateException) {
			return new ObjectOptimisticLockingFailureException(ex.getMessage(), ex);
		}
		if (optimisticLockExceptionClass.isInstance(ex)) {
			return new ObjectOptimisticLockingFailureException(ex.getMessage(), ex);
		}
		if (pessimisticLockExceptionClass != null && pessimisticLockExceptionClass.isInstance(ex)) {
			if (ex.getCause() instanceof LockAcquisitionException) {
				return new CannotAcquireLockException(ex.getMessage(), ex.getCause());
			}
			return new PessimisticLockingFailureException(ex.getMessage(), ex);
		}

		// fallback
		return new JpaSystemException(ex);
	}

	protected Session getSession(EntityManager entityManager) {
		return entityManager.unwrap(Session.class);
	}

	private static class SessionTransactionData {

		private final Session session;

		private final FlushMode previousFlushMode;

		private final boolean resetConnection;

		private final Integer previousIsolationLevel;

		public SessionTransactionData(
				Session session, FlushMode previousFlushMode, boolean resetConnection, Integer previousIsolationLevel) {
			this.session = session;
			this.previousFlushMode = previousFlushMode;
			this.resetConnection = resetConnection;
			this.previousIsolationLevel = previousIsolationLevel;
		}

		public void resetSessionState() {
			if (this.previousFlushMode != null) {
				this.session.setFlushMode(this.previousFlushMode);
			}
			if (this.resetConnection && this.session.isConnected()) {
				Connection con = HibernateConnectionHandle.doGetConnection(this.session);
				DataSourceUtils.resetConnectionAfterTransaction(con, this.previousIsolationLevel);
			}
		}
	}

	private static class HibernateConnectionHandle implements ConnectionHandle {

		// This will find a corresponding method on Hibernate 3.x but not on 4.x
		private static final Method sessionConnectionMethod =
				ClassUtils.getMethodIfAvailable(Session.class, "connection");

		private static volatile Method connectionMethodToUse = sessionConnectionMethod;

		private final Session session;

		public HibernateConnectionHandle(Session session) {
			this.session = session;
		}

		@Override
		public Connection getConnection() {
			return doGetConnection(this.session);
		}

		@Override
		public void releaseConnection(Connection con) {
			if (sessionConnectionMethod != null) {
				// Need to explicitly call close() with Hibernate 3.x in order to allow
				// for eager release of the underlying physical Connection if necessary.
				// However, do not do this on Hibernate 4.2+ since it would return the
				// physical Connection to the pool right away, making it unusable for
				// further operations within the current transaction!
				JdbcUtils.closeConnection(con);
			}
		}

		public static Connection doGetConnection(Session session) {
			try {
				if (connectionMethodToUse == null) {
					// Reflective lookup to find SessionImpl's connection() method on Hibernate 4.x
					connectionMethodToUse = session.getClass().getMethod("connection");
				}
				return (Connection) ReflectionUtils.invokeMethod(connectionMethodToUse, session);
			}
			catch (NoSuchMethodException ex) {
				throw new IllegalStateException("Cannot find connection() method on Hibernate Session", ex);
			}
		}
	}

}


text:
============
Installation
============

At the command line::

    $ easy_install packingtape

Or, if you have virtualenvwrapper installed::

    $ mkvirtualenv packingtape
    $ pip install packingtape

redpajama_set_name: RedPajamaGithub


text:
<?php namespace Arcanedev\LaravelTracker\Contracts\Models;

/**
 * Interface  RoutePathParameter
 *
 * @package   Arcanedev\LaravelTracker\Contracts\Models
 * @author    ARCANEDEV <arcanedev.maroc@gmail.com>
 */
interface RoutePathParameter
{
    //
}


text:
This document covers configuration of the AWS Load Balancer controller

!!!warning "limitation"
    The v2.0.0+ version of AWSLoadBalancerController currently only support one controller deployment(with one or multiple replicas) per cluster.

    The AWSLoadBalancerController assumes it's the solo owner of worker node security group rules with `elbv2.k8s.aws/targetGroupBinding=shared` description, running multiple controller deployment will cause these controllers compete with each other updating worker node security group rules.

    We will remove this limitation in future versions: [tracking issue](https://github.com/kubernetes-sigs/aws-load-balancer-controller/issues/2185)

## AWS API Access
To perform operations, the controller must have required IAM role capabilities for accessing and
provisioning ALB resources. There are many ways to achieve this, such as loading `AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY` as environment variables or using [kube2iam](https://github.com/jtblin/kube2iam).

Refer to the [installation guide](installation.md) for installing the controller in your kubernetes cluster and for the minimum required IAM permissions.

## Setting Ingress Resource Scope
You can limit the ingresses ALB ingress controller controls by combining following two approaches:

### Limiting ingress class
Setting the `--ingress-class` argument constrains the controller's scope to ingresses with matching `ingressClassName` field.

An example of the container spec portion of the controller, only listening for resources with the class "alb", would be as follows.

```yaml
spec:
  containers:
  - args:
    - --ingress-class=alb
```

Now, only ingress resources with the appropriate class are picked up, as seen below.

```yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: echoserver
  namespace: echoserver
spec:
  ingressClassName: alb
  ...
```

If the ingress class is not specified, the controller will reconcile Ingress objects without the ingress class specified or ingress class `alb`.

### Limiting Namespaces
Setting the `--watch-namespace` argument constrains the controller's scope to a single namespace. Ingress events outside of the namespace specified are not be seen by the controller.

An example of the container spec, for a controller watching only the `default` namespace, is as follows.

```yaml
spec:
  containers:
  - args:
    - --watch-namespace=default
```

!!!note ""
Currently, you can set only 1 namespace to watch in this flag. See [this Kubernetes issue](https://github.com/kubernetes/contrib/issues/847) for more details.

## Controller command line flags

!!!warning ""
    The --cluster-name flag is mandatory and the value must match the name of the kubernetes cluster. If you specify an incorrect name, the subnet auto-discovery will not work.

|Flag                                   | Type                            | Default         | Description |
|---------------------------------------|---------------------------------|-----------------|-------------|
|aws-api-endpoints                      | AWS API Endpoints Config        |                 | AWS API endpoints mapping, format: serviceID1=URL1,serviceID2=URL2 |
|aws-api-throttle                       | AWS Throttle Config             | [default value](#default-throttle-config ) | throttle settings for AWS APIs, format: serviceID1:operationRegex1=rate:burst,serviceID2:operationRegex2=rate:burst |
|aws-max-retries                        | int                             | 10              | Maximum retries for AWS APIs |
|aws-region                             | string                          | [instance metadata](#instance-metadata)    | AWS Region for the kubernetes cluster |
|aws-vpc-id                             | string                          | [instance metadata](#instance-metadata)    | AWS VPC ID for the Kubernetes cluster |
|backend-security-group                 | string                          |                 | Backend security group id to use for the ingress rules on the worker node SG|
|cluster-name                           | string                          |                 | Kubernetes cluster name|
|default-ssl-policy                     | string                          | ELBSecurityPolicy-2016-08 | Default SSL Policy that will be applied to all Ingresses or Services that do not have the SSL Policy annotation |
|default-tags                           | stringMap                       |                 | AWS Tags that will be applied to all AWS resources managed by this controller. Specified Tags takes highest priority |
|[disable-ingress-class-annotation](#disable-ingress-class-annotation)       | boolean                         | false           | Disable new usage of the `kubernetes.io/ingress.class` annotation |
|[disable-ingress-group-name-annotation](#disable-ingress-group-name-annotation)  | boolean                         | false           | Disallow new use of the `alb.ingress.kubernetes.io/group.name` annotation |
|disable-restricted-sg-rules            | boolean                         | false            | Disable the usage of restricted security group rules |
|enable-backend-security-group          | boolean                         | true            | Enable sharing of security groups for backend traffic |
|enable-endpoint-slices                 | boolean                         | false           | Use EndpointSlices instead of Endpoints for pod endpoint and TargetGroupBinding resolution for load balancers with IP targets. |
|enable-leader-election                 | boolean                         | true            | Enable leader election for the load balancer controller manager. Enabling this will ensure there is only one active controller manager |
|enable-pod-readiness-gate-inject       | boolean                         | true            | If enabled, targetHealth readiness gate will get injected to the pod spec for the matching endpoint pods |
|enable-shield                          | boolean                         | true            | Enable Shield addon for ALB |
|enable-waf                             | boolean                         | true            | Enable WAF addon for ALB |
|enable-wafv2                           | boolean                         | true            | Enable WAF V2 addon for ALB |
|external-managed-tags                  | stringList                      |                 | AWS Tag keys that will be managed externally. Specified Tags are ignored during reconciliation |
|[feature-gates](#feature-gates)        | stringMap                       |                 | A set of key=value pairs to enable or disable features |
|health-probe-bind-addr                 | string                          | :61779          | The address the health probes binds to |
|ingress-class                          | string                          | alb             | Name of the ingress class this controller satisfies |
|ingress-max-concurrent-reconciles      | int                             | 3               | Maximum number of concurrently running reconcile loops for ingress |
|kubeconfig                             | string                          | in-cluster config | Path to the kubeconfig file containing authorization and API server information |
|leader-election-id                     | string                          | aws-load-balancer-controller-leader | Name of the leader election ID to use for this controller |
|leader-election-namespace              | string                          |                 | Name of the leader election ID to use for this controller |
|load-balancer-class                    | string                          | service.k8s.aws/nlb| Name of the load balancer class specified in service `spec.loadBalancerClass` reconciled by this controller |
|log-level                              | string                          | info            | Set the controller log level - info, debug |
|metrics-bind-addr                      | string                          | :8080           | The address the metric endpoint binds to |
|service-max-concurrent-reconciles      | int                             | 3               | Maximum number of concurrently running reconcile loops for service |
|sync-period                            | duration                        | 1h0m0s          | Period at which the controller forces the repopulation of its local object stores|
|targetgroupbinding-max-concurrent-reconciles | int                       | 3               | Maximum number of concurrently running reconcile loops for targetGroupBinding |
|targetgroupbinding-max-exponential-backoff-delay | duration              | 16m40s          | Maximum duration of exponential backoff for targetGroupBinding reconcile failures |
|watch-namespace                        | string                          |                 | Namespace the controller watches for updates to Kubernetes objects, If empty, all namespaces are watched. |
|webhook-bind-port                      | int                             | 9443            | The TCP port the Webhook server binds to |
|webhook-cert-dir                       | string                          | /tmp/k8s-webhook-server/serving-certs | The directory that contains the server key and certificate |
|webhook-cert-file                      | string                          | tls.crt | The server certificate name |
|webhook-key-file                       | string                          | tls.key | The server key name |

### disable-ingress-class-annotation
`--disable-ingress-class-annotation` controls whether to disable new usage of the `kubernetes.io/ingress.class` annotation.

Once disabled:

* you can no longer create Ingresses with the value of the `kubernetes.io/ingress.class` annotation equal to `alb` (can be overridden via `--ingress-class` flag of this controller).

* you can no longer update Ingresses to set the value of the `kubernetes.io/ingress.class` annotation equal to `alb` (can be overridden via `--ingress-class` flag of this controller).

* you can still create Ingresses with a `kubernetes.io/ingress.class` annotation that has other values (for example: "nginx")

### disable-ingress-group-name-annotation
`--disable-ingress-group-name-annotation` controls whether to disable new usage of `alb.ingress.kubernetes.io/group.name` annotation.

Once disabled:

* you can no longer create Ingresses with the `alb.ingress.kubernetes.io/group.name` annotation.
* you can no longer alter the value of an `alb.ingress.kubernetes.io/group.name` annotation on an existing Ingress.

###  throttle config

Controller uses the following default throttle config:

```
WAF Regional:^AssociateWebACL|DisassociateWebACL=0.5:1,WAF Regional:^GetWebACLForResource|ListResourcesForWebACL=1:1,WAFV2:^AssociateWebACL|DisassociateWebACL=0.5:1,WAFV2:^GetWebACLForResource|ListResourcesForWebACL=1:1,Elastic Load Balancing v2:^RegisterTargets|^DeregisterTargets=4:20,Elastic Load Balancing v2:.*=10:40
```
Client side throttling enables gradual scaling of the api calls. Additional throttle config can be specified via the `--aws-api-throttle` flag. You can get the ServiceID from the API definition in AWS SDK. For e.g, ELBv2 it is [Elastic Load Balancing v2](https://github.com/aws/aws-sdk-go/blob/main/models/apis/elasticloadbalancingv2/2015-12-01/api-2.json#L9).

Here is an example of throttle config to specify client side throttling of ELBv2 calls.

```
--aws-api-throttle=Elastic Load Balancing v2:RegisterTargets|DeregisterTargets=4:20,Elastic Load Balancing v2:.*=10:40
```

### Instance metadata
If running on EC2, the default values are obtained from the instance metadata service.

### Feature Gates
They are a set of kye=value pairs that describe AWS load balance controller features. You can use it as flags `--feature-gates=key1=value1,key2=value2`

|Features-gate Supported Key            | Type                            | Default Value   | Description |
|---------------------------------------|---------------------------------|-----------------|-------------|
| ListenerRulesTagging                  | string                          | true           | Enable or disable tagging AWS load balancer listeners and rules |
| WeightedTargetGroups                  | string                          | true           | Enable or disable weighted target groups |
| ServiceTypeLoadBalancerOnly           | string                          | false          | If enabled, controller will be limited to reconciling service of type `LoadBalancer`|
| EndpointsFailOpen                     | string                          | false          | Enable or disable allowing endpoints with `ready:unknown` state in the target groups. |
| EnableServiceController               | string                          | true           | Toggles support for `Service` type resources. |
| EnableIPTargetType                    | string                          | true           | Used to toggle support for target-type `ip` across `Ingress` and `Service` type resources. |
| SubnetsClusterTagCheck                | string                          | true           | Enable or disable the check for `kubernetes.io/cluster/${cluster-name}` during subnet auto-discovery |


text:
var irc = require('irc');

module.exports = function(options) {
    options = options || {};

    // remember these (by taking local variables)
    var server  = options.server;
    var channel = options.channel;
    var nick    = options.nick || 'connect-error-irc';

    // make an IRC Client
    var client = new irc.Client(options.server, options.nick, {
        channels: [ options.channel ],
    });

    return function errorHandler(err, req, res, next) {
        // send this error to the server
        client.say(options.channel, err);

        // console.log(err);

        // ... and pass on the original error to the next error middleware
        next(err);
    };
};

// --------------------------------------------------------------------------------------------------------------------


text:
#include "alsasource.h"
#include <QDateTime>
#include <QDebug>

namespace media {

#define PCM_OPEN_MODE 0
//#define PCM_OPEN_MODE SND_PCM_NONBLOCK

AlsaSource::AlsaSource(ElementFactory *aFactory, const QString &aObjectName) :
    ElementBase(aFactory, aObjectName),
    mPcmHandle(NULL)
    {
    setProperty("deviceName", "default");
    setProperty("sampleRate", 8000);
    setProperty("channelsNo", 2);
    }

AlsaSource::~AlsaSource()
    {
    close();
    }

void AlsaSource::open()
    {
    Q_ASSERT(!mPcmHandle);

    int res = 0;

    // Allocate a hardware parameters object
    snd_pcm_hw_params_t *hw_params;
    snd_pcm_hw_params_alloca(&hw_params);

    do
        {
        // Open PCM device
        res = snd_pcm_open(&mPcmHandle, qPrintable(mAlsaFrame.getSourceName()), SND_PCM_STREAM_CAPTURE, PCM_OPEN_MODE);
        if (res < 0)
            {
            mPcmHandle = NULL;
            break;
            }

        // Fill it in with default values
        res = snd_pcm_hw_params_any(mPcmHandle, hw_params);
        if (res < 0)
            break;

        // Set the desired hardware parameters
        res = snd_pcm_hw_params_set_access(mPcmHandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED);
        if (res < 0)
            break;

        res = snd_pcm_hw_params_set_format(mPcmHandle, hw_params, SND_PCM_FORMAT_S16_LE);
        if (res < 0)
            break;

        res = snd_pcm_hw_params_set_channels(mPcmHandle, hw_params, mAlsaFrame.getDimensionT(AlsaFrame::Channels).mResolution);
        if (res < 0)
            break;

        int dir = 0;
        Q_ASSERT(mAlsaFrame.getDimensionT(AlsaFrame::Time).mDelta);
        int rate = 1.0/mAlsaFrame.getDimensionT(AlsaFrame::Time).mDelta;
        res = snd_pcm_hw_params_set_rate(mPcmHandle, hw_params, rate, dir);
        if (res < 0)
            break;

        dir = 0;
        snd_pcm_uframes_t frameSize = rate*AlsaFrame::DefaultFrameTime;
        res = snd_pcm_hw_params_set_period_size_near(mPcmHandle, hw_params, &frameSize, &dir);
        if (res < 0)
            break;
        mAlsaFrame.setFrameTime(static_cast<double>(frameSize)/static_cast<double>(rate));

        // Write the parameters to the driver
        res = snd_pcm_hw_params(mPcmHandle, hw_params);
        if (res < 0)
            break;

        dir = 0;
        unsigned int periodTime;
        res = snd_pcm_hw_params_get_period_time(hw_params, &periodTime, &dir);
        }
    while (0);

    if ((res < 0) && mPcmHandle)
        {
        snd_pcm_close(mPcmHandle);
        mPcmHandle = NULL;
        }
//    snd_pcm_hw_params_free(hw_params);
    }

void AlsaSource::close()
    {
    if (mPcmHandle)
        {
        snd_pcm_drain(mPcmHandle);
        snd_pcm_close(mPcmHandle);
        }
    mPcmHandle = NULL;
    }

void AlsaSource::process()
    {
    if (mAlsaFrame.getSourceName() != property("deviceName").toString())
        {
        close();
        mAlsaFrame.setSourceName(property("deviceName").toString());
        qDebug() << objectName() << ": deviceName changed to " << mAlsaFrame.getSourceName();
        }
    if (mAlsaFrame.getDimensionT(AlsaFrame::Channels).mResolution != property("channelsNo").toInt())
        {
        close();
        mAlsaFrame.setChannelsNo(property("channelsNo").toInt());
        qDebug() << objectName() << ": channelsNo changed to " << mAlsaFrame.getDimensionT(AlsaFrame::Channels).mResolution;
        }
    if (property("sampleRate").toInt() &&
        (mAlsaFrame.getDimensionT(AlsaFrame::Time).mDelta != 1.0/property("sampleRate").toInt()))
        {
        close();
        mAlsaFrame.setSampleTime(1.0/property("sampleRate").toInt());
        qDebug() << objectName() << ": sampleRate changed to " << 1.0/mAlsaFrame.getDimensionT(AlsaFrame::Time).mDelta;
        }

    snd_pcm_sframes_t ret = 0;
    if (!mPcmHandle)
        open();

    if (mPcmHandle)
        {
        ret = snd_pcm_readi(mPcmHandle, mAlsaFrame.getSoundBuffer(), mAlsaFrame.getDimensionT(AlsaFrame::Time).mResolution);
        if (ret <= 0)
            qWarning() << "snd_pcm_readi returned " << ret;
        if (ret == -EPIPE)
            {
            /* EPIPE means xrun (overrun for capture)
               The overrun can happen when an application does not take new captured samples in time from alsa-lib. */
            snd_pcm_prepare(mPcmHandle);
            ret = snd_pcm_readi(mPcmHandle, mAlsaFrame.getSoundBuffer(), mAlsaFrame.getDimensionT(AlsaFrame::Time).mResolution);
            }
        if (ret > 0)
            mAlsaFrame.setTimeStamp(QDateTime::currentDateTime().toMSecsSinceEpoch()/1000.0);
        }

    if (ret > 0)
        emit framesReady();
    else
        emit processingCompleted();
    }

} // namespace media


text:
const hooks = require('./hooks');
const service = require('./service');
const transactionManager = require('./transaction-manager');

Object.assign(service, { hooks, service });

module.exports = service;
module.exports.TransactionManager = transactionManager;


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/cpg/miracles</sem:subject>
    <sem:predicate>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</sem:predicate>
    <sem:object datatype="sem:iri">http://www.w3.org/2004/02/skos/core#Concept</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/cpg/miracles</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/curriculum-planning-guide</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/cpg/miracles</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object xml:lang="eng" datatype="xsd:string">Miracles</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/cpg/miracles</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#narrower</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept/cpg/communication-between-god-and-man</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/cpg/miracles</sem:subject>
    <sem:predicate>http://www.lds.org/core#relCount</sem:predicate>
    <sem:object datatype="xsd:integer">1</sem:object>
  </sem:triple>
</sem:triples>


text:
html {
  font-family: helvetica;
  background-color: #FAFAF5;
}

body header {
  text-align: center;
  margin-bottom: 30px;
  font-size: 40px;
  text-shadow: 2px 6px 6px gray;
}
textarea {
  font-size: 20px;
  border: gray solid 2px;
  display: inline-block;
  float: left;
  margin-left: 200px;
  height: 400px;
  width: 400px;
  overflow: hidden;
  word-wrap: break-word;
  resize: none;
}

#destination {
  font-size: 20px;
  background-color: white;
  display: inline-block;
  float:right;
  margin-right: 200px;
  border: black solid 2px;
  height: 400px;
  width: 400px;
  overflow: scroll;
  word-wrap: break-word;
  resize: none;
}


text:
/*
 * EcckeyManager.hpp
 *
 *  Created on: 2016年4月9日
 *      Author: james
 */

#ifndef SRC_CORE_ECC_KEY_MANAGER_HPP_
#define SRC_CORE_ECC_KEY_MANAGER_HPP_
#include <stdint.h>
#include "Ecc_core_define.hpp"
class Ecc_Key_Manager
{
public:
    Ecc_Key_Manager();
    virtual ~Ecc_Key_Manager();

public:
    virtual int generate_key_pair() = 0;
    virtual int export_private_key() = 0;
    virtual int import_private_key() = 0;
    virtual int load_public_key()= 0;
    virtual int set_PIN_code() = 0;

private:
    virtual int save_private_key() = 0;
    virtual int load_private_key()= 0;
    virtual int save_public_key() = 0;

private:
    uint8_t private_key[PRIVATE_KEY_BYTES];
    uint8_t public_key_x[PUBLIC_KEY_BYTES];
    uint8_t public_key_y[PUBLIC_KEY_BYTES];
    uint8_t pin_code[MAX_HASH_BYTE];

};

#endif /* SRC_CORE_ECC_KEY_MANAGER_HPP_ */


text:
<?php

if ( ! class_exists( 'WP_FacebookApiException' ) ):
/**
 * Thrown when an API call returns an exception.
 *
 * @author Naitik Shah <naitik@facebook.com>
 */
class WP_FacebookApiException extends Exception
{
  /**
   * The result from the API server that represents the exception information.
   */
  protected $result;

  /**
   * Make a new API Exception with the given result.
   *
   * @param array $result The result from the API server
   */
  public function __construct($result) {
    $this->result = $result;

    //when api call fails (no available transport, i.e. cURL etc. not working), error code comes
    // out as string 'http_failure', but $code needs to be int. is_int returns false if !isset()
    $code = is_int($result['error_code']) ? $result['error_code'] : 0;

    if (isset($result['error_description'])) {
      // OAuth 2.0 Draft 10 style
      $msg = $result['error_description'];
    } else if (isset($result['error']) && is_array($result['error'])) {
      // OAuth 2.0 Draft 00 style
      $msg = $result['error']['message'];
    } else if (isset($result['error_msg'])) {
      // Rest server style
      $msg = $result['error_msg'];
    } else {
      $msg = 'Unknown Error. Check getResult()';
    }

    parent::__construct($msg, $code);
  }

  /**
   * Return the associated result object returned by the API server.
   *
   * @return array The result from the API server
   */
  public function getResult() {
    return $this->result;
  }

  /**
   * Returns the associated type for the error. This will default to
   * 'Exception' when a type is not available.
   *
   * @return string
   */
  public function getType() {
    if (isset($this->result['error'])) {
      $error = $this->result['error'];
      if (is_string($error)) {
        // OAuth 2.0 Draft 10 style
        return $error;
      } else if (is_array($error)) {
        // OAuth 2.0 Draft 00 style
        if (isset($error['type'])) {
          return $error['type'];
        }
      }
    }

    return 'Exception';
  }

  /**
   * To make debugging easier.
   *
   * @return string The string representation of the error
   */
  public function __toString() {
    $str = $this->getType() . ': ';
    if ($this->code != 0) {
      $str .= $this->code . ': ';
    }
    return $str . $this->message;
  }
}
endif;

if ( ! class_exists( 'WP_BaseFacebook' ) ):
/**
 * Provides access to the Facebook Platform.  This class provides
 * a majority of the functionality needed, but the class is abstract
 * because it is designed to be sub-classed.  The subclass must
 * implement the four abstract methods listed at the bottom of
 * the file.
 *
 * @author Naitik Shah <naitik@facebook.com>
 */
abstract class WP_BaseFacebook
{
  /**
   * Version.
   */
  const VERSION = '3.1.1';

  /**
   * List of query parameters that get automatically dropped when rebuilding
   * the current URL.
   */
  protected static $DROP_QUERY_PARAMS = array(
    'code',
    'state',
    'signed_request',
  );

  /**
   * Maps aliases to Facebook domains.
   */
  public static $DOMAIN_MAP = array(
    'api'       => 'https://api.facebook.com/',
    'api_video' => 'https://api-video.facebook.com/',
    'api_read'  => 'https://api-read.facebook.com/',
    'graph'     => 'https://graph.facebook.com/',
    'graph_video' => 'https://graph-video.facebook.com/',
    'www'       => 'https://www.facebook.com/',
  );

  /**
   * The Application ID.
   *
   * @var string
   */
  protected $appId;

  /**
   * The Application App Secret.
   *
   * @var string
   */
  protected $appSecret;

  /**
   * The ID of the Facebook user, or 0 if the user is logged out.
   *
   * @var integer
   */
  protected $user;

  /**
   * The data from the signed_request token.
   */
  protected $signedRequest;

  /**
   * A CSRF state variable to assist in the defense against CSRF attacks.
   */
  protected $state;

  /**
   * The OAuth access token received in exchange for a valid authorization
   * code.  null means the access token has yet to be determined.
   *
   * @var string
   */
  protected $accessToken = null;

  /**
   * Indicates if the CURL based @ syntax for file uploads is enabled.
   *
   * @var boolean
   */
  protected $fileUploadSupport = false;

  /**
   * Initialize a Facebook Application.
   *
   * The configuration:
   * - appId: the application ID
   * - secret: the application secret
   * - fileUpload: (optional) boolean indicating if file uploads are enabled
   *
   * @param array $config The application configuration
   */
  public function __construct($config) {
    $this->setAppId($config['appId']);
    $this->setAppSecret($config['secret']);
    if (isset($config['fileUpload'])) {
      $this->setFileUploadSupport($config['fileUpload']);
    }

    $state = $this->getPersistentData('state');
    if (!empty($state)) {
      $this->state = $this->getPersistentData('state');
    }
  }

  /**
   * Set the Application ID.
   *
   * @param string $appId The Application ID
   * @return WP_BaseFacebook
   */
  public function setAppId($appId) {
    $this->appId = $appId;
    return $this;
  }

  /**
   * Get the Application ID.
   *
   * @return string the Application ID
   */
  public function getAppId() {
    return $this->appId;
  }

  /**
   * Set the App Secret.
   *
   * @param string $apiSecret The App Secret
   * @return WP_BaseFacebook
   * @deprecated
   */
  public function setApiSecret($apiSecret) {
    $this->setAppSecret($apiSecret);
    return $this;
  }

  /**
   * Set the App Secret.
   *
   * @param string $appSecret The App Secret
   * @return WP_BaseFacebook
   */
  public function setAppSecret($appSecret) {
    $this->appSecret = $appSecret;
    return $this;
  }

  /**
   * Get the App Secret.
   *
   * @return string the App Secret
   * @deprecated
   */
  public function getApiSecret() {
    return $this->getAppSecret();
  }

  /**
   * Get the App Secret.
   *
   * @return string the App Secret
   */
  public function getAppSecret() {
    return $this->appSecret;
  }

  /**
   * Extend an access token, while removing the short-lived token that might have been generated via client-side flow.
   * Thanks to http://stackoverflow.com/questions/486896/adding-a-parameter-to-the-url-with-javascript for the workaround
   */
  public function setExtendedAccessToken() {
    try {
      // need to circumvent json_decode by calling _oauthRequest
      // directly, since response isn't JSON format.
      $access_token_response =
        $this->_oauthRequest(
          $this->getUrl('graph', '/oauth/access_token'),
          $params = array(    'client_id' => $this->getAppId(),
          'client_secret' => $this->getAppSecret(),
          'grant_type'=>'fb_exchange_token',
          'fb_exchange_token'=>$this->getAccessToken(),
        ));
      } catch (WP_FacebookApiException $e) {
        // most likely that user very recently revoked authorization.
        // In any event, we don't have an access token, so say so.
        return false;
      }

      if (empty($access_token_response)) {
        return false;
      }

      $response_params = array();
      parse_str($access_token_response, $response_params);

      if (!isset($response_params['access_token'])) {
        return false;
      }

      $this->destroySession();

      $this->setPersistentData('access_token', $response_params['access_token']);
  }

  /**
   * Set the file upload support status.
   *
   * @param boolean $fileUploadSupport The file upload support status.
   * @return WP_BaseFacebook
   */
  public function setFileUploadSupport($fileUploadSupport) {
    $this->fileUploadSupport = $fileUploadSupport;
    return $this;
  }

  /**
   * Get the file upload support status.
   *
   * @return boolean true if and only if the server supports file upload.
   */
  public function getFileUploadSupport() {
    return $this->fileUploadSupport;
  }

  /**
   * DEPRECATED! Please use getFileUploadSupport instead.
   *
   * Get the file upload support status.
   *
   * @return boolean true if and only if the server supports file upload.
   */
  public function useFileUploadSupport() {
    return $this->getFileUploadSupport();
  }

  /**
   * Sets the access token for api calls.  Use this if you get
   * your access token by other means and just want the SDK
   * to use it.
   *
   * @param string $access_token an access token.
   * @return WP_BaseFacebook
   */
  public function setAccessToken($access_token) {
    $this->accessToken = $access_token;
    return $this;
  }

  /**
   * Determines the access token that should be used for API calls.
   * The first time this is called, $this->accessToken is set equal
   * to either a valid user access token, or it's set to the application
   * access token if a valid user access token wasn't available.  Subsequent
   * calls return whatever the first call returned.
   *
   * @return string The access token
   */
  public function getAccessToken() {
    if ($this->accessToken !== null) {
      // we've done this already and cached it.  Just return.
      return $this->accessToken;
    }

    // first establish access token to be the application
    // access token, in case we navigate to the /oauth/access_token
    // endpoint, where SOME access token is required.
    $this->setAccessToken($this->getApplicationAccessToken());
    $user_access_token = $this->getUserAccessToken();
    if ($user_access_token) {
      $this->setAccessToken($user_access_token);
    }

    return $this->accessToken;
  }

  /**
   * Determines and returns the user access token, first using
   * the signed request if present, and then falling back on
   * the authorization code if present.  The intent is to
   * return a valid user access token, or false if one is determined
   * to not be available.
   *
   * @return string A valid user access token, or false if one
   *                could not be determined.
   */
  protected function getUserAccessToken() {
    // first, consider a signed request if it's supplied.
    // if there is a signed request, then it alone determines
    // the access token.
    $signed_request = $this->getSignedRequest();
    if ($signed_request) {
      // apps.facebook.com hands the access_token in the signed_request
      if (array_key_exists('oauth_token', $signed_request)) {
        $access_token = $signed_request['oauth_token'];
        $this->setPersistentData('access_token', $access_token);
        return $access_token;
      }

      // the JS SDK puts a code in with the redirect_uri of ''
      if (array_key_exists('code', $signed_request)) {
        $code = $signed_request['code'];
        $access_token = $this->getAccessTokenFromCode($code, '');
        if ($access_token) {
          $this->setPersistentData('code', $code);
          $this->setPersistentData('access_token', $access_token);
          return $access_token;
        }
      }

      // signed request states there's no access token, so anything
      // stored should be cleared.
      $this->clearAllPersistentData();
      return false; // respect the signed request's data, even
                    // if there's an authorization code or something else
    }

    $code = $this->getCode();
    if ($code && $code != $this->getPersistentData('code')) {
      $access_token = $this->getAccessTokenFromCode($code);
      if ($access_token) {
        $this->setPersistentData('code', $code);
        $this->setPersistentData('access_token', $access_token);
        return $access_token;
      }

      // code was bogus, so everything based on it should be invalidated.
      $this->clearAllPersistentData();
      return false;
    }

    // as a fallback, just return whatever is in the persistent
    // store, knowing nothing explicit (signed request, authorization
    // code, etc.) was present to shadow it (or we saw a code in $_REQUEST,
    // but it's the same as what's in the persistent store)
    return $this->getPersistentData('access_token');
  }

  /**
   * Retrieve the signed request, either from a request parameter or,
   * if not present, from a cookie.
   *
   * @return string the signed request, if available, or null otherwise.
   */
  public function getSignedRequest() {
    if (!$this->signedRequest) {
      if (isset($_REQUEST['signed_request'])) {
        $this->signedRequest = $this->parseSignedRequest(
          $_REQUEST['signed_request']);
      } else if (isset($_COOKIE[$this->getSignedRequestCookieName()])) {
        $this->signedRequest = $this->parseSignedRequest(
          $_COOKIE[$this->getSignedRequestCookieName()]);
      }
    }
    return $this->signedRequest;
  }

  /**
   * Get the UID of the connected user, or 0
   * if the Facebook user is not connected.
   *
   * @return string the UID if available.
   */
  public function getUser() {
    if ($this->user !== null) {
      // we've already determined this and cached the value.
      return $this->user;
    }

    return $this->user = $this->getUserFromAvailableData();
  }

  /**
   * Determines the connected user by first examining any signed
   * requests, then considering an authorization code, and then
   * falling back to any persistent store storing the user.
   *
   * @return integer The id of the connected Facebook user,
   *                 or 0 if no such user exists.
   */
  protected function getUserFromAvailableData() {
    // if a signed request is supplied, then it solely determines
    // who the user is.
    $signed_request = $this->getSignedRequest();
    if ($signed_request) {
      if (array_key_exists('user_id', $signed_request)) {
        $user = $signed_request['user_id'];
        $this->setPersistentData('user_id', $signed_request['user_id']);
        return $user;
      }

      // if the signed request didn't present a user id, then invalidate
      // all entries in any persistent store.
      $this->clearAllPersistentData();
      return 0;
    }

    $user = $this->getPersistentData('user_id', $default = 0);
    $persisted_access_token = $this->getPersistentData('access_token');

    // use access_token to fetch user id if we have a user access_token, or if
    // the cached access token has changed.
    $access_token = $this->getAccessToken();
    if ($access_token &&
        $access_token != $this->getApplicationAccessToken() &&
        !($user && $persisted_access_token == $access_token)) {
      $user = $this->getUserFromAccessToken();
      if ($user) {
        $this->setPersistentData('user_id', $user);
      } else {
        $this->clearAllPersistentData();
      }
    }

    return $user;
  }

  /**
   * Get a Login URL for use with redirects. By default, full page redirect is
   * assumed. If you are using the generated URL with a window.open() call in
   * JavaScript, you can pass in display=popup as part of the $params.
   *
   * The parameters:
   * - redirect_uri: the url to go to after a successful login
   * - scope: comma separated list of requested extended perms
   *
   * @param array $params Provide custom parameters
   * @return string The URL for the login flow
   */
  public function getLoginUrl($params=array()) {
    $this->establishCSRFTokenState();
    $currentUrl = $this->getCurrentUrl();

    // if 'scope' is passed as an array, convert to comma separated list
    $scopeParams = isset($params['scope']) ? $params['scope'] : null;
    if ($scopeParams && is_array($scopeParams)) {
      $params['scope'] = implode(',', $scopeParams);
    }

    return $this->getUrl(
      'www',
      'dialog/oauth',
      array_merge(array(
                    'client_id' => $this->getAppId(),
                    'redirect_uri' => $currentUrl, // possibly overwritten
                    'state' => $this->state),
                  $params));
  }

  /**
   * Get a Logout URL suitable for use with redirects.
   *
   * The parameters:
   * - next: the url to go to after a successful logout
   *
   * @param array $params Provide custom parameters
   * @return string The URL for the logout flow
   */
  public function getLogoutUrl($params=array()) {
    return $this->getUrl(
      'www',
      'logout.php',
      array_merge(array(
        'next' => $this->getCurrentUrl(),
        'access_token' => $this->getAccessToken(),
      ), $params)
    );
  }

  /**
   * Get a login status URL to fetch the status from Facebook.
   *
   * The parameters:
   * - ok_session: the URL to go to if a session is found
   * - no_session: the URL to go to if the user is not connected
   * - no_user: the URL to go to if the user is not signed into facebook
   *
   * @param array $params Provide custom parameters
   * @return string The URL for the logout flow
   */
  public function getLoginStatusUrl($params=array()) {
    return $this->getUrl(
      'www',
      'extern/login_status.php',
      array_merge(array(
        'api_key' => $this->getAppId(),
        'no_session' => $this->getCurrentUrl(),
        'no_user' => $this->getCurrentUrl(),
        'ok_session' => $this->getCurrentUrl(),
        'session_version' => 3,
      ), $params)
    );
  }

  /**
   * Make an API call.
   *
   * @return mixed The decoded response
   */
  public function api(/* polymorphic */) {
    $args = func_get_args();
    if (is_array($args[0])) {
      return $this->_restserver($args[0]);
    } else {
      return call_user_func_array(array($this, '_graph'), $args);
    }
  }

  /**
   * Constructs and returns the name of the cookie that
   * potentially houses the signed request for the app user.
   * The cookie is not set by the WP_BaseFacebook class, but
   * it may be set by the JavaScript SDK.
   *
   * @return string the name of the cookie that would house
   *         the signed request value.
   */
  protected function getSignedRequestCookieName() {
    return 'fbsr_'.$this->getAppId();
  }

  /**
   * Constructs and returns the name of the coookie that potentially contain
   * metadata. The cookie is not set by the WP_BaseFacebook class, but it may be
   * set by the JavaScript SDK.
   *
   * @return string the name of the cookie that would house metadata.
   */
  protected function getMetadataCookieName() {
    return 'fbm_'.$this->getAppId();
  }

  /**
   * Get the authorization code from the query parameters, if it exists,
   * and otherwise return false to signal no authorization code was
   * discoverable.
   *
   * @return mixed The authorization code, or false if the authorization
   *               code could not be determined.
   */
  protected function getCode() {
    if (isset($_REQUEST['code'])) {
      if ($this->state !== null &&
          isset($_REQUEST['state']) &&
          $this->state === $_REQUEST['state']) {

        // CSRF state has done its job, so clear it
        $this->state = null;
        $this->clearPersistentData('state');
        return $_REQUEST['code'];
      } else {
        self::errorLog('CSRF state token does not match one provided.');
        return false;
      }
    }

    return false;
  }

  /**
   * Retrieves the UID with the understanding that
   * $this->accessToken has already been set and is
   * seemingly legitimate.  It relies on Facebook's Graph API
   * to retrieve user information and then extract
   * the user ID.
   *
   * @return integer Returns the UID of the Facebook user, or 0
   *                 if the Facebook user could not be determined.
   */
  protected function getUserFromAccessToken() {
    try {
      $user_info = $this->api('/me');
      return $user_info['id'];
    } catch (WP_FacebookApiException $e) {
      return 0;
    }
  }

  /**
   * Returns the access token that should be used for logged out
   * users when no authorization code is available.
   *
   * @return string The application access token, useful for gathering
   *                public information about users and applications.
   */
  protected function getApplicationAccessToken() {
    return $this->appId.'|'.$this->appSecret;
  }

  /**
   * Lays down a CSRF state token for this process.
   *
   * @return void
   */
  protected function establishCSRFTokenState() {
    if ($this->state === null) {
      $this->state = md5(uniqid(mt_rand(), true));
      $this->setPersistentData('state', $this->state);
    }
  }

  /**
   * Retrieves an access token for the given authorization code
   * (previously generated from www.facebook.com on behalf of
   * a specific user).  The authorization code is sent to graph.facebook.com
   * and a legitimate access token is generated provided the access token
   * and the user for which it was generated all match, and the user is
   * either logged in to Facebook or has granted an offline access permission.
   *
   * @param string $code An authorization code.
   * @return mixed An access token exchanged for the authorization code, or
   *               false if an access token could not be generated.
   */
  protected function getAccessTokenFromCode($code, $redirect_uri = null) {
    if (empty($code)) {
      return false;
    }

    if ($redirect_uri === null) {
      $redirect_uri = $this->getCurrentUrl();
    }

    try {
      // need to circumvent json_decode by calling _oauthRequest
      // directly, since response isn't JSON format.
      $access_token_response =
        $this->_oauthRequest(
          $this->getUrl('graph', '/oauth/access_token'),
          $params = array('client_id' => $this->getAppId(),
                          'client_secret' => $this->getAppSecret(),
                          'redirect_uri' => $redirect_uri,
                          'code' => $code));
    } catch (WP_FacebookApiException $e) {
      // most likely that user very recently revoked authorization.
      // In any event, we don't have an access token, so say so.
      return false;
    }

    if (empty($access_token_response)) {
      return false;
    }

    $response_params = array();
    parse_str($access_token_response, $response_params);
    if (!isset($response_params['access_token'])) {
      return false;
    }

    return $response_params['access_token'];
  }

  /**
   * Invoke the old restserver.php endpoint.
   *
   * @param array $params Method call object
   *
   * @return mixed The decoded response object
   * @throws WP_FacebookApiException
   */
  protected function _restserver($params) {
    // generic application level parameters
    $params['api_key'] = $this->getAppId();
    $params['format'] = 'json-strings';

    $result = json_decode($this->_oauthRequest(
      $this->getApiUrl($params['method']),
      $params
    ), true);

    // results are returned, errors are thrown
    if (is_array($result) && isset($result['error_code'])) {
      $this->throwAPIException($result);
    }

    if ($params['method'] === 'auth.expireSession' ||
        $params['method'] === 'auth.revokeAuthorization') {
      $this->destroySession();
    }

    return $result;
  }

  /**
   * Return true if this is video post.
   *
   * @param string $path The path
   * @param string $method The http method (default 'GET')
   *
   * @return boolean true if this is video post
   */
  protected function isVideoPost($path, $method = 'GET') {
    if ($method == 'POST' && preg_match("/^(\/)(.+)(\/)(videos)$/", $path)) {
      return true;
    }
    return false;
  }

  /**
   * Invoke the Graph API.
   *
   * @param string $path The path (required)
   * @param string $method The http method (default 'GET')
   * @param array $params The query/post data
   *
   * @return mixed The decoded response object
   * @throws WP_FacebookApiException
   */
  protected function _graph($path, $method = 'GET', $params = array()) {
    if (is_array($method) && empty($params)) {
      $params = $method;
      $method = 'GET';
    }
    $params['method'] = $method; // method override as we always do a POST

    if ($this->isVideoPost($path, $method)) {
      $domainKey = 'graph_video';
    } else {
      $domainKey = 'graph';
    }

    $result = json_decode($this->_oauthRequest(
      $this->getUrl($domainKey, $path),
      $params
    ), true);

    // results are returned, errors are thrown
    if (is_array($result) && isset($result['error'])) {
      $this->throwAPIException($result);
    }

    return $result;
  }

  /**
   * Make a OAuth Request.
   *
   * @param string $url The path (required)
   * @param array $params The query/post data
   *
   * @return string The decoded response object
   * @throws WP_FacebookApiException
   */
  protected function _oauthRequest($url, $params) {
    if (!isset($params['access_token'])) {
      $params['access_token'] = $this->getAccessToken();
    }

    // json_encode all params values that are not strings
    foreach ($params as $key => $value) {
      if (!is_string($value)) {
        $params[$key] = json_encode($value);
      }
    }

    return $this->makeRequest($url, $params);
  }

  /**
   * Makes an HTTP request. This method can be overridden by subclasses if
   * developers want to do fancier things or use something other than curl to
   * make the request.
   *
   * @param string $url The URL to make the request to
   * @param array $params The parameters to use for the POST body
   * @param CurlHandler $ch Initialized curl handle
   *
   * @return string The response text
   */
  protected function makeRequest($url, $params, $ch=null) {
    if (!$ch) {
      $ch = curl_init();
    }

    $opts = self::$CURL_OPTS;
    if ($this->getFileUploadSupport()) {
      $opts[CURLOPT_POSTFIELDS] = $params;
    } else {
      $opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
    }
    $opts[CURLOPT_URL] = $url;

    // disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
    // for 2 seconds if the server does not support this header.
    if (isset($opts[CURLOPT_HTTPHEADER])) {
      $existing_headers = $opts[CURLOPT_HTTPHEADER];
      $existing_headers[] = 'Expect:';
      $opts[CURLOPT_HTTPHEADER] = $existing_headers;
    } else {
      $opts[CURLOPT_HTTPHEADER] = array('Expect:');
    }

    curl_setopt_array($ch, $opts);
    $result = curl_exec($ch);

    if (curl_errno($ch) == 60) { // CURLE_SSL_CACERT
      self::errorLog('Invalid or no certificate authority found, '.
                     'using bundled information');
      curl_setopt($ch, CURLOPT_CAINFO,
                  dirname(__FILE__) . '/fb_ca_chain_bundle.crt');
      $result = curl_exec($ch);
    }

    if ($result === false) {
      $e = new WP_FacebookApiException(array(
        'error_code' => curl_errno($ch),
        'error' => array(
        'message' => curl_error($ch),
        'type' => 'CurlException',
        ),
      ));
      curl_close($ch);
      throw $e;
    }
    curl_close($ch);
    return $result;
  }

  /**
   * Parses a signed_request and validates the signature.
   *
   * @param string $signed_request A signed token
   * @return array The payload inside it or null if the sig is wrong
   */
  protected function parseSignedRequest($signed_request) {
    list($encoded_sig, $payload) = explode('.', $signed_request, 2);

    // decode the data
    $sig = self::base64UrlDecode($encoded_sig);
    $data = json_decode(self::base64UrlDecode($payload), true);

    if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
      self::errorLog('Unknown algorithm. Expected HMAC-SHA256');
      return null;
    }

    // check sig
    $expected_sig = hash_hmac('sha256', $payload,
                              $this->getAppSecret(), $raw = true);
    if ($sig !== $expected_sig) {
      self::errorLog('Bad Signed JSON signature!');
      return null;
    }

    return $data;
  }

  /**
   * Build the URL for api given parameters.
   *
   * @param $method String the method name.
   * @return string The URL for the given parameters
   */
  protected function getApiUrl($method) {
    static $READ_ONLY_CALLS =
      array('admin.getallocation' => 1,
            'admin.getappproperties' => 1,
            'admin.getbannedusers' => 1,
            'admin.getlivestreamvialink' => 1,
            'admin.getmetrics' => 1,
            'admin.getrestrictioninfo' => 1,
            'application.getpublicinfo' => 1,
            'auth.getapppublickey' => 1,
            'auth.getsession' => 1,
            'auth.getsignedpublicsessiondata' => 1,
            'comments.get' => 1,
            'connect.getunconnectedfriendscount' => 1,
            'dashboard.getactivity' => 1,
            'dashboard.getcount' => 1,
            'dashboard.getglobalnews' => 1,
            'dashboard.getnews' => 1,
            'dashboard.multigetcount' => 1,
            'dashboard.multigetnews' => 1,
            'data.getcookies' => 1,
            'events.get' => 1,
            'events.getmembers' => 1,
            'fbml.getcustomtags' => 1,
            'feed.getappfriendstories' => 1,
            'feed.getregisteredtemplatebundlebyid' => 1,
            'feed.getregisteredtemplatebundles' => 1,
            'fql.multiquery' => 1,
            'fql.query' => 1,
            'friends.arefriends' => 1,
            'friends.get' => 1,
            'friends.getappusers' => 1,
            'friends.getlists' => 1,
            'friends.getmutualfriends' => 1,
            'gifts.get' => 1,
            'groups.get' => 1,
            'groups.getmembers' => 1,
            'intl.gettranslations' => 1,
            'links.get' => 1,
            'notes.get' => 1,
            'notifications.get' => 1,
            'pages.getinfo' => 1,
            'pages.isadmin' => 1,
            'pages.isappadded' => 1,
            'pages.isfan' => 1,
            'permissions.checkavailableapiaccess' => 1,
            'permissions.checkgrantedapiaccess' => 1,
            'photos.get' => 1,
            'photos.getalbums' => 1,
            'photos.gettags' => 1,
            'profile.getinfo' => 1,
            'profile.getinfooptions' => 1,
            'stream.get' => 1,
            'stream.getcomments' => 1,
            'stream.getfilters' => 1,
            'users.getinfo' => 1,
            'users.getloggedinuser' => 1,
            'users.getstandardinfo' => 1,
            'users.hasapppermission' => 1,
            'users.isappuser' => 1,
            'users.isverified' => 1,
            'video.getuploadlimits' => 1);
    $name = 'api';
    if (isset($READ_ONLY_CALLS[strtolower($method)])) {
      $name = 'api_read';
    } else if (strtolower($method) == 'video.upload') {
      $name = 'api_video';
    }
    return self::getUrl($name, 'restserver.php');
  }

  /**
   * Build the URL for given domain alias, path and parameters.
   *
   * @param $name string The name of the domain
   * @param $path string Optional path (without a leading slash)
   * @param $params array Optional query parameters
   *
   * @return string The URL for the given parameters
   */
  protected function getUrl($name, $path='', $params=array()) {
    $url = self::$DOMAIN_MAP[$name];
    if ($path) {
      if ($path[0] === '/') {
        $path = substr($path, 1);
      }
      $url .= $path;
    }
    if ($params) {
      $url .= '?' . http_build_query($params, null, '&');
    }

    return $url;
  }

  /**
   * Returns the Current URL, stripping it of known FB parameters that should
   * not persist.
   *
   * @return string The current URL
   */
  protected function getCurrentUrl() {
    if (isset($_SERVER['HTTPS']) &&
        ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
        isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
        $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
      $protocol = 'https://';
    }
    else {
      $protocol = 'http://';
    }
    $currentUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $parts = parse_url($currentUrl);

    $query = '';
    if (!empty($parts['query'])) {
      // drop known fb params
      $params = explode('&', $parts['query']);
      $retained_params = array();
      foreach ($params as $param) {
        if ($this->shouldRetainParam($param)) {
          $retained_params[] = $param;
        }
      }

      if (!empty($retained_params)) {
        $query = '?'.implode($retained_params, '&');
      }
    }

    // use port if non default
    $port =
      isset($parts['port']) &&
      (($protocol === 'http://' && $parts['port'] !== 80) ||
       ($protocol === 'https://' && $parts['port'] !== 443))
      ? ':' . $parts['port'] : '';

    // rebuild
    return $protocol . $parts['host'] . $port . $parts['path'] . $query;
  }

  /**
   * Returns true if and only if the key or key/value pair should
   * be retained as part of the query string.  This amounts to
   * a brute-force search of the very small list of Facebook-specific
   * params that should be stripped out.
   *
   * @param string $param A key or key/value pair within a URL's query (e.g.
   *                     'foo=a', 'foo=', or 'foo'.
   *
   * @return boolean
   */
  protected function shouldRetainParam($param) {
    foreach (self::$DROP_QUERY_PARAMS as $drop_query_param) {
      if (strpos($param, $drop_query_param.'=') === 0) {
        return false;
      }
    }

    return true;
  }

  /**
   * Analyzes the supplied result to see if it was thrown
   * because the access token is no longer valid.  If that is
   * the case, then we destroy the session.
   *
   * @param $result array A record storing the error message returned
   *                      by a failed API call.
   */
  protected function throwAPIException($result) {
    $e = new WP_FacebookApiException($result);
    switch ($e->getType()) {
      // OAuth 2.0 Draft 00 style
      case 'OAuthException':
        // OAuth 2.0 Draft 10 style
      case 'invalid_token':
        // REST server errors are just Exceptions
      case 'Exception':
        $message = $e->getMessage();
        if ((strpos($message, 'Error validating access token') !== false) ||
            (strpos($message, 'Invalid OAuth access token') !== false) ||
            (strpos($message, 'An active access token must be used') !== false)
        ) {
          $this->destroySession();
        }
        break;
    }

    throw $e;
  }

  /**
   * Prints to the error log if you aren't in command line mode.
   *
   * @param string $msg Log message
   */
  protected static function errorLog($msg) {
    // disable error log if we are running in a CLI environment
    // @codeCoverageIgnoreStart
    // if (php_sapi_name() != 'cli') {
      //error_log($msg);
    // }
    // uncomment this if you want to see the errors on the page
    // print 'error_log: '.$msg."\n";
    // @codeCoverageIgnoreEnd
  }

  /**
   * Base64 encoding that doesn't need to be urlencode()ed.
   * Exactly the same as base64_encode except it uses
   *   - instead of +
   *   _ instead of /
   *
   * @param string $input base64UrlEncoded string
   * @return string
   */
  protected static function base64UrlDecode($input) {
    return base64_decode(strtr($input, '-_', '+/'));
  }

  /**
   * Destroy the current session
   */
  public function destroySession() {
    $this->accessToken = null;
    $this->signedRequest = null;
    $this->user = null;
    $this->clearAllPersistentData();

    // Javascript sets a cookie that will be used in getSignedRequest that we
    // need to clear if we can
    $cookie_name = $this->getSignedRequestCookieName();
    if (array_key_exists($cookie_name, $_COOKIE)) {
      unset($_COOKIE[$cookie_name]);
      if (!headers_sent()) {
        // The base domain is stored in the metadata cookie if not we fallback
        // to the current hostname
        $base_domain = '.'. $_SERVER['HTTP_HOST'];

        $metadata = $this->getMetadataCookie();
        if (array_key_exists('base_domain', $metadata) &&
            !empty($metadata['base_domain'])) {
          $base_domain = $metadata['base_domain'];
        }

        setcookie($cookie_name, '', 0, '/', $base_domain);
      } else {
        self::errorLog(
          'There exists a cookie that we wanted to clear that we couldn\'t '.
          'clear because headers was already sent. Make sure to do the first '.
          'API call before outputing anything'
        );
      }
    }
  }

  /**
   * Parses the metadata cookie that our Javascript API set
   *
   * @return  an array mapping key to value
   */
  protected function getMetadataCookie() {
    $cookie_name = $this->getMetadataCookieName();
    if (!array_key_exists($cookie_name, $_COOKIE)) {
      return array();
    }

    // The cookie value can be wrapped in "-characters so remove them
    $cookie_value = trim($_COOKIE[$cookie_name], '"');

    if (empty($cookie_value)) {
      return array();
    }

    $parts = explode('&', $cookie_value);
    $metadata = array();
    foreach ($parts as $part) {
      $pair = explode('=', $part, 2);
      if (!empty($pair[0])) {
        $metadata[urldecode($pair[0])] =
          (count($pair) > 1) ? urldecode($pair[1]) : '';
      }
    }

    return $metadata;
  }

  /**
   * Each of the following four methods should be overridden in
   * a concrete subclass, as they are in the provided Facebook class.
   * The Facebook class uses PHP sessions to provide a primitive
   * persistent store, but another subclass--one that you implement--
   * might use a database, memcache, or an in-memory cache.
   *
   * @see Facebook
   */

  /**
   * Stores the given ($key, $value) pair, so that future calls to
   * getPersistentData($key) return $value. This call may be in another request.
   *
   * @param string $key
   * @param array $value
   *
   * @return void
   */
  abstract protected function setPersistentData($key, $value);

  /**
   * Get the data for $key, persisted by WP_BaseFacebook::setPersistentData()
   *
   * @param string $key The key of the data to retrieve
   * @param boolean $default The default value to return if $key is not found
   *
   * @return mixed
   */
  abstract protected function getPersistentData($key, $default = false);

  /**
   * Clear the data with $key from the persistent storage
   *
   * @param string $key
   * @return void
   */
  abstract protected function clearPersistentData($key);

  /**
   * Clear all data from the persistent storage
   *
   * @return void
   */
  abstract protected function clearAllPersistentData();
}
endif;


text:
package io.vertx.ext.web.handler;

import io.vertx.codegen.annotations.Fluent;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.oauth2.OAuth2Auth;
import io.vertx.ext.web.Route;
import io.vertx.ext.web.handler.impl.OAuth2AuthHandlerImpl;

/**
 * An auth handler that provides OAuth2 Authentication support. This handler is suitable for AuthCode flows.
 *
 * @author Paulo Lopes
 */
@VertxGen
public interface OAuth2AuthHandler extends AuthHandler {

  /**
   * Create a OAuth2 auth handler with host pinning
   *
   * @param authProvider  the auth provider to use
   * @param callbackURL the callback URL you entered in your provider admin console, usually it should be something like: `https://myserver:8888/callback`
   * @return the auth handler
   */
  static OAuth2AuthHandler create(OAuth2Auth authProvider, String callbackURL) {
    return new OAuth2AuthHandlerImpl(authProvider, callbackURL);
  }

  /**
   * Create a OAuth2 auth handler without host pinning.
   * Most providers will not look to the redirect url but always redirect to
   * the preconfigured callback. So this factory does not provide a callback url.
   *
   * @param authProvider  the auth provider to use
   * @return the auth handler
   */
  static OAuth2AuthHandler create(OAuth2Auth authProvider) {
    return new OAuth2AuthHandlerImpl(authProvider, null);
  }

  /**
   * Extra parameters needed to be passed while requesting a token.
   *
   * @param extraParams extra optional parameters.
   * @return self
   */
  @Fluent
  OAuth2AuthHandler extraParams(JsonObject extraParams);

  /**
   * add the callback handler to a given route.
   * @param route a given route e.g.: `/callback`
   * @return self
   */
  @Fluent
  OAuth2AuthHandler setupCallback(Route route);
}


text:
``` diff
+namespace System.Windows.Media.Converters {
+    public abstract class BaseIListConverter : TypeConverter {
+        protected BaseIListConverter();
+        public override bool CanConvertFrom(ITypeDescriptorContext td, Type t);
+        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType);
+        public override object ConvertFrom(ITypeDescriptorContext td, CultureInfo ci, object value);
+        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType);
+    }
+    public sealed class BoolIListConverter : BaseIListConverter {
+        public BoolIListConverter();
+    }
+    public class BrushValueSerializer : ValueSerializer {
+        public BrushValueSerializer();
+        public override bool CanConvertFromString(string value, IValueSerializerContext context);
+        public override bool CanConvertToString(object value, IValueSerializerContext context);
+        public override object ConvertFromString(string value, IValueSerializerContext context);
+        public override string ConvertToString(object value, IValueSerializerContext context);
+    }
+    public class CacheModeValueSerializer : ValueSerializer {
+        public CacheModeValueSerializer();
+        public override bool CanConvertFromString(string value, IValueSerializerContext context);
+        public override bool CanConvertToString(object value, IValueSerializerContext context);
+        public override object ConvertFromString(string value, IValueSerializerContext context);
+        public override string ConvertToString(object value, IValueSerializerContext context);
+    }
+    public sealed class CharIListConverter : BaseIListConverter {
+        public CharIListConverter();
+    }
+    public class DoubleCollectionValueSerializer : ValueSerializer {
+        public DoubleCollectionValueSerializer();
+        public override bool CanConvertFromString(string value, IValueSerializerContext context);
+        public override bool CanConvertToString(object value, IValueSerializerContext context);
+        public override object ConvertFromString(string value, IValueSerializerContext context);
+        public override string ConvertToString(object value, IValueSerializerContext context);
+    }
+    public sealed class DoubleIListConverter : BaseIListConverter {
+        public DoubleIListConverter();
+    }
+    public class GeometryValueSerializer : ValueSerializer {
+        public GeometryValueSerializer();
+        public override bool CanConvertFromString(string value, IValueSerializerContext context);
+        public override bool CanConvertToString(object value, IValueSerializerContext context);
+        public override object ConvertFromString(string value, IValueSerializerContext context);
+        public override string ConvertToString(object value, IValueSerializerContext context);
+    }
+    public class Int32CollectionValueSerializer : ValueSerializer {
+        public Int32CollectionValueSerializer();
+        public override bool CanConvertFromString(string value, IValueSerializerContext context);
+        public override bool CanConvertToString(object value, IValueSerializerContext context);
+        public override object ConvertFromString(string value, IValueSerializerContext context);
+        public override string ConvertToString(object value, IValueSerializerContext context);
+    }
+    public class MatrixValueSerializer : ValueSerializer {
+        public MatrixValueSerializer();
+        public override bool CanConvertFromString(string value, IValueSerializerContext context);
+        public override bool CanConvertToString(object value, IValueSerializerContext context);
+        public override object ConvertFromString(string value, IValueSerializerContext context);
+        public override string ConvertToString(object value, IValueSerializerContext context);
+    }
+    public class PathFigureCollectionValueSerializer : ValueSerializer {
+        public PathFigureCollectionValueSerializer();
+        public override bool CanConvertFromString(string value, IValueSerializerContext context);
+        public override bool CanConvertToString(object value, IValueSerializerContext context);
+        public override object ConvertFromString(string value, IValueSerializerContext context);
+        public override string ConvertToString(object value, IValueSerializerContext context);
+    }
+    public class PointCollectionValueSerializer : ValueSerializer {
+        public PointCollectionValueSerializer();
+        public override bool CanConvertFromString(string value, IValueSerializerContext context);
+        public override bool CanConvertToString(object value, IValueSerializerContext context);
+        public override object ConvertFromString(string value, IValueSerializerContext context);
+        public override string ConvertToString(object value, IValueSerializerContext context);
+    }
+    public sealed class PointIListConverter : BaseIListConverter {
+        public PointIListConverter();
+    }
+    public class TransformValueSerializer : ValueSerializer {
+        public TransformValueSerializer();
+        public override bool CanConvertFromString(string value, IValueSerializerContext context);
+        public override bool CanConvertToString(object value, IValueSerializerContext context);
+        public override object ConvertFromString(string value, IValueSerializerContext context);
+        public override string ConvertToString(object value, IValueSerializerContext context);
+    }
+    public sealed class UShortIListConverter : BaseIListConverter {
+        public UShortIListConverter();
+    }
+    public class VectorCollectionValueSerializer : ValueSerializer {
+        public VectorCollectionValueSerializer();
+        public override bool CanConvertFromString(string value, IValueSerializerContext context);
+        public override bool CanConvertToString(object value, IValueSerializerContext context);
+        public override object ConvertFromString(string value, IValueSerializerContext context);
+        public override string ConvertToString(object value, IValueSerializerContext context);
+    }
+}
```


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 Resource Definitions //EN" "http://www.sun.com/software/appserver/dtds/sun-resources_1_3.dtd">
<resources>

	<!-- DEFINE QUEUES AND TOPICS HERE -->

	<!-- COMPUTER QUEUE -->
	<admin-object-resource enabled="true"
		jndi-name="queue.dst.ComputerQueue" res-adapter="jmsra" res-type="javax.jms.Queue">
		<property name="Name" value="queue.dst.ComputerQueue" />
	</admin-object-resource>

	<!-- CLUSTER TOPIC -->
	<admin-object-resource enabled="true"
		jndi-name="topic.dst.ClusterTopic" res-adapter="jmsra" res-type="javax.jms.Topic">
		<property name="Name" value="topic.dst.ClusterTopic" />
	</admin-object-resource>

	<!-- CLUSTER QUEUE -->
	<admin-object-resource enabled="true"
		jndi-name="queue.dst.ClusterQueue" res-adapter="jmsra" res-type="javax.jms.Queue">
		<property name="Name" value="queue.dst.ClusterQueue" />
	</admin-object-resource>

	<!-- SCHEDULER QUEUE -->
	<admin-object-resource enabled="true"
		jndi-name="queue.dst.SchedulerQueue" res-adapter="jmsra" res-type="javax.jms.Queue">
		<property name="Name" value="queue.dst.SchedulerQueue" />
	</admin-object-resource>

	<!-- SCHEDULER CALLBACK QUEUE -->
	<admin-object-resource enabled="true"
		jndi-name="queue.dst.SchedulerCallBackQueue" res-adapter="jmsra" res-type="javax.jms.Queue">
		<property name="Name" value="queue.dst.SchedulerCallBackQueue" />
	</admin-object-resource>

	<!-- FACTORY & POOL -->
	<connector-resource enabled="true" jndi-name="dst.Factory" pool-name="dst.FactoryPool" />
	<connector-connection-pool name="dst.FactoryPool" connection-definition-name="javax.jms.ConnectionFactory" resource-adapter-name="jmsra" />
</resources>


text:
#import "LinearAddrInfo.h"

#pragma mark - Socket Types

/** Socket Type Indicator */
typedef NS_ENUM(NSInteger, LinearSocketType) {
  /** NIL */
  LinearSocketTypeNIL,
  /** TCP */
  LinearSocketTypeTCP,
  /** SSL */
  LinearSocketTypeSSL,
  /** WebSocket */
  LinearSocketTypeWS,
  /** Secure WebSocket (not implemented yet) */
  LinearSocketTypeWSS,
};

#pragma mark - Socket Status

/** Socket State Indicator */
typedef NS_ENUM(NSInteger, LinearSocketState) {
  /** Disconnecting */
  LinearSocketStateDisconnecting,
  /** Disconnected */
  LinearSocketStateDisconnected,
  /** Connecting */
  LinearSocketStateConnecting,
  /** Connected */
  LinearSocketStateConnected,
};

#pragma mark - Keep Alive Type

/** Keep Alive Types */
typedef NS_ENUM(NSInteger, LinearKeepAliveType) {
  /** KEEPALIVE - TCP */
  LinearKeepAliveTCP,
  /** KEEPALIVE - WebSocket */
  LinearKeepAliveWS,
};

#pragma mark - Socket

/**
 * Socket class
 */
@interface LinearSocket : NSObject

/** Socket Id */
@property (nonatomic, assign, readonly) NSInteger ident;
/** Socket Type */
@property (nonatomic, assign, readonly) LinearSocketType type;
/** Socket State */
@property (nonatomic, assign, readonly) LinearSocketState state;
/**
 * Self Information
 * @see LinearAddrInfo
 */
@property (nonatomic, strong, readonly) LinearAddrInfo *selfInfo;
/**
 * Peer Information
 * @see LinearAddrInfo
 */
@property (nonatomic, strong, readonly) LinearAddrInfo *peerInfo;

/**
 * Connect to peer
 * @return succeed to connect or not
 */
- (BOOL)connect;
/**
 * Connect to peer with timeout
 * @param timeout timeout value (ms)
 * @return succeed to connect or not
 */
- (BOOL)connect:(NSUInteger)timeout;
/**
 * Disconnect from peer
 * @return succeed to disconnect or not
 */
- (BOOL)disconnect;
/**
 * Interface to set SO_KEEPALIVE
 * @param interval interval time(second) to send tcp-keepalive
 * @param retry retry counter
 * @return succeed to set or not
 * @note This method is enabled on iOS 7.0-.
 * @see http://stackoverflow.com/questions/9214326/tcp-keepintvl-and-tcp-keepcnt-not-defined-in-tcp-h-in-ios-sdk
 */
- (BOOL)keepAlive:(NSUInteger)interval retry:(NSUInteger)retry;

/**
 * Interface to set SO_KEEPALIVE or WebSocket KeepAlive
 * @param interval interval time(second) to send tcp-keepalive
 * @param retry retry counter
 * @param type KEEPALIVE(TCP) or KEEPALIVE(WebSocket)
 * @return succeed to set or not
 */
- (BOOL)keepAlive:(NSUInteger)interval retry:(NSUInteger)retry type:(LinearKeepAliveType)type;

/**
 * set {send, recv} MaxBuffer size, default is 8MB
 * @param limit max limit (byte)
 */
- (void)setMaxBufferSize: (NSUInteger)limit;

@end


text:
package main

import (
	"errors"
	"net/http"
	"net/http/httptest"
	"testing"

	"gopkg.in/mgo.v2"
)

type AuthTestStorage struct {
	NullStorage

	NextError error
	Created   *Account
}

func (storage *AuthTestStorage) CreateAccount(account *Account) error {
	if err := storage.NextError; err != nil {
		storage.NextError = nil
		return err
	}

	storage.Created = account
	return nil
}

func TestCreateHandlerSuccess(t *testing.T) {
	r := HTTPRequest(t, "POST", "https://localhost/v1/accounts",
		`accountName=someone%40gmail.com&password=secret`)
	w := httptest.NewRecorder()
	s := &AuthTestStorage{}
	c := &Context{Storage: s}

	CreateHandler(c, w, r)

	if w.Code != http.StatusCreated {
		t.Errorf("Expected response code %d, but was %d", http.StatusCreated, w.Code)
	}

	if w.Body.Len() != 0 {
		t.Errorf("Expected empty body, but got:<<<\n%s>>>", w.Body.String())
	}

	acct := s.Created

	if acct == nil {
		t.Fatal("Account not created")
	}

	if acct.Name != "someone@gmail.com" {
		t.Errorf("Account had unexpected name: [%s]", acct.Name)
	}
}

func TestCreateHandlerDuplicateAccount(t *testing.T) {
	r := HTTPRequest(t, "POST", "https://localhost/v1/accounts",
		`accountName=someone%40gmail.com&password=secret`)
	w := httptest.NewRecorder()
	s := &AuthTestStorage{
		// See https://github.com/go-mgo/mgo/blob/445c05a1261a0941bc48d898c8eb3ee18ab398c3/session.go#L2116
		NextError: &mgo.QueryError{Code: 11000},
	}
	c := &Context{Storage: s}

	CreateHandler(c, w, r)

	if w.Code != http.StatusConflict {
		t.Errorf("Expected response code %d, but was %d", http.StatusConflict, w.Code)
	}
}

func TestCreateHandlerStorageFailure(t *testing.T) {
	r := HTTPRequest(t, "POST", "https://localhost/v1/accounts",
		`accountName=mongo-go-boom%40gmail.com&password=uhoh`)
	w := httptest.NewRecorder()
	s := &AuthTestStorage{NextError: errors.New("WTF")}
	c := &Context{Storage: s}

	CreateHandler(c, w, r)

	if w.Code != http.StatusInternalServerError {
		t.Errorf("Expected response code %d, but was %d", http.StatusInternalServerError, w.Code)
	}
}


text:
<form name="closeForm" os-form-validator="closeForm" novalidate>

      Close

            User

            <os-users ng-model="closeSpec.user" default-current-user placeholder="{{'specimens.event_user' | translate}}">
            </os-users>

            Date and Time

                <os-date-picker date="closeSpec.date" placeholder="{{'specimens.event_time' | translate}}">
                </os-date-picker>

                <timepicker ng-model="closeSpec.date" class="os-time-no-wheels" show-meridian="false">
                </timepicker>

            Comments

            <textarea class="form-control" ng-model="closeSpec.reason" rows="2"
              placeholder="{{'specimens.reason_for_closing' | translate}}">
            </textarea>

      <button class="btn os-btn-text" ng-click="cancel()">
        Cancel
      </button>
      <button class="btn btn-primary" ng-click="close()">
        Close
      </button>

</form>


text:
Tc JOSE
=======

[![Build Status](https://travis-ci.org/carlcraig/tc-jose.svg?branch=master)](https://travis-ci.org/carlcraig/tc-jose)
[![SensioLabsInsight](https://insight.sensiolabs.com/projects/15b43357-e245-48e7-bf91-635160ca41be/mini.png)](https://insight.sensiolabs.com/projects/15b43357-e245-48e7-bf91-635160ca41be)
[![Latest Stable Version](https://poser.pugx.org/tc/jose/v/stable.svg)](https://packagist.org/packages/tc/jose)

##### A Javascript Object Signing and Encryption Library

Installation
------------

Using composer, add the following to your `composer.json`:

```json
"tc/jose": "dev-master"
```

You could also run:

```sh
$ php composer.phar require tc/jose "dev-master"
```

Supported Algorithms
--------------------

- None
- HS256, HS384, HS512
- RS256, RS384, RS512
- ES256, ES384, ES512

Creating a JWS
--------------

To create a JWS you would do something like this:

```php
<?php

use Tc\JOSE\JWS;

// ...

// Create a new JWS
$jws = new JWS();

// Add some data to the payload
$jws->setPayload(array(
    'user' => 'SomeUser'
));

// Set Issued At Claim
$jws->setIssuedAt();

// Set Expires for 1 hour
$jws->setExpires(3600);

// Sign the JWS (Can use any of the supported algorithms)
$jws->sign('HS256', 'SecretKeyHere');

// Serialize the JWS to be transported
$jwsSerialized = $jws->serialize();

// Should look like:
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpPU0UifQ.e30.ssb8sFTv7UK37oW395EUkSL9g8uNPDhMHFvRwcUenXo

// You could then return this token to the client normally or as a header/cookie

// ...

```

Decoding a Serialized JWT *(JWS or JWE)*
----------------------------------------

```php
<?php

use Tc\JOSE\JWT;
use Tc\JOSE\JWS;

// ...

// The Serialized JWT (could be from a header/request parameter)
$jwt = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpPU0UifQ.e30.ssb8sFTv7UK37oW395EUkSL9g8uNPDhMHFvRwcUenXo';

// Try to decode the Serialized JWT
try {

    $decodedJWT = JWT::decode($jwt);

    // Check if the decoded JWT is a JWS (could potentially be a JWS or JWE)
    if ( $decodedJWT instanceof JWS ) {

        // is a JWS, we now check it is valid
        $isValid = $decodedJWT->validate('SecretKeyHere');

        if ($isValid) {
            // JWS is valid
        }

    }
} catch(InvalidArgumentException $e) {
    // Invalid JWT, handle here
}

// ...

```

Using RS or ES Algorithms
-------------------------

#### Create the keys with openssl

You can adjust the format for creating the keys to work with ES or RS.

```sh
$ openssl genrsa -out private.pem -aes256 4096
$ openssl rsa -pubout -in private.pem -out public.pem
```

#### Signing a JWS

```php
<?php

// ...
$jws = new JWS();
$jws->sign('RS256', openssl_pkey_get_private('path/to/privatekey.pem', 'passphrase'));
// ...
```

#### Validate a JWS

```php
<?php

// ...
$jws->validate(openssl_pkey_get_public('path/to/publickey.pem'));
// ...
```

TODO
----

Implement JWE and JWK specifications.

License
-------

tc-jose is licensed with the MIT license.

See LICENSE for more details.