text:
package cloud::azure::database::cosmosdb::mode::document;

use base qw(cloud::azure::custom::mode);

use strict;
use warnings;

sub get_metrics_mapping {
    my ($self, %options) = @_;

    my $metrics_mapping = {
        'documentcount' => {
            'output' => 'Document Count',
            'label'  => 'document-count',
            'nlabel' => 'cosmosdb.account.document.count',
            'unit'   => '',
            'min'    => '0'
        },
        'documentquota' => {
            'output' => 'Document Quota',
            'label'  => 'document-quota',
            'nlabel' => 'cosmosdb.account.document.quota.bytes',
            'unit'   => 'B',
            'min'    => '0'
        }
    };

    return $metrics_mapping;
}

sub new {
    my ($class, %options) = @_;
    my $self = $class->SUPER::new(package => __PACKAGE__, %options, force_new_perfdata => 1);
    bless $self, $class;

    $options{options}->add_options(arguments => {
        'filter-metric:s'  => { name => 'filter_metric' },
        'resource:s'       => { name => 'resource' },
        'resource-group:s' => { name => 'resource_group' }
    });

    return $self;
}

sub check_options {
    my ($self, %options) = @_;
    $self->SUPER::check_options(%options);

    if (!defined($self->{option_results}->{resource}) || $self->{option_results}->{resource} eq '') {
        $self->{output}->add_option_msg(short_msg => 'Need to specify either --resource <name> with --resource-group option or --resource <id>.');
        $self->{output}->option_exit();
    }
    my $resource = $self->{option_results}->{resource};
    my $resource_group = defined($self->{option_results}->{resource_group}) ? $self->{option_results}->{resource_group} : '';
    if ($resource =~ /^\/subscriptions\/.*\/resourceGroups\/(.*)\/providers\/Microsoft\.DocumentDB\/databaseAccounts\/(.*)$/) {
        $resource_group = $1;
        $resource = $2;
    }

    $self->{az_resource} = $resource;
    $self->{az_resource_group} = $resource_group;
    $self->{az_resource_type} = 'databaseAccounts';
    $self->{az_resource_namespace} = 'Microsoft.DocumentDB';
    $self->{az_timeframe} = defined($self->{option_results}->{timeframe}) ? $self->{option_results}->{timeframe} : 900;
    $self->{az_interval} = defined($self->{option_results}->{interval}) ? $self->{option_results}->{interval} : 'PT5M';
    $self->{az_aggregations} = ['Total'];
    if (defined($self->{option_results}->{aggregation})) {
        $self->{az_aggregations} = [];
        foreach my $stat (@{$self->{option_results}->{aggregation}}) {
            if ($stat ne '') {
                push @{$self->{az_aggregations}}, ucfirst(lc($stat));
            }
        }
    }

    foreach my $metric (keys %{$self->{metrics_mapping}}) {
        next if (defined($self->{option_results}->{filter_metric}) && $self->{option_results}->{filter_metric} ne ''
            && $metric !~ /$self->{option_results}->{filter_metric}/);
        push @{$self->{az_metrics}}, $metric;
    }
}

1;

__END__

=head1 MODE

Check Azure Cosmos DB Accounts document statistics.

Example:

Using resource name :

perl centreon_plugins.pl --plugin=cloud::azure::database::cosmosdb::plugin --mode=document --custommode=api
--resource=<cosmosdbaccount_id> --resource-group=<resourcegroup_id> --aggregation='total'
--warning-document-count='80000' --critical-document-count='90000'

Using resource id :

perl centreon_plugins.pl --plugin=cloud::azure::database::cosmosdb::plugin --mode=document --custommode=api
--resource='/subscriptions/<subscription_id>/resourceGroups/<resourcegroup_id>/providers/Microsoft.DocumentDB/databaseAccounts/<cosmosdbaccount_id>'
--aggregation='total' --warning-document-count='80000' --critical-document-count='90000'

Default aggregation: 'total' / 'minimum', 'maximum' and 'average' are valid.

=over 8

=item B<--resource>

Set resource name or id (Required).

=item B<--resource-group>

Set resource group (Required if resource's name is used).

=item B<--warning-*>

Warning threshold where '*' can be:
'document-count', 'document-quota'.

=item B<--critical-*>

Critical threshold where '*' can be:
'document-count', 'document-quota'.

=back

=cut


text:
package example.repo;

import example.model.Customer573;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

public interface Customer573Repository extends CrudRepository<Customer573, Long> {

	List<Customer573> findByLastName(String lastName);
}

redpajama_set_name: RedPajamaGithub


text:
class DuplicateSessionError(Exception):
    pass


text:
title: Retry Link
description: Attempt an operation multiple times if it fails due to network or server errors.
---

## Overview

`@apollo/client/link/retry` can be used to retry an operation a certain amount of times. This comes in handy when dealing with unreliable communication situations, where you would rather wait longer than explicitly fail an operation. `@apollo/client/link/retry` provides exponential backoff, and jitters delays between attempts by default. It does not (currently) handle retries for GraphQL errors in the response, only for network errors.

An example use case is to hold on to a request while a network connection is offline, and retry until it comes back online.

```js
import { RetryLink } from "@apollo/client/link/retry";

const link = new RetryLink();
```

## Options

The standard retry strategy provides exponential backoff with jittering, and takes the following options, grouped into `delay` and `attempt` strategies:

### options.delay

| Option | Description |
| - | - |
| `delay.initial` | The number of milliseconds to wait before attempting the first retry. |
| `delay.max` | The maximum number of milliseconds that the link should wait for any retry. |
| `delay.jitter` | Whether delays between attempts should be randomized. |

### options.attempts

| Option | Description |
| - | - |
| `attempts.max` | The max number of times to try a single operation before giving up. |
| `attempts.retryIf` | A predicate function that can determine whether a particular response should be retried. |

### Default configuration

The default configuration is equivalent to:

```ts
new RetryLink({
  delay: {
    initial: 300,
    max: Infinity,
    jitter: true
  },
  attempts: {
    max: 5,
    retryIf: (error, _operation) => !!error
  }
});
```

## Avoiding thundering herd

Starting with `initialDelay`, the delay of each subsequent retry is increased exponentially, meaning it's multiplied by 2 each time. For example, if `initialDelay` is 100, additional retries will occur after delays of 200, 400, 800, etc.

With the `jitter` option enabled, delays are randomized anywhere between 0ms (instant), and 2x the configured delay. This way you get the same result on average, but with random delays.

These two features are combined to help alleviate [the thundering herd problem](https://en.wikipedia.org/wiki/Thundering_herd_problem), by distributing load during major outages. Without these strategies, when your server comes back up it will be hit by all of your clients at once, possibly causing it to go down again.

## Custom strategies

Instead of the options object, you may pass a function for `delay` and/or `attempts`, which implement custom strategies for each. In both cases the function is given the same arguments (`count`, `operation`, `error`).

The `attempts` function should return a boolean indicating whether the response should be retried. If yes, the `delay` function is then called, and should return the number of milliseconds to delay by.

```js
import { RetryLink } from "@apollo/client/link/retry";

const link = new RetryLink({
  attempts: (count, operation, error) => {
    return !!error && operation.operationName != 'specialCase';
  },
  delay: (count, operation, error) => {
    return count * 1000 * Math.random();
  },
});
```


text:
<?php

namespace Proxies\__CG__\Application\Sonata\NewsBundle\Entity;

/**
 * THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE.
 */
class Category extends \Application\Sonata\NewsBundle\Entity\Category implements \Doctrine\ORM\Proxy\Proxy
{
    private $_entityPersister;
    private $_identifier;
    public $__isInitialized__ = false;
    public function __construct($entityPersister, $identifier)
    {
        $this->_entityPersister = $entityPersister;
        $this->_identifier = $identifier;
    }
    /** @private */
    public function __load()
    {
        if (!$this->__isInitialized__ && $this->_entityPersister) {
            $this->__isInitialized__ = true;

            if (method_exists($this, "__wakeup")) {
                // call this after __isInitialized__to avoid infinite recursion
                // but before loading to emulate what ClassMetadata::newInstance()
                // provides.
                $this->__wakeup();
            }

            if ($this->_entityPersister->load($this->_identifier, $this) === null) {
                throw new \Doctrine\ORM\EntityNotFoundException();
            }
            unset($this->_entityPersister, $this->_identifier);
        }
    }

    /** @private */
    public function __isInitialized()
    {
        return $this->__isInitialized__;
    }

    public function getId()
    {
        if ($this->__isInitialized__ === false) {
            return (int) $this->_identifier["id"];
        }
        $this->__load();
        return parent::getId();
    }

    public function setName($name)
    {
        $this->__load();
        return parent::setName($name);
    }

    public function getName()
    {
        $this->__load();
        return parent::getName();
    }

    public function setEnabled($enabled)
    {
        $this->__load();
        return parent::setEnabled($enabled);
    }

    public function getEnabled()
    {
        $this->__load();
        return parent::getEnabled();
    }

    public function setSlug($slug)
    {
        $this->__load();
        return parent::setSlug($slug);
    }

    public function getSlug()
    {
        $this->__load();
        return parent::getSlug();
    }

    public function setDescription($description)
    {
        $this->__load();
        return parent::setDescription($description);
    }

    public function getDescription()
    {
        $this->__load();
        return parent::getDescription();
    }

    public function setCount($count)
    {
        $this->__load();
        return parent::setCount($count);
    }

    public function getCount()
    {
        $this->__load();
        return parent::getCount();
    }

    public function addPosts(\Sonata\NewsBundle\Model\PostInterface $posts)
    {
        $this->__load();
        return parent::addPosts($posts);
    }

    public function getPosts()
    {
        $this->__load();
        return parent::getPosts();
    }

    public function __toString()
    {
        $this->__load();
        return parent::__toString();
    }

    public function prePersist()
    {
        $this->__load();
        return parent::prePersist();
    }

    public function preUpdate()
    {
        $this->__load();
        return parent::preUpdate();
    }

    public function setCreatedAt(\DateTime $createdAt)
    {
        $this->__load();
        return parent::setCreatedAt($createdAt);
    }

    public function getCreatedAt()
    {
        $this->__load();
        return parent::getCreatedAt();
    }

    public function setUpdatedAt(\DateTime $updatedAt)
    {
        $this->__load();
        return parent::setUpdatedAt($updatedAt);
    }

    public function getUpdatedAt()
    {
        $this->__load();
        return parent::getUpdatedAt();
    }

    public function __sleep()
    {
        return array('__isInitialized__', 'name', 'enabled', 'slug', 'description', 'count', 'createdAt', 'updatedAt', 'id');
    }

    public function __clone()
    {
        if (!$this->__isInitialized__ && $this->_entityPersister) {
            $this->__isInitialized__ = true;
            $class = $this->_entityPersister->getClassMetadata();
            $original = $this->_entityPersister->load($this->_identifier);
            if ($original === null) {
                throw new \Doctrine\ORM\EntityNotFoundException();
            }
            foreach ($class->reflFields as $field => $reflProperty) {
                $reflProperty->setValue($this, $reflProperty->getValue($original));
            }
            unset($this->_entityPersister, $this->_identifier);
        }

    }
}


text:
import argparse
from postprocess import processdata
import config
import os
import sys
from utility import utility
import operator

os.nice(19)

parser = argparse.ArgumentParser(
        description="Tool to sum up the uses of RDF properties in queries")
parser.add_argument("--monthsFolder", "-m", default=config.monthsFolder,
        type=str, help="The folder in which the months directory are residing.")
parser.add_argument("--ignoreLock", "-i", help="Ignore locked file and "
        + "execute anyways", action="store_true")
parser.add_argument('--onlyValid', "-o", action='store_true', help="If set "
        + "only valid lines are being looked at")
parser.add_argument("month", type=str, help="The month from which lines "
        + "should be displayed.")
parser.add_argument("parameter", type=str, help="The parameter by which to group.")

if (len(sys.argv[1:]) == 0):
    parser.print_help()
    parser.exit()

args = parser.parse_args()

if os.path.isfile(utility.addMissingSlash(args.monthsFolder) + utility.addMissingSlash(args.month) + "locked") and not args.ignoreLock:
    print "ERROR: The month " + args.month + " is being edited at the moment. Use -i if you want to force the execution of this script."
    sys.exit()

class CountRdfPropertiesHandler:
	queryCount = 0
	propQueryCounts = {}

	def handle(self,sparqlQuery,processed):
		self.queryCount += 1

                if args.onlyValid:
                    if processed['#Valid'] is not 'VALID':
                        return

		props = processed[args.parameter].split(",")

		for prop in props:
			if prop in self.propQueryCounts:
				c = self.propQueryCounts[prop] + 1
			else:
				c = 1
			self.propQueryCounts[prop] = c

	def printResults(self):
		print "Queries: %d" % (self.queryCount)
		print "\n\n%s\tcount" % (args.parameter)
		for p, c in sorted(self.propQueryCounts.iteritems(), key=operator.itemgetter(1), reverse=True):
			print "%s\t%d" % (p,c)

handler = CountRdfPropertiesHandler()
processdata.processMonth(handler, args.month, args.monthsFolder)

handler.printResults()


text:
package com.alliander.osgp.adapter.ws.tariffswitching.infra.jms;

import java.io.Serializable;

import org.joda.time.DateTime;

import com.alliander.osgp.shared.infra.jms.RequestMessage;

public class TariffSwitchingRequestMessage extends RequestMessage {

    private final TariffSwitchingRequestMessageType messageType;
    private final DateTime scheduleTime;

    public TariffSwitchingRequestMessage(final TariffSwitchingRequestMessageType messageType,
            final String correlationUid, final String organisationIdentification, final String deviceIdentification,
            final Serializable request,final DateTime scheduleTime) {
        super(correlationUid, organisationIdentification, deviceIdentification, request);
        this.messageType = messageType;
        this.scheduleTime=scheduleTime;
    }

    public TariffSwitchingRequestMessageType getMessageType() {
        return this.messageType;
    }

    public DateTime getScheduleTime() {
        return this.scheduleTime;
    }
}


text:
(function(app) {
    app.controller('SearchMainCtrl', ['$stateParams', 'searchSrvc', function(stateParams, searchSrvc) {

    }]);
})(angular.module("Meanapp"));


text:
#include <aws/evidently/model/ProjectSummary.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace CloudWatchEvidently
{
namespace Model
{

ProjectSummary::ProjectSummary() :
    m_activeExperimentCount(0),
    m_activeExperimentCountHasBeenSet(false),
    m_activeLaunchCount(0),
    m_activeLaunchCountHasBeenSet(false),
    m_arnHasBeenSet(false),
    m_createdTimeHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_experimentCount(0),
    m_experimentCountHasBeenSet(false),
    m_featureCount(0),
    m_featureCountHasBeenSet(false),
    m_lastUpdatedTimeHasBeenSet(false),
    m_launchCount(0),
    m_launchCountHasBeenSet(false),
    m_nameHasBeenSet(false),
    m_status(ProjectStatus::NOT_SET),
    m_statusHasBeenSet(false),
    m_tagsHasBeenSet(false)
{
}

ProjectSummary::ProjectSummary(JsonView jsonValue) :
    m_activeExperimentCount(0),
    m_activeExperimentCountHasBeenSet(false),
    m_activeLaunchCount(0),
    m_activeLaunchCountHasBeenSet(false),
    m_arnHasBeenSet(false),
    m_createdTimeHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_experimentCount(0),
    m_experimentCountHasBeenSet(false),
    m_featureCount(0),
    m_featureCountHasBeenSet(false),
    m_lastUpdatedTimeHasBeenSet(false),
    m_launchCount(0),
    m_launchCountHasBeenSet(false),
    m_nameHasBeenSet(false),
    m_status(ProjectStatus::NOT_SET),
    m_statusHasBeenSet(false),
    m_tagsHasBeenSet(false)
{
  *this = jsonValue;
}

ProjectSummary& ProjectSummary::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("activeExperimentCount"))
  {
    m_activeExperimentCount = jsonValue.GetInt64("activeExperimentCount");

    m_activeExperimentCountHasBeenSet = true;
  }

  if(jsonValue.ValueExists("activeLaunchCount"))
  {
    m_activeLaunchCount = jsonValue.GetInt64("activeLaunchCount");

    m_activeLaunchCountHasBeenSet = true;
  }

  if(jsonValue.ValueExists("arn"))
  {
    m_arn = jsonValue.GetString("arn");

    m_arnHasBeenSet = true;
  }

  if(jsonValue.ValueExists("createdTime"))
  {
    m_createdTime = jsonValue.GetDouble("createdTime");

    m_createdTimeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("description"))
  {
    m_description = jsonValue.GetString("description");

    m_descriptionHasBeenSet = true;
  }

  if(jsonValue.ValueExists("experimentCount"))
  {
    m_experimentCount = jsonValue.GetInt64("experimentCount");

    m_experimentCountHasBeenSet = true;
  }

  if(jsonValue.ValueExists("featureCount"))
  {
    m_featureCount = jsonValue.GetInt64("featureCount");

    m_featureCountHasBeenSet = true;
  }

  if(jsonValue.ValueExists("lastUpdatedTime"))
  {
    m_lastUpdatedTime = jsonValue.GetDouble("lastUpdatedTime");

    m_lastUpdatedTimeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("launchCount"))
  {
    m_launchCount = jsonValue.GetInt64("launchCount");

    m_launchCountHasBeenSet = true;
  }

  if(jsonValue.ValueExists("name"))
  {
    m_name = jsonValue.GetString("name");

    m_nameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("status"))
  {
    m_status = ProjectStatusMapper::GetProjectStatusForName(jsonValue.GetString("status"));

    m_statusHasBeenSet = true;
  }

  if(jsonValue.ValueExists("tags"))
  {
    Aws::Map<Aws::String, JsonView> tagsJsonMap = jsonValue.GetObject("tags").GetAllObjects();
    for(auto& tagsItem : tagsJsonMap)
    {
      m_tags[tagsItem.first] = tagsItem.second.AsString();
    }
    m_tagsHasBeenSet = true;
  }

  return *this;
}

JsonValue ProjectSummary::Jsonize() const
{
  JsonValue payload;

  if(m_activeExperimentCountHasBeenSet)
  {
   payload.WithInt64("activeExperimentCount", m_activeExperimentCount);

  }

  if(m_activeLaunchCountHasBeenSet)
  {
   payload.WithInt64("activeLaunchCount", m_activeLaunchCount);

  }

  if(m_arnHasBeenSet)
  {
   payload.WithString("arn", m_arn);

  }

  if(m_createdTimeHasBeenSet)
  {
   payload.WithDouble("createdTime", m_createdTime.SecondsWithMSPrecision());
  }

  if(m_descriptionHasBeenSet)
  {
   payload.WithString("description", m_description);

  }

  if(m_experimentCountHasBeenSet)
  {
   payload.WithInt64("experimentCount", m_experimentCount);

  }

  if(m_featureCountHasBeenSet)
  {
   payload.WithInt64("featureCount", m_featureCount);

  }

  if(m_lastUpdatedTimeHasBeenSet)
  {
   payload.WithDouble("lastUpdatedTime", m_lastUpdatedTime.SecondsWithMSPrecision());
  }

  if(m_launchCountHasBeenSet)
  {
   payload.WithInt64("launchCount", m_launchCount);

  }

  if(m_nameHasBeenSet)
  {
   payload.WithString("name", m_name);

  }

  if(m_statusHasBeenSet)
  {
   payload.WithString("status", ProjectStatusMapper::GetNameForProjectStatus(m_status));
  }

  if(m_tagsHasBeenSet)
  {
   JsonValue tagsJsonMap;
   for(auto& tagsItem : m_tags)
   {
     tagsJsonMap.WithString(tagsItem.first, tagsItem.second);
   }
   payload.WithObject("tags", std::move(tagsJsonMap));

  }

  return payload;
}

} // namespace Model
} // namespace CloudWatchEvidently
} // namespace Aws


text:
package com.milkenknights.crimsoncrossbow;

/**
 * A class that ensures there is only one instance of JStick per joystick.
 * JSticks created from this class can be updated all at once.
 *
 * @author danielk
 */
public class JStickMultiton {
    public static final int MAX_JOYSTICKS = 4;
    private static final JStick[] joysticks = new JStick[MAX_JOYSTICKS];

    public static JStick getJStick(int port) {
        // we have to subtract 1 from port because arrays are 0-indexed
        if (joysticks[port - 1] == null) {
            joysticks[port - 1] = new JStick(port);
        }

        return joysticks[port - 1];
    }

    public static void updateAll() {
        for (int i = 0; i < joysticks.length; i++) {
            if (joysticks[i] != null) {
                joysticks[i].update();
            }
        }
    }
}


text:
/*******************************************************
 * siren-json representor
 * siren representor (server)
 * May 2015
 * Mike Amundsen (@mamund)
 * Soundtrack : Motown Classics Gold (2005)
 *******************************************************/

/*
  REFERENCE:
    https://github.com/kevinswiber/siren

  DEPENDS:
    - has fatal dependency to transitions.js

  HACKS:
    - Siren supports "type"(DATA) for fields.
      transitions inputs don't currently carry a data type.
    - Siren supports "type"(IANA) for links and actions.
      transitions don't currently have this.

  ISSUES:
    - emits "entities" for collections & no root properties.
      a single data record causes it to emit an "entity" and no "entities"
    - doesn't support links within subentities
*/

module.exports = siren;

// dependencies
var utils = require('../connectors/utils.js');

// defaults
var g = {};
g.ctype = "application/x-www-form-urlencoded";
g.atype = "application/vnd.siren+json";

// emit valid siren body
function siren(object, root) {
  var siren;

  siren = {};
  root = root.replace(/^\/\//,"http://");

  for(var o in object) {
    if(!siren.class) {
      siren.class = [];
    }
    siren.class.push(o);

    if(o==="error") {
      siren = getError(siren, object[o], o);
    }

    if(object[o].data) {
      if(object[o].data.length===1) {
        siren = getEntity(siren, object[o], o);
      }
      else {
        siren = getSubEntities(siren, object[o], o);
      }
    }
    if(object[o].actions) {
      siren.actions = getActions(object[o].actions, o, object[o].data);
      siren.links = getLinks(object[o].actions, o, object[o].data);
    }
  }

  return JSON.stringify(siren, null, 2);
}

// handle any error info
function getError(siren, object, o) {
  var properties;

  if(siren.properties) {
    properties = siren.properties;
  }
  else {
    properties = {};
  }

  for(var p in object) {
    properties[p] = object[p];
  }

  siren.class = [o];
  siren.properties = properties;

  return siren;
}

// handle single entity
function getEntity(siren, object, o) {
  var props, properties;

  props = object.data[0];
  if(siren.properties) {
    properties = siren.properties;
  }
  else {
    properties = {};
  }

  if(object.content) {
    properties.content = object.content;
  }

  for(var p in props) {
    properties[p] = props[p];
  }

  siren.class = [o]
  siren.properties = properties;

  return siren;
}

// handle collection of subentities
function getSubEntities(siren, object, o) {
  var items, item, i, x, data, actions;

  data = object.data;
  actions = object.actions;
  items= [];

  if(object.content) {
    if(!siren.properties) {
      siren.properties = {};
    }
    siren.properties.content = object.content;
  }

  if(data) {
    for(i=0,x=data.length;i<x;i++) {
      item = {};
      item.class = [o];
      item.href = "#";
      item.rel = [];
      item.type = g.atype;

      for(var p in data[i]) {
        if(p!=='meta') {
          item[p] = data[i][p];
        }
      }

      if(actions) {
        link = getItemLink(actions);
        if(link) {
          item.href = link.href.replace(/{key}/g,item.id);
          item.rel = link.rel;
          item.type = link.contentType||g.atype;
        }
      }

      items.push(item);
    }
  }

  siren.entities = items;

  return siren;
}

// handle actions
function getActions(actions, o, data) {
  var coll, form, action, input, i, x;

  coll = [];
  for(i=0, x=actions.length; i<x; i++) {
    if(actions[i].inputs && actions[i].inputs.length!==0 && actions[i].target.indexOf("siren")!==-1) {
      action = actions[i];
      form = {};
      form.name = action.name;
      form.title = action.prompt||action.name;
      form.href = action.href.replace(/^\/\//,"http://")||"#";
      if(data && data.length==1) {
        form.href = form.href.replace(/{key}/g,data[0].id||"");
        form.href = form.href.replace(/{id}/g,data[0].id||"");
      }
      if(action.type!=="safe") {
        form.type = action.contentType||g.ctype;
        form.method = utils.actionMethod(action.action)
      }
      else {
        form.method = "GET";
      }
      form.fields = [];
      for(j=0,y=action.inputs.length; j<y; j++) {
        input = action.inputs[j];
        field = {};
        if(input.name) {
          field.name = input.name;
          field.type = input.type||"text";
          field.value = input.value||"";
          field.title = input.prompt||input.name;
          field.class = [o];
          field.readOnly = input.readOnly||false;
          field.required = input.required||false;
          if(input.pattern) {
            field.pattern = input.pattern;
          }
          form.fields.push(field);
        }
      }
      coll.push(form);
    }
  }
  return coll;
}

// handle links
function getLinks(actions, o, data) {
  var coll, link, action, i, x;
  var single, item;

  single = (data && data.length===1);
  if(data && data.length===1) {
    item = data[0];
  }

  coll = [];
  for(i=0, x=actions.length; i<x; i++) {
    if(actions[i].type==="safe" && actions[i].target.indexOf("siren")!==-1 &&
      (actions[i].inputs===undefined || actions[i].inputs.length===0))
    {
      if(single===true && actions[i].target.indexOf("item")!==-1) {
        action = actions[i];
        link = {};
        link.rel = action.rel;
        link.href = action.href.replace(/^\/\//,"http://");
        if(item) {
          link.href = link.href.replace(/{key}/g,item.id||"");
          link.href = link.href.replace(/{id}/g,item.id)||"";
        }
        link.class = [o];
        link.title = action.prompt||"";
        link.type = action.contentType||g.atype;
        coll.push(link);
      }
      if(single===false && actions[i].target.indexOf("list")!==-1) {
        action = actions[i];
        link = {};
        link.rel = action.rel;
        link.href = action.href.replace(/^\/\//,"http://");
        if(item) {
          link.href = link.href.replace(/{key}/g,item.id||"");
          link.href = link.href.replace(/{id}/g,item.id)||"";
        }
        link.class = [o];
        link.title = action.prompt||"";
        link.type = action.contentType||g.atype;
        coll.push(link);
      }
      if(actions[i].target.indexOf("app")!==-1) {
        action = actions[i];
        link = {};
        link.rel = action.rel;
        link.href = action.href.replace(/^\/\//,"http://");
        if(item) {
          link.href = link.href.replace(/{key}/g,item.id||"");
          link.href = link.href.replace(/{id}/g,item.id)||"";
        }
        link.class = [o];
        link.title = action.prompt||"";
        link.type = action.contentType||g.atype;
        coll.push(link);
      }
    }
  }
  return coll;
}

function getItemLink(actions) {
  var i, x, link;

  for(i=0, x=actions.length;i<x;i++) {
    if(actions[i].target.indexOf("item")!==-1 && actions[i].target.indexOf("siren")!==-1) {
      link = actions[i];
      break;
    }
  }
  return link;
}

// EOF


text:
package org.eclipse.jgit.lib;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;

import org.eclipse.jgit.lib.GitIndex.Entry;

/**
 * Compares the Index, a Tree, and the working directory
 */
public class IndexDiff {
	private GitIndex index;
	private Tree tree;

	/**
	 * Construct an indexdiff for diffing the workdir against
	 * the index.
	 *
	 * @param repository
	 * @throws IOException
	 */
	public IndexDiff(Repository repository) throws IOException {
		this.tree = repository.mapTree(Constants.HEAD);
		this.index = repository.getIndex();
	}

	/**
	 * Construct an indexdiff for diffing the workdir against both
	 * the index and a tree.
	 *
	 * @param tree
	 * @param index
	 */
	public IndexDiff(Tree tree, GitIndex index) {
		this.tree = tree;
		this.index = index;
	}

	boolean anyChanges = false;

	/**
	 * Run the diff operation. Until this is called, all lists will be empty
	 * @return if anything is different between index, tree, and workdir
	 * @throws IOException
	 */
	public boolean diff() throws IOException {
		final File root = index.getRepository().getWorkDir();
		new IndexTreeWalker(index, tree, root, new AbstractIndexTreeVisitor() {
			public void visitEntry(TreeEntry treeEntry, Entry indexEntry, File file) {
				if (treeEntry == null) {
					added.add(indexEntry.getName());
					anyChanges = true;
				} else if (indexEntry == null) {
					if (!(treeEntry instanceof Tree))
						removed.add(treeEntry.getFullName());
					anyChanges = true;
				} else {
					if (!treeEntry.getId().equals(indexEntry.getObjectId())) {
						changed.add(indexEntry.getName());
						anyChanges = true;
					}
				}

				if (indexEntry != null) {
					if (!file.exists()) {
						missing.add(indexEntry.getName());
						anyChanges = true;
					} else {
						if (indexEntry.isModified(root, true)) {
							modified.add(indexEntry.getName());
							anyChanges = true;
						}
					}
				}
			}
		}).walk();

		return anyChanges;
	}

	HashSet<String> added = new HashSet<String>();
	HashSet<String> changed = new HashSet<String>();
	HashSet<String> removed = new HashSet<String>();
	HashSet<String> missing = new HashSet<String>();
	HashSet<String> modified = new HashSet<String>();

	/**
	 * @return list of files added to the index, not in the tree
	 */
	public HashSet<String> getAdded() {
		return added;
	}

	/**
	 * @return list of files changed from tree to index
	 */
	public HashSet<String> getChanged() {
		return changed;
	}

	/**
	 * @return list of files removed from index, but in tree
	 */
	public HashSet<String> getRemoved() {
		return removed;
	}

	/**
	 * @return list of files in index, but not filesystem
	 */
	public HashSet<String> getMissing() {
		return missing;
	}

	/**
	 * @return list of files on modified on disk relative to the index
	 */
	public HashSet<String> getModified() {
		return modified;
	}
}


text:
package com.asayama.gwt.angular.client.q;

import com.asayama.gwt.angular.client.Injector;
import com.asayama.gwt.angular.client.Service;
import com.asayama.gwt.jsni.client.JSArray;
import com.google.gwt.core.client.JavaScriptObject;

public class Q implements Service {

    @Injector.Inject
    private NGQ ngo;

    public <V> Deferred<V> defer() {
        return ngo.defer().cast();
    }

    public Promise<JSArray<?>> all(Promise<?>... promises) {
        return ngo.all(JSArray.create(promises));
    }
}

@Injector.Bind("$q")
class NGQ extends JavaScriptObject {

    protected NGQ() {
    }

    final native Deferred<?> defer() /*-{
        return this.defer();
    }-*/;

    final native Promise<JSArray<?>> all(JSArray<Promise<?>> jsarray) /*-{
        return this.all(jsarray);
    }-*/;
}


text:
import types

#The structure for contestants will be:
#{userId:[countryId, newWeight]}
contestants = {}

#The structure for averageWeightPerCountry will be:
#{countryId:[totalCountryWeight, totalUsersPerCountry]}
averageWeightPerCountry = {}

keepUserTrack = []

def checkUser(user):
    if user in contestants.keys():
        return True
    else:
        return False

def updateLeaderBoard(countryId="", userId=0, newWeight=0.0):
    if type(countryId) == types.StringType and type(userId) == types.IntType and type(newWeight) == types.FloatType:
        #checking for exitence of the user before submitting data
        if checkUser(userId):
            #update user's weight loss
            contestants[userId][1] = abs(newWeight-contestants[userId][1])
            averageWeightPerCountry[countryId][0] += contestants[userId][1]
        else:
            #new user
            contestants[userId] = [countryId, newWeight]
            if averageWeightPerCountry.get(countryId):
                #Calculate total users per country
                averageWeightPerCountry[countryId][1] += 1
            else:
                #new country
                averageWeightPerCountry[countryId] = [0,1]

        #print "contestants " + str(contestants)
        #print "averageWeightPerCountry " + str(averageWeightPerCountry)
        print "The new weight average per country is:"
        for eachCountry, eachCountryData in averageWeightPerCountry.iteritems():
            totalCountryWeight = eachCountryData[0]
            totalUsersPerCountry = eachCountryData[1]
            print eachCountry+": "+str(totalCountryWeight/totalUsersPerCountry)+""

    else:
        print "Some of the values, if not all of them, are wrong:"
        print "CountryId must be a string"
        print "userId must be an integer"
        print "newWeight must be a float"

    return "OK"

if __name__ == '__main__':
    #updateLeaderBoard("US", 123, 170.5)
    #updateLeaderBoard("DR", 1234, 170.5)
    #updateLeaderBoard("DR", 1234, 160.5)
    #updateLeaderBoard("DR", 12345, 200.5)
    #updateLeaderBoard("DR", 12345, 170.5)

    updateLeaderBoard('US', 123, 175.5)
    updateLeaderBoard('DE', 444, 203.0)
    updateLeaderBoard('GB', 555, 164.5)
    updateLeaderBoard('US', 123, 171.5)
    updateLeaderBoard('DE', 444, 202.0)
    updateLeaderBoard('GB', 555, 164.0)


text:
package org.spongepowered.common.data.processor.value.block;

import net.minecraft.block.BlockDoublePlant;
import net.minecraft.item.ItemStack;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.type.DoublePlantType;
import org.spongepowered.api.data.type.DoublePlantTypes;
import org.spongepowered.api.data.value.mutable.Value;
import org.spongepowered.api.item.ItemTypes;
import org.spongepowered.common.data.processor.common.AbstractCatalogDataValueProcessor;
import org.spongepowered.common.data.value.mutable.SpongeValue;

public class DoublePlantTypeValueProcessor extends
        AbstractCatalogDataValueProcessor<DoublePlantType, Value<DoublePlantType>> {

    public DoublePlantTypeValueProcessor() {
        super(Keys.DOUBLE_PLANT_TYPE);
    }

    @Override
    protected boolean supports(ItemStack container){
        return container.getItem() == ItemTypes.DOUBLE_PLANT;
    }

    @Override
    protected Value<DoublePlantType> constructValue(DoublePlantType defaultValue) {
        return new SpongeValue<>(Keys.DOUBLE_PLANT_TYPE, DoublePlantTypes.FERN, defaultValue);
    }

    @Override
    protected int setToMeta(DoublePlantType value) {
        return ((BlockDoublePlant.EnumPlantType) (Object) value).getMeta();
    }

    @Override
    protected DoublePlantType getFromMeta(int meta) {
        return (DoublePlantType) (Object) BlockDoublePlant.EnumPlantType.byMetadata(meta);
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2015 Red Hat, Inc. and/or its affiliates.
  ~
  ~ Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>io.thorntail.testsuite</groupId>
    <artifactId>testsuite-parent</artifactId>
    <version>2.7.1.Final-SNAPSHOT</version>
  </parent>

  <artifactId>testsuite-topology-consul</artifactId>

  <name>Test Suite: Topology via Consul</name>
  <description>Test Suite: Topology via Consul</description>

  <packaging>jar</packaging>

  <dependencies>
    <dependency>
      <groupId>io.thorntail</groupId>
      <artifactId>topology-consul</artifactId>
    </dependency>
    <dependency>
      <groupId>io.thorntail</groupId>
      <artifactId>jaxrs</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>io.thorntail</groupId>
      <artifactId>arquillian</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.jboss.arquillian.junit</groupId>
      <artifactId>arquillian-junit-container</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

</project>


text:
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload
from urllib.parse import parse_qs, urljoin, urlparse

from azure.core.exceptions import (
    ClientAuthenticationError,
    HttpResponseError,
    ResourceExistsError,
    ResourceNotFoundError,
    ResourceNotModifiedError,
    map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat

from .. import models as _models
from .._serialization import Serializer
from .._vendor import _convert_request, _format_url_section

T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]

_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False

def build_list_request(
    resource_group_name: str, environment_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01-preview"))  # type: str
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop(
        "template_url",
        "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.App/managedEnvironments/{environmentName}/daprComponents",
    )  # pylint: disable=line-too-long
    path_format_arguments = {
        "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1),
        "resourceGroupName": _SERIALIZER.url(
            "resource_group_name", resource_group_name, "str", max_length=90, min_length=1
        ),
        "environmentName": _SERIALIZER.url("environment_name", environment_name, "str"),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)

def build_get_request(
    resource_group_name: str, environment_name: str, component_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01-preview"))  # type: str
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop(
        "template_url",
        "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.App/managedEnvironments/{environmentName}/daprComponents/{componentName}",
    )  # pylint: disable=line-too-long
    path_format_arguments = {
        "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1),
        "resourceGroupName": _SERIALIZER.url(
            "resource_group_name", resource_group_name, "str", max_length=90, min_length=1
        ),
        "environmentName": _SERIALIZER.url("environment_name", environment_name, "str"),
        "componentName": _SERIALIZER.url("component_name", component_name, "str"),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)

def build_create_or_update_request(
    resource_group_name: str, environment_name: str, component_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01-preview"))  # type: str
    content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None))  # type: Optional[str]
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop(
        "template_url",
        "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.App/managedEnvironments/{environmentName}/daprComponents/{componentName}",
    )  # pylint: disable=line-too-long
    path_format_arguments = {
        "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1),
        "resourceGroupName": _SERIALIZER.url(
            "resource_group_name", resource_group_name, "str", max_length=90, min_length=1
        ),
        "environmentName": _SERIALIZER.url("environment_name", environment_name, "str"),
        "componentName": _SERIALIZER.url("component_name", component_name, "str"),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    if content_type is not None:
        _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)

def build_delete_request(
    resource_group_name: str, environment_name: str, component_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01-preview"))  # type: str
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop(
        "template_url",
        "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.App/managedEnvironments/{environmentName}/daprComponents/{componentName}",
    )  # pylint: disable=line-too-long
    path_format_arguments = {
        "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1),
        "resourceGroupName": _SERIALIZER.url(
            "resource_group_name", resource_group_name, "str", max_length=90, min_length=1
        ),
        "environmentName": _SERIALIZER.url("environment_name", environment_name, "str"),
        "componentName": _SERIALIZER.url("component_name", component_name, "str"),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)

def build_list_secrets_request(
    resource_group_name: str, environment_name: str, component_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01-preview"))  # type: str
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop(
        "template_url",
        "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.App/managedEnvironments/{environmentName}/daprComponents/{componentName}/listSecrets",
    )  # pylint: disable=line-too-long
    path_format_arguments = {
        "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1),
        "resourceGroupName": _SERIALIZER.url(
            "resource_group_name", resource_group_name, "str", max_length=90, min_length=1
        ),
        "environmentName": _SERIALIZER.url("environment_name", environment_name, "str"),
        "componentName": _SERIALIZER.url("component_name", component_name, "str"),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)

class DaprComponentsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.appcontainers.ContainerAppsAPIClient`'s
        :attr:`dapr_components` attribute.
    """

    models = _models

    def __init__(self, *args, **kwargs):
        input_args = list(args)
        self._client = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list(self, resource_group_name: str, environment_name: str, **kwargs: Any) -> Iterable["_models.DaprComponent"]:
        """Get the Dapr Components for a managed environment.

        Get the Dapr Components for a managed environment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param environment_name: Name of the Managed Environment. Required.
        :type environment_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either DaprComponent or the result of cls(response)
        :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.appcontainers.models.DaprComponent]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))  # type: str
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.DaprComponentsCollection]

        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                request = build_list_request(
                    resource_group_name=resource_group_name,
                    environment_name=environment_name,
                    subscription_id=self._config.subscription_id,
                    api_version=api_version,
                    template_url=self.list.metadata["url"],
                    headers=_headers,
                    params=_params,
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urlparse(next_link)
                _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query))
                _next_request_params["api-version"] = self._config.api_version
                request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params)
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore
                request.method = "GET"
            return request

        def extract_data(pipeline_response):
            deserialized = self._deserialize("DaprComponentsCollection", pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, iter(list_of_elem)

        def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
                request, stream=False, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response)
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return ItemPaged(get_next, extract_data)

    list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.App/managedEnvironments/{environmentName}/daprComponents"}  # type: ignore

    @distributed_trace
    def get(
        self, resource_group_name: str, environment_name: str, component_name: str, **kwargs: Any
    ) -> _models.DaprComponent:
        """Get a dapr component.

        Get a dapr component.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param environment_name: Name of the Managed Environment. Required.
        :type environment_name: str
        :param component_name: Name of the Dapr Component. Required.
        :type component_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: DaprComponent or the result of cls(response)
        :rtype: ~azure.mgmt.appcontainers.models.DaprComponent
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))  # type: str
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.DaprComponent]

        request = build_get_request(
            resource_group_name=resource_group_name,
            environment_name=environment_name,
            component_name=component_name,
            subscription_id=self._config.subscription_id,
            api_version=api_version,
            template_url=self.get.metadata["url"],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request, stream=False, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        deserialized = self._deserialize("DaprComponent", pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized

    get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.App/managedEnvironments/{environmentName}/daprComponents/{componentName}"}  # type: ignore

    @overload
    def create_or_update(
        self,
        resource_group_name: str,
        environment_name: str,
        component_name: str,
        dapr_component_envelope: _models.DaprComponent,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.DaprComponent:
        """Creates or updates a Dapr Component.

        Creates or updates a Dapr Component in a Managed Environment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param environment_name: Name of the Managed Environment. Required.
        :type environment_name: str
        :param component_name: Name of the Dapr Component. Required.
        :type component_name: str
        :param dapr_component_envelope: Configuration details of the Dapr Component. Required.
        :type dapr_component_envelope: ~azure.mgmt.appcontainers.models.DaprComponent
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: DaprComponent or the result of cls(response)
        :rtype: ~azure.mgmt.appcontainers.models.DaprComponent
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    def create_or_update(
        self,
        resource_group_name: str,
        environment_name: str,
        component_name: str,
        dapr_component_envelope: IO,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.DaprComponent:
        """Creates or updates a Dapr Component.

        Creates or updates a Dapr Component in a Managed Environment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param environment_name: Name of the Managed Environment. Required.
        :type environment_name: str
        :param component_name: Name of the Dapr Component. Required.
        :type component_name: str
        :param dapr_component_envelope: Configuration details of the Dapr Component. Required.
        :type dapr_component_envelope: IO
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: DaprComponent or the result of cls(response)
        :rtype: ~azure.mgmt.appcontainers.models.DaprComponent
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace
    def create_or_update(
        self,
        resource_group_name: str,
        environment_name: str,
        component_name: str,
        dapr_component_envelope: Union[_models.DaprComponent, IO],
        **kwargs: Any
    ) -> _models.DaprComponent:
        """Creates or updates a Dapr Component.

        Creates or updates a Dapr Component in a Managed Environment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param environment_name: Name of the Managed Environment. Required.
        :type environment_name: str
        :param component_name: Name of the Dapr Component. Required.
        :type component_name: str
        :param dapr_component_envelope: Configuration details of the Dapr Component. Is either a model
         type or a IO type. Required.
        :type dapr_component_envelope: ~azure.mgmt.appcontainers.models.DaprComponent or IO
        :keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
         Default value is None.
        :paramtype content_type: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: DaprComponent or the result of cls(response)
        :rtype: ~azure.mgmt.appcontainers.models.DaprComponent
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))  # type: str
        content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None))  # type: Optional[str]
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.DaprComponent]

        content_type = content_type or "application/json"
        _json = None
        _content = None
        if isinstance(dapr_component_envelope, (IO, bytes)):
            _content = dapr_component_envelope
        else:
            _json = self._serialize.body(dapr_component_envelope, "DaprComponent")

        request = build_create_or_update_request(
            resource_group_name=resource_group_name,
            environment_name=environment_name,
            component_name=component_name,
            subscription_id=self._config.subscription_id,
            api_version=api_version,
            content_type=content_type,
            json=_json,
            content=_content,
            template_url=self.create_or_update.metadata["url"],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request, stream=False, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        deserialized = self._deserialize("DaprComponent", pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized

    create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.App/managedEnvironments/{environmentName}/daprComponents/{componentName}"}  # type: ignore

    @distributed_trace
    def delete(  # pylint: disable=inconsistent-return-statements
        self, resource_group_name: str, environment_name: str, component_name: str, **kwargs: Any
    ) -> None:
        """Delete a Dapr Component.

        Delete a Dapr Component from a Managed Environment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param environment_name: Name of the Managed Environment. Required.
        :type environment_name: str
        :param component_name: Name of the Dapr Component. Required.
        :type component_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None or the result of cls(response)
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))  # type: str
        cls = kwargs.pop("cls", None)  # type: ClsType[None]

        request = build_delete_request(
            resource_group_name=resource_group_name,
            environment_name=environment_name,
            component_name=component_name,
            subscription_id=self._config.subscription_id,
            api_version=api_version,
            template_url=self.delete.metadata["url"],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request, stream=False, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})

    delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.App/managedEnvironments/{environmentName}/daprComponents/{componentName}"}  # type: ignore

    @distributed_trace
    def list_secrets(
        self, resource_group_name: str, environment_name: str, component_name: str, **kwargs: Any
    ) -> _models.DaprSecretsCollection:
        """List secrets for a dapr component.

        List secrets for a dapr component.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param environment_name: Name of the Managed Environment. Required.
        :type environment_name: str
        :param component_name: Name of the Dapr Component. Required.
        :type component_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: DaprSecretsCollection or the result of cls(response)
        :rtype: ~azure.mgmt.appcontainers.models.DaprSecretsCollection
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))  # type: str
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.DaprSecretsCollection]

        request = build_list_secrets_request(
            resource_group_name=resource_group_name,
            environment_name=environment_name,
            component_name=component_name,
            subscription_id=self._config.subscription_id,
            api_version=api_version,
            template_url=self.list_secrets.metadata["url"],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request, stream=False, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        deserialized = self._deserialize("DaprSecretsCollection", pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized

    list_secrets.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.App/managedEnvironments/{environmentName}/daprComponents/{componentName}/listSecrets"}  # type: ignore


text:
package com.google.idea.blaze.android.run.runner;

import static org.jetbrains.android.actions.RunAndroidAvdManagerAction.getName;

import com.android.ddmlib.IDevice;
import com.android.tools.idea.run.AndroidProcessHandler;
import com.android.tools.idea.run.AndroidSessionInfo;
import com.android.tools.idea.run.ApkProvisionException;
import com.android.tools.idea.run.ApplicationIdProvider;
import com.android.tools.idea.run.DeviceFutures;
import com.android.tools.idea.run.LaunchInfo;
import com.android.tools.idea.run.LaunchOptions;
import com.android.tools.idea.run.LaunchTaskRunner;
import com.android.tools.idea.run.editor.DeployTarget;
import com.android.tools.idea.run.editor.DeployTargetState;
import com.android.tools.idea.run.tasks.LaunchTasksProvider;
import com.android.tools.idea.run.util.LaunchUtils;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.idea.blaze.base.experiments.ExperimentScope;
import com.google.idea.blaze.base.run.confighandler.BlazeCommandRunConfigurationRunner;
import com.google.idea.blaze.base.run.smrunner.SmRunnerUtils;
import com.google.idea.blaze.base.scope.Scope;
import com.google.idea.blaze.base.scope.output.IssueOutput;
import com.google.idea.blaze.base.scope.scopes.BlazeConsoleScope;
import com.google.idea.blaze.base.scope.scopes.IdeaLogScope;
import com.google.idea.blaze.base.scope.scopes.IssuesScope;
import com.google.idea.blaze.base.settings.BlazeUserSettings;
import com.google.idea.blaze.base.settings.BlazeUserSettings.BlazeConsolePopupBehavior;
import com.intellij.execution.DefaultExecutionResult;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.ExecutionResult;
import com.intellij.execution.Executor;
import com.intellij.execution.configurations.RunProfileState;
import com.intellij.execution.executors.DefaultDebugExecutor;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.runners.ProgramRunner;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import org.jetbrains.android.facet.AndroidFacet;
import org.jetbrains.android.sdk.AndroidSdkUtils;
import org.jetbrains.android.util.AndroidBundle;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * Supports the execution. Used by both android_binary and android_test.
 *
 *
Builds the APK and installs it, launches and debug tasks, etc.
 *
 *
Any indirection between android_binary/android_test, mobile-install, InstantRun etc. should
 * come via the strategy class.
 */
public final class BlazeAndroidRunConfigurationRunner
    implements BlazeCommandRunConfigurationRunner {

  private static final Logger LOG = Logger.getInstance(BlazeAndroidRunConfigurationRunner.class);

  private static final Key<BlazeAndroidRunContext> RUN_CONTEXT_KEY =
      Key.create("blaze.run.context");
  public static final Key<BlazeAndroidDeviceSelector.DeviceSession> DEVICE_SESSION_KEY =
      Key.create("blaze.device.session");

  private final Module module;
  private final BlazeAndroidRunContext runContext;
  private final BlazeAndroidRunConfigurationDeployTargetManager deployTargetManager;
  private final BlazeAndroidRunConfigurationDebuggerManager debuggerManager;
  private final int runConfigId;

  public BlazeAndroidRunConfigurationRunner(
      Module module,
      BlazeAndroidRunContext runContext,
      BlazeAndroidRunConfigurationDeployTargetManager deployTargetManager,
      BlazeAndroidRunConfigurationDebuggerManager debuggerManager,
      int runConfigId) {
    this.module = module;
    this.runContext = runContext;
    this.deployTargetManager = deployTargetManager;
    this.debuggerManager = debuggerManager;
    this.runConfigId = runConfigId;
  }

  @Override
  @Nullable
  public final RunProfileState getRunProfileState(final Executor executor, ExecutionEnvironment env)
      throws ExecutionException {

    final AndroidFacet facet = AndroidFacet.getInstance(module);
    assert facet != null : "Enforced by fatal validation check in createRunner.";
    final Project project = env.getProject();

    runContext.augmentEnvironment(env);

    boolean isDebug = executor instanceof DefaultDebugExecutor;
    if (isDebug && !AndroidSdkUtils.activateDdmsIfNecessary(facet.getModule().getProject())) {
      throw new ExecutionException(
          "Unable to obtain debug bridge. "
              + "Please check if there is a different tool using adb that is active.");
    }

    AndroidSessionInfo info = AndroidSessionInfo.findOldSession(project, null, runConfigId);

    BlazeAndroidDeviceSelector deviceSelector = runContext.getDeviceSelector();
    BlazeAndroidDeviceSelector.DeviceSession deviceSession =
        deviceSelector.getDevice(
            project, facet, deployTargetManager, executor, env, info, isDebug, runConfigId);
    if (deviceSession == null) {
      return null;
    }

    DeployTarget deployTarget = deviceSession.deployTarget;
    if (deployTarget != null && deployTarget.hasCustomRunProfileState(executor)) {
      DeployTargetState deployTargetState = deployTargetManager.getCurrentDeployTargetState();
      return deployTarget.getRunProfileState(executor, env, deployTargetState);
    }

    DeviceFutures deviceFutures = deviceSession.deviceFutures;
    if (deviceFutures == null) {
      // The user deliberately canceled, or some error was encountered and exposed by the chooser.
      // Quietly exit.
      return null;
    }

    if (deviceFutures.get().isEmpty()) {
      throw new ExecutionException(AndroidBundle.message("deployment.target.not.found"));
    }

    if (isDebug) {
      String error = canDebug(deviceFutures, facet, module.getName());
      if (error != null) {
        throw new ExecutionException(error);
      }
    }

    LaunchOptions.Builder launchOptionsBuilder = getDefaultLaunchOptions().setDebug(isDebug);
    runContext.augmentLaunchOptions(launchOptionsBuilder);

    // Store the run context on the execution environment so before-run tasks can access it.
    env.putCopyableUserData(RUN_CONTEXT_KEY, runContext);
    env.putCopyableUserData(DEVICE_SESSION_KEY, deviceSession);

    return new BlazeAndroidRunState(
        module, env, getName(), launchOptionsBuilder, isDebug, deviceSession, runContext);
  }

  private static String canDebug(
      DeviceFutures deviceFutures, AndroidFacet facet, String moduleName) {
    // If we are debugging on a device, then the app needs to be debuggable
    for (ListenableFuture<IDevice> future : deviceFutures.get()) {
      if (!future.isDone()) {
        // this is an emulator, and we assume that all emulators are debuggable
        continue;
      }
      IDevice device = Futures.getUnchecked(future);
      if (!LaunchUtils.canDebugAppOnDevice(facet, device)) {
        return AndroidBundle.message(
            "android.cannot.debug.noDebugPermissions", moduleName, device.getName());
      }
    }
    return null;
  }

  private static LaunchOptions.Builder getDefaultLaunchOptions() {
    return LaunchOptions.builder()
        .setClearLogcatBeforeStart(false)
        .setSkipNoopApkInstallations(true)
        .setForceStopRunningApp(true);
  }

  @Override
  public boolean executeBeforeRunTask(ExecutionEnvironment env) {
    final Project project = env.getProject();
    BlazeConsolePopupBehavior consolePopupBehavior =
        BlazeUserSettings.getInstance().getSuppressConsoleForRunAction()
            ? BlazeConsolePopupBehavior.NEVER
            : BlazeConsolePopupBehavior.ALWAYS;
    return Scope.root(
        context -> {
          context
              .push(new IssuesScope(project))
              .push(new ExperimentScope())
              .push(
                  new BlazeConsoleScope.Builder(project)
                      .setPopupBehavior(consolePopupBehavior)
                      .build())
              .push(new IdeaLogScope());

          BlazeAndroidRunContext runContext = env.getCopyableUserData(RUN_CONTEXT_KEY);
          if (runContext == null) {
            IssueOutput.error("Could not find run context. Please try again").submit(context);
            return false;
          }
          BlazeAndroidDeviceSelector.DeviceSession deviceSession =
              env.getCopyableUserData(DEVICE_SESSION_KEY);

          BlazeApkBuildStep buildStep = runContext.getBuildStep();
          try {
            return buildStep.build(context, deviceSession);
          } catch (Exception e) {
            LOG.error(e);
            return false;
          }
        });
  }

  private final class BlazeAndroidRunState implements RunProfileState {

    private final Module module;
    private final ExecutionEnvironment env;
    private final String launchConfigName;
    private final BlazeAndroidDeviceSelector.DeviceSession deviceSession;
    private final BlazeAndroidRunContext runContext;
    private final LaunchOptions.Builder launchOptionsBuilder;
    private final boolean isDebug;

    private BlazeAndroidRunState(
        Module module,
        ExecutionEnvironment env,
        String launchConfigName,
        LaunchOptions.Builder launchOptionsBuilder,
        boolean isDebug,
        BlazeAndroidDeviceSelector.DeviceSession deviceSession,
        BlazeAndroidRunContext runContext) {
      this.module = module;
      this.env = env;
      this.launchConfigName = launchConfigName;
      this.deviceSession = deviceSession;
      this.runContext = runContext;
      this.launchOptionsBuilder = launchOptionsBuilder;
      this.isDebug = isDebug;
    }

    @Nullable
    @Override
    public ExecutionResult execute(Executor executor, ProgramRunner runner)
        throws ExecutionException {
      DefaultExecutionResult result = executeInner(executor, runner);
      if (result == null) {
        return null;
      }
      return SmRunnerUtils.attachRerunFailedTestsAction(result);
    }

    @Nullable
    private DefaultExecutionResult executeInner(Executor executor, @NotNull ProgramRunner<?> runner)
        throws ExecutionException {
      ProcessHandler processHandler;
      ConsoleView console;

      ApplicationIdProvider applicationIdProvider = runContext.getApplicationIdProvider();

      String applicationId;
      try {
        applicationId = applicationIdProvider.getPackageName();
      } catch (ApkProvisionException e) {
        throw new ExecutionException("Unable to obtain application id", e);
      }

      LaunchTasksProvider launchTasksProvider =
          runContext.getLaunchTasksProvider(launchOptionsBuilder, isDebug, debuggerManager);

      DeviceFutures deviceFutures = deviceSession.deviceFutures;
      assert deviceFutures != null;
      ProcessHandler previousSessionProcessHandler =
          deviceSession.sessionInfo != null ? deviceSession.sessionInfo.getProcessHandler() : null;

      if (launchTasksProvider.createsNewProcess()) {
        // In the case of cold swap, there is an existing process that is connected,
        // but we are going to launch a new one.
        // Detach the previous process handler so that we don't end up with
        // 2 run tabs for the same launch (the existing one and the new one).
        if (previousSessionProcessHandler != null) {
          previousSessionProcessHandler.detachProcess();
        }

        processHandler =
            new AndroidProcessHandler(applicationId, launchTasksProvider.monitorRemoteProcess());
        console =
            runContext
                .getConsoleProvider()
                .createAndAttach(module.getProject(), processHandler, executor);
      } else {
        assert previousSessionProcessHandler != null
            : "No process handler from previous session, yet current tasks don't create one";
        processHandler = previousSessionProcessHandler;
        console = null;
      }

      LaunchInfo launchInfo =
          new LaunchInfo(executor, runner, env, runContext.getConsoleProvider());

      LaunchTaskRunner task =
          new LaunchTaskRunner(
              module.getProject(),
              launchConfigName,
              launchInfo,
              processHandler,
              deviceSession.deviceFutures,
              launchTasksProvider);
      ProgressManager.getInstance().run(task);

      return console == null ? null : new DefaultExecutionResult(console, processHandler);
    }
  }
}


text:
class Struct(object):
    def __init__(self, content=None):
        if type(content) == dict:
            self.__dict__ = content

    def __getitem__(self, index):
        return self.__dict__[index]

    def __setitem__(self, index, value):
        self.__dict__[index] = value

    def __iter__(self):
        for i in self.__dict__:
            yield self[i]

    def keys(self):
        return self.__dict__.keys()

    def __len__(self):
        return len(self.__dict__)

    def __str__(self):
        longest = max([len(i) for i in self.__dict__])
        return '\n'.join(['%s : ' % i.rjust(longest) + str(self[i]) for i in self.__dict__])

    def __repr__(self):
        return 'Struct( %s )' % str(self.__dict__)