text:
<?php

namespace Teclliure\QuestionBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Form\FormEvents;
use Doctrine\ORM\EntityRepository;

class PatientQuestionaryValidationType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $data = $builder->getData();

        $questionary = $data->getQuestionary();

        /*$transformer = new PatientQuestionaryValidationToNumberTransformer($this->em);

        $builder->add(
            $builder->create('validations', 'entity', array(
                      'class'    => 'TeclliureQuestionBundle:Validation' ,
                      'property' => 'name',
                      'expanded' => true ,
                      'multiple' => true,
                      'query_builder' => function(EntityRepository $er) use ($questionary) {
                            return $er->createQueryBuilder('q')
                               ->where('q.questionary = :questionary')
                               ->setParameter('questionary',$questionary->getId())
                               ->orderBy('q.name', 'ASC');
                      },
            ))->addModelTransformer($transformer)
        );*/

        $builder->add('validations', 'entity', array(
                'class'    => 'TeclliureQuestionBundle:Validation' ,
                'property' => 'name',
                'expanded' => true ,
                'multiple' => true,
                'query_builder' => function(EntityRepository $er) use ($questionary) {
                    return $er->createQueryBuilder('q')
                        ->where('q.questionary = :questionary')
                        ->setParameter('questionary',$questionary->getId())
                        ->orderBy('q.name', 'ASC');
                },
            )
        );
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Teclliure\QuestionBundle\Entity\PatientQuestionary'
        ));
    }

    public function getName()
    {
        return 'teclliure_questionbundle_patientquestionary_validationtype';
    }
}


text:
from cairis.core.ARM import *
from cairis.daemon.CairisHTTPError import CairisHTTPError, ARMHTTPError
from cairis.data.CairisDAO import CairisDAO
__author__ = 'Shamal Faily'

class ValidationDAO(CairisDAO):

  def __init__(self, session_id):
    CairisDAO.__init__(self, session_id)

  def model_validation(self,envName):
    try:
      return self.db_proxy.modelValidation(envName)
    except ARMException as ex:
      self.close()
      raise ARMHTTPError(ex)

redpajama_set_name: RedPajamaGithub


text:
package eu.bcvsolutions.idm.core.model.service.impl;

import java.io.InputStream;
import java.util.List;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import eu.bcvsolutions.idm.core.api.dto.IdmExportImportDto;
import eu.bcvsolutions.idm.core.api.dto.filter.IdmExportImportFilter;
import eu.bcvsolutions.idm.core.api.dto.filter.IdmImportLogFilter;
import eu.bcvsolutions.idm.core.api.service.AbstractEventableDtoService;
import eu.bcvsolutions.idm.core.api.service.EntityEventManager;
import eu.bcvsolutions.idm.core.api.service.IdmExportImportService;
import eu.bcvsolutions.idm.core.api.service.IdmImportLogService;
import eu.bcvsolutions.idm.core.api.utils.DtoUtils;
import eu.bcvsolutions.idm.core.ecm.api.service.AttachmentManager;
import eu.bcvsolutions.idm.core.model.domain.CoreGroupPermission;
import eu.bcvsolutions.idm.core.model.entity.IdmExportImport;
import eu.bcvsolutions.idm.core.model.entity.IdmExportImport_;
import eu.bcvsolutions.idm.core.model.repository.IdmExportImportRepository;
import eu.bcvsolutions.idm.core.scheduler.api.dto.IdmLongRunningTaskDto;
import eu.bcvsolutions.idm.core.scheduler.entity.IdmLongRunningTask_;
import eu.bcvsolutions.idm.core.security.api.dto.AuthorizableType;

/**
 * CRUD for export and import data
 *
 * @author Vít Švanda
 *
 */
@Service("exportImportService")
public class DefaultIdmExportImportService
	extends AbstractEventableDtoService<IdmExportImportDto, IdmExportImport, IdmExportImportFilter>
	implements IdmExportImportService {

	@Autowired
	private AttachmentManager attachmentManager;
	@Autowired
	private IdmImportLogService importLogService;

	@Autowired
	public DefaultIdmExportImportService(
			IdmExportImportRepository repository,
			EntityEventManager entityEventManager) {
		super(repository, entityEventManager);
	}

	@Override
	@Transactional
	public void deleteInternal(IdmExportImportDto dto) {
		Assert.notNull(dto, "Batch cannot be null for delete!");
		Assert.notNull(dto.getId(), "Batch ID cannot be null for delete!");

		// delete attachments
		attachmentManager.deleteAttachments(dto);
		// Delete all logs for this batch.
		IdmImportLogFilter logFilter = new IdmImportLogFilter();
		logFilter.setBatchId(dto.getId());
		importLogService.findIds(logFilter, null)//
				.getContent()//
				.forEach(logId -> {
					importLogService.deleteById(logId);
				});

		super.deleteInternal(dto);
	}

	@Override
	public AuthorizableType getAuthorizableType() {
		return new AuthorizableType(CoreGroupPermission.EXPORTIMPORT, getEntityClass());
	}

	@Override
	public InputStream download(IdmExportImportDto batch) {
		Assert.notNull(batch, "Batch cannot be null!");
		Assert.notNull(batch.getData(), "Batch must contains attachment ID!");

		return attachmentManager.getAttachmentData(batch.getData());
	}

	@Override
	protected IdmExportImportDto toDto(IdmExportImport entity, IdmExportImportDto dto, IdmExportImportFilter filter) {
		dto = super.toDto(entity, dto, filter);
		if (dto != null && dto.getLongRunningTask() != null) {
			IdmLongRunningTaskDto lrt = DtoUtils.getEmbedded(dto, IdmExportImport_.longRunningTask.getName(),
					IdmLongRunningTaskDto.class);
			if (lrt != null) {
				dto.setResult(lrt.getResult());
			}
		}

		return dto;
	}

	@Override
	public boolean supportsToDtoWithFilter() {
		return true;
	}

	@Override
	protected List<Predicate> toPredicates(Root<IdmExportImport> root, CriteriaQuery<?> query, CriteriaBuilder builder,
			IdmExportImportFilter filter) {
		List<Predicate> predicates =  super.toPredicates(root, query, builder, filter);
		//
		if (StringUtils.isNotEmpty(filter.getText())) {
			predicates.add(builder.like(builder.lower(root.get(IdmExportImport_.name)), "%" + filter.getText().toLowerCase() + "%"));
		}
		UUID longRunningTaskId = filter.getLongRunningTaskId();
		if (longRunningTaskId != null) {
			predicates.add(builder.equal(root.get(IdmExportImport_.longRunningTask).get(IdmLongRunningTask_.id), longRunningTaskId));
		}
		if (filter.getType() != null) {
			predicates.add(builder.equal(root.get(IdmExportImport_.type), filter.getType()));
		}
		//
		return predicates;
	}
}


text:
using MatterHackers.Agg.UI;

namespace MatterHackers.MatterControl.Tour
{
	public class TourLocation
	{
		public string WidgetName { get; set; }

		public string Title { get; set; }

		public string Description { get; set; }

		public GuiWidget Widget { get; internal set; }
	}
}


text:
These scripts should be run from the repository root,
with an activated virtualenv.

You may also need to set the environment variable `DJANGO_SETTINGS_MODULE`
appropriately.

Invoke a script as follows:

```
python -m stagecraft.tools.script arg1 arg2
```

## (import_dashboards.py) Importing data from the Transactions Explorer Google spreadsheet

The application in `backdrop-transactions-explorer-collector` is used to import data
from the Transactions Explorer Google spreadsheet into the Backdrop database every quarter.

As a follow-on step, it is necessary to create or update dashboard and module
configuration data in the Stagecraft database, so that the data imported into
Backdrop can be presented on the Performance Platform.

To do so:

1. Get access to the Google Spreadsheet
2. Set up environment variables needed by the import
3. Run the import

### Get access to the Google spreadsheet

When `import_dashboards.py` is run, its first task is to collect data from the Google spreadsheet.

Access to the Google spreadsheet is via OAuth 2.0 using the Python `oauth2client`. For this,
you will need a Google Service Account, which is an account that belongs to an application
instead of an individual end user.

You can set up a Service Account in the Google Development Console. Simply log in,
create a project and then add Service Account credentials for this project of key
type 'JSON'. Download the JSON credentials files.

Now ask the on-boarding team to grant access to the Google spreadsheet for the client
email address that can be found in JSON credentials file.

### Set up environment variables needed by the import

Two environment variables should be set before running the script:

SUMMARIES_URL - location of imported Transactions Explorer data in Backdrop

```bash
export SUMMARIES_URL='http://www.performance.service.gov.uk/data/transactional-services/summaries'
```

GOOGLE_APPLICATION_CREDENTIALS - location of the JSON credentials file generated in previous step

```bash
export GOOGLE_APPLICATION_CREDENTIALS='path/to/file'
```

### Run the import in development

```bash
export DJANGO_SETTINGS_MODULE=stagecraft.settings.development
```

```
python -m stagecraft.tools.import_dashboards
```

The script accepts the flags: --update, --commit and --publish.

--update: Update the dashboard config of all existing dashboards from the spreadsheet as well as creating new dashboards.

--commit: Save the changes to the database. Sets the dry_run flag to false.

--publish: Publish all dashboards, even those that have not been signed off yet.

### Run the import in other environments

```bash
sudo -u deploy DJANGO_SETTINGS_MODULE=stagecraft.settings.production GOOGLE_APPLICATION_CREDENTIALS='path/to/file' SUMMARIES_URL='http://www.performance.service.gov.uk/data/transactional-services/summaries' venv/bin/python -m stagecraft.tools.import_dashboards --update --commit --publish
```

## (import_organisations.py) Link imported dashboards to an organisation

After `import_dashboards.py` has run, `import_organisations.py` needs to be run to associate a dashboard with an organisation.  These organisations are used in spotlight as service groups to filter services.

`import_organisations.py` uses the same environment variables that were set up for `import_dashboards.py`

`import_organisations.py` reuses the two pickle files (names_values.pickle, tx_values.pickle) created by the `import_dashboards.py` script.

### Run the import in development

```
python -m stagecraft.tools.import_organisations
```

### Run the import in other environments

```bash
sudo -u deploy DJANGO_SETTINGS_MODULE=stagecraft.settings.production GOOGLE_APPLICATION_CREDENTIALS='path/to/file' venv/bin/python -m stagecraft.tools.import_organisations
```


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

The com.clockwork.animation package contains various classes
for managing animation inside a jME3 application. Currently, the majority
of classes are for handling skeletal animation. The primary control class is
the {@link com.clockwork.animation.AnimControl}, through which animations can be played,
looped, combined, transitioned, etc.

Usage

// Create or load a model with skeletal animation:

Spatial model = assetManager.loadModel("...");

// Retrieve the AnimControl.

AnimControl animCtrl = model.getControl(AnimControl.class);

// Create an animation channel, by default assigned to all bones.

AnimChannel animChan = animCtrl.createChannel();

// Play an animation

animChan.setAnim("MyAnim");

Skeletal Animation System

jME3 uses a system of bone-weights: A vertex is assigned up to 4 bones by which
it is influenced and 4 weights that describe how much the bone influences the
vertex. The maximum weight value being 1.0, and the requirement that all 4 weights
for a given vertex must sum to 1.0. This data is specified
for each skin/mesh that is influenced by the animation control via the
{link com.clockwork.scene.VertexBuffer}s BoneWeight and BoneIndex.
The BoneIndex buffer must be of the format UnsignedByte, thus
placing the limit of up to 256 bones for a skeleton. The BoneWeight buffer
should be of the format Float. Both buffers should reference 4
bones, even if the maximum number of bones any vertex is influenced is less or more
than 4.

If a vertex is influenced by less than 4 bones, the indices following the last
valid bone should be 0 and the weights following the last valid bone should be 0.0.
The buffers are designed in such a way so as to permit hardware skinning.

The {@link com.clockwork.animation.Skeleton} class describes a bone heirarchy with one
or more root bones having children, thus containing all bones of the skeleton.
In addition to accessing the bones in the skeleton via the tree heirarchy, it
is also possible to access bones via index. The index for any given bone is
arbitrary and does not depend on the bone's location in the tree hierarchy.
It is this index that is specified in the BoneIndex VertexBuffer mentioned above
, and is also used to apply transformations to the bones through the animations.

Every bone has a local and model space transformation. The local space
transformation is relative to its parent, if it has one, otherwise it is relative
to the model. The model space transformation is relative to model space.
The bones additionally have a bind pose transformation, which describes
the transformations for bones when no animated pose is applied to the skeleton.
All bones must have a bind pose transformation before they can be
animated. To set the bind pose for the skeleton, set the local (relative
to parent) transformations for all the bones using the call
{@link com.clockwork.animation.Bone#setBindTransforms(com.clockwork.math.Vector3f, com.clockwork.math.Quaternion, com.clockwork.math.Vector3f) }.
Then call {@link com.clockwork.animation.Skeleton#updateWorldVectors() } followed by
{@link com.clockwork.animation.Skeleton#setBindingPose() }.

Animations are stored in a HashMap object, accessed by name. An animation
is simply a list of tracks, each track describes a timeline with each keyframe
having a transformation. For bone animations, every track is assigned to a bone,
while for morph animations, every track is assigned to a mesh.


text:
@implementation HeaderImageView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)awakeFromNib {
    [self.label.layer setShadowColor:[UIColor blackColor].CGColor];
    [self.label.layer setShadowOffset:CGSizeMake(0, 1)];
    [self.label.layer setShadowOpacity:0.8];
    [self.label.layer setShadowRadius:1];

}

- (CGSize)intrinsicContentSize {
    return CGSizeMake(UIViewNoIntrinsicMetric, 200);
}

- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];
    self.imageView.frame = self.bounds;
}

- (void)layoutSubviews {
    [super layoutSubviews];

    self.imageView.center = CGPointMake(CGRectGetWidth(self.frame)/2, CGRectGetHeight(self.frame)/2);
}

@end


text:
package testclasses;

public class SimpleCastSuccess1 {

   public static void main(String[] args) {

   }

    /**
     * x has Type TOP, y has typ PUBLIC, return value is dynamic
     */
   public static int m(int x, int y) {
      int z = castTopToDyn(x);
      z += castPubToDyn(y);
      if (z >= 0) {
         return 1;
      } else {
         return 0;
      }
   }

   private static int castTopToDyn(int x) {
      return x;
   }

   private static int castPubToDyn(int x) {
      return x;
   }

}


text:
package com.alibaba.dubbo.rpc.protocol.injvm;

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

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;

import org.junit.After;
import org.junit.Test;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.extension.ExtensionLoader;
import com.alibaba.dubbo.rpc.Exporter;
import com.alibaba.dubbo.rpc.Protocol;
import com.alibaba.dubbo.rpc.ProxyFactory;

/**
 * ProxiesTest
 */

public class InjvmProtocolTest
{
    private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
    private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
    private List<Exporter<?>> exporters = new ArrayList<Exporter<?>>();

    @After
    public void after() throws Exception {
        for(Exporter<?> exporter : exporters) {
            exporter.unexport();
        }
        exporters.clear();
    }

	@Test
	public void testLocalProtocol() throws Exception
	{
		DemoService service = new DemoServiceImpl();
		Exporter<?> exporter = protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("injvm://127.0.0.1/TestService").addParameter(Constants.INTERFACE_KEY, DemoService.class.getName())));
        exporters.add(exporter);
		service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("injvm://127.0.0.1/TestService").addParameter(Constants.INTERFACE_KEY, DemoService.class.getName())));
		assertEquals(service.getSize(new String[]{"", "", ""}), 3);
		service.invoke("injvm://127.0.0.1/TestService", "invoke");
	}

    @Test
    public void testIsInjvmRefer() throws Exception {
        DemoService service = new DemoServiceImpl();
        URL url = URL.valueOf("injvm://127.0.0.1/TestService")
            .addParameter(Constants.INTERFACE_KEY, DemoService.class.getName());
        Exporter<?> exporter = protocol.export(proxy.getInvoker(service, DemoService.class, url));
        exporters.add(exporter);

        url = url.setProtocol("dubbo");
        assertTrue(InjvmProtocol.getInjvmProtocol().isInjvmRefer(url));

        url = url.addParameter(Constants.GROUP_KEY, "*")
            .addParameter(Constants.VERSION_KEY, "*");
        assertTrue(InjvmProtocol.getInjvmProtocol().isInjvmRefer(url));
    }

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bull. Torrey bot. Club 64: 39 (1937)

#### Original name
Ravenelia caesalpiniae Arthur, 1904

### Remarks
null


text:
if Sinatra::Application.development?
  ActiveRecord::Base.logger = Logger.new(STDOUT)
end

# See http://www.rubyinside.com/ruby-techniques-revealed-autoload-1652.html
Dir[APP_ROOT.join('app', 'models', '*.rb')].each do |model_file|
  filename = File.basename(model_file).gsub('.rb', '')
  autoload ActiveSupport::Inflector.camelize(filename), model_file
end

# Heroku controls what database we connect to by setting the DATABASE_URL environment variable
# We need to respect that if we want our Sinatra apps to run on Heroku without modification
db = URI.parse(ENV['DATABASE_URL'] || "postgres://localhost/#{APP_NAME}_#{Sinatra::Application.environment}")

DB_NAME = db.path[1..-1] # chomps off '/' because `db.path` is a path

# Note:
#   Sinatra::Application.environment is set to the value of ENV['RACK_ENV']
#   if ENV['RACK_ENV'] is set.  If ENV['RACK_ENV'] is not set, it defaults
#   to :development

ActiveRecord::Base.establish_connection(
:adapter => db.scheme == 'postgres' ? 'postgresql' : db.scheme,
:host => db.host,
# :username => 'postgres',
:username => db.user,
# :password => 'pass',
:password => db.password,
:database => DB_NAME,
:encoding => 'utf8'
  )


text:
#include "gstcurlqueue.h"

/**
 * gst_curl_http_src_add_queue_item:
 *
 * Function to add an item to a queue. If the queue is empty (i.e. NULL), then
 * it creates the new head of the queue, otherwise it scans to the end and adds
 * the entry there.
 * @param queue The queue to add an item to. Can be NULL.
 * @param s The item to be added to the queue.
 * @return Returns TRUE (0) on success, FALSE (!0) is an error.
 */
gboolean
gst_curl_http_src_add_queue_item (GstCurlHttpSrcQueueElement ** queue,
    GstCurlHttpSrc * s)
{
  GstCurlHttpSrcQueueElement *insert_point;

  if (*queue == NULL) {
    /* Queue is currently empty, so create a new item on the head */
    *queue = (GstCurlHttpSrcQueueElement *)
        g_malloc (sizeof (GstCurlHttpSrcQueueElement));
    if (*queue == NULL) {
      return FALSE;
    }
    insert_point = *queue;
  } else {
    insert_point = *queue;
    while (insert_point->next != NULL) {
      insert_point = insert_point->next;
    }
    insert_point->next = (GstCurlHttpSrcQueueElement *)
        g_malloc (sizeof (GstCurlHttpSrcQueueElement));
    if (insert_point->next == NULL) {
      return FALSE;
    }
    insert_point = insert_point->next;
  }

  insert_point->p = s;
  g_atomic_int_set (&insert_point->running, 0);
  insert_point->next = NULL;
  s->connection_status = GSTCURL_CONNECTED;
  return TRUE;
}

/**
 * gst_curl_http_src_remove_queue_item:
 *
 * Function to remove an item from a queue.
 * @param queue The queue to remove an item from.
 * @param s The item to be removed.
 * @return Returns TRUE if item removed, FALSE if item couldn't be found.
 */
gboolean
gst_curl_http_src_remove_queue_item (GstCurlHttpSrcQueueElement ** queue,
    GstCurlHttpSrc * s)
{
  GstCurlHttpSrcQueueElement *prev_qelement, *this_qelement;

  prev_qelement = NULL;
  this_qelement = *queue;
  while (this_qelement && (this_qelement->p != s)) {
    prev_qelement = this_qelement;
    this_qelement = this_qelement->next;
  }
  if (this_qelement == NULL) {
    /* Reached end of list without finding anything */
    return FALSE;
  }

  /* First queue item matched. */
  if (prev_qelement == NULL) {
    /* First and only element? If so, free the element and make queue NULL */
    if (this_qelement->next == NULL) {
      g_free (*queue);
      *queue = NULL;
      return TRUE;
    } else {
      *queue = this_qelement->next;
    }
  } else {
    prev_qelement->next = this_qelement->next;
  }
  g_free (this_qelement);
  s->connection_status = GSTCURL_NOT_CONNECTED;
  return TRUE;
}

/**
 * gst_curl_http_src_remove_queue_handle:
 *
 * Convenience function to remove an item from a queue by it's contained curl
 * handle. Only ever called from within the multi loop when the CURL handle
 * returns, so it's safe to assume that the transfer completed and the result
 * can be set as GSTCURL_RETURN_DONE (which doesn't necessarily mean that the
 * transfer was a success, just that CURL is finished with it)
 * @param queue The queue to remove an item from.
 * @param s The item to be removed.
 * @return Returns TRUE if item removed, FALSE if item couldn't be found.
 */
gboolean
gst_curl_http_src_remove_queue_handle (GstCurlHttpSrcQueueElement ** queue,
    CURL * handle, CURLcode result)
{
  GstCurlHttpSrcQueueElement *prev_qelement, *this_qelement;

  prev_qelement = NULL;
  this_qelement = *queue;
  while (this_qelement && (this_qelement->p->curl_handle != handle)) {
    prev_qelement = this_qelement;
    this_qelement = this_qelement->next;
  }
  if (this_qelement == NULL) {
    /* Reached end of list without finding anything */
    return FALSE;
  }

  /*GST_DEBUG_OBJECT (this_qelement->p,
     "Removing queue item via curl handle for URI %s",
     this_qelement->p->uri); */
  /* First, signal the transfer owner thread to wake up */
  g_mutex_lock (&this_qelement->p->buffer_mutex);
  g_cond_signal (&this_qelement->p->buffer_cond);
  if (this_qelement->p->state != GSTCURL_UNLOCK) {
    this_qelement->p->state = GSTCURL_DONE;
  } else {
    this_qelement->p->pending_state = GSTCURL_DONE;
  }
  this_qelement->p->connection_status = GSTCURL_NOT_CONNECTED;
  this_qelement->p->curl_result = result;
  g_mutex_unlock (&this_qelement->p->buffer_mutex);

  /* First queue item matched. */
  if (prev_qelement == NULL) {
    /* First and only element? If so, free the element and make queue NULL */
    if (this_qelement->next == NULL) {
      g_free (*queue);
      *queue = NULL;
      return TRUE;
    } else {
      *queue = this_qelement->next;
    }
  } else {
    prev_qelement->next = this_qelement->next;
  }
  g_free (this_qelement);
  return TRUE;
}


text:
#nullable enable

using System;
using System.Collections.Generic;
using System.Linq;
using Pchp.Core.Reflection;
using Pchp.Core.Utilities;

namespace Pchp.Core
{
    partial class Context
    {
        #region Functions

        /// <summary>
        /// Declare user function into the PHP runtime context.
        /// </summary>
        /// <param name="name">Global PHP function name.</param>
        /// <param name="delegate">Delegate to represent the PHP function.</param>
        public void DeclareFunction(string name, Delegate @delegate) => _functions.DeclarePhpRoutine(RoutineInfo.CreateUserRoutine(name, @delegate));

        /// <summary>
        /// Call a function by its name dynamically.
        /// </summary>
        /// <param name="function">Function name valid within current runtime context.</param>
        /// <returns>Returns value given from the function call.</returns>
        public PhpValue Call(string function) => PhpCallback.Create(function).Invoke(this, Array.Empty<PhpValue>());

        /// <summary>
        /// Call a function by its name dynamically.
        /// </summary>
        /// <param name="function">Function name valid within current runtime context.</param>
        /// <param name="arguments">Arguments to be passed to the function call.</param>
        /// <returns>Returns value given from the function call.</returns>
        public PhpValue Call(string function, params PhpValue[] arguments) => PhpCallback.Create(function).Invoke(this, arguments);

        /// <summary>
        /// Call a function by its name dynamically.
        /// </summary>
        /// <param name="function">Function name valid within current runtime context.</param>
        /// <param name="arguments">Arguments to be passed to the function call.</param>
        /// <returns>Returns value given from the function call.</returns>
        public PhpValue Call(string function, params object[] arguments) => PhpCallback.Create(function).Invoke(this, PhpValue.FromClr(arguments));

        #endregion

        #region Instantiation

        /// <summary>
        /// Creates an instance of a type dynamically with constructor overload resolution.
        /// </summary>
        /// <typeparam name="T">Object type.</typeparam>
        /// <param name="arguments">Arguments to be passed to the constructor.</param>
        /// <returns>New instance of <typeparamref name="T"/>.</returns>
        public T Create<T>(params PhpValue[] arguments) => (T)TypeInfoHolder<T>.TypeInfo.Creator(this, arguments);

        /// <summary>
        /// Creates an instance of a type dynamically with constructor overload resolution.
        /// </summary>
        /// <typeparam name="T">Object type.</typeparam>
        /// <param name="caller">
        /// Class context for resolving constructors visibility.
        /// Can be <c>default(<see cref="RuntimeTypeHandle"/>)</c> to resolve public constructors only.</param>
        /// <param name="arguments">Arguments to be passed to the constructor.</param>
        /// <returns>New instance of <typeparamref name="T"/>.</returns>
        public T Create<T>([ImportValue(ImportValueAttribute.ValueSpec.CallerClass)] RuntimeTypeHandle caller, params PhpValue[] arguments)
            => (T)TypeInfoHolder<T>.TypeInfo.ResolveCreator(Type.GetTypeFromHandle(caller))(this, arguments);

        /// <summary>
        /// Creates an instance of a type dynamically.
        /// </summary>
        /// <exception cref="InvalidOperationException">If the class is not declared.</exception>
        public object Create(string classname) => Create(classname, Array.Empty<PhpValue>());

        /// <summary>
        /// Creates an instance of a type dynamically with constructor overload resolution.
        /// </summary>
        /// <param name="classname">Full name of the class to instantiate. The name uses PHP syntax of name separators (<c>\</c>) and is case insensitive.</param>
        /// <param name="arguments">Arguments to be passed to the constructor.</param>
        /// <returns>The object instance.</returns>
        /// <exception cref="InvalidOperationException">If the class is not declared.</exception>
        public object Create(string classname, params object[] arguments) => Create(classname, PhpValue.FromClr(arguments));

        /// <summary>
        /// Creates an instance of a type dynamically with constructor overload resolution.
        /// </summary>
        /// <param name="classname">Full name of the class to instantiate. The name uses PHP syntax of name separators (<c>\</c>) and is case insensitive.</param>
        /// <param name="arguments">Arguments to be passed to the constructor.</param>
        /// <returns>The object instance.</returns>
        /// <exception cref="InvalidOperationException">If the class is not declared.</exception>
        public object Create(string classname, params PhpValue[] arguments) => Create(default(RuntimeTypeHandle), classname, arguments);

        /// <summary>
        /// Creates an instance of a type dynamically with constructor overload resolution.
        /// </summary>
        /// <param name="caller">
        /// Class context for resolving constructors visibility.
        /// Can be <c>default(<see cref="RuntimeTypeHandle"/>)</c> to resolve public constructors only.</param>
        /// <param name="classname">Full name of the class to instantiate. The name uses PHP syntax of name separators (<c>\</c>) and is case insensitive.</param>
        /// <param name="arguments">Arguments to be passed to the constructor.</param>
        /// <returns>The object instance.</returns>
        /// <exception cref="InvalidOperationException">If the class is not declared.</exception>
        public object Create([ImportValue(ImportValueAttribute.ValueSpec.CallerClass)] RuntimeTypeHandle caller, string classname, params PhpValue[] arguments)
        {
            var tinfo = this.GetDeclaredTypeOrThrow(classname, true);
            return Create(caller, tinfo, arguments);
        }

        /// <summary>
        /// Creates an instance of a type dynamically with constructor overload resolution.
        /// </summary>
        /// <param name="caller">
        /// Class context for resolving constructors visibility.
        /// Can be <c>default(<see cref="RuntimeTypeHandle"/>)</c> to resolve public constructors only.</param>
        /// <param name="tinfo">Type to be instantiated.</param>
        /// <param name="arguments">Arguments to be passed to the constructor.</param>
        /// <returns>The object instance.</returns>
        /// <exception cref="ArgumentNullException">If provided <paramref name="tinfo"/> is <c>null</c>.</exception>
        public object Create([ImportValue(ImportValueAttribute.ValueSpec.CallerClass)] RuntimeTypeHandle caller, PhpTypeInfo tinfo, params PhpValue[] arguments)
        {
            if (tinfo != null)
            {
                return tinfo.ResolveCreator(Type.GetTypeFromHandle(caller))(this, arguments);
            }
            else
            {
                throw new ArgumentNullException(nameof(tinfo));
            }
        }

        #endregion

        #region Extensions

        /// <summary>
        /// Gets collection of extension names loaded into the application context.
        /// </summary>
        public static ICollection<string> GetLoadedExtensions() => ExtensionsAppContext.ExtensionsTable.GetExtensions();

        /// <summary>
        /// Gets value indicating that given extension was loaded.
        /// </summary>
        public static bool IsExtensionLoaded(string extension) => ExtensionsAppContext.ExtensionsTable.ContainsExtension(extension);

        /// <summary>
        /// Gets routines associated with specified extension.
        /// </summary>
        /// <param name="extension">Extension name.</param>
        /// <returns>Enumeration of routine names associated with given extension.</returns>
        public static IEnumerable<RoutineInfo> GetRoutinesByExtension(string extension)
        {
            return ExtensionsAppContext.ExtensionsTable.GetRoutinesByExtension(extension);
        }

        /// <summary>
        /// Gets types (classes, interfaces and traits) associated with specified extension.
        /// </summary>
        /// <param name="extension">Extension name.</param>
        /// <returns>Enumeration of types associated with given extension.</returns>
        public static IEnumerable<PhpTypeInfo> GetTypesByExtension(string extension)
        {
            return ExtensionsAppContext.ExtensionsTable.GetTypesByExtension(extension);
        }

        #endregion

        #region Scripts

        /// <summary>
        /// Gets enumeration of scripts that were included.
        /// </summary>
        public IEnumerable<ScriptInfo> GetIncludedScripts() => _scripts.GetIncludedScripts();

        /// <summary>
        /// Declares or redeclares script within runtime using delegate.
        /// The script will be available for inclusions.
        /// </summary>
        /// <param name="relpath">Relative path of the script without leading slash.</param>
        /// <param name="main">Script entry point.</param>
        public static void DeclareScript(string relpath, MainDelegate main) => ScriptsMap.DeclareScript(relpath, main);

        /// <summary>
        /// Tries to resolve compiled script according to given path.
        /// </summary>
        public static ScriptInfo TryResolveScript(string root, string path) => ScriptsMap.ResolveInclude(path, root, include_path: null, working_dir: root, script_dir: null);

        /// <summary>
        /// Gets script according to its relative path as it was declared in <see cref="Context"/>.
        /// </summary>
        /// <param name="relpath">Relative script path.</param>
        /// <returns>Script descriptor, can be invalid if script was not declared.</returns>
        public static ScriptInfo TryGetDeclaredScript(string relpath) => ScriptsMap.GetDeclaredScript(relpath);

        /// <summary>
        /// Gets scripts in given directory.
        /// </summary>
        public static bool TryGetScriptsInDirectory(string root, string path, out ScriptInfo[] scripts)
        {
            // assert: root is not suffixed with directory separator

            // trim leading {root} path:
            if (!string.IsNullOrEmpty(root) && path.StartsWith(root, CurrentPlatform.PathStringComparison))
            {
                if (path.Length == root.Length)
                {
                    path = string.Empty;
                }
                else if (path[root.Length] == CurrentPlatform.DirectorySeparator)
                {
                    path = (path.Length > root.Length + 1) ? path.Substring(root.Length + 1) : string.Empty;
                }
                else
                {
                    scripts = Array.Empty<ScriptInfo>();
                    return false;
                }
            }

            // try to get compiled scripts within path:
            return ScriptsMap.TryGetDirectory(path, out scripts);
        }

        #endregion

        #region Constants

        /// <summary>
        /// Tries to get a global constant from current context.
        /// </summary>
        public bool TryGetConstant(string name, out PhpValue value)
        {
            int idx = 0;
            return TryGetConstant(name, out value, ref idx);
        }

        /// <summary>
        /// Tries to get a global constant from current context.
        /// </summary>
        internal bool TryGetConstant(string name, out PhpValue value, ref int idx) => _constants.TryGetConstant(name, ref idx, out value);

        /// <summary>
        /// Defines a user constant.
        /// </summary>
        public bool DefineConstant(string name, PhpValue value, bool ignorecase = false)
        {
            int idx = 0;
            return DefineConstant(name, value, ref idx, ignorecase);
        }

        /// <summary>
        /// Defines a user constant.
        /// </summary>
        internal bool DefineConstant(string name, PhpValue value, ref int idx, bool ignorecase = false)
        {
            var success = ConstsMap.DefineConstant(ref _constants, name, value, ref idx, ignorecase);
            if (success == false)
            {
                PhpException.Throw(PhpError.Notice, string.Format(Resources.ErrResources.constant_redefined, name));
            }
            return success;
        }

        /// <summary>
        /// Determines whether a constant with given name is defined.
        /// </summary>
        public bool IsConstantDefined(string name) => _constants.TryGetConstant(name, out _);

        /// <summary>
        /// Gets enumeration of all available constants and their values.
        /// </summary>
        /// <param name="extension">Optionally specify the extension name; only constants defined within this extension will be enumerated.</param>
        public ConstsMap.Enumerator GetConstants(string? extension = null) => _constants.GetEnumerator(extension);

        #endregion
    }
}


text:
package com.wangjie.rapidfloatingactionbutton.example;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.wangjie.androidinject.annotation.annotations.base.AIClick;
import com.wangjie.androidinject.annotation.annotations.base.AILayout;
import com.wangjie.androidinject.annotation.present.AIActionBarActivity;
import com.wangjie.rapidfloatingactionbutton.example.cardtest.CardListSampleActivity;
import com.wangjie.rapidfloatingactionbutton.example.rfabgroup.RFABGroupSampleActivity;

@AILayout(R.layout.activity_main)
public class MainActivity extends AIActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    @AIClick({R.id.activity_main_separate_rfab_sample_btn, R.id.activity_main_label_list_sample_btn,
            R.id.activity_main_rfab_group_btn, R.id.activity_main_card_list_sample_btn})
    public void onClickCallbackSample(View view) {
        switch (view.getId()) {
            case R.id.activity_main_label_list_sample_btn:
                startActivity(new Intent(context, LabelListSampleActivity.class));
                break;
            case R.id.activity_main_separate_rfab_sample_btn:
                startActivity(new Intent(context, SeparateRFABSampleActivity.class));
                break;
            case R.id.activity_main_rfab_group_btn:
                startActivity(new Intent(context, RFABGroupSampleActivity.class));
                break;
            case R.id.activity_main_card_list_sample_btn:
                startActivity(new Intent(context, CardListSampleActivity.class));
                break;
            default:
                break;
        }
    }
}


text:
<!DOCTYPE html>

<title>DevOps | DevOps Specialist Company</title>
<link href="favicon.ico" rel="shortcut icon">
<link href="images/favicon_img.png" type="image/png" rel="icon">
<meta charset="utf-8" />
<meta name="description" content="Relevance Lab is a DevOps Specialist Company, Making Cloud Adoption easy for Enterprises. Know more.">
<meta name="keywords" content="Azure solutions, Devops cloud, dev test cloud, DevOps Solutions, devops company, Chef and Puppet, cloud solutions for business,sharepoint cloud, Cloud deployments, Infrastructure Automation, Amazon solutions">
<meta name="robots" content="all">
<meta name="googlebot" content="all,index,follow">
<meta name="author" content="Srinivasa kumar">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

     <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
    <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet">
    <link href="css/bootstrap.css" rel="stylesheet">
    <link href="css/boot-responsive.css" rel="stylesheet">
    <link href="css/bootstrap-responsive.css" rel="stylesheet">
    <link href="css/bootstrap-override.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="css/theme.css">
    <link rel="stylesheet" type="text/css" href="css/isotope.css">
    <link rel="stylesheet" href="css/index.css" type="text/css" media="screen" />
    <link rel="stylesheet" type="text/css" href="css/flex.css">
     <link rel="stylesheet" type="text/css" href="css/services.css">
    <link rel="stylesheet" type="text/css" href="css/portfolio.css">
    <link href="css/font.css" rel='stylesheet' type='text/css'>
    <link href="css/customstyles.css" rel='stylesheet' type='text/css'>

<link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" />

HOME

DEVOPS

OFFERINGS

VERTICALS

IDENTITY

BUZZ

CAREERS

CONTACT

DevOps

"DevOps is a new discipline that complements the Agile Delivery models for software engineering by bringing in Automation and Monitoring on the IT side and leverages Cloud computing concepts.
    DevOps leverages collaboration, tool-chain pipelines, automation and Cloud adoption. The immediate benefits can be observed as improved processes, more standardizations and building trust and improve productivity across development, QA and IT operations teams."

Value of DevOps

Faster Time to Market

Improved Quality

Better Organization Effectiveness

Drives Business Agility through Continuous Integration and Continuous Delivery of Products

Improves infrastructure provisioning through automated deployments and self service portals

Speeds Deployments by aligning development  and operations with Enterprise Architecture guidelines

Improves Production Performance Monitoring and Proactive Incident Management through Automation, Development and Collaboration

Strengthens Service Delivery, Automation of Dev + QA + Ops Processes and Management with a Common Lifecycle View

Use Cases that Relevance Lab DevOps Platform addresses

Relevance Lab has built a DevOps platform that offers an integrated solution of application/service development, testing, deployment, scaling and monitoring, as well as ensure software quality, security, availability, reliability and performance.

In the current world there is a dramatic shift in larger organizations openness to look at open source technologies and cloud platforms to leverage the benefits of cost, scale and open architectures. As enterprises look to start the journey for DevOps Relevance Lab Cloud Platform can help solve critical business case in following areas:

DevOps Driven Engineering for Continuous Integration for Dev and Ops

Infrastructure Automation for Cloud and Private Data Centre Support

Cloud Management for Application Release Orchestration and Cloud Recipes

Cloud Command Centre for Performance Monitoring and optimizations, Proactive corrective actions (Watch-list), Business Operations Monitoring

How can the DevOps Platform be used by enterprises?

Relevance Lab DevOps platform is available in both On-Premise and Hosted mode and supports multiple Private and Public Cloud deployments options.

Key components of the DevOps Platform

The DevOps Platform is created with a loosely couple architecture modelled around the following key roles. It currently supports two technology stacks:

Open Source based tools with support for Private and Public Clouds

Microsoft Software Stack of Tools on Azure

Relevance Lab DevOps Partnerships and Ecosystem

© 2013 Relevance Lab. All rights reserved |

Sitemap


text:
package org.camelcookbook.routing.loadbalancer;

import org.apache.camel.EndpointInject;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.CamelSpringTestSupport;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class LoadBalancerStickySpringTest extends CamelSpringTestSupport {
    @Produce(uri = "direct:start")
    protected ProducerTemplate template;

    @EndpointInject(uri = "mock:first")
    private MockEndpoint first;

    @EndpointInject(uri = "mock:second")
    private MockEndpoint second;

    @EndpointInject(uri = "mock:third")
    private MockEndpoint third;

    @EndpointInject(uri = "mock:out")
    private MockEndpoint out;

    @Override
    protected AbstractApplicationContext createApplicationContext() {
        return new ClassPathXmlApplicationContext("META-INF/spring/loadBalancer-sticky-context.xml");
    }

    @Test
    public void testMessageLoadBalancedToStickyEndpoints() throws InterruptedException {
        final String messageBody = "Client has bought something";

        first.setExpectedMessageCount(4);
        first.message(0).header("customerId").isEqualTo(0);
        first.message(1).header("customerId").isEqualTo(3);
        first.message(2).header("customerId").isEqualTo(0);
        first.message(3).header("customerId").isEqualTo(3);

        second.setExpectedMessageCount(2);
        second.message(0).header("customerId").isEqualTo(1);
        second.message(1).header("customerId").isEqualTo(1);

        third.setExpectedMessageCount(2);
        third.message(0).header("customerId").isEqualTo(2);
        third.message(1).header("customerId").isEqualTo(2);

        for (int messageCount = 0; messageCount < 2; messageCount++) {
            for (int customerCount = 0; customerCount < 4; customerCount++) {
                template.sendBodyAndHeader(messageBody, "customerId", customerCount);
            }
        }

        assertMockEndpointsSatisfied();
    }

}


text:
// AFURLSessionManager.m
//
// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import "AFURLSessionManager.h"
#import <objc/runtime.h>

#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090)

static dispatch_queue_t url_session_manager_creation_queue() {
    static dispatch_queue_t af_url_session_manager_creation_queue;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        af_url_session_manager_creation_queue = dispatch_queue_create("com.alamofire.networking.session.manager.creation", DISPATCH_QUEUE_SERIAL);
    });

    return af_url_session_manager_creation_queue;
}

static dispatch_queue_t url_session_manager_processing_queue() {
    static dispatch_queue_t af_url_session_manager_processing_queue;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        af_url_session_manager_processing_queue = dispatch_queue_create("com.alamofire.networking.session.manager.processing", DISPATCH_QUEUE_CONCURRENT);
    });

    return af_url_session_manager_processing_queue;
}

static dispatch_group_t url_session_manager_completion_group() {
    static dispatch_group_t af_url_session_manager_completion_group;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        af_url_session_manager_completion_group = dispatch_group_create();
    });

    return af_url_session_manager_completion_group;
}

NSString * const AFNetworkingTaskDidResumeNotification = @"com.alamofire.networking.task.resume";
NSString * const AFNetworkingTaskDidCompleteNotification = @"com.alamofire.networking.task.complete";
NSString * const AFNetworkingTaskDidSuspendNotification = @"com.alamofire.networking.task.suspend";
NSString * const AFURLSessionDidInvalidateNotification = @"com.alamofire.networking.session.invalidate";
NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error";

NSString * const AFNetworkingTaskDidStartNotification = @"com.alamofire.networking.task.resume"; // Deprecated
NSString * const AFNetworkingTaskDidFinishNotification = @"com.alamofire.networking.task.complete"; // Deprecated

NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse";
NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer";
NSString * const AFNetworkingTaskDidCompleteResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata";
NSString * const AFNetworkingTaskDidCompleteErrorKey = @"com.alamofire.networking.task.complete.error";
NSString * const AFNetworkingTaskDidCompleteAssetPathKey = @"com.alamofire.networking.task.complete.assetpath";

NSString * const AFNetworkingTaskDidFinishSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse"; // Deprecated
NSString * const AFNetworkingTaskDidFinishResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer"; // Deprecated
NSString * const AFNetworkingTaskDidFinishResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata"; // Deprecated
NSString * const AFNetworkingTaskDidFinishErrorKey = @"com.alamofire.networking.task.complete.error"; // Deprecated
NSString * const AFNetworkingTaskDidFinishAssetPathKey = @"com.alamofire.networking.task.complete.assetpath"; // Deprecated

static NSString * const AFURLSessionManagerLockName = @"com.alamofire.networking.session.manager.lock";

static NSUInteger const AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask = 3;

static void * AFTaskStateChangedContext = &AFTaskStateChangedContext;

typedef void (^AFURLSessionDidBecomeInvalidBlock)(NSURLSession *session, NSError *error);
typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential);

typedef NSURLRequest * (^AFURLSessionTaskWillPerformHTTPRedirectionBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request);
typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionTaskDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential);
typedef void (^AFURLSessionDidFinishEventsForBackgroundURLSessionBlock)(NSURLSession *session);

typedef NSInputStream * (^AFURLSessionTaskNeedNewBodyStreamBlock)(NSURLSession *session, NSURLSessionTask *task);
typedef void (^AFURLSessionTaskDidSendBodyDataBlock)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend);
typedef void (^AFURLSessionTaskDidCompleteBlock)(NSURLSession *session, NSURLSessionTask *task, NSError *error);

typedef NSURLSessionResponseDisposition (^AFURLSessionDataTaskDidReceiveResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response);
typedef void (^AFURLSessionDataTaskDidBecomeDownloadTaskBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask);
typedef void (^AFURLSessionDataTaskDidReceiveDataBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data);
typedef NSCachedURLResponse * (^AFURLSessionDataTaskWillCacheResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse);

typedef NSURL * (^AFURLSessionDownloadTaskDidFinishDownloadingBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location);
typedef void (^AFURLSessionDownloadTaskDidWriteDataBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite);
typedef void (^AFURLSessionDownloadTaskDidResumeBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes);

typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id responseObject, NSError *error);

#pragma mark -

@interface AFURLSessionManagerTaskDelegate : NSObject <NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate>
@property (nonatomic, weak) AFURLSessionManager *manager;
@property (nonatomic, strong) NSMutableData *mutableData;
@property (nonatomic, strong) NSProgress *progress;
@property (nonatomic, copy) NSURL *downloadFileURL;
@property (nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading;
@property (nonatomic, copy) AFURLSessionTaskCompletionHandler completionHandler;
@end

@implementation AFURLSessionManagerTaskDelegate

- (instancetype)init {
    self = [super init];
    if (!self) {
        return nil;
    }

    self.mutableData = [NSMutableData data];

    self.progress = [NSProgress progressWithTotalUnitCount:0];

    return self;
}

#pragma mark - NSURLSessionTaskDelegate

- (void)URLSession:(__unused NSURLSession *)session
              task:(__unused NSURLSessionTask *)task
   didSendBodyData:(__unused int64_t)bytesSent
    totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{
    self.progress.totalUnitCount = totalBytesExpectedToSend;
    self.progress.completedUnitCount = totalBytesSent;
}

- (void)URLSession:(__unused NSURLSession *)session
              task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
    __strong AFURLSessionManager *manager = self.manager;

    __block id responseObject = nil;

    __block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
    userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer;

    if (self.downloadFileURL) {
        userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL;
    } else if (self.mutableData) {
        userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = [NSData dataWithData:self.mutableData];
    }

    if (error) {
        userInfo[AFNetworkingTaskDidCompleteErrorKey] = error;

        dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
            if (self.completionHandler) {
                self.completionHandler(task.response, responseObject, error);
            }

            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
            });
        });
    } else {
        dispatch_async(url_session_manager_processing_queue(), ^{
            NSError *serializationError = nil;
            responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:[NSData dataWithData:self.mutableData] error:&serializationError];

            if (self.downloadFileURL) {
                responseObject = self.downloadFileURL;
            }

            if (responseObject) {
                userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject;
            }

            if (serializationError) {
                userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError;
            }

            dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
                if (self.completionHandler) {
                    self.completionHandler(task.response, responseObject, serializationError);
                }

                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
                });
            });
        });
    }
#pragma clang diagnostic pop
}

#pragma mark - NSURLSessionDataTaskDelegate

- (void)URLSession:(__unused NSURLSession *)session
          dataTask:(__unused NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data
{
    [self.mutableData appendData:data];
}

#pragma mark - NSURLSessionDownloadTaskDelegate

- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
    NSError *fileManagerError = nil;
    self.downloadFileURL = nil;

    if (self.downloadTaskDidFinishDownloading) {
        self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location);
        if (self.downloadFileURL) {
            [[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError];

            if (fileManagerError) {
                [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo];
            }
        }
    }
}

- (void)URLSession:(__unused NSURLSession *)session
      downloadTask:(__unused NSURLSessionDownloadTask *)downloadTask
      didWriteData:(__unused int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    self.progress.totalUnitCount = totalBytesExpectedToWrite;
    self.progress.completedUnitCount = totalBytesWritten;
}

- (void)URLSession:(__unused NSURLSession *)session
      downloadTask:(__unused NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes {
    self.progress.totalUnitCount = expectedTotalBytes;
    self.progress.completedUnitCount = fileOffset;
}

@end

#pragma mark -

/*
 A workaround for issues related to key-value observing the `state` of an `NSURLSessionTask`.

 See https://github.com/AFNetworking/AFNetworking/issues/1477
 */

static inline void af_swizzleSelector(Class class, SEL originalSelector, SEL swizzledSelector) {
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    if (class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))) {
        class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

static NSString * const AFNSURLSessionTaskDidResumeNotification  = @"com.alamofire.networking.nsurlsessiontask.resume";
static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofire.networking.nsurlsessiontask.suspend";

@interface NSURLSessionTask (_AFStateObserving)
@end

@implementation NSURLSessionTask (_AFStateObserving)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        af_swizzleSelector([self class], @selector(resume), @selector(af_resume));
        af_swizzleSelector([self class], @selector(suspend), @selector(af_suspend));
    });
}

#pragma mark -

- (void)af_resume {
    NSURLSessionTaskState state = self.state;
    [self af_resume];

    if (state != NSURLSessionTaskStateRunning) {
        [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidResumeNotification object:self];
    }
}

- (void)af_suspend {
    NSURLSessionTaskState state = self.state;
    [self af_suspend];

    if (state != NSURLSessionTaskStateSuspended) {
        [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidSuspendNotification object:self];
    }
}

@end

#pragma mark -

@interface AFURLSessionManager ()
@property (readwrite, nonatomic, strong) NSURLSessionConfiguration *sessionConfiguration;
@property (readwrite, nonatomic, strong) NSOperationQueue *operationQueue;
@property (readwrite, nonatomic, strong) NSURLSession *session;
@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableTaskDelegatesKeyedByTaskIdentifier;
@property (readwrite, nonatomic, strong) NSLock *lock;
@property (readwrite, nonatomic, copy) AFURLSessionDidBecomeInvalidBlock sessionDidBecomeInvalid;
@property (readwrite, nonatomic, copy) AFURLSessionDidReceiveAuthenticationChallengeBlock sessionDidReceiveAuthenticationChallenge;
@property (readwrite, nonatomic, copy) AFURLSessionDidFinishEventsForBackgroundURLSessionBlock didFinishEventsForBackgroundURLSession;
@property (readwrite, nonatomic, copy) AFURLSessionTaskWillPerformHTTPRedirectionBlock taskWillPerformHTTPRedirection;
@property (readwrite, nonatomic, copy) AFURLSessionTaskDidReceiveAuthenticationChallengeBlock taskDidReceiveAuthenticationChallenge;
@property (readwrite, nonatomic, copy) AFURLSessionTaskNeedNewBodyStreamBlock taskNeedNewBodyStream;
@property (readwrite, nonatomic, copy) AFURLSessionTaskDidSendBodyDataBlock taskDidSendBodyData;
@property (readwrite, nonatomic, copy) AFURLSessionTaskDidCompleteBlock taskDidComplete;
@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveResponseBlock dataTaskDidReceiveResponse;
@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidBecomeDownloadTaskBlock dataTaskDidBecomeDownloadTask;
@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveDataBlock dataTaskDidReceiveData;
@property (readwrite, nonatomic, copy) AFURLSessionDataTaskWillCacheResponseBlock dataTaskWillCacheResponse;
@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading;
@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidWriteDataBlock downloadTaskDidWriteData;
@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidResumeBlock downloadTaskDidResume;
@end

@implementation AFURLSessionManager

- (instancetype)init {
    return [self initWithSessionConfiguration:nil];
}

- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
    self = [super init];
    if (!self) {
        return nil;
    }

    if (!configuration) {
        configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    }

    self.sessionConfiguration = configuration;

    self.operationQueue = [[NSOperationQueue alloc] init];
    self.operationQueue.maxConcurrentOperationCount = 1;

    self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue];

    self.responseSerializer = [AFJSONResponseSerializer serializer];

    self.securityPolicy = [AFSecurityPolicy defaultPolicy];

    self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];

    self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init];

    self.lock = [[NSLock alloc] init];
    self.lock.name = AFURLSessionManagerLockName;

    [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
        for (NSURLSessionDataTask *task in dataTasks) {
            [self addDelegateForDataTask:task completionHandler:nil];
        }

        for (NSURLSessionUploadTask *uploadTask in uploadTasks) {
            [self addDelegateForUploadTask:uploadTask progress:nil completionHandler:nil];
        }

        for (NSURLSessionDownloadTask *downloadTask in downloadTasks) {
            [self addDelegateForDownloadTask:downloadTask progress:nil destination:nil completionHandler:nil];
        }
    }];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidResume:) name:AFNSURLSessionTaskDidResumeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidSuspend:) name:AFNSURLSessionTaskDidSuspendNotification object:nil];

    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)taskDidResume:(NSNotification *)notification {
    NSURLSessionTask *task = notification.object;
    if ([task isKindOfClass:[NSURLSessionTask class]]) {
        AFURLSessionManager *manager = [self delegateForTask:task].manager;
        if ([manager isEqual:self]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidResumeNotification object:task];
            });
        }
    }
}

- (void)taskDidSuspend:(NSNotification *)notification {
    NSURLSessionTask *task = notification.object;
    if ([task isKindOfClass:[NSURLSessionTask class]]) {
        AFURLSessionManager *manager = [self delegateForTask:task].manager;
        if ([manager isEqual:self]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidSuspendNotification object:task];
            });
        }
    }
}

#pragma mark -

- (AFURLSessionManagerTaskDelegate *)delegateForTask:(NSURLSessionTask *)task {
    NSParameterAssert(task);

    AFURLSessionManagerTaskDelegate *delegate = nil;
    [self.lock lock];
    delegate = self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)];
    [self.lock unlock];

    return delegate;
}

- (void)setDelegate:(AFURLSessionManagerTaskDelegate *)delegate
            forTask:(NSURLSessionTask *)task
{
    NSParameterAssert(task);
    NSParameterAssert(delegate);

    [self.lock lock];
    self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate;
    [self.lock unlock];
}

- (void)addDelegateForDataTask:(NSURLSessionDataTask *)dataTask
             completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{
    AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init];
    delegate.manager = self;
    delegate.completionHandler = completionHandler;

    [self setDelegate:delegate forTask:dataTask];
}

- (void)addDelegateForUploadTask:(NSURLSessionUploadTask *)uploadTask
                        progress:(NSProgress * __autoreleasing *)progress
               completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{
    AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init];
    delegate.manager = self;
    delegate.completionHandler = completionHandler;

    int64_t totalUnitCount = uploadTask.countOfBytesExpectedToSend;
    if(totalUnitCount == NSURLSessionTransferSizeUnknown) {
        NSString *contentLength = [uploadTask.originalRequest valueForHTTPHeaderField:@"Content-Length"];
        if(contentLength) {
            totalUnitCount = (int64_t) [contentLength longLongValue];
        }
    }

    if (delegate.progress) {
        delegate.progress.totalUnitCount = totalUnitCount;
    } else {
        delegate.progress = [NSProgress progressWithTotalUnitCount:totalUnitCount];
    }

    delegate.progress.pausingHandler = ^{
        [uploadTask suspend];
    };
    delegate.progress.cancellationHandler = ^{
        [uploadTask cancel];
    };

    if (progress) {
        *progress = delegate.progress;
    }

    [self setDelegate:delegate forTask:uploadTask];
}

- (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask
                          progress:(NSProgress * __autoreleasing *)progress
                       destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
                 completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
{
    AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init];
    delegate.manager = self;
    delegate.completionHandler = completionHandler;

    if (destination) {
        delegate.downloadTaskDidFinishDownloading = ^NSURL * (NSURLSession * __unused session, NSURLSessionDownloadTask *task, NSURL *location) {
            return destination(location, task.response);
        };
    }

    if (progress) {
        *progress = delegate.progress;
    }

    [self setDelegate:delegate forTask:downloadTask];
}

- (void)removeDelegateForTask:(NSURLSessionTask *)task {
    NSParameterAssert(task);

    [self.lock lock];
    [self.mutableTaskDelegatesKeyedByTaskIdentifier removeObjectForKey:@(task.taskIdentifier)];
    [self.lock unlock];
}

- (void)removeAllDelegates {
    [self.lock lock];
    [self.mutableTaskDelegatesKeyedByTaskIdentifier removeAllObjects];
    [self.lock unlock];
}

#pragma mark -

- (NSArray *)tasksForKeyPath:(NSString *)keyPath {
    __block NSArray *tasks = nil;
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
        if ([keyPath isEqualToString:NSStringFromSelector(@selector(dataTasks))]) {
            tasks = dataTasks;
        } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(uploadTasks))]) {
            tasks = uploadTasks;
        } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(downloadTasks))]) {
            tasks = downloadTasks;
        } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(tasks))]) {
            tasks = [@[dataTasks, uploadTasks, downloadTasks] valueForKeyPath:@"@unionOfArrays.self"];
        }

        dispatch_semaphore_signal(semaphore);
    }];

    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

    return tasks;
}

- (NSArray *)tasks {
    return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
}

- (NSArray *)dataTasks {
    return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
}

- (NSArray *)uploadTasks {
    return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
}

- (NSArray *)downloadTasks {
    return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
}

#pragma mark -

- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (cancelPendingTasks) {
            [self.session invalidateAndCancel];
        } else {
            [self.session finishTasksAndInvalidate];
        }
    });
}

#pragma mark -

- (void)setResponseSerializer:(id <AFURLResponseSerialization>)responseSerializer {
    NSParameterAssert(responseSerializer);

    _responseSerializer = responseSerializer;
}

#pragma mark -

- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
                            completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{
    __block NSURLSessionDataTask *dataTask = nil;
    dispatch_sync(url_session_manager_creation_queue(), ^{
        dataTask = [self.session dataTaskWithRequest:request];
    });

    [self addDelegateForDataTask:dataTask completionHandler:completionHandler];

    return dataTask;
}

#pragma mark -

- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
                                         fromFile:(NSURL *)fileURL
                                         progress:(NSProgress * __autoreleasing *)progress
                                completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{
    __block NSURLSessionUploadTask *uploadTask = nil;
    dispatch_sync(url_session_manager_creation_queue(), ^{
        uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL];
    });

    if (!uploadTask && self.attemptsToRecreateUploadTasksForBackgroundSessions && self.session.configuration.identifier) {
        for (NSUInteger attempts = 0; !uploadTask && attempts < AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask; attempts++) {
            uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL];
        }
    }

    [self addDelegateForUploadTask:uploadTask progress:progress completionHandler:completionHandler];

    return uploadTask;
}

- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
                                         fromData:(NSData *)bodyData
                                         progress:(NSProgress * __autoreleasing *)progress
                                completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{
    __block NSURLSessionUploadTask *uploadTask = nil;
    dispatch_sync(url_session_manager_creation_queue(), ^{
        uploadTask = [self.session uploadTaskWithRequest:request fromData:bodyData];
    });

    [self addDelegateForUploadTask:uploadTask progress:progress completionHandler:completionHandler];

    return uploadTask;
}

- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request
                                                 progress:(NSProgress * __autoreleasing *)progress
                                        completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{
    __block NSURLSessionUploadTask *uploadTask = nil;
    dispatch_sync(url_session_manager_creation_queue(), ^{
        uploadTask = [self.session uploadTaskWithStreamedRequest:request];
    });

    [self addDelegateForUploadTask:uploadTask progress:progress completionHandler:completionHandler];

    return uploadTask;
}

#pragma mark -

- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
                                             progress:(NSProgress * __autoreleasing *)progress
                                          destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
                                    completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
{
    __block NSURLSessionDownloadTask *downloadTask = nil;
    dispatch_sync(url_session_manager_creation_queue(), ^{
        downloadTask = [self.session downloadTaskWithRequest:request];
    });

    [self addDelegateForDownloadTask:downloadTask progress:progress destination:destination completionHandler:completionHandler];

    return downloadTask;
}

- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData
                                                progress:(NSProgress * __autoreleasing *)progress
                                             destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
                                       completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
{
    __block NSURLSessionDownloadTask *downloadTask = nil;
    dispatch_sync(url_session_manager_creation_queue(), ^{
        downloadTask = [self.session downloadTaskWithResumeData:resumeData];
    });

    [self addDelegateForDownloadTask:downloadTask progress:progress destination:destination completionHandler:completionHandler];

    return downloadTask;
}

- (void)initWithDownloadTask:(NSURLSessionDownloadTask *)downloadTask
                    progress:(NSProgress * __autoreleasing *)progress
                 destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
           completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
{
    [self addDelegateForDownloadTask:downloadTask progress:progress destination:destination completionHandler:completionHandler];
}

#pragma mark -

- (NSProgress *)uploadProgressForTask:(NSURLSessionUploadTask *)uploadTask {
    return [[self delegateForTask:uploadTask] progress];
}

- (NSProgress *)downloadProgressForTask:(NSURLSessionDownloadTask *)downloadTask {
    return [[self delegateForTask:downloadTask] progress];
}

#pragma mark -

- (void)setSessionDidBecomeInvalidBlock:(void (^)(NSURLSession *session, NSError *error))block {
    self.sessionDidBecomeInvalid = block;
}

- (void)setSessionDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block {
    self.sessionDidReceiveAuthenticationChallenge = block;
}

- (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession *session))block {
    self.didFinishEventsForBackgroundURLSession = block;
}

#pragma mark -

- (void)setTaskNeedNewBodyStreamBlock:(NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block {
    self.taskNeedNewBodyStream = block;
}

- (void)setTaskWillPerformHTTPRedirectionBlock:(NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block {
    self.taskWillPerformHTTPRedirection = block;
}

- (void)setTaskDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block {
    self.taskDidReceiveAuthenticationChallenge = block;
}

- (void)setTaskDidSendBodyDataBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block {
    self.taskDidSendBodyData = block;
}

- (void)setTaskDidCompleteBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block {
    self.taskDidComplete = block;
}

#pragma mark -

- (void)setDataTaskDidReceiveResponseBlock:(NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block {
    self.dataTaskDidReceiveResponse = block;
}

- (void)setDataTaskDidBecomeDownloadTaskBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block {
    self.dataTaskDidBecomeDownloadTask = block;
}

- (void)setDataTaskDidReceiveDataBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block {
    self.dataTaskDidReceiveData = block;
}

- (void)setDataTaskWillCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block {
    self.dataTaskWillCacheResponse = block;
}

#pragma mark -

- (void)setDownloadTaskDidFinishDownloadingBlock:(NSURL * (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block {
    self.downloadTaskDidFinishDownloading = block;
}

- (void)setDownloadTaskDidWriteDataBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block {
    self.downloadTaskDidWriteData = block;
}

- (void)setDownloadTaskDidResumeBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block {
    self.downloadTaskDidResume = block;
}

#pragma mark - NSObject

- (NSString *)description {
    return [NSString stringWithFormat:@"<%@: %p, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, self.session, self.operationQueue];
}

- (BOOL)respondsToSelector:(SEL)selector {
    if (selector == @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)) {
        return self.taskWillPerformHTTPRedirection != nil;
    } else if (selector == @selector(URLSession:dataTask:didReceiveResponse:completionHandler:)) {
        return self.dataTaskDidReceiveResponse != nil;
    } else if (selector == @selector(URLSession:dataTask:willCacheResponse:completionHandler:)) {
        return self.dataTaskWillCacheResponse != nil;
    } else if (selector == @selector(URLSessionDidFinishEventsForBackgroundURLSession:)) {
        return self.didFinishEventsForBackgroundURLSession != nil;
    }

    return [[self class] instancesRespondToSelector:selector];
}

#pragma mark - NSURLSessionDelegate

- (void)URLSession:(NSURLSession *)session
didBecomeInvalidWithError:(NSError *)error
{
    if (self.sessionDidBecomeInvalid) {
        self.sessionDidBecomeInvalid(session, error);
    }

    [self removeAllDelegates];
    [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDidInvalidateNotification object:session];
}

- (void)URLSession:(NSURLSession *)session
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
    NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
    __block NSURLCredential *credential = nil;

    if (self.sessionDidReceiveAuthenticationChallenge) {
        disposition = self.sessionDidReceiveAuthenticationChallenge(session, challenge, &credential);
    } else {
        if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
            if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
                credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
                if (credential) {
                    disposition = NSURLSessionAuthChallengeUseCredential;
                } else {
                    disposition = NSURLSessionAuthChallengePerformDefaultHandling;
                }
            } else {
                disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
            }
        } else {
            disposition = NSURLSessionAuthChallengePerformDefaultHandling;
        }
    }

    if (completionHandler) {
        completionHandler(disposition, credential);
    }
}

#pragma mark - NSURLSessionTaskDelegate

- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
willPerformHTTPRedirection:(NSHTTPURLResponse *)response
        newRequest:(NSURLRequest *)request
 completionHandler:(void (^)(NSURLRequest *))completionHandler
{
    NSURLRequest *redirectRequest = request;

    if (self.taskWillPerformHTTPRedirection) {
        redirectRequest = self.taskWillPerformHTTPRedirection(session, task, response, request);
    }

    if (completionHandler) {
        completionHandler(redirectRequest);
    }
}

- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
    NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
    __block NSURLCredential *credential = nil;

    if (self.taskDidReceiveAuthenticationChallenge) {
        disposition = self.taskDidReceiveAuthenticationChallenge(session, task, challenge, &credential);
    } else {
        if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
            if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
                disposition = NSURLSessionAuthChallengeUseCredential;
                credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            } else {
                disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
            }
        } else {
            disposition = NSURLSessionAuthChallengePerformDefaultHandling;
        }
    }

    if (completionHandler) {
        completionHandler(disposition, credential);
    }
}

- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
 needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler
{
    NSInputStream *inputStream = nil;

    if (self.taskNeedNewBodyStream) {
        inputStream = self.taskNeedNewBodyStream(session, task);
    } else if (task.originalRequest.HTTPBodyStream && [task.originalRequest.HTTPBodyStream conformsToProtocol:@protocol(NSCopying)]) {
        inputStream = [task.originalRequest.HTTPBodyStream copy];
    }

    if (completionHandler) {
        completionHandler(inputStream);
    }
}

- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
   didSendBodyData:(int64_t)bytesSent
    totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{

    int64_t totalUnitCount = totalBytesExpectedToSend;
    if(totalUnitCount == NSURLSessionTransferSizeUnknown) {
        NSString *contentLength = [task.originalRequest valueForHTTPHeaderField:@"Content-Length"];
        if(contentLength) {
            totalUnitCount = (int64_t) [contentLength longLongValue];
        }
    }

    AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task];
    [delegate URLSession:session task:task didSendBodyData:bytesSent totalBytesSent:totalBytesSent totalBytesExpectedToSend:totalUnitCount];

    if (self.taskDidSendBodyData) {
        self.taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalUnitCount);
    }
}

- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
    AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task];

    // delegate may be nil when completing a task in the background
    if (delegate) {
        [delegate URLSession:session task:task didCompleteWithError:error];

        [self removeDelegateForTask:task];
    }

    if (self.taskDidComplete) {
        self.taskDidComplete(session, task, error);
    }

}

#pragma mark - NSURLSessionDataDelegate

- (void)URLSession:(NSURLSession *)session
          dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
{
    NSURLSessionResponseDisposition disposition = NSURLSessionResponseAllow;

    if (self.dataTaskDidReceiveResponse) {
        disposition = self.dataTaskDidReceiveResponse(session, dataTask, response);
    }

    if (completionHandler) {
        completionHandler(disposition);
    }
}

- (void)URLSession:(NSURLSession *)session
          dataTask:(NSURLSessionDataTask *)dataTask
didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask
{
    AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask];
    if (delegate) {
        [self removeDelegateForTask:dataTask];
        [self setDelegate:delegate forTask:downloadTask];
    }

    if (self.dataTaskDidBecomeDownloadTask) {
        self.dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask);
    }
}

- (void)URLSession:(NSURLSession *)session
          dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data
{
    AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask];
    [delegate URLSession:session dataTask:dataTask didReceiveData:data];

    if (self.dataTaskDidReceiveData) {
        self.dataTaskDidReceiveData(session, dataTask, data);
    }
}

- (void)URLSession:(NSURLSession *)session
          dataTask:(NSURLSessionDataTask *)dataTask
 willCacheResponse:(NSCachedURLResponse *)proposedResponse
 completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler
{
    NSCachedURLResponse *cachedResponse = proposedResponse;

    if (self.dataTaskWillCacheResponse) {
        cachedResponse = self.dataTaskWillCacheResponse(session, dataTask, proposedResponse);
    }

    if (completionHandler) {
        completionHandler(cachedResponse);
    }
}

- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
    if (self.didFinishEventsForBackgroundURLSession) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.didFinishEventsForBackgroundURLSession(session);
        });
    }
}

#pragma mark - NSURLSessionDownloadDelegate

- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
    AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
    if (self.downloadTaskDidFinishDownloading) {
        NSURL *fileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location);
        if (fileURL) {
            delegate.downloadFileURL = fileURL;
            NSError *error = nil;
            [[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error];
            if (error) {
                [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo];
            }

            return;
        }
    }

    if (delegate) {
        [delegate URLSession:session downloadTask:downloadTask didFinishDownloadingToURL:location];
    }
}

- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
    [delegate URLSession:session downloadTask:downloadTask didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite];

    if (self.downloadTaskDidWriteData) {
        self.downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
    }
}

- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
    AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
    [delegate URLSession:session downloadTask:downloadTask didResumeAtOffset:fileOffset expectedTotalBytes:expectedTotalBytes];

    if (self.downloadTaskDidResume) {
        self.downloadTaskDidResume(session, downloadTask, fileOffset, expectedTotalBytes);
    }
}

#pragma mark - NSSecureCoding

+ (BOOL)supportsSecureCoding {
    return YES;
}

- (id)initWithCoder:(NSCoder *)decoder {
    NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"];

    self = [self initWithSessionConfiguration:configuration];
    if (!self) {
        return nil;
    }

    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder {
    [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"];
}

#pragma mark - NSCopying

- (id)copyWithZone:(NSZone *)zone {
    return [[[self class] allocWithZone:zone] initWithSessionConfiguration:self.session.configuration];
}

@end

#endif


text:
<?php
namespace Google\Service\DoubleClickBidManager;

class FilterPair extends \Google\Model
{
  public $type;
  public $value;

  public function setType($type)
  {
    $this->type = $type;
  }

  public function getType()
  {
    return $this->type;
  }

  public function setValue($value)
  {
    $this->value = $value;
  }

  public function getValue()
  {
    return $this->value;
  }
}