text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RestSharp;
using TraceSourceLogger;
using TradeHub.Common.Core.DomainModels;
using TradeHub.Common.Core.MarketDataProvider;
using TradeHub.Common.Core.ValueObjects.MarketData;
using TradeHub.MarketDataProvider.Tradier.Utility;
using TradeHub.MarketDataProvider.Tradier.ValueObject;
using Constants = TradeHub.Common.Core.Constants;

namespace TradeHub.MarketDataProvider.Tradier.Provider
{
    public class TradierMarketDataProvider : ILiveTickDataProvider, IHistoricBarDataProvider
    {
        private readonly Type _type = typeof(TradierMarketDataProvider);

        private AsyncClassLogger _logger;

        private readonly string _marketDataProviderName;

        /// <summary>
        /// Indicates if the Provider session is connected or not
        /// </summary>
        private bool _isConnected;

        /// <summary>
        /// Indicates if quotes from stream session are to be consumed or not
        /// </summary>
        private bool _consumeQuoteStream;

        /// <summary>
        /// Holds parameters required for connectivity
        /// </summary>
        private Credentials _credentials;

        /// <summary>
        /// Contains session details for Quote Stream
        /// </summary>
        private TradierStreamSession _tradierStreamSession;

        /// <summary>
        /// Contains list of symbols which are subscribe for Quote Stream
        /// </summary>
        private List<string> _subscribedSymbols;

        /// <summary>
        /// Used for holding symbols for tick subscriptions untill the request is processed
        /// </summary>
        private ConcurrentQueue<Subscribe> _symbolSubscriptionQueue;

        /// <summary>
        /// Wraps the Order symbol concurrent queue
        /// </summary>
        private BlockingCollection<Subscribe> _symbolSubscriptionCollection;

        /// <summary>
        /// Dedicated task to consume quote messages
        /// </summary>
        private Task _quotesConsumerTask;

        /// <summary>
        /// Token source used with Quotes Consumer Task
        /// </summary>
        private CancellationTokenSource _quotesConsumerCancellationToken;

        /// <summary>
        /// Is Market Data client connected
        /// </summary>
        /// <returns></returns>
        public bool IsConnected()
        {
            return _isConnected;
        }

        #region Events

        /// <summary>
        /// Fired each time a Logon is arrived
        /// </summary>
        public event Action<string> LogonArrived;

        /// <summary>
        /// Fired each time a Logout is arrived
        /// </summary>
        public event Action<string> LogoutArrived;

        /// <summary>
        /// Fired each time a new tick arrives.
        /// </summary>
        public event Action<Tick> TickArrived;

        /// <summary>
        /// Fired when requested Historic Bar Data arrives
        /// </summary>
        public event Action<HistoricBarData> HistoricBarDataArrived;

        /// <summary>
        /// Fired each time when market data rejection arrives.
        /// </summary>
        public event Action<MarketDataEvent> MarketDataRejectionArrived;

        #endregion

        /// <summary>
        /// Default Constructor
        /// </summary>
        public TradierMarketDataProvider()
        {
            // Set provider name to be used in all calls
            _marketDataProviderName = Constants.MarketDataProvider.Tradier;

            // Create object for logging details
            _logger= new AsyncClassLogger("TradierDataProvider");
            _logger.SetLoggingLevel();
            _logger.LogDirectory(Constants.DirectoryStructure.MDE_LOGS_LOCATION);

            // Initialize local list/queue for subscriptions
            _subscribedSymbols = new List<string>();
        }

        #region Connect/Disconnect

        /// <summary>
        /// Connects/Starts a client
        /// </summary>
        public bool Start()
        {
            try
            {
                // Read account credentials
                _credentials = CredentialReader.ReadCredentials("TradierParams.xml");

                if (String.IsNullOrEmpty(_credentials.ApiUrl) || String.IsNullOrWhiteSpace(_credentials.ApiUrl))
                {
                    return false;
                }

                // Create HTTP Request
                var client = new RestClient(_credentials.ApiUrl + "/user/profile");
                var request = new RestRequest(Method.GET);
                request.AddHeader("authorization", "Bearer " + _credentials.AccessToken);
                request.AddHeader("accept", "application/json");

                // Send Request
                IRestResponse response = client.Execute(request);

                var requestResult = JsonConvert.DeserializeObject<dynamic>(response.Content);

                string profileId = requestResult.profile.id.ToString();

                if (!String.IsNullOrEmpty(profileId))
                {
                    _isConnected = true;

                    // Start process to consume quotes
                    StartDataConsumer();

                    if (Logger.IsInfoEnabled)
                    {
                        Logger.Info("Session is available.", _type.FullName, "Start");
                    }

                    if (LogonArrived != null)
                    {
                        LogonArrived(_marketDataProviderName);
                    }

                    return _isConnected;
                }

                // Get error message
                string faultstring = requestResult.fault.faultstring.ToString();

                if (Logger.IsInfoEnabled)
                {
                    Logger.Info("Session not available " + faultstring, _type.FullName, "Start");
                }

                return _isConnected;
            }
            catch (Exception exception)
            {
                _logger.Error(exception, _type.FullName, "Start");
            }
            return false;
        }

        /// <summary>
        /// Disconnects/Stops a client
        /// </summary>
        public bool Stop()
        {
            _isConnected = false;
            _consumeQuoteStream = false;

            // Stop consuming data
            StopComsumer();

            // Clear subscription symbols
            _subscribedSymbols.Clear();

            if (Logger.IsInfoEnabled)
            {
                Logger.Info("Session closed.", _type.FullName, "Stop");
            }

            if (LogoutArrived != null)
            {
                LogoutArrived(_marketDataProviderName);
            }

            return _isConnected;
        }

        #endregion

        #region Subscribe Data

        /// <summary>
        /// Market data request message
        /// </summary>
        public bool SubscribeTickData(Subscribe subscribe)
        {
            try
            {
                // Saftey check to avoid duplication
                if (_subscribedSymbols.Contains(subscribe.Security.Symbol))
                {
                    if (_logger.IsInfoEnabled)
                    {
                        _logger.Info("Symbol already subscribed", _type.FullName, "SubscribeTickData");
                    }

                    return false;
                }

                // Stop comsuming current data
                _consumeQuoteStream = false;

                // Reset Consumer
                StopComsumer();
                StartDataConsumer();

                Thread.Sleep(50);

                // Add request to queue
                _symbolSubscriptionCollection.Add(subscribe);

                return true;
            }
            catch (Exception exception)
            {
                _logger.Error(exception, _type.FullName, "SubscribeTickData");
                return false;
            }
        }

        /// <summary>
        /// Unsubscribe Market data message
        /// </summary>
        public bool UnsubscribeTickData(Unsubscribe unsubscribe)
        {
            try
            {
                // Saftey check to avoid duplication
                if (!_subscribedSymbols.Contains(unsubscribe.Security.Symbol))
                {
                    if (_logger.IsInfoEnabled)
                    {
                        _logger.Info("Symbol is not subscribed", _type.FullName, "UnsubscribeTickData");
                    }

                    return false;
                }

                // Stop comsuming current data
                _consumeQuoteStream = false;

                // Remove from subscribed symbols map
                _subscribedSymbols.Remove(unsubscribe.Security.Symbol);

                if (_subscribedSymbols.Count != 0)
                {
                    // Create a new subscription message with empty symbol
                    // This will allow the remaining symbols to be subscribed
                    // While the unsubcribed symbol is removed from the stream request
                    var subscribe = new Subscribe() {Security = new Security() {Symbol = String.Empty}};

                    // Add request to queue
                    _symbolSubscriptionCollection.Add(subscribe);
                }

                if (_logger.IsInfoEnabled)
                {
                    _logger.Info(unsubscribe.Security.Symbol + " unsubscribed", _type.FullName, "UnsubscribeTickData");
                }

                return true;
            }
            catch (Exception exception)
            {
                _logger.Error(exception, _type.FullName, "UnsubscribeTickData");
                return false;
            }
        }

        /// <summary>
        /// Historic Bar Data Request Message
        /// </summary>
        public bool HistoricBarDataRequest(HistoricDataRequest historicDataRequest)
        {
            try
            {
                // Create Query Properties
                string symbol = "symbol=" + historicDataRequest.Security.Symbol;
                string interval = "interval=" + historicDataRequest.BarType.ToLowerInvariant();
                string start = "start=" + historicDataRequest.StartTime.ToString("yyyy-MM-dd");
                string end = "end=" + historicDataRequest.EndTime.ToString("yyyy-MM-dd");

                // Create complete HTTP Url
                string url = _credentials.ApiUrl + "/markets/history?" + symbol + "&" + interval + "&" + start + "&" + end;

                // Create request message
                var client = new RestClient(url);
                var request = new RestRequest(Method.GET);
                request.AddHeader("authorization", "Bearer " + _credentials.AccessToken);
                request.AddHeader("accept", "application/json");

                // Send Request
                IRestResponse response = client.Execute(request);

                // Parse JSON object
                var responseResult = JsonConvert.DeserializeObject<TradierHistoricalData>(response.Content);

                // Create TradeHub Historic Bar Data Object
                var historicBarData = CreateHistoricalBarData(responseResult, historicDataRequest.Security, historicDataRequest.Id);

                if (historicBarData!=null)
                {
                    // Raise event to notify listeners
                    if (HistoricBarDataArrived!=null)
                    {
                        HistoricBarDataArrived(historicBarData);
                    }
                    return true;
                }

                return false;
            }
            catch (Exception exception)
            {
                _logger.Error(exception, _type.FullName, "HistoricBarDataRequest");
                return false;
            }
        }

        #endregion

        /// <summary>
        /// Reads quotes from stream session established with the server
        /// </summary>
        private void ConsumeQuoteStream()
        {
            try
            {
                while (true)
                {
                    // Retrive new subscription
                    var subscribe = _symbolSubscriptionCollection.Take();

                    // Get session details for requesting Quote Stream
                    GetStreamSessionDetails();

                    if (_tradierStreamSession == null)
                    {
                        if (_logger.IsInfoEnabled)
                        {
                            _logger.Info("Stream Session details not found", _type.FullName, "ConsumeQuoteStream");
                        }

                        break;
                    }

                    // Construct query string to be used with request message
                    string queryString = CreateQuotesQueryString(subscribe);

                    // Create request message
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_tradierStreamSession.Url + queryString);
                    request.Method = "POST";
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.Accept = "application/json";

                    // Get response message
                    HttpWebResponse response = (HttpWebResponse) request.GetResponse();

                    // Extract stream from incoming response message
                    StreamReader readStream = new StreamReader(response.GetResponseStream(), Encoding.UTF8);

                    _consumeQuoteStream = true;

                    // Add symbol to local collection
                    _subscribedSymbols.Add(subscribe.Security.Symbol);

                    // Read individual data from extracted stream
                    string streamLine = readStream.ReadLine();
                    while (_consumeQuoteStream)
                    {
                        if (streamLine != null)
                        {
                            // Exctract information from JSON object
                            var streamResult = JsonConvert.DeserializeObject<QuoteStream>(streamLine);

                            // Construct Tick object
                            var tick = CreateTickData(streamResult);

                            if (tick != null)
                            {
                                // Raise Event to notify listeners
                                if (TickArrived != null)
                                {
                                    TickArrived(tick);
                                }
                            }
                        }

                        // Read next line of data
                        streamLine = readStream.ReadLine();
                    }

                    readStream.Close();
                }
            }
            catch (Exception exception)
            {
                _logger.Error(exception, _type.FullName, "ConsumeQuoteStream");
                StopComsumer();
            }
        }

        /// <summary>
        /// Create Query String for requesting Quote Stream
        /// </summary>
        /// <returns></returns>
        private string CreateQuotesQueryString(Subscribe subscribe)
        {
            int count = 0;
            int subscribedSymbolsCount = _subscribedSymbols.Count;

            // Create Query parameters
            string sessionId = "sessionid=" + _tradierStreamSession.Sessionid;

            string symbols = "symbols=";

            if (subscribe.Security.Symbol!=String.Empty)
            {
                symbols += subscribe.Security.Symbol;
            }

            // Traverse all currently subscribed symbols
            foreach (string subscribedSymbol in _subscribedSymbols)
            {
                //if (++count != subscribedSymbolsCount)
                {
                    symbols += ",";
                }

                symbols += subscribedSymbol;

            }

            //symbols += ",CAKE,MSFT,NFLX";

            if (subscribe.Security.Symbol.Equals(""))
            {
                symbols = symbols.Remove(0, 1);
            }

            string linebreak = "linebreak=true";

            // Combine all parameters and return
            return  "?" + sessionId + "&" + symbols + "&" + linebreak;
        }

        /// <summary>
        /// Gets session details to be used for streaming quotes
        /// </summary>
        /// <returns></returns>
        private void GetStreamSessionDetails()
        {
            try
            {
                // Verify if the existing session is valid or not
                if (CheckStreamSessionValidity())
                {
                    return;
                }

                // Create request message
                var client = new RestClient(_credentials.ApiUrl + "/markets/events/session");
                var request = new RestRequest(Method.POST);
                request.AddHeader("authorization", "Bearer " + _credentials.AccessToken);
                request.AddHeader("accept", "application/json");

                // Send request
                IRestResponse response = client.Execute(request);

                // Parse received JSON message
                var responseResult = JsonConvert.DeserializeObject<dynamic>(response.Content);

                string sessionId = responseResult.stream.sessionid.ToString();
                string sessionUrl = responseResult.stream.url.ToString();

                if (!String.IsNullOrEmpty(sessionId) && !String.IsNullOrEmpty(sessionUrl))
                {
                    _tradierStreamSession = new TradierStreamSession();

                    // Copy session details
                    _tradierStreamSession.Sessionid = sessionId;
                    _tradierStreamSession.Url = sessionUrl;
                    _tradierStreamSession.CreationTime = DateTime.Now.AddMinutes(5);
                }
            }
            catch (Exception exception)
            {
                _logger.Error(exception, _type.FullName, "GetStreamSessionDetails");
            }
        }

        /// <summary>
        /// Verifies if the Stream Session is still valid or not
        /// </summary>
        /// <returns></returns>
        private bool CheckStreamSessionValidity()
        {
            if (_tradierStreamSession != null && (_tradierStreamSession.CreationTime < DateTime.Now))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// Creates a new TradeHub Tick Data object
        /// </summary>
        /// <param name="quoteStream"></param>
        /// <returns></returns>
        private Tick CreateTickData(QuoteStream quoteStream)
        {
            try
            {
                if (quoteStream.type.Equals("summary"))
                {
                    return null;
                }
                // Format our new DateTime object to start at the UNIX Epoch
                DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);

                // Create new Tick object
                Tick tick = new Tick(new Security() { Symbol = quoteStream.symbol }, _marketDataProviderName);

                if (quoteStream.type.Equals("quote"))
                {
                    // Extract UNIX timestamp
                    var timestamp = Convert.ToDouble(quoteStream.biddate);

                    // Add the timestamp (number of seconds since the Epoch) to be converted
                    dateTime = dateTime.AddMilliseconds(timestamp);

                    // Set time to local object
                    tick.DateTime = dateTime;

                    // Extract BID information
                    tick.BidPrice = Convert.ToDecimal(quoteStream.bid);
                    tick.BidSize = Convert.ToDecimal(quoteStream.bidsz);
                    tick.BidExchange = quoteStream.bidexch;

                    // Extract ASK information
                    tick.AskPrice = Convert.ToDecimal(quoteStream.ask);
                    tick.AskSize = Convert.ToDecimal(quoteStream.asksz);
                    tick.AskExchange = quoteStream.askexch;
                }
                else if (quoteStream.type.Equals("trade"))
                {
                    // Extract UNIX timestamp
                    var timestamp = Convert.ToDouble(quoteStream.date);

                    // Add the timestamp (number of seconds since the Epoch) to be converted
                    dateTime = dateTime.AddMilliseconds(timestamp);

                    // Set time to local object
                    tick.DateTime = dateTime;

                    // Extract LAST/TRADE information
                    tick.LastPrice = Convert.ToDecimal(quoteStream.price);
                    tick.LastSize = Convert.ToDecimal(quoteStream.size);
                    tick.LastExchange = quoteStream.exch;
                }

                return tick;
            }
            catch (Exception exception)
            {
                _logger.Error(exception, _type.FullName, "CreateTickData");
                return null;
            }
        }

        /// <summary>
        /// Create TradeHub Historical Bar Data object from the Tradier data
        /// </summary>
        /// <param name="tradierHistoricalData"></param>
        /// <param name="security"></param>
        /// <param name="requestId"></param>
        private HistoricBarData CreateHistoricalBarData(TradierHistoricalData tradierHistoricalData, Security security, string requestId)
        {
            try
            {
                // Create new TradeHub Historical Bar Data object to be used withing the application
                HistoricBarData historicBarData = new HistoricBarData(security, _marketDataProviderName, DateTime.UtcNow);

                Bar[] bars = new Bar[tradierHistoricalData.history.day.Count];
                int count = 0;

                foreach (var historicalDataDetail in tradierHistoricalData.history.day)
                {
                    var time = DateTime.ParseExact(historicalDataDetail.date, "yyyy-MM-dd", CultureInfo.InvariantCulture);

                    // Create new TradeHub Bar
                    Bar bar = new Bar(security, _marketDataProviderName, requestId, time)
                    {
                        Close = Convert.ToDecimal(historicalDataDetail.close),
                        Open = Convert.ToDecimal(historicalDataDetail.open),
                        High = Convert.ToDecimal(historicalDataDetail.high),
                        Low = Convert.ToDecimal(historicalDataDetail.low),
                        Volume = historicalDataDetail.volume
                    };

                    // Add to the Array
                    bars[count] = bar;
                    count++;
                }

                // Add Bars array to root object
                historicBarData.Bars = bars;

                // Add Request ID to root object
                historicBarData.ReqId = requestId;

                return historicBarData;
            }
            catch (Exception exception)
            {
                _logger.Error(exception, _type.FullName, "CreateHistoricalBarData");
                return null;
            }
        }

        /// <summary>
        /// Starts process to consume streaming quote data
        /// </summary>
        private void StartDataConsumer()
        {
            if (_quotesConsumerCancellationToken == null)
            {
                _symbolSubscriptionQueue = new ConcurrentQueue<Subscribe>();
                _symbolSubscriptionCollection = new BlockingCollection<Subscribe>(_symbolSubscriptionQueue);

                // Initialize Consumer Token
                _quotesConsumerCancellationToken = new CancellationTokenSource();

                // Start consumer for quotes from local collection
                _quotesConsumerTask = Task.Factory.StartNew(ConsumeQuoteStream, _quotesConsumerCancellationToken.Token);
            }
        }

        /// <summary>
        /// Stops data comsumer process
        /// </summary>
        private void StopComsumer()
        {
            if (_quotesConsumerCancellationToken != null)
            {
                _consumeQuoteStream = false;
                _quotesConsumerCancellationToken.Cancel();

                _quotesConsumerTask = null;
                _quotesConsumerCancellationToken = null;

                // Stop data comsumer
                _symbolSubscriptionCollection.Dispose();
                _symbolSubscriptionCollection = null;
                _symbolSubscriptionQueue = null;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<? require_once "ccookie.php"; ?>
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
  <title>Petit Giselle Paris is a trademark of StrianoBabies</title>
  <meta name="description" content="Abbigliamento Danza junior - Junior - Baby - Kids - Petit Giselle Paris: abbigliamento, scarpe e accessori inspirati al mondo della danza."/>

  <meta property="og:url" content="http://petitgiselleparis.tk" />
  <meta property="og:title" content="Petit Giselle Paris is a trademark of StrianoBabies" />
  <meta property="og:image" content="http://petitgiselleparis.tk/images/petitgiselleparis.jpg" width="267" height="397"/>
  <meta property="og:description" content="Abbigliamento Danza junior - Junior - Baby - Kids - Petit Giselle Paris: abbigliamento, scarpe e accessori inspirati al mondo della danza." />

  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>

  <link href='https://fonts.googleapis.com/css?family=Raleway|Satisfy' rel='stylesheet' type='text/css'>

  <link rel="stylesheet" href="font-awesome/css/font-awesome.min.css">

  <link rel="shortcut icon" href="favicon.ico" />
  <link rel="icon" href="favicon.ico" />

       Petit Giselle Paris
        menu

Prodotti

Registrati

Offerta

Prodotti

Registrati

Offerta

Sentirsi Giselle
per un giorno...

....Scopri la nuova fantastica collezione

Tutu Skirts

Tutu Dresses

T-shirt Macarons

T-shirt Dance

Sweaters

T-shirt birthday

Hat

Shoes

New Arrivals

          mail_outline

Vuoi saperne di più sui nostri articoli, colori, taglie e prezzi?

Registrati alla nostra Newsletter!

        <input type="hidden" id="sib_embed_signup_lang" value="it">
        <input type="hidden" id="sib_embed_invalid_email_message" value="Email non valida, Riprova.">

        <form class="description" id="theform" name="theform" action="https://my.sendinblue.com/users/subscribeembed/js_id/2abce/id/1" onsubmit="return false;">

<input type="hidden" name="js_id" id="js_id" value="2abce"><input type="hidden" name="listid" id="listid" value="4">
<input type="hidden" name="from_url" id="from_url" value="yes">
<input type="hidden" name="hdn_email_txt" id="hdn_email_txt" value="">

   <input type="hidden" name="req_hid" id="req_hid" value="">

   <input type="text" name="email" id="email" value="" class="validate white center black-text" placeholder="Inserisci qui la tua email!">
  <button class="btn btn-registrazione waves-effect waves-light purple lighten-2" type="submit" data-editfield="subscribe" name="action">Voglio iscrivermi!</button>

  100% Sicuro. Odiamo lo Spam quanto te.

        </form>

          card_giftcard

Vuoi acquistare i nostri articoli con le migliori promozioni?

Compila il questionario per ricevere promozioni personalizzate.

          Ti ricontatteremo entro 24h.

          Scegli l'offerta adatta a TE!

Contattaci

2015 &copy PetitGiselleParis P.I. 04321690655 | Via della Repubblica 10, Pagani SA | +39 081/5158954 | Privacy

PRIVACY POLICY COMPLETA

Your browser does not support iframes.

      OK

<? ccookie(); ?>


text:
    {% block modal-clock %}{% endblock %}
    {% block modal-calendar %}{% endblock %}

    {% block after-timeinfo %}{% endblock %}

  {% block modal-content %}
  {% endblock %}


text:
module Bosh::Director
  module ProblemHandlers
    class Base
      include CloudcheckHelper
      attr_reader :data
      attr_accessor :job # so we can checkpoint task

      def self.create_from_model(model)
        create_by_type(model.type, model.resource_id, model.data)
      end

      # create_by_type might not be able to initialize
      # problem handler if some part of its state
      # or dependencies is invalid. In this case it
      # just substitutes a generic "invalid_problem"
      # handler that reports the fact that the original
      # problem is invalid and offers closing it as
      # the only solution.
      def self.create_by_type(type, resource_id, data)
        handler_class = Base.handlers[type.to_s]
        if handler_class.nil?
          raise "Cannot find handler for '#{type}' problem"
        end

        handler_class.new(resource_id, data)
      rescue ProblemHandlerError => e
        create_by_type(:invalid_problem, resource_id,
                       {"error" => e, "original_type" => type.to_s})
      end

      # Problem state is  described by constructor parameters.
      # Problem handler can reach out to check if the problem
      # is still present and attempt to fix it by applying
      # a potential resolution tagged with one or more labels.
      def initialize(resource_id, data)
        @logger = Config.logger
        @event_log = Config.event_log
        @job = nil
      end

      def checkpoint
        @job.task_checkpoint if @job
      end

      # Talking to cloud should only be possible
      # in the context of DJ job
      def cloud
        if @job.nil?
          handler_error("Cannot talk to cloud outside of job context")
        end
        super
      end

      # Problem description
      def description; end

      def resolutions
        self.class.resolutions.map do |name|
          { :name => name.to_s, :plan => resolution_plan(name) }
        end
      end

      def resolution_plan(resolution)
        plan = self.class.plan_for(resolution)
        return nil if plan.nil?
        instance_eval(&plan)
      end

      def auto_resolution
        self.class.get_auto_resolution
      end

      # @param resolution desired resolution
      def apply_resolution(resolution)
        action = self.class.action_for(resolution)
        if action.nil?
          handler_error("Cannot find '#{resolution}' resolution for '#{self.class}'")
        end
        instance_eval(&action)
      end

      def auto_resolve
        apply_resolution(auto_resolution)
      end

      # Registration DSL
      class << self
        attr_accessor :handlers
      end

      def self.register_as(type)
        Base.handlers ||= {}
        Base.handlers[type.to_s] = self
      end

      # Resolution DSL
      class << self
        attr_reader :resolutions
      end

      def self.init_dsl_data
        @resolutions = []
        @plans = {}
        @actions = {}
        @auto_resolution = nil
      end

      init_dsl_data

      def self.inherited(base)
        base.class_eval { init_dsl_data }
      end

      def self.plan_for(resolution)
        @plans[resolution.to_s]
      end

      def self.action_for(resolution)
        @actions[resolution.to_s]
      end

      def self.plan(&block)
        @plans[@pending_name.to_s] = block
      end

      def self.action(&block)
        @actions[@pending_name.to_s] = block
      end

      def self.get_auto_resolution
        @auto_resolution
      end

      def self.auto_resolution(name)
        @auto_resolution = name
      end

      def self.resolution(name, &block)
        @resolutions << name
        @pending_name = name
        instance_eval(&block)
      ensure
        @pending_name = nil
      end

    end
  end
end


text:
{% extends "base.html" %}
{% from "macros.html" import render_flashed_messages, render_pagination %}
{% from "macros_forms.html" import render_form %}
{% block content  %}

  {{ render_flashed_messages() }}
  {% if current_user.is_authenticated() %}

  {% endif %}

  {% for c in characters %}

	      		{% if c.image_id %}

	      		{% endif %}

{{ c.name }}{% if current_user.is_authenticated() %} {% endif %}

{{ c.quick_desription }}

  {% endfor %}

  {% if pagination %}

    {{ render_pagination(pagination=pagination, endpoint='character') }}

  {% endif %}

{% endblock %}


text:
package com.google.sps.servlets;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.common.base.Preconditions;
import com.google.gson.Gson;
import com.google.sps.data.Availability;
import com.google.sps.data.AvailabilityDao;
import com.google.sps.data.DatastoreAvailabilityDao;
import com.google.sps.data.DatastorePersonDao;
import com.google.sps.data.DatastoreScheduledInterviewDao;
import com.google.sps.data.Job;
import com.google.sps.data.Person;
import com.google.sps.data.PersonDao;
import com.google.sps.data.PossibleInterviewer;
import com.google.sps.data.ScheduledInterview;
import com.google.sps.data.ScheduledInterviewDao;
import com.google.sps.data.TimeRange;
import java.io.IOException;
import java.io.BufferedReader;
import java.lang.Integer;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.TextStyle;
import java.util.Locale;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.RequestDispatcher;
import java.util.Optional;

@WebServlet("/shadow-show-interviewers")
public class ShadowShowInterviewersServlet extends HttpServlet {
  private ScheduledInterviewDao scheduledInterviewDao;
  private PersonDao personDao;

  @Override
  public void init() {
    init(new DatastoreScheduledInterviewDao(), new DatastorePersonDao());
  }

  public void init(ScheduledInterviewDao scheduledInterviewDao, PersonDao personDao) {
    this.scheduledInterviewDao = scheduledInterviewDao;
    this.personDao = personDao;
  }

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String utcStartTime = request.getParameter("utcStartTime");
    TimeRange interviewTimeRange =
        new TimeRange(
            Instant.parse(utcStartTime), Instant.parse(utcStartTime).plus(1, ChronoUnit.HOURS));
    UserService userService = UserServiceFactory.getUserService();
    String userEmail = userService.getCurrentUser().getEmail();
    String userId = userService.getCurrentUser().getUserId();
    // Since Users returned from the LocalUserService (in tests) do not have userIds, here we set
    // the userId equal to a hashcode.
    if (userId == null) {
      userId = String.format("%d", userEmail.hashCode());
    }
    String position = request.getParameter("position");
    Job selectedPosition = Job.valueOf(Job.class, position);
    List<ScheduledInterview> possibleInterviews =
        ShadowLoadInterviewsServlet.getPossibleInterviews(
            scheduledInterviewDao, selectedPosition, interviewTimeRange, personDao, userId);
    Set<PossibleInterviewer> possibleInterviewers = new HashSet<PossibleInterviewer>();
    for (ScheduledInterview interview : possibleInterviews) {
      String company = personDao.get(interview.interviewerId()).get().company();
      String job = personDao.get(interview.interviewerId()).get().job();
      possibleInterviewers.add(PossibleInterviewer.create(company, job));
    }
    request.setAttribute("interviewers", possibleInterviewers);
    RequestDispatcher rd = request.getRequestDispatcher("/possibleInterviewers.jsp");
    try {
      rd.forward(request, response);
    } catch (ServletException e) {
      throw new RuntimeException(e);
    }
  }
}


text:
layout: blog-page
title: Announcing Dotty 0.4.0-RC1
author: Allan Renucci
authorImg: images/allan.jpg
date: 2017-10-16
---

Today, we are excited to release Dotty version 0.4.0-RC1. This release
serves as a technology preview that demonstrates new language features
and the compiler supporting them.

If you're not familiar with Dotty, it's a platform to try out new language concepts and compiler
technologies for Scala. The focus is mainly on simplification. We remove extraneous syntax
(e.g. no XML literals), and try to boil down Scala's types into a smaller set of more fundamental
constructs. The theory behind these constructs is researched in
[DOT](https://infoscience.epfl.ch/record/215280), a calculus for dependent object types.
You can learn more about Dotty on our [website](http://dotty.epfl.ch).

<!--more-->

This is our fourth scheduled release according to our [6-week release schedule](https://dotty.epfl.ch/docs/usage/version-numbers.html).
The [previous technology preview](/blog/2017/09/07/third-dotty-milestone-release.html) improved
stability and reliability.

## What's new in the 0.4.0-RC1 technology preview?

### Rewritten REPL [#2991](https://github.com/lampepfl/dotty/pull/2991)
The original Dotty REPL was a proof of concept hacked together
from
[an ancient version of the scalac REPL](https://github.com/lampepfl/dotty/pull/1082#issuecomment-183905504).
It worked by creating Scala source files from the user input using string
concatenation, this made it easy to adapt it for Dotty since it did not rely on
the internals of scalac, but it was also fragile and hard to reason about.
The [new REPL](https://github.com/lampepfl/dotty/pull/2991) instead works by
manipulating ASTs (Abstract Syntax Trees), this is more robust and will make it
easier to develop new features: we have already implemented auto-completion
support (by reusing the APIs we had created for
the [Dotty IDE](https://dotty.epfl.ch/docs/usage/ide-support.html)) and we have
plans for displaying API documentation in the REPL.

Note that the user interface of the REPL has not changed: like in the old REPL
we use code adapted from the [Ammonite REPL](http://ammonite.io/#Ammonite-REPL)
to provide syntax highlighting, multi-line editing, history, etc.

### Scala 2.12 support [#2827](https://github.com/lampepfl/dotty/pull/2827)
Since our first release, it has been possible to use Scala 2 libraries in a
Dotty project as explained in the
[dotty-example-project](https://github.com/smarter/dotty-example-project#getting-your-project-to-compile-with-dotty).
Previously, we supported libraries compiled by Scala 2.11, but starting with this
release we support Scala 2.12 instead. If your Dotty project has Scala 2
dependencies this change should be transparent for you assuming all your
dependencies have been published for 2.12.

### Performance work
Over the last few weeks, we started working on compilation speed with some good results:
compiling [ScalaPB](https://github.com/dotty-staging/scalapb) is now 20% faster
than with Dotty 0.3.0-RC2. You can follow along our progress on
http://dotty-bench.epfl.ch/.

## Trying out Dotty
### Scastie
[Scastie], the online Scala playground, supports Dotty.
This is an easy way to try Dotty without installing anything.

### sbt
Using sbt 0.13.13 or newer, do:

```
sbt new lampepfl/dotty.g8
```

This will setup a new sbt project with Dotty as compiler. For more details on
using Dotty with sbt, see the
[example project](https://github.com/lampepfl/dotty-example-project).

### IDE support
It is very easy to start using the Dotty IDE in any Dotty project by following
the [IDE guide](https://dotty.epfl.ch/docs/usage/ide-support.html).

### Standalone installation
Releases are available for download on the _Releases_
section of the Dotty repository:
[https://github.com/lampepfl/dotty/releases](https://github.com/lampepfl/dotty/releases)

We also provide a [homebrew](https://brew.sh/) package that can be installed by running:

```
brew install lampepfl/brew/dotty
```

In case you have already installed Dotty via brew, you should instead update it:

```
brew upgrade dotty
```

## Let us know what you think!
If you have questions or any sort of feedback, feel free to send us a message on our
[Gitter channel](https://gitter.im/lampepfl/dotty). If you encounter a bug, please
[open an issue on GitHub](https://github.com/lampepfl/dotty/issues/new).

## Contributing
Thank you to all the contributors who made this release possible!

According to `git shortlog -sn --no-merges 0.3.0-RC2..0.4.0-RC1` these are:

```
   226  Martin Odersky
   112  Felix Mulder
   104  Nicolas Stucki
    41  Allan Renucci
    41  Guillaume Martres
    33  liu fengyun
     8  Olivier Blanvillain
     4  Aggelos Biboudis
     3  Dmitry Petrashko
     2  Raymond Tay
     2  esarbe
     2  Enno Runne
     1  Brandon Elam Barker
     1  Raphael Bosshard
     1  Jacob J
     1  Aleksander Boruch-Gruszecki
     1  Jim Van Horn
     1  Matthias Sperl
     1  Michal Gutowski
```

If you want to get your hands dirty and contribute to Dotty, now is a good time to get involved!
You can have a look at our [Getting Started page for new contributors](https://dotty.epfl.ch/docs/contributing/getting-started.html),
the [Awesome Error Messages](http://scala-lang.org/blog/2016/10/14/dotty-errors.html) project or some of
the simple [Dotty issues](https://github.com/lampepfl/dotty/issues?q=is%3Aissue+is%3Aopen+label%3Aexp%3Anovice).
They make perfect entry-points into hacking on the compiler.

We are looking forward to having you join the team of contributors.

## Library authors: Join our community build
Dotty now has a set of widely-used community libraries that are built against every nightly Dotty
snapshot. Currently this includes ScalaPB, algebra, scalatest, scopt and squants.
Join our [community build](https://github.com/lampepfl/dotty-community-build)
to make sure that our regression suite includes your library.

To get started, see [https://github.com/lampepfl/dotty](https://github.com/lampepfl/dotty).

[Scastie]: https://scastie.scala-lang.org/?target=dotty

[@odersky]: https://github.com/odersky
[@DarkDimius]: https://github.com/DarkDimius
[@smarter]: https://github.com/smarter
[@felixmulder]: https://github.com/felixmulder
[@nicolasstucki]: https://github.com/nicolasstucki
[@liufengyun]: https://github.com/liufengyun
[@OlivierBlanvillain]: https://github.com/OlivierBlanvillain
[@biboudis]: https://github.com/biboudis
[@allanrenucci]: https://github.com/allanrenucci


text:
import { Chain } from './Chain';
import { generateUUID } from './Util';
import lodash from 'lodash';

export const ChainStorage = {};
export const putChain = (name, chain) => {
    if (exists(name)) {
        throw Error('A chain with the same name as "' + name + '" has already been stored.')
    }
    lodash.set(ChainStorage, name, () => chain);
};
export const addChainState = (key, name, spec, param, context) => {
    const state = {};
    if (spec && spec.length) {
        const params = {};
        spec.forEach(chainSpec => {
            lodash.set(params, chainSpec.field, param[chainSpec.field] ? param[chainSpec.field]() : '');
        });
        lodash.set(state, 'spec', spec);
        lodash.set(state, 'params', param);
    }
    lodash.set(state, 'context', lodash.clone(context));
    if (!lodash.get(ChainStorage, key)) {
        lodash.set(ChainStorage, key, {});
    }
    const chainState = lodash.get(ChainStorage, key);
    lodash.set(chainState, name, state);
};
export const createChainState = (name, spec, param, context) => {
    const key = generateUUID();
    addChainState(key, name, spec, param, context);
    return key;
};
export const removeState = (key) => {
    lodash.unset(ChainStorage, key);
};
export const getState = (key, name, param) => {
    const state = lodash.get(ChainStorage, key);
    const stateChain = lodash.get(state, name);
    let context = undefined;
    if (stateChain) {
        if (stateChain.spec) {
            let valid = [];
            stateChain.spec.forEach(fieldSpec => {
                if (param[fieldSpec.field]) {
                    valid.push(param[fieldSpec.field]() === stateChain.params[fieldSpec.field]());
                } else {
                    valid.push('' === stateChain.params[fieldSpec.field]());
                }
            });
            if (lodash.filter(valid, value => value).length === stateChain.spec.length) {
                context = stateChain.context;
            }
        } else {
            context = stateChain.context;
        }
    }
    return context;
};
export const getChains = () => {
    const chains = [];
    lodash.forEach(ChainStorage, (storage) => {
        if (storage instanceof Function) {
            const chain = storage();
            if (chain instanceof Chain) {
                chains.push(chain.info().name);
            }
        }
    });
    return chains;
}
export const getConfig = () => {
    let config = lodash.get(ChainStorage, '$chain.$config');
    if (!config) {
        lodash.set(ChainStorage, '$chain.$config', {});
        config = lodash.get(ChainStorage, '$chain.$config');
    }
    return config;
};
export const putConfig = (name, value) => {
    lodash.set(getConfig(), name, value);
};
export const clearStorage = () => {
    lodash.forIn(ChainStorage, (field, key) => {
        lodash.unset(ChainStorage, key);
    });
};
export const exists = (chainName) => {
    return !!lodash.get(ChainStorage, chainName);
}


text:
import reg
import dectate
import morepath
from morepath import core
from morepath import compat
from .fixtures import identity_policy

def objects(actions):
    result = []
    for action, obj in actions:
        result.append(obj)
    return result

def builtin_ref(s):
    if compat.PY3:
        return 'builtins.%s' % s
    else:
        return '__builtin__.%s' % s

def test_setting():
    class App(morepath.App):
        pass

    @App.setting(section='foo', name='bar')
    def f():
        return "Hello"

    @App.setting(section='foo', name='qux')
    def g():
        return "Dag"

    dectate.commit(App)

    assert objects(dectate.query_app(App, 'setting')) == [f, g]

    assert objects(dectate.query_app(App, 'setting', name='bar')) == [f]

    assert objects(dectate.query_app(App, 'setting_section')) == [f, g]

def test_predicate_fallback():
    class App(morepath.App):
        pass

    dectate.commit(App)

    r = objects(dectate.query_app(App, 'predicate_fallback'))
    assert r == [
        core.model_not_found,
        core.name_not_found,
        core.method_not_allowed,
        core.body_model_unprocessable
    ]

    r = objects(dectate.query_app(App, 'predicate_fallback',
                                  dispatch='morepath.App.get_view'))
    assert r == [
        core.model_not_found,
        core.name_not_found,
        core.method_not_allowed,
        core.body_model_unprocessable
    ]

    # there aren't any predicates for class_path
    r = objects(dectate.query_app(
        App, 'predicate_fallback',
        dispatch='morepath.App._class_path'))
    assert r == []

    r = objects(dectate.query_app(App, 'predicate_fallback',
                                  func='morepath.core.model_predicate'))
    assert r == [
        core.model_not_found,
    ]

def test_predicate():
    class App(morepath.App):
        pass

    dectate.commit(App)

    r = objects(dectate.query_app(App, 'predicate'))
    assert r == [
        core.model_predicate,
        core.name_predicate,
        core.request_method_predicate,
        core.body_model_predicate
    ]

    r = objects(dectate.query_app(App, 'predicate',
                                  dispatch='morepath.App.get_view'))
    assert r == [
        core.model_predicate,
        core.name_predicate,
        core.request_method_predicate,
        core.body_model_predicate
    ]

    # there aren't any predicates for class_path
    r = objects(dectate.query_app(
        App, 'predicate',
        dispatch='morepath.App._class_path'))
    assert r == []

    r = objects(dectate.query_app(App, 'predicate',
                                  name='name'))
    assert r == [
        core.name_predicate,
    ]

    r = objects(dectate.query_app(App, 'predicate',
                                  index='reg.ClassIndex'))
    assert r == [
        core.model_predicate,
        core.body_model_predicate
    ]

    r = objects(dectate.query_app(App, 'predicate',
                                  after='morepath.core.model_predicate'))
    assert r == [
        core.name_predicate
    ]

class App(morepath.App):
    @morepath.dispatch_method()
    def generic(self, v):
        pass

def test_method():

    @App.predicate(App.generic, name='v', default='', index=reg.KeyIndex)
    def get(self, v):
        return v

    @App.method(App.generic, v='A')
    def a(app, v):
        return v

    @App.method(App.generic, v='B')
    def b(app, v):
        return v

    dectate.commit(App)

    app = App()

    assert app.generic('A') == 'A'
    assert app.generic('B') == 'B'

    r = objects(dectate.query_app(App, 'method'))
    assert r == [a, b]

    r = objects(
        dectate.query_app(
            App, 'method',
            dispatch_method='morepath.tests.test_querytool.App.generic'))
    assert r == [a, b]

    r = objects(dectate.query_app(App, 'method', v='A'))
    assert r == [a]

def test_converter():
    class App(morepath.App):
        pass

    dectate.commit(App)

    r = objects(dectate.query_app(App, 'converter'))

    expected = [
        core.int_converter,
        core.unicode_converter
    ]
    if not compat.PY3:
        expected.append(core.str_converter)

    expected.extend([
        core.date_converter,
        core.datetime_converter
    ])

    assert r == expected

    r = objects(dectate.query_app(App, 'converter', type=builtin_ref('int')))

    assert r == [
        core.int_converter
    ]

class Foos(object):
    pass

class Base(object):
    pass

class Foo(Base):
    pass

class SubFoo(Foo):
    pass

class Bar(Base):
    pass

class SubBar(Bar):
    pass

def get_variables(obj):
    pass

def get_converters():
    return {}

def test_path():
    class App(morepath.App):
        pass

    @App.path('base', model=Base)
    def get_base():
        pass

    @App.path('foos', model=Foos, variables=get_variables)
    def get_foos():
        pass

    @App.path('foos/{id}', model=Foo, get_converters=get_converters,
              absorb=True)
    def get_foo(id):
        pass

    dectate.commit(App)

    r = objects(dectate.query_app(App, 'path'))

    assert r == [get_base, get_foos, get_foo]

    r = objects(dectate.query_app(
        App, 'path',
        model='morepath.tests.test_querytool.Foo'))
    assert r == [get_base, get_foo]

    r = objects(dectate.query_app(
        App, 'path',
        model='morepath.tests.test_querytool.SubFoo'))

    assert r == [get_base, get_foo]

    r = objects(dectate.query_app(
        App, 'path',
        model='morepath.tests.test_querytool.Base'))

    assert r == [get_base]

    r = objects(dectate.query_app(
        App, 'path',
        model='morepath.tests.test_querytool.Bar'))

    assert r == [get_base]

    r = objects(dectate.query_app(App, 'path', path='foos'))

    assert r == [get_foos]

    r = objects(dectate.query_app(App, 'path', path='/foos'))

    assert r == [get_foos]

    r = objects(dectate.query_app(App, 'path', path='foos/{id}'))

    assert r == [get_foo]

    r = objects(dectate.query_app(App, 'path', path='foos/{blah}'))

    assert r == [get_foo]

    r = objects(dectate.query_app(
        App, 'path',
        variables='morepath.tests.test_querytool.get_variables'))

    assert r == [get_foos]

    r = objects(dectate.query_app(
        App, 'path',
        get_converters='morepath.tests.test_querytool.get_converters'))

    assert r == [get_foo]

    r = objects(dectate.query_app(
        App, 'path', absorb='True'))

    assert r == [get_foo]

class BasePermission(object):
    pass

class Permission(BasePermission):
    pass

class SubPermission(Permission):
    pass

class SubIdentity(morepath.Identity):
    pass

def test_permission_rule():
    class App(morepath.App):
        pass

    @App.permission_rule(model=Base, permission=BasePermission)
    def rule_base(obj, permission, identity):
        return True

    @App.permission_rule(model=Foo, permission=Permission)
    def rule_foo(obj, permission, identity):
        return True

    @App.permission_rule(model=Foos, permission=SubPermission,
                         identity=SubIdentity)
    def rule_foos(obj, permission, identity):
        return True

    dectate.commit(App)

    r = objects(dectate.query_app(App, 'permission_rule'))

    assert r == [rule_base, rule_foo, rule_foos]

    r = objects(dectate.query_app(
        App, 'permission_rule',
        model='morepath.tests.test_querytool.Foo'))

    assert r == [rule_base, rule_foo]

    r = objects(dectate.query_app(
        App, 'permission_rule',
        model='morepath.tests.test_querytool.Base'))

    assert r == [rule_base]

    r = objects(dectate.query_app(
        App, 'permission_rule',
        model='morepath.tests.test_querytool.Bar'))

    assert r == [rule_base]

    r = objects(dectate.query_app(
        App, 'permission_rule',
        permission='morepath.tests.test_querytool.Permission'))

    assert r == [rule_foo, rule_foos]

    r = objects(dectate.query_app(
        App, 'permission_rule',
        permission='morepath.tests.test_querytool.BasePermission'))

    assert r == [rule_base, rule_foo, rule_foos]

    r = objects(dectate.query_app(
        App, 'permission_rule',
        permission='morepath.tests.test_querytool.SubPermission'))

    assert r == [rule_foos]

    r = objects(dectate.query_app(
        App, 'permission_rule',
        model='morepath.tests.test_querytool.Foo',
        permission='morepath.tests.test_querytool.BasePermission'))

    assert r == [rule_base, rule_foo]

    r = objects(dectate.query_app(
        App, 'permission_rule',
        identity='morepath.Identity'))

    assert r == [rule_base, rule_foo, rule_foos]

    r = objects(dectate.query_app(
        App, 'permission_rule',
        identity='morepath.tests.test_querytool.SubIdentity'))

    assert r == [rule_foos]

def template_directory_a():
    return '/'

def test_template_directory():
    class App(morepath.App):
        pass

    # non-decorator so we can import template_directory_a
    App.template_directory()(template_directory_a)

    @App.template_directory(after=template_directory_a, name='blah')
    def b():
        return '/'

    dectate.commit(App)

    r = objects(dectate.query_app(App, 'template_directory'))

    assert r == [template_directory_a, b]

    r = objects(dectate.query_app(App, 'template_directory',
                                  name='blah'))

    assert r == [b]

    r = objects(dectate.query_app(
        App, 'template_directory',
        after='morepath.tests.test_querytool.template_directory_a'))
    assert r == [b]

def test_template_render():
    class App(morepath.App):
        pass

    @App.template_render('.zpt')
    def render(loader, name, original_render):
        pass

    @App.template_render('.blah')
    def render2(loader, name, original_render):
        pass

    dectate.commit(App)

    r = objects(dectate.query_app(App, 'template_render'))

    assert r == [render, render2]

    r = objects(dectate.query_app(App, 'template_render', extension='.blah'))

    assert r == [render2]

def test_view():
    class App(morepath.App):
        pass

    @App.json(model=Foo)
    def foo_default(self, request):
        pass

    @App.view(model=Base)
    def base_default(self, request):
        pass

    @App.view(model=Foo, name='edit')
    def foo_edit(self, request):
        pass

    dectate.commit(App)

    r = objects(dectate.query_app(App, 'view'))

    assert r == [core.standard_exception_view,
                 foo_default, base_default, foo_edit]

    r = objects(dectate.query_app(App, 'json'))

    assert r == [core.standard_exception_view,
                 foo_default, base_default, foo_edit]

    r = objects(dectate.query_app(
        App, 'view',
        model='morepath.tests.test_querytool.Base'))

    assert r == [base_default]

    r = objects(dectate.query_app(
        App, 'view',
        model='morepath.tests.test_querytool.Foo'))

    assert r == [foo_default, base_default, foo_edit]

    r = objects(dectate.query_app(
        App, 'view',
        model='morepath.tests.test_querytool.Bar'))

    assert r == [base_default]

    r = objects(dectate.query_app(
        App, 'view',
        name='edit'))

    assert r == [foo_edit]

def test_view_permission():
    class App(morepath.App):
        pass

    @App.view(model=Foo, name='n')
    def foo_n(self, request):
        pass

    @App.view(model=Foo, name='b', permission=BasePermission)
    def foo_b(self, request):
        pass

    @App.view(model=Foo, name='p', permission=Permission)
    def foo_p(self, request):
        pass

    @App.view(model=Foo, name='s', permission=SubPermission)
    def foo_s(self, request):
        pass

    dectate.commit(App)

    r = objects(dectate.query_app(
        App, 'view',
        permission='morepath.tests.test_querytool.BasePermission'))

    assert r == [foo_b, foo_p, foo_s]

    r = objects(dectate.query_app(
        App, 'view',
        permission='morepath.tests.test_querytool.Permission'))

    assert r == [foo_p, foo_s]

    r = objects(dectate.query_app(
        App, 'view',
        permission='morepath.tests.test_querytool.SubPermission'))

    assert r == [foo_s]

    r = objects(dectate.query_app(App, 'view',
                                  model='morepath.tests.test_querytool.Foo',
                                  permission=builtin_ref('None')))

    assert r == [foo_n]

def test_view_body_model():
    class App(morepath.App):
        pass

    @App.view(model=Foo, request_method='POST', body_model=Base)
    def foo_base(self, request):
        pass

    @App.view(model=Foo, request_method='POST', body_model=Foo)
    def foo_foo(self, request):
        pass

    dectate.commit(App)

    r = objects(dectate.query_app(
        App, 'view',
        model='morepath.tests.test_querytool.Foo',
        body_model='morepath.tests.test_querytool.Base'))

    assert r == [foo_base]

    r = objects(dectate.query_app(
        App, 'view',
        model='morepath.tests.test_querytool.Foo',
        body_model='morepath.tests.test_querytool.Foo'))
    assert r == [foo_base, foo_foo]

class Mounted(morepath.App):
    pass

def test_mount():
    class App(morepath.App):
        pass

    @App.path(path='foo', model=Foo)
    def get_foo():
        pass

    @App.mount(path='mounted', app=Mounted)
    def mount_app():
        return Mounted()

    dectate.commit(App, Mounted)

    r = objects(dectate.query_app(
        App, 'mount'))

    assert r == [get_foo, mount_app]

    r = objects(dectate.query_app(
        App, 'mount', app='morepath.tests.test_querytool.Mounted'))

    assert r == [mount_app]

    r = objects(dectate.query_app(
        App, 'mount', model='morepath.tests.test_querytool.Foo'))

    assert r == [get_foo]

def test_defer_links():
    class App(morepath.App):
        pass

    class Mounted2(morepath.App):
        pass

    @App.path(path='foo', model=Foo)
    def get_foo():
        pass

    @App.defer_links(model=Bar)
    def defer_bar(app, obj):
        return app.child('mounted')

    @App.mount(path='mounted', app=Mounted2)
    def mount_app():
        return Mounted2()

    dectate.commit(App, Mounted2)

    r = objects(dectate.query_app(App, 'defer_links'))

    assert r == [get_foo, defer_bar, mount_app]

    r = objects(dectate.query_app(
        App, 'defer_links',
        model='morepath.tests.test_querytool.Bar'))

    assert r == [defer_bar]

    r = objects(dectate.query_app(
        App, 'defer_links',
        model='morepath.tests.test_querytool.SubBar'))

    assert r == [defer_bar]

    r = objects(dectate.query_app(App, 'defer_links',
                                  model='morepath.tests.test_querytool.Foo'))
    assert r == [get_foo]

def tween_a_factory():
    pass

def tween_b_factory():
    pass

def test_tween_factory():
    class App(morepath.App):
        pass

    App.tween_factory()(tween_a_factory)
    App.tween_factory(over=tween_a_factory)(tween_b_factory)

    dectate.commit(App)

    r = objects(dectate.query_app(
        App, 'tween_factory'))

    assert r == [
        core.excview_tween_factory,
        core.poisoned_host_header_protection_tween_factory,
        tween_a_factory,
        tween_b_factory
    ]

    r = objects(dectate.query_app(
        App, 'tween_factory',
        over='morepath.tests.test_querytool.tween_a_factory'))

    assert r == [tween_b_factory]

def test_identity_policy():
    class App(morepath.App):
        pass

    @App.identity_policy()
    def get_identity_policy():
        return identity_policy.IdentityPolicy()

    dectate.commit(App)

    r = objects(dectate.query_app(
        App, 'identity_policy'))

    assert len(r) == 1

def test_verify_identity():
    class App(morepath.App):
        pass

    @App.verify_identity()
    def verify(identity):
        return True

    dectate.commit(App)

    r = objects(dectate.query_app(
        App, 'verify_identity'))

    assert r == [verify]

def test_dump_json():
    class App(morepath.App):
        pass

    @App.dump_json(model=Foo)
    def dump_foo(self, request):
        pass

    @App.dump_json(model=Bar)
    def dump_bar(self, request):
        pass

    dectate.commit(App)

    r = objects(dectate.query_app(
        App, 'dump_json'))

    assert r == [dump_foo, dump_bar]

    r = objects(dectate.query_app(
        App, 'dump_json',
        model='morepath.tests.test_querytool.Foo'))

    assert r == [dump_foo]

    r = objects(dectate.query_app(
        App, 'dump_json',
        model='morepath.tests.test_querytool.SubFoo'))

    assert r == [dump_foo]

def test_load_json():
    class App(morepath.App):
        pass

    @App.load_json()
    def load(json, request):
        pass

    dectate.commit(App)

    r = objects(dectate.query_app(
        App, 'load_json'))

    assert r == [load]

def test_link_prefix():
    class App(morepath.App):
        pass

    @App.link_prefix()
    def prefix(s):
        pass

    dectate.commit(App)

    r = objects(dectate.query_app(
        App, 'link_prefix'))

    assert r == [prefix]


text:
package org.apache.flink.streaming.connectors.kafka;

/**
 * IT cases for the {@link FlinkKafkaProducer09}.
 */
@SuppressWarnings("serial")
public class Kafka09ProducerITCase extends KafkaProducerTestBase {
	@Override
	public void testOneToOneAtLeastOnceCustomOperator() throws Exception {
		// Disable this test since FlinkKafka09Producer doesn't support custom operator mode
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data;
using MySql.Data.MySqlClient;

namespace EurekaQuiz
{
    public class DBConnection
    {
        private DBConnection()
        {
        }

        private string databaseName = string.Empty;
        public string DatabaseName
        {
            get { return databaseName; }
            set { databaseName = value; }
        }

        public string Password { get; set; }
        private MySqlConnection connection = null;
        public MySqlConnection Connection
        {
            get { return connection; }
        }

        private static DBConnection _instance = null;
        public static DBConnection Instance()
        {
            if (_instance == null)
                _instance = new DBConnection();
            return _instance;
        }

        public bool IsConnect()
        {
            bool result = true;
            if (Connection == null)
            {
                if (String.IsNullOrEmpty(databaseName))
                    result = false;
                string connstring = string.Format("Server=localhost; database=eurekadb; UID=root; password=");
                connection = new MySqlConnection(connstring);
                connection.Open();
                result = true;
            }

            return result;
        }

        public void Close()
        {
            connection.Close();
        }

        public void conexao(MySqlConnection connection)
        {
            String server = "localhost";
            String database = "eurekadb";
            String uid = "root";
            String password = "";
            string connectionString;
            connectionString = "SERVER=" + server + ";" + "DATABASE=" +
            database + ";" + "U`enter code here`ID=" + uid + ";" + "PASSWORD=" + password + ";";

            connection = new MySqlConnection(connectionString);

        }
    }
}


text:
:mod:`subprocess` --- Subprocess management
===========================================

.. module:: subprocess
   :synopsis: Subprocess management.
.. moduleauthor:: Peter Åstrand <astrand@lysator.liu.se>
.. sectionauthor:: Peter Åstrand <astrand@lysator.liu.se>

.. versionadded:: 2.4

The :mod:`subprocess` module allows you to spawn new processes, connect to their
input/output/error pipes, and obtain their return codes.  This module intends to
replace several other, older modules and functions, such as::

   os.system
   os.spawn*
   os.popen*
   popen2.*
   commands.*

Information about how the :mod:`subprocess` module can be used to replace these
modules and functions can be found in the following sections.

.. seealso::

   :pep:`324` -- PEP proposing the subprocess module

Using the subprocess Module
---------------------------

This module defines one class called :class:`Popen`:

.. class:: Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)

   Arguments are:

   *args* should be a string, or a sequence of program arguments.  The program
   to execute is normally the first item in the args sequence or the string if a
   string is given, but can be explicitly set by using the *executable*
   argument.

   On Unix, with *shell=False* (default): In this case, the Popen class uses
   :meth:`os.execvp` to execute the child program. *args* should normally be a
   sequence.  A string will be treated as a sequence with the string as the only
   item (the program to execute).

   On Unix, with *shell=True*: If args is a string, it specifies the command string
   to execute through the shell.  If *args* is a sequence, the first item specifies
   the command string, and any additional items will be treated as additional shell
   arguments.

   On Windows: the :class:`Popen` class uses CreateProcess() to execute the child
   program, which operates on strings.  If *args* is a sequence, it will be
   converted to a string using the :meth:`list2cmdline` method.  Please note that
   not all MS Windows applications interpret the command line the same way:
   :meth:`list2cmdline` is designed for applications using the same rules as the MS
   C runtime.

   *bufsize*, if given, has the same meaning as the corresponding argument to the
   built-in open() function: :const:`0` means unbuffered, :const:`1` means line
   buffered, any other positive value means use a buffer of (approximately) that
   size.  A negative *bufsize* means to use the system default, which usually means
   fully buffered.  The default value for *bufsize* is :const:`0` (unbuffered).

   The *executable* argument specifies the program to execute. It is very seldom
   needed: Usually, the program to execute is defined by the *args* argument. If
   ``shell=True``, the *executable* argument specifies which shell to use. On Unix,
   the default shell is :file:`/bin/sh`.  On Windows, the default shell is
   specified by the :envvar:`COMSPEC` environment variable.

   *stdin*, *stdout* and *stderr* specify the executed programs' standard input,
   standard output and standard error file handles, respectively.  Valid values
   are :data:`PIPE`, an existing file descriptor (a positive integer), an
   existing file object, and ``None``.  :data:`PIPE` indicates that a new pipe
   to the child should be created.  With ``None``, no redirection will occur;
   the child's file handles will be inherited from the parent.  Additionally,
   *stderr* can be :data:`STDOUT`, which indicates that the stderr data from the
   applications should be captured into the same file handle as for stdout.

   If *preexec_fn* is set to a callable object, this object will be called in the
   child process just before the child is executed. (Unix only)

   If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and
   :const:`2` will be closed before the child process is executed. (Unix only).
   Or, on Windows, if *close_fds* is true then no handles will be inherited by the
   child process.  Note that on Windows, you cannot set *close_fds* to true and
   also redirect the standard handles by setting *stdin*, *stdout* or *stderr*.

   If *shell* is :const:`True`, the specified command will be executed through the
   shell.

   If *cwd* is not ``None``, the child's current directory will be changed to *cwd*
   before it is executed.  Note that this directory is not considered when
   searching the executable, so you can't specify the program's path relative to
   *cwd*.

   If *env* is not ``None``, it must be a mapping that defines the environment
   variables for the new process; these are used instead of inheriting the current
   process' environment, which is the default behavior.

   If *universal_newlines* is :const:`True`, the file objects stdout and stderr are
   opened as text files, but lines may be terminated by any of ``'\n'``, the Unix
   end-of-line convention, ``'\r'``, the old Macintosh convention or ``'\r\n'``, the
   Windows convention. All of these external representations are seen as ``'\n'``
   by the Python program.

   .. note::

      This feature is only available if Python is built with universal newline support
      (the default).  Also, the newlines attribute of the file objects :attr:`stdout`,
      :attr:`stdin` and :attr:`stderr` are not updated by the communicate() method.

   The *startupinfo* and *creationflags*, if given, will be passed to the
   underlying CreateProcess() function.  They can specify things such as appearance
   of the main window and priority for the new process.  (Windows only)

.. data:: PIPE

   Special value that can be used as the *stdin*, *stdout* or *stderr* argument
   to :class:`Popen` and indicates that a pipe to the standard stream should be
   opened.

.. data:: STDOUT

   Special value that can be used as the *stderr* argument to :class:`Popen` and
   indicates that standard error should go into the same handle as standard
   output.

Convenience Functions
^^^^^^^^^^^^^^^^^^^^^

This module also defines two shortcut functions:

.. function:: call(*popenargs, **kwargs)

   Run command with arguments.  Wait for command to complete, then return the
   :attr:`returncode` attribute.

   The arguments are the same as for the Popen constructor.  Example::

      retcode = call(["ls", "-l"])

.. function:: check_call(*popenargs, **kwargs)

   Run command with arguments.  Wait for command to complete. If the exit code was
   zero then return, otherwise raise :exc:`CalledProcessError`. The
   :exc:`CalledProcessError` object will have the return code in the
   :attr:`returncode` attribute.

   The arguments are the same as for the Popen constructor.  Example::

      check_call(["ls", "-l"])

   .. versionadded:: 2.5

Exceptions
^^^^^^^^^^

Exceptions raised in the child process, before the new program has started to
execute, will be re-raised in the parent.  Additionally, the exception object
will have one extra attribute called :attr:`child_traceback`, which is a string
containing traceback information from the childs point of view.

The most common exception raised is :exc:`OSError`.  This occurs, for example,
when trying to execute a non-existent file.  Applications should prepare for
:exc:`OSError` exceptions.

A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
arguments.

check_call() will raise :exc:`CalledProcessError`, if the called process returns
a non-zero return code.

Security
^^^^^^^^

Unlike some other popen functions, this implementation will never call /bin/sh
implicitly.  This means that all characters, including shell metacharacters, can
safely be passed to child processes.

Popen Objects
-------------

Instances of the :class:`Popen` class have the following methods:

.. method:: Popen.poll()

   Check if child process has terminated.  Set and return :attr:`returncode`
   attribute.

.. method:: Popen.wait()

   Wait for child process to terminate.  Set and return :attr:`returncode`
   attribute.

   .. warning::

      This will deadlock if the child process generates enough output to a
      stdout or stderr pipe such that it blocks waiting for the OS pipe buffer
      to accept more data.  Use :meth:`communicate` to avoid that.

.. method:: Popen.communicate(input=None)

   Interact with process: Send data to stdin.  Read data from stdout and stderr,
   until end-of-file is reached.  Wait for process to terminate. The optional
   *input* argument should be a string to be sent to the child process, or
   ``None``, if no data should be sent to the child.

   :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``.

   Note that if you want to send data to the process's stdin, you need to create
   the Popen object with ``stdin=PIPE``.  Similarly, to get anything other than
   ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or
   ``stderr=PIPE`` too.

   .. note::

      The data read is buffered in memory, so do not use this method if the data
      size is large or unlimited.

.. method:: Popen.send_signal(signal)

   Sends the signal *signal* to the child.

   .. note::

      On Windows only SIGTERM is supported so far. It's an alias for
      :meth:`terminate`.

   .. versionadded:: 2.6

.. method:: Popen.terminate()

   Stop the child. On Posix OSs the method sends SIGTERM to the
   child. On Windows the Win32 API function :cfunc:`TerminateProcess` is called
   to stop the child.

   .. versionadded:: 2.6

.. method:: Popen.kill()

   Kills the child. On Posix OSs the function sends SIGKILL to the child.
   On Windows :meth:`kill` is an alias for :meth:`terminate`.

   .. versionadded:: 2.6

The following attributes are also available:

.. warning::

   Use :meth:`communicate` rather than :meth:`.stdin.write`,
   :meth:`.stdout.read` or :meth:`.stderr.read` to avoid deadlocks due
   to any of the other OS pipe buffers filling up and blocking the child
   process.

.. attribute:: Popen.stdin

   If the *stdin* argument was :data:`PIPE`, this attribute is a file object
   that provides input to the child process.  Otherwise, it is ``None``.

.. attribute:: Popen.stdout

   If the *stdout* argument was :data:`PIPE`, this attribute is a file object
   that provides output from the child process.  Otherwise, it is ``None``.

.. attribute:: Popen.stderr

   If the *stderr* argument was :data:`PIPE`, this attribute is a file object
   that provides error output from the child process.  Otherwise, it is
   ``None``.

.. attribute:: Popen.pid

   The process ID of the child process.

.. attribute:: Popen.returncode

   The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly
   by :meth:`communicate`).  A ``None`` value indicates that the process
   hasn't terminated yet.

   A negative value ``-N`` indicates that the child was terminated by signal
   ``N`` (Unix only).

.. _subprocess-replacements:

Replacing Older Functions with the subprocess Module
----------------------------------------------------

In this section, "a ==> b" means that b can be used as a replacement for a.

.. note::

   All functions in this section fail (more or less) silently if the executed
   program cannot be found; this module raises an :exc:`OSError` exception.

In the following examples, we assume that the subprocess module is imported with
"from subprocess import \*".

Replacing /bin/sh shell backquote
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

::

   output=`mycmd myarg`
   ==>
   output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]

Replacing shell pipeline
^^^^^^^^^^^^^^^^^^^^^^^^

::

   output=`dmesg | grep hda`
   ==>
   p1 = Popen(["dmesg"], stdout=PIPE)
   p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
   output = p2.communicate()[0]

Replacing os.system()
^^^^^^^^^^^^^^^^^^^^^

::

   sts = os.system("mycmd" + " myarg")
   ==>
   p = Popen("mycmd" + " myarg", shell=True)
   sts = os.waitpid(p.pid, 0)

Notes:

* Calling the program through the shell is usually not required.

* It's easier to look at the :attr:`returncode` attribute than the exit status.

A more realistic example would look like this::

   try:
       retcode = call("mycmd" + " myarg", shell=True)
       if retcode < 0:
           print >>sys.stderr, "Child was terminated by signal", -retcode
       else:
           print >>sys.stderr, "Child returned", retcode
   except OSError, e:
       print >>sys.stderr, "Execution failed:", e

Replacing the os.spawn family
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

P_NOWAIT example::

   pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
   ==>
   pid = Popen(["/bin/mycmd", "myarg"]).pid

P_WAIT example::

   retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
   ==>
   retcode = call(["/bin/mycmd", "myarg"])

Vector example::

   os.spawnvp(os.P_NOWAIT, path, args)
   ==>
   Popen([path] + args[1:])

Environment example::

   os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
   ==>
   Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})

Replacing os.popen, os.popen2, os.popen3
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

::

   pipe = os.popen(cmd, 'r', bufsize)
   ==>
   pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout

::

   pipe = os.popen(cmd, 'w', bufsize)
   ==>
   pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin

::

   (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
   ==>
   p = Popen(cmd, shell=True, bufsize=bufsize,
             stdin=PIPE, stdout=PIPE, close_fds=True)
   (child_stdin, child_stdout) = (p.stdin, p.stdout)

::

   (child_stdin,
    child_stdout,
    child_stderr) = os.popen3(cmd, mode, bufsize)
   ==>
   p = Popen(cmd, shell=True, bufsize=bufsize,
             stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
   (child_stdin,
    child_stdout,
    child_stderr) = (p.stdin, p.stdout, p.stderr)

::

   (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
   ==>
   p = Popen(cmd, shell=True, bufsize=bufsize,
             stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
   (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)

Replacing functions from the popen2 module
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. note::

   If the cmd argument to popen2 functions is a string, the command is executed
   through /bin/sh.  If it is a list, the command is directly executed.

::

   (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
   ==>
   p = Popen(["somestring"], shell=True, bufsize=bufsize,
             stdin=PIPE, stdout=PIPE, close_fds=True)
   (child_stdout, child_stdin) = (p.stdout, p.stdin)

::

   (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
   ==>
   p = Popen(["mycmd", "myarg"], bufsize=bufsize,
             stdin=PIPE, stdout=PIPE, close_fds=True)
   (child_stdout, child_stdin) = (p.stdout, p.stdin)

:class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as
:class:`subprocess.Popen`, except that:

* :class:`Popen` raises an exception if the execution fails.

* the *capturestderr* argument is replaced with the *stderr* argument.

* ``stdin=PIPE`` and ``stdout=PIPE`` must be specified.

* popen2 closes all file descriptors by default, but you have to specify
  ``close_fds=True`` with :class:`Popen`.


text:
package com.siyeh.ipp.switchtoif;

import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.ipp.base.Intention;
import com.siyeh.ipp.base.PsiElementPredicate;
import com.siyeh.ipp.psiutils.ControlFlowUtils;
import com.siyeh.ipp.psiutils.SideEffectChecker;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ReplaceSwitchWithIfIntention extends Intention {

    @NotNull
    public PsiElementPredicate getElementPredicate() {
        return new SwitchPredicate();
    }

    public void processIntention(PsiElement element)
            throws IncorrectOperationException {
        final PsiJavaToken switchToken =
                (PsiJavaToken)element;
        final PsiSwitchStatement switchStatement =
                (PsiSwitchStatement)switchToken.getParent();
        if (switchStatement == null) {
            return;
        }
        final PsiManager manager = switchStatement.getManager();
        final PsiExpression switchExpression = switchStatement.getExpression();
        if (switchExpression == null) {
            return;
        }
        final CodeStyleManager codeStyleMgr = manager.getCodeStyleManager();
        final String declarationString;
        final boolean hadSideEffects;
        final String expressionText;
        final Project project = element.getProject();
        if (SideEffectChecker.mayHaveSideEffects(switchExpression)) {
            hadSideEffects = true;
            final PsiType switchExpressionType = switchExpression.getType();
            if (switchExpressionType == null) {
                return;
            }
            final JavaCodeStyleManager javaCodeStyleManager =
                    JavaCodeStyleManager.getInstance(project);
            final String variableName =
                    javaCodeStyleManager.suggestUniqueVariableName("i",
                            switchExpression, true);
            expressionText = variableName;
            declarationString =
                    switchExpressionType.getPresentableText() + ' ' +
                            variableName + " = " +
                            switchExpression.getText() + ';';
        } else {
            hadSideEffects = false;
            declarationString = null;
            expressionText = switchExpression.getText();
        }
        final PsiCodeBlock body = switchStatement.getBody();
        if (body == null) {
            return;
        }
        final PsiStatement[] statements = body.getStatements();
        boolean renameBreaks = false;
        for (int i = 1; i < statements.length - 1; i++) {
            if (CaseUtil.containsHiddenBreak(statements[i])) {
                renameBreaks = true;
                break;
            }
        }

        final List<SwitchStatementBranch> openBranches =
                new ArrayList<SwitchStatementBranch>();
        final Set<PsiLocalVariable> declaredVariables =
                new HashSet<PsiLocalVariable>();
        final List<SwitchStatementBranch> allBranches =
                new ArrayList<SwitchStatementBranch>();
        SwitchStatementBranch currentBranch = null;
        final PsiElement[] children = body.getChildren();
        for (int i = 1; i < children.length - 1; i++) {
            final PsiElement statement = children[i];
            if (statement instanceof PsiSwitchLabelStatement) {
                final PsiSwitchLabelStatement label =
                        (PsiSwitchLabelStatement)statement;
                if (currentBranch == null) {
                    openBranches.clear();
                    currentBranch = new SwitchStatementBranch();
                    currentBranch.addPendingVariableDeclarations(declaredVariables);
                    allBranches.add(currentBranch);
                    openBranches.add(currentBranch);
                } else if (currentBranch.hasStatements()) {
                    currentBranch = new SwitchStatementBranch();
                    allBranches.add(currentBranch);
                    openBranches.add(currentBranch);
                }
                if (label.isDefaultCase()) {
                    currentBranch.setDefault();
                } else {
                    final PsiExpression value = label.getCaseValue();
                    final String valueText = getCaseValueText(value);
                    currentBranch.addCaseValue(valueText);
                }
            } else {
                if (statement instanceof PsiStatement) {
                    if (statement instanceof PsiDeclarationStatement) {
                        final PsiDeclarationStatement declarationStatement =
                                (PsiDeclarationStatement)statement;
                        final PsiElement[] elements =
                                declarationStatement.getDeclaredElements();
                        for (PsiElement varElement : elements) {
                            final PsiLocalVariable variable =
                                    (PsiLocalVariable)varElement;
                            declaredVariables.add(variable);
                        }
                    }
                    for (SwitchStatementBranch branch : openBranches) {
                        branch.addStatement(statement);
                    }
                    if (!ControlFlowUtils.statementMayCompleteNormally(
                            (PsiStatement)statement)) {
                        currentBranch = null;
                    }
                } else {
                    for (SwitchStatementBranch branch : openBranches) {
                        if (statement instanceof PsiWhiteSpace) {
                            branch.addWhiteSpace(statement);
                        } else {
                            branch.addComment(statement);
                        }
                    }
                }
            }
        }
        final StringBuilder ifStatementBuffer = new StringBuilder();
        String breakLabel = null;
        if (renameBreaks) {
            breakLabel = CaseUtil.findUniqueLabel(switchStatement, "Label");
            ifStatementBuffer.append(breakLabel);
            ifStatementBuffer.append(':');
        }
        boolean firstBranch = true;
        SwitchStatementBranch defaultBranch = null;
        for (SwitchStatementBranch branch : allBranches) {
            if (branch.isDefault()) {
                defaultBranch = branch;
            } else {
                final List<String> caseValues = branch.getCaseValues();
                final List<PsiElement> bodyElements = branch.getBodyElements();
                final Set<PsiLocalVariable> pendingVariableDeclarations =
                        branch.getPendingVariableDeclarations();
                dumpBranch(ifStatementBuffer, expressionText,
                        caseValues, bodyElements, firstBranch,
                        renameBreaks, breakLabel,
                        pendingVariableDeclarations);
                firstBranch = false;
            }
        }
        if (defaultBranch != null) {
            final List<PsiElement> bodyElements =
                    defaultBranch.getBodyElements();
            final Set<PsiLocalVariable> pendingVariableDeclarations =
                    defaultBranch.getPendingVariableDeclarations();
            dumpDefaultBranch(ifStatementBuffer, bodyElements,
                    firstBranch, renameBreaks, breakLabel,
                    pendingVariableDeclarations);
        }
        final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
        final PsiElementFactory factory = psiFacade.getElementFactory();
        if (hadSideEffects) {
            final PsiStatement declarationStatement =
                    factory.createStatementFromText(declarationString, null);
            final String ifStatementString = ifStatementBuffer.toString();
            final PsiStatement ifStatement =
                    factory.createStatementFromText(ifStatementString, null);
            PsiElement ifElement = switchStatement.replace(ifStatement);
            ifElement = codeStyleMgr.reformat(ifElement);
            final PsiElement parent = ifElement.getParent();
            assert parent != null;
            final PsiElement declarationElement =
                    parent.addBefore(declarationStatement, ifElement);
            codeStyleMgr.reformat(declarationElement);
            codeStyleMgr.reformat(parent);
        } else {
            final String ifStatementString = ifStatementBuffer.toString();
            final PsiStatement newStatement =
                    factory.createStatementFromText(ifStatementString, null);
            final PsiElement replacedStatement =
                    switchStatement.replace(newStatement);
            codeStyleMgr.reformat(replacedStatement);
        }
    }

    private String getCaseValueText(PsiExpression value) {
        if (value == null) {
            return "";
        }
        if (value instanceof PsiParenthesizedExpression) {
            PsiParenthesizedExpression parenthesizedExpression =
                    (PsiParenthesizedExpression) value;
            final PsiExpression expression =
                    parenthesizedExpression.getExpression();
            return getCaseValueText(expression);
        }
        if (!(value instanceof PsiReferenceExpression)) {
            return value.getText();
        }
        PsiReferenceExpression referenceExpression =
                (PsiReferenceExpression) value;
        final PsiElement target = referenceExpression.resolve();
        final String text = referenceExpression.getText();
        if (!(target instanceof PsiEnumConstant)) {
            return value.getText();
        }
        PsiEnumConstant enumConstant = (PsiEnumConstant) target;
        final PsiClass aClass = enumConstant.getContainingClass();
        if (aClass == null) {
            return value.getText();
        }
        final String name = aClass.getQualifiedName();
        return name + "." + text;
    }

    private static void dumpBranch(@NonNls StringBuilder ifStatementString,
                                   String expressionText, List<String> caseValues,
                                   List<PsiElement> bodyStatements,
                                   boolean firstBranch,
                                   boolean renameBreaks,
                                   String breakLabel,
                                   Set<PsiLocalVariable> variables) {
        if (!firstBranch) {
            ifStatementString.append("else ");
        }
        dumpCaseValues(ifStatementString, expressionText, caseValues);
        dumpBody(ifStatementString, bodyStatements, renameBreaks, breakLabel,
                variables);
    }

    private static void dumpDefaultBranch(@NonNls StringBuilder ifStatementString,
                                          List<PsiElement> bodyStatements,
                                          boolean firstBranch,
                                          boolean renameBreaks,
                                          String breakLabel,
                                          Set<PsiLocalVariable> variables) {
        if (!firstBranch) {
            ifStatementString.append("else ");
        }
        dumpBody(ifStatementString, bodyStatements, renameBreaks, breakLabel,
                variables);
    }

    private static void dumpCaseValues(@NonNls StringBuilder ifStatementString,
                                   String expressionText, List<String> caseValues) {
        ifStatementString.append("if(");
        boolean firstCaseValue = true;
        for (String caseValue : caseValues) {
            if (!firstCaseValue) {
                ifStatementString.append("||");
            }
            firstCaseValue = false;
            ifStatementString.append(expressionText);
            ifStatementString.append("==");
            ifStatementString.append(caseValue);
        }
        ifStatementString.append(')');
    }

    private static void dumpBody(@NonNls StringBuilder ifStatementString,
                                 List<PsiElement> bodyStatements,
                                 boolean renameBreaks,
                                 String breakLabel,
                                 Set<PsiLocalVariable> variables) {
        ifStatementString.append('{');
        for (PsiLocalVariable variable : variables) {
            if (CaseUtil.isUsedByStatementList(variable, bodyStatements)) {
                final PsiType varType = variable.getType();
                ifStatementString.append(varType.getPresentableText());
                ifStatementString.append(' ');
                ifStatementString.append(variable.getName());
                ifStatementString.append(';');
            }
        }
        for (PsiElement bodyStatement : bodyStatements) {
            @NonNls final String text = bodyStatement.getText();
            if (!"break;".equals(text)) {
                appendElement(ifStatementString, bodyStatement, renameBreaks,
                        breakLabel);
            }
        }
        ifStatementString.append("\n}");
    }

    private static void appendElement(@NonNls StringBuilder ifStatementString,
                                      PsiElement element,
                                      boolean renameBreakElements,
                                      String breakLabelString) {
        if (!renameBreakElements) {
            final String text = element.getText();
            ifStatementString.append(text);
        } else if (element instanceof PsiBreakStatement) {
            final PsiIdentifier identifier =
                    ((PsiBreakStatement)element).getLabelIdentifier();
            if (identifier == null || "".equals(identifier.getText())) {
                ifStatementString.append("break ");
                ifStatementString.append(breakLabelString);
                ifStatementString.append(';');
            } else {
                final String text = element.getText();
                ifStatementString.append(text);
            }
        } else if (element instanceof PsiBlockStatement ||
                element instanceof PsiCodeBlock ||
                element instanceof PsiIfStatement) {
            final PsiElement[] children = element.getChildren();
            for (PsiElement child : children) {
                appendElement(ifStatementString, child, renameBreakElements,
                        breakLabelString);
            }
        } else {
            final String text = element.getText();
            ifStatementString.append(text);
        }
    }
}