text:
package com.dw.leetcode;

public class minimum_time_visiting_all_points_1266 {

	public int minTimeToVisitAllPoints(int[][] points) {
		int result = 0;

		for(int i=0;i<points.length - 1;i++) {
			result += Math.max(Math.abs(points[i][0] - points[i+1][0]), Math.abs(points[i][1] - points[i+1][1]));
		}

		return result;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[][] points = {{1,1},{3,4},{-1,0}};
		minimum_time_visiting_all_points_1266 s = new minimum_time_visiting_all_points_1266();
		System.out.println(s.minTimeToVisitAllPoints(points));
	}
}


text:
'use strict';

module.exports = function (collection, context, cb) {
	if (!context.isJson()) {
		return cb(context.setStatus(415)); // Unsupported Media Type
	}

	const resources = collection.getList();
	for (let i = 0; i < resources.length; i++) {
		const resource = resources[i];

		if (!context.mayDelete(resource)) {
			return cb(context.disallow(resource)); // Method not allowed
		}
	}

	collection.delAll(function (error) {
		if (error) {
			return cb(context.setStatus(500, error)); // Internal server error
		}

		return cb(context.setStatus(204)); // No content
	});
};

redpajama_set_name: RedPajamaGithub


text:
package com.budget.dao;

import java.util.List;

import com.budget.entity.Entree;

public interface IEntreeDao {

	public void createEntree(Entree entity);
	public void updateEntree(String nomEntree, double sommeEntity);
	public void deleteEntree(String nomEntree);
	public Entree findEntree(String nomEntree);
	public List<Entree> findAll();
	public double totalEntree();
	public void editableEntree(String nomEntree);

}


text:
import { BaseModel } from './base-model.model';
import { serializable } from './serializable.decorator';
import { Program } from './program.model';
import { DatePipe } from '@angular/common';
import { TitleCasePipe } from '../shared/pipes/title-case.pipe';

export class ProgramEnrollment extends BaseModel {
  private _program: Program;
  private _location: any;
  private _dateEnrolled: Date;
  private _dateCompleted: Date;
  private _datePipe: DatePipe;
  private _titleCasePipe: TitleCasePipe;

  constructor(openmrsModel?: any) {
    super(openmrsModel);
    this._datePipe = new DatePipe('en-US');
    this._titleCasePipe = new TitleCasePipe();
  }

  @serializable(true, false)
  public get program(): Program {
    if (this._program === null || this._program === undefined) {
      this.initializeNavigationProperty('program');
      this._program = new Program(this._openmrsModel.program);
    }
    return this._program;
  }

  public set program(v: Program) {
    this._openmrsModel.program = v.openmrsModel;
    this._program = v;
  }
  @serializable()
  public get display(): string {
    return this._titleCasePipe.transform(this._openmrsModel.display);
  }

  public set display(v: string) {
    this._openmrsModel.display = v;
  }

  public get location(): any {
    return this._openmrsModel.location;
  }

  public get states(): any {
    return this._openmrsModel.states;
  }

  public get programUuid(): string {
    return this._openmrsModel.program.uuid;
  }

  public get voided(): boolean {
    return this._openmrsModel.voided;
  }

  @serializable()
  public get dateEnrolled(): Date {
    if (this._dateEnrolled === null || this._dateEnrolled === undefined) {
      this._dateEnrolled = this.resolveDate(this._openmrsModel.dateEnrolled);
    }
    return this._dateEnrolled;
  }

  public set dateEnrolled(v: Date) {
    this._openmrsModel.dateEnrolled = v.toServerTimezoneString();
    this._dateEnrolled = v;
  }

  @serializable()
  public get dateCompleted(): Date {
    if (this._dateCompleted === null || this._dateCompleted === undefined) {
      this._dateCompleted = this.resolveDate(this._openmrsModel.dateCompleted);
    }
    return this._dateCompleted;
  }

  public set dateCompleted(v: Date) {
    this._openmrsModel.dateCompleted = v.toServerTimezoneString();
    this._dateCompleted = v;
  }

  private resolveDate(date) {
    const dateFormat = 'MMM dd, yyyy';
    const parsedDate = Date.parse(date);
    return isNaN(parsedDate)
      ? date
      : this._datePipe.transform(date, dateFormat);
  }
}


text:
package org.axonframework.integrationtests.modelling.command;

import org.axonframework.commandhandling.CommandBus;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.commandhandling.SimpleCommandBus;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.commandhandling.gateway.DefaultCommandGateway;
import org.axonframework.common.AxonConfigurationException;
import org.axonframework.eventhandling.EventMessage;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.eventsourcing.EventSourcingRepository;
import org.axonframework.eventsourcing.eventstore.EmbeddedEventStore;
import org.axonframework.eventsourcing.eventstore.EventStore;
import org.axonframework.eventsourcing.eventstore.inmemory.InMemoryEventStorageEngine;
import org.axonframework.messaging.InterceptorChain;
import org.axonframework.modelling.command.AggregateAnnotationCommandHandler;
import org.axonframework.modelling.command.AggregateIdentifier;
import org.axonframework.modelling.command.AggregateMember;
import org.axonframework.modelling.command.CommandHandlerInterceptor;
import org.axonframework.modelling.command.EntityId;
import org.axonframework.modelling.command.Repository;
import org.axonframework.modelling.command.TargetAggregateIdentifier;
import org.junit.jupiter.api.*;
import org.mockito.*;

import java.util.Objects;

import static org.axonframework.commandhandling.GenericCommandMessage.asCommandMessage;
import static org.axonframework.modelling.command.AggregateLifecycle.apply;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

/**
 * Tests for annotated command handler interceptor on aggregate / child entities.
 *
 * @author Milan Savic
 */
class CommandHandlerInterceptorTest {

    private CommandGateway commandGateway;
    private EventStore eventStore;

    @BeforeEach
    void setUp() {
        eventStore = spy(EmbeddedEventStore.builder().storageEngine(new InMemoryEventStorageEngine()).build());
        Repository<MyAggregate> myAggregateRepository = EventSourcingRepository.builder(MyAggregate.class)
                                                                               .eventStore(eventStore)
                                                                               .build();
        CommandBus commandBus = SimpleCommandBus.builder().build();
        commandGateway = DefaultCommandGateway.builder().commandBus(commandBus).build();
        AggregateAnnotationCommandHandler<MyAggregate> myAggregateCommandHandler =
                AggregateAnnotationCommandHandler.<MyAggregate>builder()
                        .aggregateType(MyAggregate.class)
                        .repository(myAggregateRepository)
                        .build();

        myAggregateCommandHandler.subscribe(commandBus);
    }

    @SuppressWarnings("unchecked")
    @Test
    void interceptor() {
        commandGateway.sendAndWait(asCommandMessage(new CreateMyAggregateCommand("id")));
        String result = commandGateway
                .sendAndWait(asCommandMessage(new UpdateMyAggregateStateCommand("id", "state")));

        ArgumentCaptor<EventMessage<?>> eventCaptor = ArgumentCaptor.forClass(EventMessage.class);

        verify(eventStore, times(3)).publish(eventCaptor.capture());
        assertEquals(new MyAggregateCreatedEvent("id"), eventCaptor.getAllValues().get(0).getPayload());
        assertEquals(new AnyCommandInterceptedEvent(UpdateMyAggregateStateCommand.class.getName()),
                     eventCaptor.getAllValues().get(1).getPayload());
        assertEquals(new MyAggregateStateUpdatedEvent("id", "state intercepted"),
                     eventCaptor.getAllValues().get(2).getPayload());

        assertEquals("aggregateUpdateResult", result);
    }

    @SuppressWarnings("unchecked")
    @Test
    void interceptorWithChainProceeding() {
        commandGateway.sendAndWait(asCommandMessage(new CreateMyAggregateCommand("id")));
        commandGateway.sendAndWait(asCommandMessage(new ClearMyAggregateStateCommand("id", true)));

        ArgumentCaptor<EventMessage<?>> eventCaptor = ArgumentCaptor.forClass(EventMessage.class);
        verify(eventStore, times(3)).publish(eventCaptor.capture());
        assertEquals(new MyAggregateCreatedEvent("id"), eventCaptor.getAllValues().get(0).getPayload());
        assertEquals(new AnyCommandInterceptedEvent(ClearMyAggregateStateCommand.class.getName()),
                     eventCaptor.getAllValues().get(1).getPayload());
        assertEquals(new MyAggregateStateClearedEvent("id"), eventCaptor.getAllValues().get(2).getPayload());
    }

    @SuppressWarnings("unchecked")
    @Test
    void interceptorWithoutChainProceeding() {
        commandGateway.sendAndWait(asCommandMessage(new CreateMyAggregateCommand("id")));
        commandGateway.sendAndWait(asCommandMessage(new ClearMyAggregateStateCommand("id", false)));

        ArgumentCaptor<EventMessage<?>> eventCaptor = ArgumentCaptor.forClass(EventMessage.class);
        verify(eventStore, times(2)).publish(eventCaptor.capture());
        assertEquals(new MyAggregateCreatedEvent("id"), eventCaptor.getAllValues().get(0).getPayload());
        assertEquals(new MyAggregateStateNotClearedEvent("id"), eventCaptor.getAllValues().get(1).getPayload());
    }

    @SuppressWarnings("unchecked")
    @Test
    void interceptorWithNestedEntity() {
        commandGateway.sendAndWait(asCommandMessage(new CreateMyAggregateCommand("id")));
        commandGateway.sendAndWait(asCommandMessage(new MyNestedCommand("id", "state")));

        ArgumentCaptor<EventMessage<?>> eventCaptor = ArgumentCaptor.forClass(EventMessage.class);
        verify(eventStore, times(4)).publish(eventCaptor.capture());
        assertEquals(new MyAggregateCreatedEvent("id"), eventCaptor.getAllValues().get(0).getPayload());
        assertEquals(new AnyCommandMatchingPatternInterceptedEvent(MyNestedCommand.class.getName()),
                     eventCaptor.getAllValues().get(1).getPayload());
        assertEquals(new AnyCommandInterceptedEvent(MyNestedCommand.class.getName()),
                     eventCaptor.getAllValues().get(2).getPayload());
        assertEquals(new MyNestedEvent("id", "state intercepted"), eventCaptor.getAllValues().get(3).getPayload());
    }

    @SuppressWarnings("unchecked")
    @Test
    void interceptorWithNestedNestedEntity() {
        commandGateway.sendAndWait(asCommandMessage(new CreateMyAggregateCommand("id")));
        commandGateway.sendAndWait(asCommandMessage(new MyNestedNestedCommand("id", "state")));

        ArgumentCaptor<EventMessage<?>> eventCaptor = ArgumentCaptor.forClass(EventMessage.class);
        verify(eventStore, times(6)).publish(eventCaptor.capture());
        assertEquals(new MyAggregateCreatedEvent("id"), eventCaptor.getAllValues().get(0).getPayload());
        assertEquals(new AnyCommandMatchingPatternInterceptedEvent(MyNestedNestedCommand.class.getName()),
                     eventCaptor.getAllValues().get(1).getPayload());
        assertEquals(new AnyCommandInterceptedEvent(MyNestedNestedCommand.class.getName()),
                     eventCaptor.getAllValues().get(2).getPayload());
        assertEquals(new AnyCommandInterceptedEvent("StaticNestedNested" + MyNestedNestedCommand.class.getName()),
                     eventCaptor.getAllValues().get(3).getPayload());
        assertEquals(new AnyCommandInterceptedEvent("NestedNested" + MyNestedNestedCommand.class.getName()),
                     eventCaptor.getAllValues().get(4).getPayload());
        assertEquals(new MyNestedNestedEvent("id", "state parent intercepted intercepted"),
                     eventCaptor.getAllValues().get(5).getPayload());
    }

    @Test
    void interceptorWithNonVoidReturnType() {
        EventSourcingRepository.Builder<MyAggregateWithInterceptorReturningNonVoid> builder =
                EventSourcingRepository.builder(MyAggregateWithInterceptorReturningNonVoid.class)
                        .eventStore(eventStore);

        assertThrows(AxonConfigurationException.class, builder::build);
    }

    @Test
    void interceptorWithDeclaredChainAllowedToDeclareNonVoidReturnType() {
        EventSourcingRepository.builder(MyAggregateWithDeclaredInterceptorChainInterceptorReturningNonVoid.class)
                .eventStore(eventStore)
                .build();
    }

    @SuppressWarnings("unchecked")
    @Test
    void interceptorThrowingAnException() {
        commandGateway.sendAndWait(asCommandMessage(new CreateMyAggregateCommand("id")));
        assertThrows(
                InterceptorException.class,
                () -> commandGateway.sendAndWait(asCommandMessage(new InterceptorThrowingCommand("id")))
        );
        ArgumentCaptor<EventMessage<?>> eventCaptor = ArgumentCaptor.forClass(EventMessage.class);
        verify(eventStore, times(1)).publish(eventCaptor.capture());
        assertEquals(new MyAggregateCreatedEvent("id"), eventCaptor.getAllValues().get(0).getPayload());
    }

    private static class CreateMyAggregateCommand {

        private final String id;

        private CreateMyAggregateCommand(String id) {
            this.id = id;
        }

        public String getId() {
            return id;
        }
    }

    private static class UpdateMyAggregateStateCommand {

        @TargetAggregateIdentifier
        private final String id;
        private String state;

        private UpdateMyAggregateStateCommand(String id, String state) {
            this.id = id;
            this.state = state;
        }

        public String getId() {
            return id;
        }

        public String getState() {
            return state;
        }

        public void setState(String state) {
            this.state = state;
        }
    }

    private static class ClearMyAggregateStateCommand {

        @TargetAggregateIdentifier
        private final String id;
        private final boolean proceed;

        private ClearMyAggregateStateCommand(String id, boolean proceed) {
            this.id = id;
            this.proceed = proceed;
        }

        public String getId() {
            return id;
        }

        public boolean isProceed() {
            return proceed;
        }
    }

    private static class MyNestedCommand {

        @TargetAggregateIdentifier
        private final String id;
        private String state;

        private MyNestedCommand(String id, String state) {
            this.id = id;
            this.state = state;
        }

        public String getId() {
            return id;
        }

        public String getState() {
            return state;
        }

        public void setState(String state) {
            this.state = state;
        }
    }

    private static class MyNestedNestedCommand {

        @TargetAggregateIdentifier
        private final String id;
        private String state;

        private MyNestedNestedCommand(String id, String state) {
            this.id = id;
            this.state = state;
        }

        public String getId() {
            return id;
        }

        public String getState() {
            return state;
        }

        public void setState(String state) {
            this.state = state;
        }
    }

    public static class InterceptorThrowingCommand {

        @TargetAggregateIdentifier
        private final String id;

        public InterceptorThrowingCommand(String id) {
            this.id = id;
        }

        public String getId() {
            return id;
        }
    }

    private static class MyAggregateCreatedEvent {

        private final String id;

        private MyAggregateCreatedEvent(String id) {
            this.id = id;
        }

        public String getId() {
            return id;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            MyAggregateCreatedEvent that = (MyAggregateCreatedEvent) o;
            return Objects.equals(id, that.id);
        }

        @Override
        public int hashCode() {
            return Objects.hash(id);
        }
    }

    private static class MyAggregateStateUpdatedEvent {

        @TargetAggregateIdentifier
        private final String id;
        private final String state;

        private MyAggregateStateUpdatedEvent(String id, String state) {
            this.id = id;
            this.state = state;
        }

        public String getId() {
            return id;
        }

        public String getState() {
            return state;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            MyAggregateStateUpdatedEvent that = (MyAggregateStateUpdatedEvent) o;
            return Objects.equals(id, that.id) &&
                    Objects.equals(state, that.state);
        }

        @Override
        public int hashCode() {
            return Objects.hash(id, state);
        }
    }

    private static class MyAggregateStateClearedEvent {

        private final String id;

        private MyAggregateStateClearedEvent(String id) {
            this.id = id;
        }

        public String getId() {
            return id;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            MyAggregateStateClearedEvent that = (MyAggregateStateClearedEvent) o;
            return Objects.equals(id, that.id);
        }

        @Override
        public int hashCode() {
            return Objects.hash(id);
        }
    }

    private static class MyAggregateStateNotClearedEvent {

        private final String id;

        private MyAggregateStateNotClearedEvent(String id) {
            this.id = id;
        }

        public String getId() {
            return id;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            MyAggregateStateNotClearedEvent that = (MyAggregateStateNotClearedEvent) o;
            return Objects.equals(id, that.id);
        }

        @Override
        public int hashCode() {
            return Objects.hash(id);
        }
    }

    private static class MyNestedEvent {

        private final String id;
        private final String state;

        private MyNestedEvent(String id, String state) {
            this.id = id;
            this.state = state;
        }

        public String getId() {
            return id;
        }

        public String getState() {
            return state;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            MyNestedEvent that = (MyNestedEvent) o;
            return Objects.equals(id, that.id) &&
                    Objects.equals(state, that.state);
        }

        @Override
        public int hashCode() {
            return Objects.hash(id, state);
        }
    }

    private static class MyNestedNestedEvent {

        private final String id;
        private final String state;

        private MyNestedNestedEvent(String id, String state) {
            this.id = id;
            this.state = state;
        }

        public String getId() {
            return id;
        }

        public String getState() {
            return state;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            MyNestedNestedEvent that = (MyNestedNestedEvent) o;
            return Objects.equals(id, that.id) &&
                    Objects.equals(state, that.state);
        }

        @Override
        public int hashCode() {
            return Objects.hash(id, state);
        }
    }

    private static class InterceptorThrewEvent {

        private final String id;

        private InterceptorThrewEvent(String id) {
            this.id = id;
        }

        public String getId() {
            return id;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            InterceptorThrewEvent that = (InterceptorThrewEvent) o;
            return Objects.equals(id, that.id);
        }

        @Override
        public int hashCode() {
            return Objects.hash(id);
        }
    }

    private static class AnyCommandInterceptedEvent {

        private final String id;

        private AnyCommandInterceptedEvent(String id) {
            this.id = id;
        }

        public String getId() {
            return id;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            AnyCommandInterceptedEvent that = (AnyCommandInterceptedEvent) o;
            return Objects.equals(id, that.id);
        }

        @Override
        public int hashCode() {
            return Objects.hash(id);
        }
    }

    private static class AnyCommandMatchingPatternInterceptedEvent {

        private final String id;

        private AnyCommandMatchingPatternInterceptedEvent(String id) {
            this.id = id;
        }

        public String getId() {
            return id;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            AnyCommandMatchingPatternInterceptedEvent that = (AnyCommandMatchingPatternInterceptedEvent) o;
            return Objects.equals(id, that.id);
        }

        @Override
        public int hashCode() {
            return Objects.hash(id);
        }
    }

    @SuppressWarnings("unused")
    private static class MyAggregate {

        @AggregateIdentifier
        private String id;
        private String state;
        @AggregateMember
        private MyNestedEntity myNestedEntity;

        public MyAggregate() {
            // do nothing
        }

        @CommandHandler
        public MyAggregate(CreateMyAggregateCommand command) {
            apply(new MyAggregateCreatedEvent(command.getId()));
        }

        @CommandHandlerInterceptor
        public void interceptAll(Object command) {
            apply(new AnyCommandInterceptedEvent(command.getClass().getName()));
        }

        @CommandHandlerInterceptor(commandNamePattern = ".*Nested.*")
        public void interceptAllMatchingPattern(Object command, InterceptorChain interceptorChain) throws Exception {
            apply(new AnyCommandMatchingPatternInterceptedEvent(command.getClass().getName()));
            interceptorChain.proceed();
        }

        @EventSourcingHandler
        public void on(MyAggregateCreatedEvent event) {
            this.id = event.getId();
            myNestedEntity = new MyNestedEntity(id);
        }

        @CommandHandlerInterceptor
        public void intercept(UpdateMyAggregateStateCommand command) {
            command.setState(command.getState() + " intercepted");
        }

        @CommandHandler
        public String handle(UpdateMyAggregateStateCommand command) {
            apply(new MyAggregateStateUpdatedEvent(command.getId(), command.getState()));
            return "aggregateUpdateResult";
        }

        @EventSourcingHandler
        public void on(MyAggregateStateUpdatedEvent event) {
            this.state = event.getState();
        }

        @CommandHandlerInterceptor
        public void intercept(ClearMyAggregateStateCommand command, InterceptorChain interceptorChain)
                throws Exception {
            if (command.isProceed()) {
                interceptorChain.proceed();
            } else {
                apply(new MyAggregateStateNotClearedEvent(command.getId()));
            }
        }

        @CommandHandler
        public void handle(ClearMyAggregateStateCommand command) {
            apply(new MyAggregateStateClearedEvent(command.getId()));
        }

        @EventSourcingHandler
        public void on(MyAggregateStateClearedEvent event) {
            this.state = "";
        }

        @EventSourcingHandler
        public void on(MyAggregateStateNotClearedEvent event) {
            // do nothing
        }

        @CommandHandlerInterceptor
        public void interceptChildCommand(MyNestedNestedCommand command) {
            command.setState(command.getState() + " parent intercepted");
        }

        @CommandHandlerInterceptor
        public void intercept(InterceptorThrowingCommand command) {
            throw new InterceptorException();
        }

        @CommandHandler
        public void handle(InterceptorThrowingCommand command) {
            apply(new InterceptorThrewEvent(command.getId()));
        }

        @EventSourcingHandler
        public void on(InterceptorThrewEvent event) {
            // do nothing
        }
    }

    @SuppressWarnings("unused")
    private static class MyNestedEntity {

        @EntityId
        private final String id;
        private String state;
        @AggregateMember
        private MyNestedNestedEntity myNestedNestedEntity;

        private MyNestedEntity(String id) {
            this.id = id;
            myNestedNestedEntity = new MyNestedNestedEntity(id);
        }

        @CommandHandlerInterceptor
        public void intercept(MyNestedCommand command) {
            command.setState(command.getState() + " intercepted");
        }

        @CommandHandler
        public void handle(MyNestedCommand command) {
            apply(new MyNestedEvent(command.getId(), command.getState()));
        }

        @EventSourcingHandler
        public void on(MyNestedEvent event) {
            this.state = event.getState();
        }
    }

    @SuppressWarnings("unused")
    private static class MyNestedNestedEntity {

        @EntityId
        private final String id;
        private String state;

        @CommandHandlerInterceptor
        public static void interceptAll(Object command, InterceptorChain chain) throws Exception {
            apply(new AnyCommandInterceptedEvent("StaticNestedNested" + command.getClass().getName()));
            chain.proceed();
        }

        private MyNestedNestedEntity(String id) {
            this.id = id;
        }

        @CommandHandlerInterceptor
        public void interceptAll(Object command) {
            apply(new AnyCommandInterceptedEvent("NestedNested" + command.getClass().getName()));
        }

        @CommandHandlerInterceptor
        public void intercept(MyNestedNestedCommand command) {
            command.setState(command.getState() + " intercepted");
        }

        @CommandHandler
        public void handle(MyNestedNestedCommand command) {
            apply(new MyNestedNestedEvent(command.getId(), command.getState()));
        }

        @EventSourcingHandler
        public void on(MyNestedNestedEvent event) {
            this.state = event.state;
        }
    }

    @SuppressWarnings("unused")
    private static class MyAggregateWithInterceptorReturningNonVoid {

        @CommandHandlerInterceptor
        public Object intercept() {
            return new Object();
        }
    }

    @SuppressWarnings("unused")
    private static class MyAggregateWithDeclaredInterceptorChainInterceptorReturningNonVoid {

        @CommandHandlerInterceptor
        public Object intercept(InterceptorChain chain) {
            return new Object();
        }
    }

    private static class InterceptorException extends RuntimeException {

    }
}


text:
package utils.helpers

import play.api.Logger
import scala.concurrent.duration.DurationInt
import uk.gov.dvla.vehicles.presentation.{common => VPC}
import VPC.ConfigProperties.booleanProp
import VPC.ConfigProperties.getOptionalProperty
import VPC.ConfigProperties.getProperty
import VPC.ConfigProperties.getStringListProperty
import VPC.ConfigProperties.getIntListProperty
import VPC.ConfigProperties.intProp
import VPC.ConfigProperties.longProp
import VPC.ConfigProperties.stringProp
import VPC.services.SEND.EmailConfiguration
import VPC.webserviceclients.emailservice.From

final class ConfigImpl extends Config {

  val assetsUrl: Option[String] = getOptionalProperty[String]("assets.url")

  // Payment Service
  override val purchaseAmountInPence: String = getProperty[String]("retention.purchaseAmountInPence")

  override val secureCookies = getOptionalProperty[Boolean]("secureCookies").getOrElse(ConfigImpl.DefaultSecureCookies)

  override val encryptCookies = getOptionalProperty[Boolean]("encryptCookies").getOrElse(ConfigImpl.DefaultEncryptCookies)

  override val applicationCode: String = getProperty[String]("webHeader.applicationCode")
  override val channelCode: String = getProperty[String]("webHeader.channelCode")
  override val contactId: Long = getProperty[Long]("webHeader.contactId")
  override val orgBusinessUnit: String = getProperty[String]("webHeader.orgBusinessUnit")
  override val vssServiceTypeCode: String = getProperty[String]("webHeader.vssServiceTypeCode")
  override val dmsServiceTypeCode: String = getProperty[String]("webHeader.dmsServiceTypeCode")

  override val vrmRetentionEligibilityMicroServiceUrlBase: String = getProperty[String]("vrmRetentionEligibilityMicroServiceUrlBase")

  override val vrmRetentionRetainMicroServiceUrlBase: String = getProperty[String]("vrmRetentionRetainMicroServiceUrlBase")

  override val vehicleAndKeeperLookupMicroServiceBaseUrl: String = getProperty[String]("vehicleAndKeeperLookupMicroServiceUrlBase")

  override val vrmRetentionEligibilityMsRequestTimeout: Int =
    getOptionalProperty[Int]("vrmRetentionEligibility.requesttimeout")
      .getOrElse(ConfigImpl.DefaultRequestTimeoutSecs.seconds.toMillis.toInt)

  override val vrmRetentionRetainMsRequestTimeout: Int =
    getOptionalProperty[Int]("vrmRetentionRetain.requesttimeout")
      .getOrElse(ConfigImpl.DefaultRequestTimeoutSecs.seconds.toMillis.toInt)

  override val paymentSolveMicroServiceUrlBase: String = getProperty[String]("paymentSolveMicroServiceUrlBase")

  override val paymentSolveMsRequestTimeout: Int =
    getOptionalProperty[Int]("paymentSolve.ms.requesttimeout")
      .getOrElse(ConfigImpl.DefaultSolveRequestTimeoutSecs.seconds.toMillis.toInt)

  override val vehicleAndKeeperLookupRequestTimeout: Int =
    getOptionalProperty[Int]("vehicleAndKeeperLookup.requesttimeout")
      .getOrElse(ConfigImpl.DefaultRequestTimeoutSecs.seconds.toMillis.toInt)

  override val isPrototypeBannerVisible: Boolean = getOptionalProperty[Boolean]("prototype.disclaimer")
    .getOrElse(ConfigImpl.DefaultPrototypeBannerEnabled)

  override val googleAnalyticsTrackingId: Option[String] = getOptionalProperty[String]("googleAnalytics.id.retention")

  override val emailWhitelist: Option[List[String]] = getStringListProperty("email.whitelist")

  override val emailSenderAddress: String = getOptionalProperty[String]("email.senderAddress")
    .getOrElse(ConfigImpl.DefaultSenderEmail)

  override val cookieMaxAge = getOptionalProperty[Int]("application.cookieMaxAge")
    .getOrElse(ConfigImpl.DefaultCookieMaxAgeMins.minutes.toSeconds.toInt)

  override val storeBusinessDetailsMaxAge =
    getOptionalProperty[Int]("storeBusinessDetails.cookieMaxAge")
      .getOrElse(ConfigImpl.DefaultBusinessDetailsCookieMaxAgeDays.days.toSeconds.toInt)

  override val auditMicroServiceUrlBase: String = getProperty[String]("auditMicroServiceUrlBase")

  override val auditMsRequestTimeout: Int =
    getOptionalProperty[Int]("audit.requesttimeout")
      .getOrElse(ConfigImpl.DefaultAuditRequestTimeoutSecs.seconds.toMillis.toInt)

  // Email microservice
  override val emailServiceMicroServiceUrlBase: String = getProperty[String]("emailServiceMicroServiceUrlBase")
  override val emailServiceMsRequestTimeout: Int =
    getOptionalProperty[Int]("emailService.ms.requesttimeout")
      .getOrElse(ConfigImpl.DefaultRequestTimeoutSecs.seconds.toMillis.toInt)
  override val emailConfiguration: EmailConfiguration = EmailConfiguration(
    From(getProperty[String]("email.senderAddress"), ConfigImpl.EmailFromName),
    From(getProperty[String]("email.feedbackAddress"), ConfigImpl.EmailFeedbackFromName),
    getStringListProperty("email.whitelist")
  )

  override val openingTimeMinOfDay: Int = getProperty[Int]("openingTimeMinOfDay")
  override val closingTimeMinOfDay: Int = getProperty[Int]("closingTimeMinOfDay")
  override val closingWarnPeriodMins: Int = getOptionalProperty[Int]("closingWarnPeriodMins")
    .getOrElse(ConfigImpl.DefaultClosingWarnPeriodMins)
  override val closedDays: List[Int] = {
    getIntListProperty("closedDays").getOrElse(List())
  }

  // TODO make property survey.url mandatory
  override val surveyUrl: Option[String] = getOptionalProperty[String]("survey.url")

  override val liveAgentEnvironmentId: Option[String] = {
    val liveAgentId: Option[String] = getOptionalProperty[String]("webchat.liveAgent.environmentId")
    liveAgentId.fold(Logger.info("Webchat functionality is not enabled"))
      {id => Logger.info("Webchat functionality is enabled")}
    liveAgentId
  }

  override val liveAgentButtonId: String = getProperty[String]("webchat.liveAgent.buttonId")
  override val liveAgentOrgId: String = getProperty[String]("webchat.liveAgent.orgId")
  override val liveAgentUrl: String = getProperty[String]("webchat.liveAgent.url")
  override val liveAgentjsUrl: String = getProperty[String]("webchat.liveAgent.jsUrl")

  override val failureCodeBlacklist: Option[List[String]] = getStringListProperty("webchat.failureCodes.blacklist")
}

object ConfigImpl {
  final val NotFound = "NOT FOUND"

  final val EmailFromName = "DO-NOT-REPLY"
  final val EmailFeedbackFromName = "Feedback"

  //defaults
  final val DefaultSenderEmail = ""
  final val DefaultSecureCookies = true
  final val DefaultPrototypeBannerEnabled = true
  final val DefaultEncryptCookies = true
  final val DefaultBusinessDetailsCookieMaxAgeDays = 7
  final val DefaultClosingWarnPeriodMins = 15
  final val DefaultCookieMaxAgeMins = 30
  final val DefaultAuditRequestTimeoutSecs = 30
  final val DefaultRequestTimeoutSecs = 30
  final val DefaultSolveRequestTimeoutSecs = 5
}


text:
//  Copyright 2017 Twitter. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

package com.twitter.heron.streamlet.impl.operators;

import java.util.Map;

import com.twitter.heron.api.bolt.OutputCollector;
import com.twitter.heron.api.topology.TopologyContext;
import com.twitter.heron.api.tuple.Tuple;
import com.twitter.heron.api.tuple.Values;

/**
 * UnionOperator is the class that implements the union functionality.
 * Its a very simple bolt that re-emits every tuple that it sees.
 */
public class UnionOperator<I> extends StreamletOperator {
  private static final long serialVersionUID = -7326832064961413315L;
  private OutputCollector collector;

  public UnionOperator() {
  }

  @SuppressWarnings("rawtypes")
  @Override
  public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) {
    collector = outputCollector;
  }

  @SuppressWarnings("unchecked")
  @Override
  public void execute(Tuple tuple) {
    I obj = (I) tuple.getValue(0);
    collector.emit(new Values(obj));
    collector.ack(tuple);
  }
}


text:
@interface NSMutableArray (Sorted)

- (void) insertSorted:(id)newObject;

@end


text:
from collections import OrderedDict
import os
import re
from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union

from google.api_core import client_options as client_options_lib
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials  # type: ignore
from google.auth.exceptions import MutualTLSChannelError  # type: ignore
from google.auth.transport import mtls  # type: ignore
from google.auth.transport.grpc import SslCredentials  # type: ignore
from google.oauth2 import service_account  # type: ignore
import pkg_resources

try:
    OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
except AttributeError:  # pragma: NO COVER
    OptionalRetry = Union[retries.Retry, object]  # type: ignore

from google.iam.v1 import iam_policy_pb2  # type: ignore
from google.iam.v1 import policy_pb2  # type: ignore
from google.protobuf import timestamp_pb2  # type: ignore

from google.cloud.resourcemanager_v3.services.organizations import pagers
from google.cloud.resourcemanager_v3.types import organizations

from .transports.base import DEFAULT_CLIENT_INFO, OrganizationsTransport
from .transports.grpc import OrganizationsGrpcTransport
from .transports.grpc_asyncio import OrganizationsGrpcAsyncIOTransport

class OrganizationsClientMeta(type):
    """Metaclass for the Organizations client.

    This provides class-level methods for building and retrieving
    support objects (e.g. transport) without polluting the client instance
    objects.
    """

    _transport_registry = OrderedDict()  # type: Dict[str, Type[OrganizationsTransport]]
    _transport_registry["grpc"] = OrganizationsGrpcTransport
    _transport_registry["grpc_asyncio"] = OrganizationsGrpcAsyncIOTransport

    def get_transport_class(
        cls,
        label: str = None,
    ) -> Type[OrganizationsTransport]:
        """Returns an appropriate transport class.

        Args:
            label: The name of the desired transport. If none is
                provided, then the first transport in the registry is used.

        Returns:
            The transport class to use.
        """
        # If a specific transport is requested, return that one.
        if label:
            return cls._transport_registry[label]

        # No transport is requested; return the default (that is, the first one
        # in the dictionary).
        return next(iter(cls._transport_registry.values()))

class OrganizationsClient(metaclass=OrganizationsClientMeta):
    """Allows users to manage their organization resources."""

    @staticmethod
    def _get_default_mtls_endpoint(api_endpoint):
        """Converts api endpoint to mTLS endpoint.

        Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
        "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
        Args:
            api_endpoint (Optional[str]): the api endpoint to convert.
        Returns:
            str: converted mTLS api endpoint.
        """
        if not api_endpoint:
            return api_endpoint

        mtls_endpoint_re = re.compile(
            r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
        )

        m = mtls_endpoint_re.match(api_endpoint)
        name, mtls, sandbox, googledomain = m.groups()
        if mtls or not googledomain:
            return api_endpoint

        if sandbox:
            return api_endpoint.replace(
                "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
            )

        return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")

    DEFAULT_ENDPOINT = "cloudresourcemanager.googleapis.com"
    DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__(  # type: ignore
        DEFAULT_ENDPOINT
    )

    @classmethod
    def from_service_account_info(cls, info: dict, *args, **kwargs):
        """Creates an instance of this client using the provided credentials
            info.

        Args:
            info (dict): The service account private key info.
            args: Additional arguments to pass to the constructor.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            OrganizationsClient: The constructed client.
        """
        credentials = service_account.Credentials.from_service_account_info(info)
        kwargs["credentials"] = credentials
        return cls(*args, **kwargs)

    @classmethod
    def from_service_account_file(cls, filename: str, *args, **kwargs):
        """Creates an instance of this client using the provided credentials
            file.

        Args:
            filename (str): The path to the service account private key json
                file.
            args: Additional arguments to pass to the constructor.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            OrganizationsClient: The constructed client.
        """
        credentials = service_account.Credentials.from_service_account_file(filename)
        kwargs["credentials"] = credentials
        return cls(*args, **kwargs)

    from_service_account_json = from_service_account_file

    @property
    def transport(self) -> OrganizationsTransport:
        """Returns the transport used by the client instance.

        Returns:
            OrganizationsTransport: The transport used by the client
                instance.
        """
        return self._transport

    @staticmethod
    def organization_path(
        organization: str,
    ) -> str:
        """Returns a fully-qualified organization string."""
        return "organizations/{organization}".format(
            organization=organization,
        )

    @staticmethod
    def parse_organization_path(path: str) -> Dict[str, str]:
        """Parses a organization path into its component segments."""
        m = re.match(r"^organizations/(?P<organization>.+?)$", path)
        return m.groupdict() if m else {}

    @staticmethod
    def common_billing_account_path(
        billing_account: str,
    ) -> str:
        """Returns a fully-qualified billing_account string."""
        return "billingAccounts/{billing_account}".format(
            billing_account=billing_account,
        )

    @staticmethod
    def parse_common_billing_account_path(path: str) -> Dict[str, str]:
        """Parse a billing_account path into its component segments."""
        m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
        return m.groupdict() if m else {}

    @staticmethod
    def common_folder_path(
        folder: str,
    ) -> str:
        """Returns a fully-qualified folder string."""
        return "folders/{folder}".format(
            folder=folder,
        )

    @staticmethod
    def parse_common_folder_path(path: str) -> Dict[str, str]:
        """Parse a folder path into its component segments."""
        m = re.match(r"^folders/(?P<folder>.+?)$", path)
        return m.groupdict() if m else {}

    @staticmethod
    def common_organization_path(
        organization: str,
    ) -> str:
        """Returns a fully-qualified organization string."""
        return "organizations/{organization}".format(
            organization=organization,
        )

    @staticmethod
    def parse_common_organization_path(path: str) -> Dict[str, str]:
        """Parse a organization path into its component segments."""
        m = re.match(r"^organizations/(?P<organization>.+?)$", path)
        return m.groupdict() if m else {}

    @staticmethod
    def common_project_path(
        project: str,
    ) -> str:
        """Returns a fully-qualified project string."""
        return "projects/{project}".format(
            project=project,
        )

    @staticmethod
    def parse_common_project_path(path: str) -> Dict[str, str]:
        """Parse a project path into its component segments."""
        m = re.match(r"^projects/(?P<project>.+?)$", path)
        return m.groupdict() if m else {}

    @staticmethod
    def common_location_path(
        project: str,
        location: str,
    ) -> str:
        """Returns a fully-qualified location string."""
        return "projects/{project}/locations/{location}".format(
            project=project,
            location=location,
        )

    @staticmethod
    def parse_common_location_path(path: str) -> Dict[str, str]:
        """Parse a location path into its component segments."""
        m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
        return m.groupdict() if m else {}

    @classmethod
    def get_mtls_endpoint_and_cert_source(
        cls, client_options: Optional[client_options_lib.ClientOptions] = None
    ):
        """Return the API endpoint and client cert source for mutual TLS.

        The client cert source is determined in the following order:
        (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
        client cert source is None.
        (2) if `client_options.client_cert_source` is provided, use the provided one; if the
        default client cert source exists, use the default one; otherwise the client cert
        source is None.

        The API endpoint is determined in the following order:
        (1) if `client_options.api_endpoint` if provided, use the provided one.
        (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
        default mTLS endpoint; if the environment variabel is "never", use the default API
        endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
        use the default API endpoint.

        More details can be found at https://google.aip.dev/auth/4114.

        Args:
            client_options (google.api_core.client_options.ClientOptions): Custom options for the
                client. Only the `api_endpoint` and `client_cert_source` properties may be used
                in this method.

        Returns:
            Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
                client cert source to use.

        Raises:
            google.auth.exceptions.MutualTLSChannelError: If any errors happen.
        """
        if client_options is None:
            client_options = client_options_lib.ClientOptions()
        use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")
        use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
        if use_client_cert not in ("true", "false"):
            raise ValueError(
                "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
            )
        if use_mtls_endpoint not in ("auto", "never", "always"):
            raise MutualTLSChannelError(
                "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
            )

        # Figure out the client cert source to use.
        client_cert_source = None
        if use_client_cert == "true":
            if client_options.client_cert_source:
                client_cert_source = client_options.client_cert_source
            elif mtls.has_default_client_cert_source():
                client_cert_source = mtls.default_client_cert_source()

        # Figure out which api endpoint to use.
        if client_options.api_endpoint is not None:
            api_endpoint = client_options.api_endpoint
        elif use_mtls_endpoint == "always" or (
            use_mtls_endpoint == "auto" and client_cert_source
        ):
            api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
        else:
            api_endpoint = cls.DEFAULT_ENDPOINT

        return api_endpoint, client_cert_source

    def __init__(
        self,
        *,
        credentials: Optional[ga_credentials.Credentials] = None,
        transport: Union[str, OrganizationsTransport, None] = None,
        client_options: Optional[client_options_lib.ClientOptions] = None,
        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
    ) -> None:
        """Instantiates the organizations client.

        Args:
            credentials (Optional[google.auth.credentials.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify the application to the service; if none
                are specified, the client will attempt to ascertain the
                credentials from the environment.
            transport (Union[str, OrganizationsTransport]): The
                transport to use. If set to None, a transport is chosen
                automatically.
            client_options (google.api_core.client_options.ClientOptions): Custom options for the
                client. It won't take effect if a ``transport`` instance is provided.
                (1) The ``api_endpoint`` property can be used to override the
                default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
                environment variable can also be used to override the endpoint:
                "always" (always use the default mTLS endpoint), "never" (always
                use the default regular endpoint) and "auto" (auto switch to the
                default mTLS endpoint if client certificate is present, this is
                the default value). However, the ``api_endpoint`` property takes
                precedence if provided.
                (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
                is "true", then the ``client_cert_source`` property can be used
                to provide client certificate for mutual TLS transport. If
                not provided, the default SSL client certificate will be used if
                present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
                set, no client certificate will be used.
            client_info (google.api_core.gapic_v1.client_info.ClientInfo):
                The client info used to send a user-agent string along with
                API requests. If ``None``, then default info will be used.
                Generally, you only need to set this if you're developing
                your own client library.

        Raises:
            google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
                creation failed for any reason.
        """
        if isinstance(client_options, dict):
            client_options = client_options_lib.from_dict(client_options)
        if client_options is None:
            client_options = client_options_lib.ClientOptions()

        api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(
            client_options
        )

        api_key_value = getattr(client_options, "api_key", None)
        if api_key_value and credentials:
            raise ValueError(
                "client_options.api_key and credentials are mutually exclusive"
            )

        # Save or instantiate the transport.
        # Ordinarily, we provide the transport, but allowing a custom transport
        # instance provides an extensibility point for unusual situations.
        if isinstance(transport, OrganizationsTransport):
            # transport is a OrganizationsTransport instance.
            if credentials or client_options.credentials_file or api_key_value:
                raise ValueError(
                    "When providing a transport instance, "
                    "provide its credentials directly."
                )
            if client_options.scopes:
                raise ValueError(
                    "When providing a transport instance, provide its scopes "
                    "directly."
                )
            self._transport = transport
        else:
            import google.auth._default  # type: ignore

            if api_key_value and hasattr(
                google.auth._default, "get_api_key_credentials"
            ):
                credentials = google.auth._default.get_api_key_credentials(
                    api_key_value
                )

            Transport = type(self).get_transport_class(transport)
            self._transport = Transport(
                credentials=credentials,
                credentials_file=client_options.credentials_file,
                host=api_endpoint,
                scopes=client_options.scopes,
                client_cert_source_for_mtls=client_cert_source_func,
                quota_project_id=client_options.quota_project_id,
                client_info=client_info,
                always_use_jwt_access=True,
                api_audience=client_options.api_audience,
            )

    def get_organization(
        self,
        request: Union[organizations.GetOrganizationRequest, dict] = None,
        *,
        name: str = None,
        retry: OptionalRetry = gapic_v1.method.DEFAULT,
        timeout: float = None,
        metadata: Sequence[Tuple[str, str]] = (),
    ) -> organizations.Organization:
        r"""Fetches an organization resource identified by the
        specified resource name.

        .. code-block:: python

            # This snippet has been automatically generated and should be regarded as a
            # code template only.
            # It will require modifications to work:
            # - It may require correct/in-range values for request initialization.
            # - It may require specifying regional endpoints when creating the service
            #   client as shown in:
            #   https://googleapis.dev/python/google-api-core/latest/client_options.html
            from google.cloud import resourcemanager_v3

            def sample_get_organization():
                # Create a client
                client = resourcemanager_v3.OrganizationsClient()

                # Initialize request argument(s)
                request = resourcemanager_v3.GetOrganizationRequest(
                    name="name_value",
                )

                # Make the request
                response = client.get_organization(request=request)

                # Handle the response
                print(response)

        Args:
            request (Union[google.cloud.resourcemanager_v3.types.GetOrganizationRequest, dict]):
                The request object. The request sent to the
                `GetOrganization` method. The `name` field is required.
                `organization_id` is no longer accepted.
            name (str):
                Required. The resource name of the Organization to
                fetch. This is the organization's relative path in the
                API, formatted as "organizations/[organizationId]". For
                example, "organizations/1234".

                This corresponds to the ``name`` field
                on the ``request`` instance; if ``request`` is provided, this
                should not be set.
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.

        Returns:
            google.cloud.resourcemanager_v3.types.Organization:
                The root node in the resource
                hierarchy to which a particular entity's
                (a company, for example) resources
                belong.

        """
        # Create or coerce a protobuf request object.
        # Quick check: If we got a request object, we should *not* have
        # gotten any keyword arguments that map to the request.
        has_flattened_params = any([name])
        if request is not None and has_flattened_params:
            raise ValueError(
                "If the `request` argument is set, then none of "
                "the individual field arguments should be set."
            )

        # Minor optimization to avoid making a copy if the user passes
        # in a organizations.GetOrganizationRequest.
        # There's no risk of modifying the input as we've already verified
        # there are no flattened fields.
        if not isinstance(request, organizations.GetOrganizationRequest):
            request = organizations.GetOrganizationRequest(request)
            # If we have keyword arguments corresponding to fields on the
            # request, apply these.
            if name is not None:
                request.name = name

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = self._transport._wrapped_methods[self._transport.get_organization]

        # Certain fields should be provided within the metadata header;
        # add these here.
        metadata = tuple(metadata) + (
            gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
        )

        # Send the request.
        response = rpc(
            request,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

        # Done; return the response.
        return response

    def search_organizations(
        self,
        request: Union[organizations.SearchOrganizationsRequest, dict] = None,
        *,
        query: str = None,
        retry: OptionalRetry = gapic_v1.method.DEFAULT,
        timeout: float = None,
        metadata: Sequence[Tuple[str, str]] = (),
    ) -> pagers.SearchOrganizationsPager:
        r"""Searches organization resources that are visible to the user and
        satisfy the specified filter. This method returns organizations
        in an unspecified order. New organizations do not necessarily
        appear at the end of the results, and may take a small amount of
        time to appear.

        Search will only return organizations on which the user has the
        permission ``resourcemanager.organizations.get``

        .. code-block:: python

            # This snippet has been automatically generated and should be regarded as a
            # code template only.
            # It will require modifications to work:
            # - It may require correct/in-range values for request initialization.
            # - It may require specifying regional endpoints when creating the service
            #   client as shown in:
            #   https://googleapis.dev/python/google-api-core/latest/client_options.html
            from google.cloud import resourcemanager_v3

            def sample_search_organizations():
                # Create a client
                client = resourcemanager_v3.OrganizationsClient()

                # Initialize request argument(s)
                request = resourcemanager_v3.SearchOrganizationsRequest(
                )

                # Make the request
                page_result = client.search_organizations(request=request)

                # Handle the response
                for response in page_result:
                    print(response)

        Args:
            request (Union[google.cloud.resourcemanager_v3.types.SearchOrganizationsRequest, dict]):
                The request object. The request sent to the
                `SearchOrganizations` method.
            query (str):
                Optional. An optional query string used to filter the
                Organizations to return in the response. Query rules are
                case-insensitive.

                ::

                   | Field            | Description                                |
                   |------------------|--------------------------------------------|
                   | directoryCustomerId, owner.directoryCustomerId | Filters by directory
                   customer id. |
                   | domain           | Filters by domain.                         |

                Organizations may be queried by ``directoryCustomerId``
                or by ``domain``, where the domain is a G Suite domain,
                for example:

                -  Query ``directorycustomerid:123456789`` returns
                   Organization resources with
                   ``owner.directory_customer_id`` equal to
                   ``123456789``.
                -  Query ``domain:google.com`` returns Organization
                   resources corresponding to the domain ``google.com``.

                This corresponds to the ``query`` field
                on the ``request`` instance; if ``request`` is provided, this
                should not be set.
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.

        Returns:
            google.cloud.resourcemanager_v3.services.organizations.pagers.SearchOrganizationsPager:
                The response returned from the SearchOrganizations
                method.

                Iterating over this object will yield results and
                resolve additional pages automatically.

        """
        # Create or coerce a protobuf request object.
        # Quick check: If we got a request object, we should *not* have
        # gotten any keyword arguments that map to the request.
        has_flattened_params = any([query])
        if request is not None and has_flattened_params:
            raise ValueError(
                "If the `request` argument is set, then none of "
                "the individual field arguments should be set."
            )

        # Minor optimization to avoid making a copy if the user passes
        # in a organizations.SearchOrganizationsRequest.
        # There's no risk of modifying the input as we've already verified
        # there are no flattened fields.
        if not isinstance(request, organizations.SearchOrganizationsRequest):
            request = organizations.SearchOrganizationsRequest(request)
            # If we have keyword arguments corresponding to fields on the
            # request, apply these.
            if query is not None:
                request.query = query

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = self._transport._wrapped_methods[self._transport.search_organizations]

        # Send the request.
        response = rpc(
            request,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

        # This method is paged; wrap the response in a pager, which provides
        # an `__iter__` convenience method.
        response = pagers.SearchOrganizationsPager(
            method=rpc,
            request=request,
            response=response,
            metadata=metadata,
        )

        # Done; return the response.
        return response

    def get_iam_policy(
        self,
        request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None,
        *,
        resource: str = None,
        retry: OptionalRetry = gapic_v1.method.DEFAULT,
        timeout: float = None,
        metadata: Sequence[Tuple[str, str]] = (),
    ) -> policy_pb2.Policy:
        r"""Gets the access control policy for an organization resource. The
        policy may be empty if no such policy or resource exists. The
        ``resource`` field should be the organization's resource name,
        for example: "organizations/123".

        Authorization requires the IAM permission
        ``resourcemanager.organizations.getIamPolicy`` on the specified
        organization.

        .. code-block:: python

            # This snippet has been automatically generated and should be regarded as a
            # code template only.
            # It will require modifications to work:
            # - It may require correct/in-range values for request initialization.
            # - It may require specifying regional endpoints when creating the service
            #   client as shown in:
            #   https://googleapis.dev/python/google-api-core/latest/client_options.html
            from google.cloud import resourcemanager_v3
            from google.iam.v1 import iam_policy_pb2  # type: ignore

            def sample_get_iam_policy():
                # Create a client
                client = resourcemanager_v3.OrganizationsClient()

                # Initialize request argument(s)
                request = iam_policy_pb2.GetIamPolicyRequest(
                    resource="resource_value",
                )

                # Make the request
                response = client.get_iam_policy(request=request)

                # Handle the response
                print(response)

        Args:
            request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]):
                The request object. Request message for `GetIamPolicy`
                method.
            resource (str):
                REQUIRED: The resource for which the
                policy is being requested. See the
                operation documentation for the
                appropriate value for this field.

                This corresponds to the ``resource`` field
                on the ``request`` instance; if ``request`` is provided, this
                should not be set.
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.

        Returns:
            google.iam.v1.policy_pb2.Policy:
                An Identity and Access Management (IAM) policy, which specifies access
                   controls for Google Cloud resources.

                   A Policy is a collection of bindings. A binding binds
                   one or more members, or principals, to a single role.
                   Principals can be user accounts, service accounts,
                   Google groups, and domains (such as G Suite). A role
                   is a named list of permissions; each role can be an
                   IAM predefined role or a user-created custom role.

                   For some types of Google Cloud resources, a binding
                   can also specify a condition, which is a logical
                   expression that allows access to a resource only if
                   the expression evaluates to true. A condition can add
                   constraints based on attributes of the request, the
                   resource, or both. To learn which resources support
                   conditions in their IAM policies, see the [IAM
                   documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies).

                   **JSON example:**

                      {
                         "bindings": [
                            {
                               "role":
                               "roles/resourcemanager.organizationAdmin",
                               "members": [ "user:mike@example.com",
                               "group:admins@example.com",
                               "domain:google.com",
                               "serviceAccount:my-project-id@appspot.gserviceaccount.com"
                               ]

                            }, { "role":
                            "roles/resourcemanager.organizationViewer",
                            "members": [ "user:eve@example.com" ],
                            "condition": { "title": "expirable access",
                            "description": "Does not grant access after
                            Sep 2020", "expression": "request.time <
                            timestamp('2020-10-01T00:00:00.000Z')", } }

                         ], "etag": "BwWWja0YfJA=", "version": 3

                      }

                   **YAML example:**

                      bindings: - members: - user:\ mike@example.com -
                      group:\ admins@example.com - domain:google.com -
                      serviceAccount:\ my-project-id@appspot.gserviceaccount.com
                      role: roles/resourcemanager.organizationAdmin -
                      members: - user:\ eve@example.com role:
                      roles/resourcemanager.organizationViewer
                      condition: title: expirable access description:
                      Does not grant access after Sep 2020 expression:
                      request.time <
                      timestamp('2020-10-01T00:00:00.000Z') etag:
                      BwWWja0YfJA= version: 3

                   For a description of IAM and its features, see the
                   [IAM
                   documentation](\ https://cloud.google.com/iam/docs/).

        """
        # Create or coerce a protobuf request object.
        # Quick check: If we got a request object, we should *not* have
        # gotten any keyword arguments that map to the request.
        has_flattened_params = any([resource])
        if request is not None and has_flattened_params:
            raise ValueError(
                "If the `request` argument is set, then none of "
                "the individual field arguments should be set."
            )

        if isinstance(request, dict):
            # The request isn't a proto-plus wrapped type,
            # so it must be constructed via keyword expansion.
            request = iam_policy_pb2.GetIamPolicyRequest(**request)
        elif not request:
            # Null request, just make one.
            request = iam_policy_pb2.GetIamPolicyRequest()
            if resource is not None:
                request.resource = resource

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = self._transport._wrapped_methods[self._transport.get_iam_policy]

        # Certain fields should be provided within the metadata header;
        # add these here.
        metadata = tuple(metadata) + (
            gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
        )

        # Send the request.
        response = rpc(
            request,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

        # Done; return the response.
        return response

    def set_iam_policy(
        self,
        request: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None,
        *,
        resource: str = None,
        retry: OptionalRetry = gapic_v1.method.DEFAULT,
        timeout: float = None,
        metadata: Sequence[Tuple[str, str]] = (),
    ) -> policy_pb2.Policy:
        r"""Sets the access control policy on an organization resource.
        Replaces any existing policy. The ``resource`` field should be
        the organization's resource name, for example:
        "organizations/123".

        Authorization requires the IAM permission
        ``resourcemanager.organizations.setIamPolicy`` on the specified
        organization.

        .. code-block:: python

            # This snippet has been automatically generated and should be regarded as a
            # code template only.
            # It will require modifications to work:
            # - It may require correct/in-range values for request initialization.
            # - It may require specifying regional endpoints when creating the service
            #   client as shown in:
            #   https://googleapis.dev/python/google-api-core/latest/client_options.html
            from google.cloud import resourcemanager_v3
            from google.iam.v1 import iam_policy_pb2  # type: ignore

            def sample_set_iam_policy():
                # Create a client
                client = resourcemanager_v3.OrganizationsClient()

                # Initialize request argument(s)
                request = iam_policy_pb2.SetIamPolicyRequest(
                    resource="resource_value",
                )

                # Make the request
                response = client.set_iam_policy(request=request)

                # Handle the response
                print(response)

        Args:
            request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]):
                The request object. Request message for `SetIamPolicy`
                method.
            resource (str):
                REQUIRED: The resource for which the
                policy is being specified. See the
                operation documentation for the
                appropriate value for this field.

                This corresponds to the ``resource`` field
                on the ``request`` instance; if ``request`` is provided, this
                should not be set.
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.

        Returns:
            google.iam.v1.policy_pb2.Policy:
                An Identity and Access Management (IAM) policy, which specifies access
                   controls for Google Cloud resources.

                   A Policy is a collection of bindings. A binding binds
                   one or more members, or principals, to a single role.
                   Principals can be user accounts, service accounts,
                   Google groups, and domains (such as G Suite). A role
                   is a named list of permissions; each role can be an
                   IAM predefined role or a user-created custom role.

                   For some types of Google Cloud resources, a binding
                   can also specify a condition, which is a logical
                   expression that allows access to a resource only if
                   the expression evaluates to true. A condition can add
                   constraints based on attributes of the request, the
                   resource, or both. To learn which resources support
                   conditions in their IAM policies, see the [IAM
                   documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies).

                   **JSON example:**

                      {
                         "bindings": [
                            {
                               "role":
                               "roles/resourcemanager.organizationAdmin",
                               "members": [ "user:mike@example.com",
                               "group:admins@example.com",
                               "domain:google.com",
                               "serviceAccount:my-project-id@appspot.gserviceaccount.com"
                               ]

                            }, { "role":
                            "roles/resourcemanager.organizationViewer",
                            "members": [ "user:eve@example.com" ],
                            "condition": { "title": "expirable access",
                            "description": "Does not grant access after
                            Sep 2020", "expression": "request.time <
                            timestamp('2020-10-01T00:00:00.000Z')", } }

                         ], "etag": "BwWWja0YfJA=", "version": 3

                      }

                   **YAML example:**

                      bindings: - members: - user:\ mike@example.com -
                      group:\ admins@example.com - domain:google.com -
                      serviceAccount:\ my-project-id@appspot.gserviceaccount.com
                      role: roles/resourcemanager.organizationAdmin -
                      members: - user:\ eve@example.com role:
                      roles/resourcemanager.organizationViewer
                      condition: title: expirable access description:
                      Does not grant access after Sep 2020 expression:
                      request.time <
                      timestamp('2020-10-01T00:00:00.000Z') etag:
                      BwWWja0YfJA= version: 3

                   For a description of IAM and its features, see the
                   [IAM
                   documentation](\ https://cloud.google.com/iam/docs/).

        """
        # Create or coerce a protobuf request object.
        # Quick check: If we got a request object, we should *not* have
        # gotten any keyword arguments that map to the request.
        has_flattened_params = any([resource])
        if request is not None and has_flattened_params:
            raise ValueError(
                "If the `request` argument is set, then none of "
                "the individual field arguments should be set."
            )

        if isinstance(request, dict):
            # The request isn't a proto-plus wrapped type,
            # so it must be constructed via keyword expansion.
            request = iam_policy_pb2.SetIamPolicyRequest(**request)
        elif not request:
            # Null request, just make one.
            request = iam_policy_pb2.SetIamPolicyRequest()
            if resource is not None:
                request.resource = resource

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = self._transport._wrapped_methods[self._transport.set_iam_policy]

        # Certain fields should be provided within the metadata header;
        # add these here.
        metadata = tuple(metadata) + (
            gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
        )

        # Send the request.
        response = rpc(
            request,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

        # Done; return the response.
        return response

    def test_iam_permissions(
        self,
        request: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None,
        *,
        resource: str = None,
        permissions: Sequence[str] = None,
        retry: OptionalRetry = gapic_v1.method.DEFAULT,
        timeout: float = None,
        metadata: Sequence[Tuple[str, str]] = (),
    ) -> iam_policy_pb2.TestIamPermissionsResponse:
        r"""Returns the permissions that a caller has on the specified
        organization. The ``resource`` field should be the
        organization's resource name, for example: "organizations/123".

        There are no permissions required for making this API call.

        .. code-block:: python

            # This snippet has been automatically generated and should be regarded as a
            # code template only.
            # It will require modifications to work:
            # - It may require correct/in-range values for request initialization.
            # - It may require specifying regional endpoints when creating the service
            #   client as shown in:
            #   https://googleapis.dev/python/google-api-core/latest/client_options.html
            from google.cloud import resourcemanager_v3
            from google.iam.v1 import iam_policy_pb2  # type: ignore

            def sample_test_iam_permissions():
                # Create a client
                client = resourcemanager_v3.OrganizationsClient()

                # Initialize request argument(s)
                request = iam_policy_pb2.TestIamPermissionsRequest(
                    resource="resource_value",
                    permissions=['permissions_value1', 'permissions_value2'],
                )

                # Make the request
                response = client.test_iam_permissions(request=request)

                # Handle the response
                print(response)

        Args:
            request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]):
                The request object. Request message for
                `TestIamPermissions` method.
            resource (str):
                REQUIRED: The resource for which the
                policy detail is being requested. See
                the operation documentation for the
                appropriate value for this field.

                This corresponds to the ``resource`` field
                on the ``request`` instance; if ``request`` is provided, this
                should not be set.
            permissions (Sequence[str]):
                The set of permissions to check for the ``resource``.
                Permissions with wildcards (such as '*' or 'storage.*')
                are not allowed. For more information see `IAM
                Overview <https://cloud.google.com/iam/docs/overview#permissions>`__.

                This corresponds to the ``permissions`` field
                on the ``request`` instance; if ``request`` is provided, this
                should not be set.
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.

        Returns:
            google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse:
                Response message for TestIamPermissions method.
        """
        # Create or coerce a protobuf request object.
        # Quick check: If we got a request object, we should *not* have
        # gotten any keyword arguments that map to the request.
        has_flattened_params = any([resource, permissions])
        if request is not None and has_flattened_params:
            raise ValueError(
                "If the `request` argument is set, then none of "
                "the individual field arguments should be set."
            )

        if isinstance(request, dict):
            # The request isn't a proto-plus wrapped type,
            # so it must be constructed via keyword expansion.
            request = iam_policy_pb2.TestIamPermissionsRequest(**request)
        elif not request:
            # Null request, just make one.
            request = iam_policy_pb2.TestIamPermissionsRequest()
            if resource is not None:
                request.resource = resource
            if permissions:
                request.permissions.extend(permissions)

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions]

        # Certain fields should be provided within the metadata header;
        # add these here.
        metadata = tuple(metadata) + (
            gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
        )

        # Send the request.
        response = rpc(
            request,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

        # Done; return the response.
        return response

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        """Releases underlying transport's resources.

        .. warning::
            ONLY use as a context manager if the transport is NOT shared
            with other clients! Exiting the with block will CLOSE the transport
            and may cause errors in other clients!
        """
        self.transport.close()

try:
    DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
        gapic_version=pkg_resources.get_distribution(
            "google-cloud-resourcemanager",
        ).version,
    )
except pkg_resources.DistributionNotFound:
    DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()

__all__ = ("OrganizationsClient",)


text:
package javax.mail;

/**
 * @version $Rev: 467553 $ $Date: 2006-10-24 23:01:51 -0500 (Tue, 24 Oct 2006) $
 */
public class IllegalWriteException extends MessagingException {
    public IllegalWriteException() {
        super();
    }

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


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebStore.Services;
using Magelia.WebStore.Services.Contract;
using Magelia.WebStore.Services.Contract.Data;
using System.Threading;
using WebStore.Models;
using Orchard.Localization;
using WebStore.Models.Order;

namespace WebStore.Controllers
{
    public class OrderController : Controller
    {
        private IWebStoreConfigurationService _webStoreConfigurationServices;
        private IBasketServices _basketServices;
        private IWebStoreProfileServices _webstoreProfileServices;
        private Localizer T;

        private const String BillingAddressSessionKey = "BillingAddress";
        private const String ShippingAddressSessionKey = "ShippingAddress";

        private AddressViewModel BillingAddress
        {
            get
            {
                return System.Web.HttpContext.Current.Session[BillingAddressSessionKey] as AddressViewModel;
            }
            set
            {
                System.Web.HttpContext.Current.Session[BillingAddressSessionKey] = value;
            }
        }

        private AddressViewModel ShippingAddress
        {
            get
            {
                return System.Web.HttpContext.Current.Session[ShippingAddressSessionKey] as AddressViewModel;
            }
            set
            {
                System.Web.HttpContext.Current.Session[ShippingAddressSessionKey] = value;
            }
        }

        public OrderController(IWebStoreConfigurationService webStoreConfigurationServices, IBasketServices basketServices, IWebStoreProfileServices webstoreProfileServices)
        {
            this.T = NullLocalizer.Instance;
            this._basketServices = basketServices;
            this._webstoreProfileServices = webstoreProfileServices;
            this._webStoreConfigurationServices = webStoreConfigurationServices;
        }

        private IEnumerable<Country> GetAvailableCountries()
        {
            WebStoreConfigurationPart configuration = this._webStoreConfigurationServices.GetConfiguration();
            WebStoreServices webStoreServices = new WebStoreServices(configuration);
            IEnumerable<Country> availableCountries = webStoreServices.CreateWebStoreChannel<IProfileService>().GetCountries(new GetCountriesParameters { MerchantId = configuration.MerchantId.Value, CultureName = Thread.CurrentThread.CurrentUICulture.Name }).OrderBy(c => c.DisplayName);
            webStoreServices.Dispose();
            return availableCountries;
        }

        [HttpGet]
        public ActionResult OrderPanel()
        {
            this.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Boolean hasBasket = this._basketServices.GetBasket() != default(Basket);
            if (this.User.Identity.IsAuthenticated)
            {
                return this.Address(false);
            }
            else
            {
                return this.View(new OrderPanelViewModel { HasBasket = hasBasket, UserName = this.User.Identity.Name, IsAuthenticated = this.User.Identity.IsAuthenticated, ReturnUrl = VirtualPathUtility.ToAbsolute("~/WebStore/Order") });
            }
        }

        [HttpGet]
        public ActionResult Address(Boolean express)
        {
            this.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            IEnumerable<Country> availableCountries = this.GetAvailableCountries();
            AddressViewModel viewModel = (this.BillingAddress == default(AddressViewModel)) ? new AddressViewModel { AddressType = AddressViewModel.AddressTypes.Billing } : this.BillingAddress;
            viewModel.AvailableCountries = availableCountries;
            return this.View("~/Modules/WebStore/Views/Order/Address.cshtml", viewModel);
        }

        [HttpPost]
        public ActionResult ShippingMethods(ShippingMethodsViewModel viewModel)
        {
            WebStoreServices webStoreServices = new WebStoreServices(this._webStoreConfigurationServices.GetConfiguration());
            if (this.ModelState.IsValid)
            {
                IOrderService orderServices = webStoreServices.CreateWebStoreChannel<IOrderService>();
                orderServices.UpdateBasket(
                    new UpdateBasketParameters
                    {
                        BasketId = this._basketServices.GetBasketId().Value,
                        UserId = this._webstoreProfileServices.GetUser(),
                        ShippingMethodId = Guid.Parse(viewModel.ShippingMethod),
                        CultureName = Thread.CurrentThread.CurrentUICulture.Name,
                        CountryId = this.BillingAddress.ShippingAddressIsDifferent ? this.ShippingAddress.Country : this.BillingAddress.Country
                    }
                );
                webStoreServices.Dispose();
                Basket b = this._basketServices.GetBasket();
                return this.View("~/Modules/WebStore/Views/Order/Pay.cshtml", new PayViewModel { Total = b.Total, ShippingCost = b.ShippingTotal, SubTotal = b.SubTotal, Currency = b.Currency });
            }
            else
            {
                viewModel.AvailableShippingMethods = webStoreServices.CreateWebStoreChannel<IOrderService>().GetShippingMethods(new GetShippingMethodsParameters { BasketId = this._basketServices.GetBasketId().Value, CultureName = Thread.CurrentThread.CurrentUICulture.Name, MerchantId = this._webStoreConfigurationServices.GetConfiguration().MerchantId.Value, UserId = this._webstoreProfileServices.GetUser() });
                webStoreServices.Dispose();
            }
            return this.View(viewModel);
        }

        [HttpPost]
        public ActionResult Address(AddressViewModel viewModel)
        {
            IEnumerable<Country> availableCountries = this.GetAvailableCountries();
            if (this.ModelState.IsValid)
            {
                if (viewModel.AddressType == AddressViewModel.AddressTypes.Billing)
                {
                    this.BillingAddress = viewModel;
                }
                else
                {
                    this.ShippingAddress = viewModel;
                }

                if (viewModel.ShippingAddressIsDifferent)
                {
                    this.ModelState.Clear();
                    viewModel = (this.ShippingAddress == default(AddressViewModel)) ? new AddressViewModel { AddressType = AddressViewModel.AddressTypes.Shipping } : this.ShippingAddress;
                }
                else
                {
                    using (WebStoreServices webStoreServices = new WebStoreServices(this._webStoreConfigurationServices.GetConfiguration()))
                    {
                        IProfileService profileService = webStoreServices.CreateWebStoreChannel<IProfileService>();
                        IOrderService orderServices = webStoreServices.CreateWebStoreChannel<IOrderService>();
                        Guid userId = this._webstoreProfileServices.GetUser();
                        UpdateBasketParameters updatBasketParameters = new UpdateBasketParameters { BasketId = this._basketServices.GetBasketId().Value, CountryId = this.BillingAddress.Country, UserId = userId, CultureName = Thread.CurrentThread.CurrentUICulture.Name };
                        this.BillingAddress.AddressId = profileService.SetAddress(this.BillingAddress.GetAddressParameters(userId)).AddressId;
                        updatBasketParameters.BillingAddressId = this.BillingAddress.AddressId;
                        if (this.BillingAddress.ShippingAddressIsDifferent)
                        {
                            this.ShippingAddress.AddressId = profileService.SetAddress(this.ShippingAddress.GetAddressParameters(userId)).AddressId;
                            updatBasketParameters.ShippingAddressId = this.ShippingAddress.AddressId;
                            updatBasketParameters.CountryId = this.ShippingAddress.Country;
                        }
                        orderServices.UpdateBasket(updatBasketParameters);
                    }
                    return this.ShippingMethods();
                }
            }
            viewModel.AvailableCountries = availableCountries;
            return this.View(viewModel);
        }

        [HttpGet]
        public ActionResult ShippingMethods()
        {
            WebStoreConfigurationPart configuration = this._webStoreConfigurationServices.GetConfiguration();
            WebStoreServices webStoreServices = new WebStoreServices(configuration);
            Basket basket = this._basketServices.GetBasket();
            ShippingMethodsViewModel viewModel = new ShippingMethodsViewModel { AvailableShippingMethods = webStoreServices.CreateWebStoreChannel<IOrderService>().GetShippingMethods(new GetShippingMethodsParameters { BasketId = this._basketServices.GetBasketId().Value, CultureName = Thread.CurrentThread.CurrentUICulture.Name, MerchantId = configuration.MerchantId.Value, UserId = this._webstoreProfileServices.GetUser() }), Currency = basket.Currency, ShippingMethod = basket.OrderFormHeaders.First().LineItems.First().ShippingMethodId.ToString() };
            webStoreServices.Dispose();
            this.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            return this.View("~/Modules/WebStore/Views/Order/ShippingMethods.cshtml", viewModel);
        }

        [HttpGet]
        public ActionResult LastAddress()
        {
            this.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            AddressViewModel viewModel = (this.BillingAddress.ShippingAddressIsDifferent) ? this.ShippingAddress : this.BillingAddress;
            viewModel.AvailableCountries = this.GetAvailableCountries();
            return this.View("~/Modules/WebStore/Views/Order/Address.cshtml", viewModel);
        }

        [HttpGet]
        public JsonResult GetStates(String countryId)
        {
            this.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Country country = this.GetAvailableCountries().FirstOrDefault(c => c.CountryId == countryId);
            return this.Json(country == default(Country) ? new State[] { } : country.States, JsonRequestBehavior.AllowGet);
        }
    }
}