text:
<?php
	//$self->css('/components/ckeditor/ckeditor.css');
	$self->js('/components/ckeditor/ckeditor.js');
	$self->js('/components/ckeditor/adapters/jquery.js');
?>
<div class="container">
	<?php $self->renderPartial("layout", array("areas"=>$layoutAreas, "page"=>$page)) ?>
</div>

redpajama_set_name: RedPajamaGithub


text:
package nl.mprog.whattoeat;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;

public class recipeProductActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recipe_product);

        final EditText editText = (EditText) findViewById(R.id.products);
        ImageButton search = (ImageButton) findViewById(R.id.Search);

        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String products = editText.getText().toString();
                System.out.println(products);

                Intent intent = new Intent(recipeProductActivity.this, RecipeActivity.class);
                intent.putExtra("products", products);
                startActivity(intent);

            }
        });

    }
}


text:
package com.common;

import org.apache.log4j.Logger;
import org.junit.Test;

public class Log4jTest {
    static Logger log = Logger.getLogger(Log4jTest.class);

    @Test
    public void testLog4j() {
        log.debug("This is a debug message.");
        log.info("This is a info message.");
        log.warn("This is a warn message.");
        log.error("This is an error message.");
    }
}


text:
<?php

namespace Eilander\Repository;

class RepositoryException extends \Exception
{
    /**
     * The exception description.
     *
     * @var string
     */
    protected $message = 'Repository error. Sorry!';
}


text:
package smartAutocomplete;

import fig.basic.*;

// State associated with doing inference in one example.
// Task: predict doc.tokens[i] given everything in the past.
public class InferState {
  // Constructor arguments
  private final FeatureDomain[] featureDomains;
  private final Params params;
  private final Statistics statistics;
  private final PredictionContext context;
  private final Token trueToken;

  // Accessors for constructor arguments
  public FeatureDomain[] getFeatureDomains() { return featureDomains; }
  public Params getParams() { return params; }
  public Statistics getStatistics() { return statistics; }
  public PredictionContext getContext() { return context; }
  public Token getTrueToken() { return trueToken; }

  // Computed values
  private Candidate trueCandidate = null;
  private CandidateList candidates;
  private boolean oracle = false; // whether any candidate is correct
  private boolean oov = false;
  private boolean ident = false;
  private boolean correct = false; // whether highest scoring candidate is
                                   // correct.
  private double entropy = Double.NaN;
  private int rank = 0;

  // Accessors for computed values
  public Candidate getTrueCandidate() { return trueCandidate; }
  public CandidateList getCandidates() { return candidates; }
  public boolean isOracle() { return oracle; }
  public boolean isOov() { return oov; }
  public boolean isIdent() { return ident; }
  public boolean isCorrect() { return correct; }
  public double getEntropy() { return entropy; }
  public int getRank() { return rank; }

  public double getReciprocalRank() {
    return oracle ? 1.0/(double)(rank+1) : 0;
  }

  public InferState(FeatureDomain[] featureDomains, Params params,
                    Statistics statistics, PredictionContext context,
                    Token trueToken) {
    this.featureDomains = featureDomains;
    this.params = params;
    this.statistics = statistics;
    this.context = context;
    this.trueToken = trueToken;
    this.candidates =
      new CandidateList(featureDomains, params, statistics, context);

    // True answer.
    String trueTokenStr = trueToken.str();

    // Is the true token an identifier?
    ident = (trueToken.type() == Token.Type.ACTUAL &&
             trueToken.context() == Token.Context.NONE &&
             Tokenizer.isIdentifier(trueTokenStr));

    // Find true token on the beam and set oracle, trueCandidate and rank
    for (Candidate candidate : candidates) {
      if (candidate.token.equals(trueTokenStr)) {
        oracle = true;
        trueCandidate = candidate;
        break;
      }
      rank++;
    }

    // Correct?
    if (candidates.size() > 0) {
      correct = candidates.get(0).token.equals(trueTokenStr);
    }

    if (!oracle) {
      // FixMe: [correctness] When we have global corpus, use vocab from that
      Vocab vocab;
      if (Main.isFixedVocab()) {
        vocab = Main.getVocab();
      } else {
        Corpus corpus = statistics.getProjectLangCorpus(context.getPath());
        DataSummary inDomainSummary =
          statistics.getStatistic(NgramKNCounts.class, corpus).getSummary();
        vocab = inDomainSummary.getVocab();
      }
      oov = !vocab.contains(trueTokenStr);

      trueCandidate = new Candidate(trueTokenStr, Main.clusters);
      trueCandidate.computeScores(featureDomains, params, context,
                                  Main.clusters);
    }

    // Compute entropy
    entropy = oracle ? -Math.log(trueCandidate.prob) : Double.NaN;
  }
};


text:
#pragma once
#include <cstdarg>
#include <string>

namespace Doremi
{
    namespace Utilities
    {
        namespace String
        {

            /**
            Code found on stackoverflow.
            Converts valist to string.
            \param dst String to store formatted message
            \param format Format of message
            \param ap Variable argument list
            */
            void toString(std::string& dst, const char* format, std::va_list ap) throw();

            /**
            Code found on stackoverflow.
            Converts valist to string.
            \param dst String to store formatted message
            \param format Format of message
            \param ap Variable argument list
            */
            void toString(std::string& dst, const char* format, ...) throw();
        }
    }
}


text:
{% extends "base.html" %}

{% block titulo %}{{ flatpage.title }} - {{ block.super }}{% endblock %}

{% block h1 %}{{ flatpage.title }}{% endblock %}
{% block conteudo %}

{{ flatpage.content|linebreaks }}

{% endblock %}


text:
title: Blog
never_cache_twig: true
visible: true
admin:
    children_display_order: collection
---

'Codando' com café

Acessar blog


text:
CUR_DIR=${0%/*}

cd $CUR_DIR/mac

qmake ../ -r -spec unsupported/macx-clang CONFIG+=x86_64

make clean
make
make install


text:
import { Component, DoCheck, HostListener, OnDestroy, OnInit, Renderer2 } from '@angular/core';
import { SecurityInfo } from '../../shared/model/about/security-info.model';
import { AuthService } from '../../auth/auth.service';
import { SharedAboutService } from 'src/app/shared/services/shared-about.service';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

/**
 * Navigation component
 *
 * @author Gunnar Hillert
 * @author Damien Vitrac
 */
@Component({
  selector: 'app-navigation',
  templateUrl: './navigation.component.html',
})
export class NavigationComponent implements DoCheck, OnInit, OnDestroy {

  /**
   * Unubscribe
   */
  private ngUnsubscribe$: Subject<any> = new Subject();

  /**
   * Security Info
   */
  securityInfo: SecurityInfo;

  /**
   * Is the feature information (required for role-based visibility of features)
   * available?
   */
  featureInfoLoaded = false;

  /**
   * Collapsed state
   * @type {boolean}
   */
  isCollapsed = true;

  /**
   * Small screen size
   * @type {boolean}
   */
  isSm = false;

  /**
   * Contructor
   *
   * @param {AuthService} authService
   * @param {SharedAboutService} sharedAboutService
   * @param {Renderer2} renderer
   */
  constructor(private authService: AuthService,
              private sharedAboutService: SharedAboutService,
              private renderer: Renderer2) {
    this.securityInfo = authService.securityInfo;
  }

  /**
   * Will clean up any {@link Subscription}s to prevent
   * memory leaks.
   */
  ngOnDestroy() {
    this.ngUnsubscribe$.next();
    this.ngUnsubscribe$.complete();
  }

  /**
   * Init
   */
  ngOnInit() {
    if (this.isCollapsed) {
      this.renderer.addClass(document.body, 'sidebar-fixed');
    }

    this.sharedAboutService.featureInfoSubject
      .pipe(takeUntil(this.ngUnsubscribe$))
      .subscribe(event => {
        if (event) {
          this.featureInfoLoaded = true;
        }
      });
  }

  /**
   * Do check
   */
  ngDoCheck() {
    this.securityInfo = this.authService.securityInfo;
  }

  /**
   * Listener on Resize Window
   */
  @HostListener('window:resize', ['$event'])
  onResize(event) {
    this.update();
  }

  /**
   * Update states
   */
  update() {
    this.isSm = document.documentElement.clientWidth < 900;
    if (this.isSm && this.isCollapsed) {
      this.toggle();
    }
  }

  /**
   * Toggle sidebar
   */
  toggle() {
    if (this.isCollapsed) {
      this.renderer.removeClass(document.body, 'sidebar-fixed');
      this.renderer.removeClass(document.body, 'sidebar-open');
    } else {
      this.renderer.addClass(document.body, 'sidebar-fixed');
    }
    this.isCollapsed = !this.isCollapsed;
  }

}


text:
package com.sampa.tasksreminder;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import com.sampa.tasksreminder.R.id;
import org.androidannotations.api.SdkVersionHelper;
import org.androidannotations.api.view.HasViews;
import org.androidannotations.api.view.OnViewChangedListener;
import org.androidannotations.api.view.OnViewChangedNotifier;

public final class NewTaskActivity_
    extends NewTaskActivity
    implements HasViews, OnViewChangedListener
{

    private final OnViewChangedNotifier onViewChangedNotifier_ = new OnViewChangedNotifier();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        OnViewChangedNotifier previousNotifier = OnViewChangedNotifier.replaceNotifier(onViewChangedNotifier_);
        init_(savedInstanceState);
        super.onCreate(savedInstanceState);
        OnViewChangedNotifier.replaceNotifier(previousNotifier);
    }

    private void init_(Bundle savedInstanceState) {
        OnViewChangedNotifier.registerOnViewChangedListener(this);
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        onViewChangedNotifier_.notifyViewChanged(this);
    }

    @Override
    public void setContentView(View view, LayoutParams params) {
        super.setContentView(view, params);
        onViewChangedNotifier_.notifyViewChanged(this);
    }

    @Override
    public void setContentView(View view) {
        super.setContentView(view);
        onViewChangedNotifier_.notifyViewChanged(this);
    }

    public static NewTaskActivity_.IntentBuilder_ intent(Context context) {
        return new NewTaskActivity_.IntentBuilder_(context);
    }

    public static NewTaskActivity_.IntentBuilder_ intent(Fragment supportFragment) {
        return new NewTaskActivity_.IntentBuilder_(supportFragment);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (((SdkVersionHelper.getSdkInt()< 5)&&(keyCode == KeyEvent.KEYCODE_BACK))&&(event.getRepeatCount() == 0)) {
            onBackPressed();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onViewChanged(HasViews hasViews) {
        timeReminderButton = ((Button) hasViews.findViewById(id.timeReminderButton));
        reminderInput = ((EditText) hasViews.findViewById(id.reminderInput));
        dateButton = ((Button) hasViews.findViewById(id.dateButton));
        dateReminderButton = ((Button) hasViews.findViewById(id.dateReminderButton));
        reminderSpinner = ((Spinner) hasViews.findViewById(id.reminderSpinner));
        timeButton = ((Button) hasViews.findViewById(id.timeButton));
        toggleReminderCheckBox = ((CheckBox) hasViews.findViewById(id.toggleReminderCheckBox));
        deleteButton = ((Button) hasViews.findViewById(id.deleteButton));
        startReminderText = ((TextView) hasViews.findViewById(id.startReminderText));
        descriptionInput = ((EditText) hasViews.findViewById(id.descriptionInput));
        reminderFrequencyText = ((TextView) hasViews.findViewById(id.reminderFrequencyText));
        titleInput = ((EditText) hasViews.findViewById(id.titleInput));
        {
            View view = hasViews.findViewById(id.dateButton);
            if (view!= null) {
                view.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        NewTaskActivity_.this.chooseDate();
                    }

                }
                );
            }
        }
        {
            View view = hasViews.findViewById(id.timeButton);
            if (view!= null) {
                view.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        NewTaskActivity_.this.chooseTime();
                    }

                }
                );
            }
        }
        {
            View view = hasViews.findViewById(id.deleteButton);
            if (view!= null) {
                view.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        NewTaskActivity_.this.deleteTask();
                    }

                }
                );
            }
        }
        {
            View view = hasViews.findViewById(id.dateReminderButton);
            if (view!= null) {
                view.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        NewTaskActivity_.this.chooseReminderDate();
                    }

                }
                );
            }
        }
        {
            View view = hasViews.findViewById(id.timeReminderButton);
            if (view!= null) {
                view.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        NewTaskActivity_.this.chooseReminderTime();
                    }

                }
                );
            }
        }
        {
            CompoundButton view = ((CompoundButton) hasViews.findViewById(id.toggleReminderCheckBox));
            if (view!= null) {
                view.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        NewTaskActivity_.this.checkedChangedOnHelloCheckBox();
                    }

                }
                );
            }
        }
        init();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(com.sampa.tasksreminder.R.menu.new_task, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        boolean handled = super.onOptionsItemSelected(item);
        if (handled) {
            return true;
        }
        int itemId_ = item.getItemId();
        if (itemId_ == id.accept) {
            accept();
            return true;
        }
        if (itemId_ == id.cancel) {
            cancel();
            return true;
        }
        return false;
    }

    public static class IntentBuilder_ {

        private Context context_;
        private final Intent intent_;
        private Fragment fragmentSupport_;

        public IntentBuilder_(Context context) {
            context_ = context;
            intent_ = new Intent(context, NewTaskActivity_.class);
        }

        public IntentBuilder_(Fragment fragment) {
            fragmentSupport_ = fragment;
            context_ = fragment.getActivity();
            intent_ = new Intent(context_, NewTaskActivity_.class);
        }

        public Intent get() {
            return intent_;
        }

        public NewTaskActivity_.IntentBuilder_ flags(int flags) {
            intent_.setFlags(flags);
            return this;
        }

        public void start() {
            context_.startActivity(intent_);
        }

        public void startForResult(int requestCode) {
            if (fragmentSupport_!= null) {
                fragmentSupport_.startActivityForResult(intent_, requestCode);
            } else {
                if (context_ instanceof Activity) {
                    ((Activity) context_).startActivityForResult(intent_, requestCode);
                } else {
                    context_.startActivity(intent_);
                }
            }
        }

    }

}


text:
package apps

import (
	"encoding/json"
	"fmt"
	"strings"

	. "github.com/cloudfoundry/cf-acceptance-tests/cats_suite_helpers"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gexec"

	"github.com/cloudfoundry-incubator/cf-test-helpers/cf"
	"github.com/cloudfoundry-incubator/cf-test-helpers/helpers"
	"github.com/cloudfoundry-incubator/cf-test-helpers/workflowhelpers"
	"github.com/cloudfoundry/cf-acceptance-tests/helpers/app_helpers"
	"github.com/cloudfoundry/cf-acceptance-tests/helpers/assets"
	"github.com/cloudfoundry/cf-acceptance-tests/helpers/random_name"
)

var _ = AppsDescribe("Changing an app's start command", func() {
	var appName string

	BeforeEach(func() {
		appName = random_name.CATSRandomName("APP")
	})

	AfterEach(func() {
		app_helpers.AppReport(appName, Config.DefaultTimeoutDuration())

		Expect(cf.Cf("delete", appName, "-f", "-r").Wait(Config.DefaultTimeoutDuration())).To(Exit(0))
	})

	Context("by using the command flag", func() {
		var expectedNullResponse string

		BeforeEach(func() {

			appUrl := "https://" + appName + "." + Config.GetAppsDomain()
			nullSession := helpers.CurlSkipSSL(Config.GetSkipSSLValidation(), appUrl).Wait(Config.DefaultTimeoutDuration())
			expectedNullResponse = string(nullSession.Buffer().Contents())

			Expect(cf.Cf(
				"push", appName,
				"--no-start",
				"-b", Config.GetRubyBuildpackName(),
				"-m", DEFAULT_MEMORY_LIMIT,
				"-p", assets.NewAssets().Dora,
				"-d", Config.GetAppsDomain(),
				"-c", "FOO=foo bundle exec rackup config.ru -p $PORT",
			).Wait(Config.DefaultTimeoutDuration())).To(Exit(0))
			app_helpers.SetBackend(appName)
			Expect(cf.Cf("start", appName).Wait(Config.CfPushTimeoutDuration())).To(Exit(0))
		})

		It("takes effect after a restart, not requiring a push", func() {
			Eventually(func() string {
				return helpers.CurlApp(Config, appName, "/env/FOO")
			}, Config.DefaultTimeoutDuration()).Should(ContainSubstring("foo"))

			guid := cf.Cf("app", appName, "--guid").Wait(Config.DefaultTimeoutDuration()).Out.Contents()
			appGuid := strings.TrimSpace(string(guid))

			workflowhelpers.ApiRequest(
				"PUT",
				"/v2/apps/"+appGuid,
				nil,
				Config.DefaultTimeoutDuration(),
				`{"command":"FOO=bar bundle exec rackup config.ru -p $PORT"}`,
			)

			Expect(cf.Cf("stop", appName).Wait(Config.DefaultTimeoutDuration())).To(Exit(0))

			Eventually(func() string {
				return helpers.CurlApp(Config, appName, "/env/FOO")
			}, Config.DefaultTimeoutDuration()).Should(ContainSubstring(expectedNullResponse))

			Expect(cf.Cf("start", appName).Wait(Config.CfPushTimeoutDuration())).To(Exit(0))

			Eventually(func() string {
				return helpers.CurlApp(Config, appName, "/env/FOO")
			}, Config.DefaultTimeoutDuration()).Should(ContainSubstring("bar"))
		})
	})

	Context("by using a Procfile", func() {
		type AppResource struct {
			Entity struct {
				DetectedStartCommand string `json:"detected_start_command"`
			} `json:"entity"`
		}

		type AppsResponse struct {
			Resources []AppResource `json:"resources"`
		}

		BeforeEach(func() {
			Expect(cf.Cf("push", appName, "--no-start", "-b", Config.GetNodejsBuildpackName(), "-m", DEFAULT_MEMORY_LIMIT, "-p", assets.NewAssets().NodeWithProcfile, "-d", Config.GetAppsDomain()).Wait(Config.DefaultTimeoutDuration())).To(Exit(0))
			app_helpers.SetBackend(appName)
			Expect(cf.Cf("start", appName).Wait(Config.CfPushTimeoutDuration())).To(Exit(0))
		})

		It("detects the use of the start command in the 'web' process type", func() {
			var appsResponse AppsResponse
			cfResponse := cf.Cf("curl", fmt.Sprintf("/v2/apps?q=name:%s", appName)).Wait(Config.DefaultTimeoutDuration()).Out.Contents()
			json.Unmarshal(cfResponse, &appsResponse)

			Expect(appsResponse.Resources[0].Entity.DetectedStartCommand).To(Equal("node app.js"))
		})
	})
})


text:
/// <summary>
/// Heat map renderer inspector.
/// </summary>
/// This code manages the portion of the inspector that
/// controls the Heat Map renderer.

using System;
using System.Collections;
using UnityEditor;
using UnityEngine;

namespace UnityAnalyticsHeatmap
{
    public class HeatmapRendererInspector
    {
        const string k_HighColorDensityKey = "UnityAnalyticsHeatmapHighDensityColor";
        const string k_MediumColorDensityKey = "UnityAnalyticsHeatmapMediumDensityColor";
        const string k_LowColorDensityKey = "UnityAnalyticsHeatmapLowDensityColor";

        const string k_HighThresholdKey = "UnityAnalyticsHeatmapHighThreshold";
        const string k_LowThresholdKey = "UnityAnalyticsHeatmapLowThreshold";

        const string k_StartTimeKey = "UnityAnalyticsHeatmapStartTime";
        const string k_EndTimeKey = "UnityAnalyticsHeatmapEndTime";
        const string k_PlaySpeedKey = "UnityAnalyticsHeatmapPlaySpeed";

        const string k_ParticleSizeKey = "UnityAnalyticsHeatmapParticleSize";
        const string k_ParticleShapeKey = "UnityAnalyticsHeatmapParticleShape";
        const string k_ParticleDirectionKey = "UnityAnalyticsHeatmapParticleDirection";

        Heatmapper m_Heatmapper;

        Color m_HighDensityColor = new Color(1f, 0, 0, .1f);
        Color m_MediumDensityColor = new Color(1f, 1f, 0, .1f);
        Color m_LowDensityColor = new Color(0, 1f, 1f, .1f);

        float m_HighThreshold = .9f;
        float m_LowThreshold = .1f;

        float m_StartTime = 0f;
        float m_EndTime = 1f;
        float m_MaxTime = 1f;

        float m_ParticleSize = 1f;
        int m_ParticleShapeIndex = 0;
        GUIContent[] m_ParticleShapeOptions = new GUIContent[]{ new GUIContent("Cube"), new GUIContent("Arrow"), new GUIContent("Square"), new GUIContent("Triangle") };
        RenderShape[] m_ParticleShapeIds = new RenderShape[]{ RenderShape.Cube, RenderShape.Arrow, RenderShape.Square, RenderShape.Triangle };

        int m_ParticleDirectionIndex = 0;
        GUIContent[] m_ParticleDirectionOptions = new GUIContent[]{ new GUIContent("YZ"), new GUIContent("XZ"), new GUIContent("XY") };
        RenderDirection[] m_ParticleDirectionIds = new RenderDirection[]{ RenderDirection.YZ, RenderDirection.XZ, RenderDirection.XY };

        bool m_IsPlaying = false;
        float m_PlaySpeed = 1f;

        GameObject m_GameObject;

        public HeatmapRendererInspector()
        {
            m_HighDensityColor = GetColorFromString(EditorPrefs.GetString(k_HighColorDensityKey), m_HighDensityColor);
            m_MediumDensityColor = GetColorFromString(EditorPrefs.GetString(k_MediumColorDensityKey), m_MediumDensityColor);
            m_LowDensityColor = GetColorFromString(EditorPrefs.GetString(k_LowColorDensityKey), m_LowDensityColor);

            m_HighThreshold = EditorPrefs.GetFloat(k_HighThresholdKey, m_HighThreshold);
            m_LowThreshold = EditorPrefs.GetFloat(k_LowThresholdKey, m_LowThreshold);

            m_StartTime = EditorPrefs.GetFloat(k_StartTimeKey, m_StartTime);
            m_EndTime = EditorPrefs.GetFloat(k_EndTimeKey, m_EndTime);
            m_PlaySpeed = EditorPrefs.GetFloat(k_PlaySpeedKey, m_PlaySpeed);

            m_ParticleSize = EditorPrefs.GetFloat(k_ParticleSizeKey, m_ParticleSize);

            m_ParticleShapeIndex = EditorPrefs.GetInt(k_ParticleShapeKey, m_ParticleShapeIndex);
            m_ParticleDirectionIndex = EditorPrefs.GetInt(k_ParticleDirectionKey, m_ParticleDirectionIndex);
        }

        public static HeatmapRendererInspector Init(Heatmapper heatmapper)
        {
            var inspector = new HeatmapRendererInspector();
            inspector.m_Heatmapper = heatmapper;
            return inspector;
        }

        public void OnGUI()
        {
            // COLORS
            EditorGUILayout.BeginVertical("box");
            m_HighDensityColor = SetAndSaveColor(new GUIContent("High Color", "Color for high density data"), k_HighColorDensityKey, m_HighDensityColor);
            m_MediumDensityColor = SetAndSaveColor(new GUIContent("Medium Color", "Color for medium density data"), k_MediumColorDensityKey, m_MediumDensityColor);
            m_LowDensityColor = SetAndSaveColor(new GUIContent("Low Color", "Color for low density data"), k_LowColorDensityKey, m_LowDensityColor);

            // THRESHOLDS
            var oldLowThreshold = m_LowThreshold;
            var oldHighThreshold = m_HighThreshold;

            m_LowThreshold = EditorGUILayout.FloatField(new GUIContent("Low Threshold", "Normalized threshold between low-density and medium-density data"), m_LowThreshold);
            m_HighThreshold = EditorGUILayout.FloatField(new GUIContent("High Threshold", "Normalized threshold between medium-density and high-density data"), m_HighThreshold);

            m_LowThreshold = Mathf.Min(m_LowThreshold, m_HighThreshold);
            m_HighThreshold = Mathf.Max(m_LowThreshold, m_HighThreshold);

            EditorGUILayout.MinMaxSlider(ref m_LowThreshold, ref m_HighThreshold, 0f, 1f);
            if (oldLowThreshold != m_LowThreshold)
            {
                EditorPrefs.SetFloat(k_LowThresholdKey, m_LowThreshold);
            }
            if (oldHighThreshold != m_HighThreshold)
            {
                EditorPrefs.SetFloat(k_HighThresholdKey, m_HighThreshold);
            }
            EditorGUILayout.EndVertical();

            // TIME WINDOW
            EditorGUILayout.BeginVertical("box");
            var oldStartTime = m_StartTime;
            var oldEndTime = m_EndTime;

            m_StartTime = EditorGUILayout.FloatField(new GUIContent("Start Time", "Show only data after this time"), m_StartTime);
            m_EndTime = EditorGUILayout.FloatField(new GUIContent("End Time", "Show only data before this time"), m_EndTime);

            m_StartTime = Mathf.Min(m_StartTime, m_EndTime);
            m_EndTime = Mathf.Max(m_StartTime, m_EndTime);

            EditorGUILayout.MinMaxSlider(ref m_StartTime, ref m_EndTime, 0f, m_MaxTime);
            if (GUILayout.Button(new GUIContent("Max Time", "Set time to maximum extents")))
            {
                m_StartTime = 0;
                m_EndTime = m_MaxTime;
            }
            EditorGUILayout.EndVertical();

            EditorGUILayout.BeginVertical("box");

            var oldPlaySpeed = m_PlaySpeed;
            m_PlaySpeed = EditorGUILayout.FloatField(new GUIContent("Play Speed", "Speed at which playback occurs"), m_PlaySpeed);

            if (oldPlaySpeed != m_PlaySpeed)
            {
                EditorPrefs.SetFloat(k_PlaySpeedKey, m_PlaySpeed);
            }

            EditorGUILayout.BeginHorizontal();
            GUIContent restartContent = new GUIContent("<<", "Back to Start");
            if (GUILayout.Button(restartContent))
            {
                Restart();
                m_IsPlaying = false;
            }

            string playTip = m_IsPlaying ? "Pause" : "Play";
            string playText = m_IsPlaying ? "||" : ">";
            GUIContent playContent = new GUIContent(playText, playTip);
            if (GUILayout.Button(playContent))
            {
                if (m_EndTime == m_MaxTime)
                {
                    Restart();
                }
                m_IsPlaying = !m_IsPlaying;
            }
            EditorGUILayout.EndHorizontal();

            bool forceTime = false;
            if (oldStartTime != m_StartTime)
            {
                forceTime = true;
                EditorPrefs.SetFloat(k_StartTimeKey, m_StartTime);
            }
            if (oldEndTime != m_EndTime)
            {
                forceTime = true;
                EditorPrefs.SetFloat(k_EndTimeKey, m_EndTime);
            }

            Update(forceTime);

            EditorGUILayout.EndVertical();

            // PARTICLE SIZE/SHAPE
            EditorGUILayout.BeginVertical("box");
            var oldParticleSize = m_ParticleSize;
            m_ParticleSize = EditorGUILayout.FloatField(new GUIContent("Particle Size", "The display size of an individual data point"), m_ParticleSize);
            m_ParticleSize = Mathf.Max(0.05f, m_ParticleSize);
            if (oldParticleSize != m_ParticleSize)
            {
                EditorPrefs.SetFloat(k_ParticleSizeKey, m_ParticleSize);
            }

            var oldParticleShapeIndex = m_ParticleShapeIndex;
            m_ParticleShapeIndex = EditorGUILayout.Popup(new GUIContent("Particle Shape", "The display shape of an individual data point"), m_ParticleShapeIndex, m_ParticleShapeOptions);
            if (oldParticleShapeIndex != m_ParticleShapeIndex)
            {
                EditorPrefs.SetInt(k_ParticleShapeKey, m_ParticleShapeIndex);
            }

            if (m_ParticleShapeIndex > 0)
            {
                var oldParticleDirectionIndex = m_ParticleDirectionIndex;
                m_ParticleDirectionIndex = EditorGUILayout.Popup(new GUIContent("Billboard plane", "For 2D shapes, the facing direction of an individual data point"), m_ParticleDirectionIndex, m_ParticleDirectionOptions);
                if (oldParticleDirectionIndex != m_ParticleDirectionIndex)
                {
                    EditorPrefs.SetInt(k_ParticleDirectionKey, m_ParticleDirectionIndex);
                }
            }
            EditorGUILayout.EndVertical();

            if (m_GameObject != null && m_GameObject.GetComponent<IHeatmapRenderer>() != null)
            {
                int total = m_GameObject.GetComponent<IHeatmapRenderer>().totalPoints;
                int current = m_GameObject.GetComponent<IHeatmapRenderer>().currentPoints;
                GUILayout.Label("Points in current set: " + total);
                GUILayout.Label("Points currently displayed: " + current);
            }

            // PASS VALUES TO RENDERER
            if (m_GameObject != null)
            {
                IHeatmapRenderer r = m_GameObject.GetComponent<IHeatmapRenderer>() as IHeatmapRenderer;
                r.UpdateColors(new Color[]{ m_LowDensityColor, m_MediumDensityColor, m_HighDensityColor });
                r.UpdateThresholds(new float[]{ m_LowThreshold, m_HighThreshold });
                r.pointSize = m_ParticleSize;
                r.UpdateRenderStyle(m_ParticleShapeIds[m_ParticleShapeIndex], m_ParticleDirectionIds[m_ParticleDirectionIndex]);
            }
        }

        public void Update(bool forceUpdate = false)
        {
            if (m_GameObject != null)
            {
                float oldStartTime = m_StartTime;
                float oldEndTime = m_EndTime;
                UpdateTime();
                if (forceUpdate || oldStartTime != m_StartTime || oldEndTime != m_EndTime)
                {
                    IHeatmapRenderer r = m_GameObject.GetComponent<IHeatmapRenderer>() as IHeatmapRenderer;
                    if (r != null)
                    {
                        r.UpdateTimeLimits(m_StartTime, m_EndTime);
                        m_Heatmapper.Repaint();
                    }
                }
            }
        }

        void UpdateTime()
        {
            if (m_IsPlaying)
            {
                m_StartTime += m_PlaySpeed;
                m_EndTime += m_PlaySpeed;
            }
            if (m_EndTime >= m_MaxTime)
            {
                float diff = m_EndTime - m_StartTime;
                m_EndTime = m_MaxTime;
                m_StartTime = Mathf.Max(m_EndTime - diff, 0);
                m_IsPlaying = false;
            }
        }

        public void SetMaxTime(float maxTime)
        {
            m_EndTime = m_MaxTime = maxTime;
            m_StartTime = 0f;
        }

        void Restart()
        {
            float diff = m_EndTime - m_StartTime;
            m_StartTime = 0;
            m_EndTime = m_StartTime + diff;
        }

        public void SetGameObject(GameObject go)
        {
            m_GameObject = go;
        }

        string FormatColorToString(Color c)
        {
            return c.r + "|" + c.g + "|" + c.b + "|" + c.a;
        }

        Color GetColorFromString(string s, Color defaultColor)
        {
            if (string.IsNullOrEmpty(s))
            {
                return defaultColor;
            }

            string[] cols = s.Split('|');

            float r = 0, g = 0, b = 0, a = 1;
            try
            {
                r = float.Parse(cols[0]);
                g = float.Parse(cols[1]);
                b = float.Parse(cols[2]);
                a = float.Parse(cols[3]);
            }
            catch
            {
                r = 1f;
                g = 1f;
                b = 0f;
                a = 1f;
            }
            return new Color(r, g, b, a);
            ;
        }

        Color SetAndSaveColor(GUIContent content, string key, Color currentColor)
        {
            var oldColor = currentColor;
            Color updatedColor = EditorGUILayout.ColorField(content, currentColor);
            if (oldColor != updatedColor)
            {
                string colorString = FormatColorToString(updatedColor);
                EditorPrefs.SetString(key, colorString);
            }
            return updatedColor;
        }
    }
}


text:
#ifndef CORE_NODE_FACTORY_HH
# define CORE_NODE_FACTORY_HH

# include <ozulis/ast/ast.hh>

namespace ozulis
{
  namespace ast
  {
    class NodeFactory
    {
    public:
      static VoidType * createVoidType();
      static BoolType * createBoolType();
      static FloatType * createFloatType();
      static DoubleType * createDoubleType();
      static IntegerType * createIntegerType(bool isSigned, uint8_t size);
      static PointerType * createConstStringType();

      static RegisterAddress * createRegisterAddress();
      static MemoryAddress * createMemoryAddress();

      static IntegerType * createUIntForPtr();
      static Exp * createSizeofValue(Type * type);
      static CastExp * createCastPtrToUInt(Exp * exp);
      static CastExp * createCastUIntToPtr(Exp * exp, Type * type);
    };
  }
}

#endif /* !CORE_NODE_FACTORY_HH */


text:
package com.fiberlink.elasticsearch.batchmonitor.report;

import org.quartz.JobExecutionContext;

public class ClusterNodeStatisticReport implements Report {

	@Override
	public void createReport() {
		// TODO Auto-generated method stub

	}

	@Override
	public void loadSubscriptionFile() {

	}

	@Override
	public void execute(JobExecutionContext context) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mailReport() {
		// TODO Auto-generated method stub

	}

}


text:
<?php

declare(strict_types=1);

namespace NAttreid\WebManager\Presenters;

use NAttreid\Form\Form;
use Nette\Application\AbortException;
use Nette\Http\FileUpload;
use Nette\Utils\ArrayHash;

/**
 * Hlavni nastaveni stranek
 *
 * @author Attreid <attreid@gmail.com>
 */
class SettingsPresenter extends BasePresenter
{
	/** @var string */
	private $favicon;

	public function setDir(string $dir): void
	{
		$this->favicon = $dir . '/favicon.ico';
	}

	/**
	 * Zobrazeni nastaveni
	 */
	public function renderDefault(): void
	{
		$this['settingsForm']->setDefaults($this->configurator->fetchConfigurations());
	}

	public function handleDeleteFavicon(): void
	{
		@unlink($this->favicon);
		$this->redirect('default');
	}

	/**
	 * Hlavni nastaveni stranek
	 * @return Form
	 */
	protected function createComponentSettingsForm(): Form
	{
		$form = $this->formFactory->create();

		$form->addImageUpload('logo', 'webManager.web.settings.logo', 'webManager.web.settings.deleteLogo')
			->setNamespace('front')
			->setPreview('300x100');
		$form->addText('title', 'webManager.web.settings.pagesTitle');
		$form->addTextArea('keywords', 'webManager.web.settings.keywords');
		$form->addTextArea('description', 'webManager.web.settings.description');
		$form->addUpload('favicon', 'webManager.web.settings.favicon');
		if (file_exists($this->favicon)) {
			$form->addLink('faviconDelete', 'webManager.web.settings.faviconDelete', $this->link('deleteFavicon!'))
				->setAttribute('class', 'btn-danger');
		}

		$form->addSubmit('save', 'form.save');

		$form->onSuccess[] = [$this, 'settingsFormSucceeded'];

		return $form;
	}

	/**
	 * Ulozeni hlavniho nastaveni
	 * @param Form $form
	 * @param array $values
	 * @throws AbortException
	 */
	public function settingsFormSucceeded(Form $form, ArrayHash $values): void
	{
		$this->configurator->logo = $values->logo;
		$this->configurator->title = $values->title;
		$this->configurator->keywords = $values->keywords;
		$this->configurator->description = $values->description;

		/* @var $favicon FileUpload */
		$favicon = $values->favicon;
		if ($values->favicon !== null && $favicon->isOk()) {
			$favicon->move($this->favicon);
		}

		$this->flashNotifier->success('webManager.web.settings.saved');

		if ($this->isAjax()) {
			$this->redrawControl('settings');
		} else {
			$this->redirect('default');
		}
	}

}


text:
package org.springframework.messaging.simp.stomp;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.TransportConnector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageDeliveryException;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.StubMessageChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.broker.BrokerAvailabilityEvent;
import org.springframework.messaging.support.ExecutorSubscribableChannel;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.tcp.TcpOperations;
import org.springframework.util.Assert;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

/**
 * Integration tests for {@link StompBrokerRelayMessageHandler} running against ActiveMQ.
 *
 * @author Rossen Stoyanchev
 */
public abstract class AbstractStompBrokerRelayIntegrationTests {

	private static final Log logger = LogFactory.getLog(AbstractStompBrokerRelayIntegrationTests.class);

	private StompBrokerRelayMessageHandler relay;

	private BrokerService activeMQBroker;

	private ExecutorSubscribableChannel responseChannel;

	private TestMessageHandler responseHandler;

	private TestEventPublisher eventPublisher;

	// initial value of zero implies that a random ephemeral port should be used
	private int port = 0;

	@BeforeEach
	public void setup(TestInfo testInfo) throws Exception {
		logger.debug("Setting up before '" + testInfo.getTestMethod().get().getName() + "'");

		this.responseChannel = new ExecutorSubscribableChannel();
		this.responseHandler = new TestMessageHandler();
		this.responseChannel.subscribe(this.responseHandler);
		this.eventPublisher = new TestEventPublisher();
		startActiveMQBroker();
		createAndStartRelay();
	}

	private void startActiveMQBroker() throws Exception {
		TransportConnector stompConnector = createStompConnector(this.port);
		this.activeMQBroker = new BrokerService();
		this.activeMQBroker.addConnector(stompConnector);
		this.activeMQBroker.setStartAsync(false);
		this.activeMQBroker.setPersistent(false);
		this.activeMQBroker.setUseJmx(false);
		this.activeMQBroker.getSystemUsage().getMemoryUsage().setLimit(1024 * 1024 * 5);
		this.activeMQBroker.getSystemUsage().getTempUsage().setLimit(1024 * 1024 * 5);
		this.activeMQBroker.start();

		// Reuse existing ephemeral port on restart (i.e., the next time this method
		// is invoked) since it will already be configured in the relay
		this.port = (this.port != 0 ? this.port : stompConnector.getServer().getSocketAddress().getPort());
	}

	private TransportConnector createStompConnector(int port) throws Exception {
		TransportConnector connector = new TransportConnector();
		connector.setUri(new URI("stomp://localhost:" + port));
		return connector;
	}

	private void createAndStartRelay() throws InterruptedException {
		StubMessageChannel channel = new StubMessageChannel();
		List<String> prefixes = Arrays.asList("/queue/", "/topic/");
		this.relay = new StompBrokerRelayMessageHandler(channel, this.responseChannel, channel, prefixes);
		this.relay.setRelayPort(this.port);
		this.relay.setApplicationEventPublisher(this.eventPublisher);
		this.relay.setSystemHeartbeatReceiveInterval(0);
		this.relay.setSystemHeartbeatSendInterval(0);
		this.relay.setPreservePublishOrder(true);

		TcpOperations<byte[]> tcpClient = initTcpClient(this.port);
		this.relay.setTcpClient(tcpClient);

		this.relay.start();
		this.eventPublisher.expectBrokerAvailabilityEvent(true);
	}

	protected abstract TcpOperations<byte[]> initTcpClient(int port);

	@AfterEach
	public void stop() throws Exception {
		try {
			logger.debug("STOMP broker relay stats: " + this.relay.getStatsInfo());
			this.relay.stop();
		}
		finally {
			stopActiveMqBrokerAndAwait();
		}
	}

	private void stopActiveMqBrokerAndAwait() throws Exception {
		logger.debug("Stopping ActiveMQ broker and will await shutdown");
		if (!this.activeMQBroker.isStarted()) {
			logger.debug("Broker not running");
			return;
		}
		final CountDownLatch latch = new CountDownLatch(1);
		this.activeMQBroker.addShutdownHook(latch::countDown);
		this.activeMQBroker.stop();
		assertThat(latch.await(5, TimeUnit.SECONDS)).as("Broker did not stop").isTrue();
		logger.debug("Broker stopped");
	}

	@Test
	public void publishSubscribe() throws Exception {
		logger.debug("Starting test publishSubscribe()");

		String sess1 = "sess1";
		String sess2 = "sess2";
		String subs1 = "subs1";
		String destination = "/topic/test";

		MessageExchange conn1 = MessageExchangeBuilder.connect(sess1).build();
		MessageExchange conn2 = MessageExchangeBuilder.connect(sess2).build();
		this.relay.handleMessage(conn1.message);
		this.relay.handleMessage(conn2.message);
		this.responseHandler.expectMessages(conn1, conn2);

		MessageExchange subscribe = MessageExchangeBuilder.subscribeWithReceipt(sess1, subs1, destination, "r1").build();
		this.relay.handleMessage(subscribe.message);
		this.responseHandler.expectMessages(subscribe);

		MessageExchange send = MessageExchangeBuilder.send(destination, "foo").andExpectMessage(sess1, subs1).build();
		this.relay.handleMessage(send.message);
		this.responseHandler.expectMessages(send);
	}

	@Test
	public void messageDeliveryExceptionIfSystemSessionForwardFails() throws Exception {
		logger.debug("Starting test messageDeliveryExceptionIfSystemSessionForwardFails()");

		stopActiveMqBrokerAndAwait();
		this.eventPublisher.expectBrokerAvailabilityEvent(false);

		StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SEND);
		assertThatExceptionOfType(MessageDeliveryException.class).isThrownBy(() ->
				this.relay.handleMessage(MessageBuilder.createMessage("test".getBytes(), headers.getMessageHeaders())));
	}

	@Test
	public void brokerBecomingUnavailableTriggersErrorFrame() throws Exception {
		logger.debug("Starting test brokerBecomingUnavailableTriggersErrorFrame()");

		String sess1 = "sess1";
		MessageExchange connect = MessageExchangeBuilder.connect(sess1).build();
		this.relay.handleMessage(connect.message);
		this.responseHandler.expectMessages(connect);

		MessageExchange error = MessageExchangeBuilder.error(sess1).build();
		stopActiveMqBrokerAndAwait();
		this.eventPublisher.expectBrokerAvailabilityEvent(false);
		this.responseHandler.expectMessages(error);
	}

	@Test
	public void brokerAvailabilityEventWhenStopped() throws Exception {
		logger.debug("Starting test brokerAvailabilityEventWhenStopped()");

		stopActiveMqBrokerAndAwait();
		this.eventPublisher.expectBrokerAvailabilityEvent(false);
	}

	@Test
	public void relayReconnectsIfBrokerComesBackUp() throws Exception {
		logger.debug("Starting test relayReconnectsIfBrokerComesBackUp()");

		String sess1 = "sess1";
		MessageExchange conn1 = MessageExchangeBuilder.connect(sess1).build();
		this.relay.handleMessage(conn1.message);
		this.responseHandler.expectMessages(conn1);

		String subs1 = "subs1";
		String destination = "/topic/test";
		MessageExchange subscribe = MessageExchangeBuilder.subscribeWithReceipt(sess1, subs1, destination, "r1").build();
		this.relay.handleMessage(subscribe.message);
		this.responseHandler.expectMessages(subscribe);

		MessageExchange error = MessageExchangeBuilder.error(sess1).build();
		stopActiveMqBrokerAndAwait();
		this.responseHandler.expectMessages(error);

		this.eventPublisher.expectBrokerAvailabilityEvent(false);

		startActiveMQBroker();
		this.eventPublisher.expectBrokerAvailabilityEvent(true);
	}

	@Test
	public void disconnectWithReceipt() throws Exception {
		logger.debug("Starting test disconnectWithReceipt()");

		MessageExchange connect = MessageExchangeBuilder.connect("sess1").build();
		this.relay.handleMessage(connect.message);
		this.responseHandler.expectMessages(connect);

		MessageExchange disconnect = MessageExchangeBuilder.disconnectWithReceipt("sess1", "r123").build();
		this.relay.handleMessage(disconnect.message);

		this.responseHandler.expectMessages(disconnect);
	}

	private static class TestEventPublisher implements ApplicationEventPublisher {

		private final BlockingQueue<BrokerAvailabilityEvent> eventQueue = new LinkedBlockingQueue<>();

		@Override
		public void publishEvent(ApplicationEvent event) {
			publishEvent((Object) event);
		}

		@Override
		public void publishEvent(Object event) {
			logger.debug("Processing ApplicationEvent " + event);
			if (event instanceof BrokerAvailabilityEvent) {
				this.eventQueue.add((BrokerAvailabilityEvent) event);
			}
		}

		public void expectBrokerAvailabilityEvent(boolean isBrokerAvailable) throws InterruptedException {
			BrokerAvailabilityEvent event = this.eventQueue.poll(20000, TimeUnit.MILLISECONDS);
			assertThat(event).as("Times out waiting for BrokerAvailabilityEvent[" + isBrokerAvailable + "]").isNotNull();
			assertThat(event.isBrokerAvailable()).isEqualTo(isBrokerAvailable);
		}
	}

	private static class TestMessageHandler implements MessageHandler {

		private final BlockingQueue<Message<?>> queue = new LinkedBlockingQueue<>();

		@Override
		public void handleMessage(Message<?> message) throws MessagingException {
			if (SimpMessageType.HEARTBEAT == SimpMessageHeaderAccessor.getMessageType(message.getHeaders())) {
				return;
			}
			this.queue.add(message);
		}

		public void expectMessages(MessageExchange... messageExchanges) throws InterruptedException {
			List<MessageExchange> expectedMessages = new ArrayList<>(Arrays.asList(messageExchanges));
			while (expectedMessages.size() > 0) {
				Message<?> message = this.queue.poll(10000, TimeUnit.MILLISECONDS);
				assertThat(message).as("Timed out waiting for messages, expected [" + expectedMessages + "]").isNotNull();
				MessageExchange match = findMatch(expectedMessages, message);
				assertThat(match).as("Unexpected message=" + message + ", expected [" + expectedMessages + "]").isNotNull();
				expectedMessages.remove(match);
			}
		}

		private MessageExchange findMatch(List<MessageExchange> expectedMessages, Message<?> message) {
			for (MessageExchange exchange : expectedMessages) {
				if (exchange.matchMessage(message)) {
					return exchange;
				}
			}
			return null;
		}
	}

	/**
	 * Holds a message as well as expected and actual messages matched against expectations.
	 */
	private static class MessageExchange {

		private final Message<?> message;

		private final MessageMatcher[] expected;

		private final Message<?>[] actual;

		public MessageExchange(Message<?> message, MessageMatcher... expected) {
			this.message = message;
			this.expected = expected;
			this.actual = new Message<?>[expected.length];
		}

		public boolean matchMessage(Message<?> message) {
			for (int i = 0 ; i < this.expected.length; i++) {
				if (this.expected[i].match(message)) {
					this.actual[i] = message;
					return true;
				}
			}
			return false;
		}

		@Override
		public String toString() {
			return "Forwarded message:\n" + this.message + "\n" +
					"Should receive back:\n" + Arrays.toString(this.expected) + "\n" +
					"Actually received:\n" + Arrays.toString(this.actual) + "\n";
		}
	}

	private static class MessageExchangeBuilder {

		private final Message<?> message;

		private final StompHeaderAccessor headers;

		private final List<MessageMatcher> expected = new ArrayList<>();

		public MessageExchangeBuilder(Message<?> message) {
			this.message = message;
			this.headers = StompHeaderAccessor.wrap(message);
		}

		public static MessageExchangeBuilder error(String sessionId) {
			return new MessageExchangeBuilder(null).andExpectError(sessionId);
		}

		public static MessageExchangeBuilder connect(String sessionId) {
			StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT);
			headers.setSessionId(sessionId);
			headers.setAcceptVersion("1.1,1.2");
			headers.setHeartbeat(0, 0);
			Message<?> message = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders());

			MessageExchangeBuilder builder = new MessageExchangeBuilder(message);
			builder.expected.add(new StompConnectedFrameMessageMatcher(sessionId));
			return builder;
		}

		// TODO Determine why connectWithError() is unused.
		@SuppressWarnings("unused")
		public static MessageExchangeBuilder connectWithError(String sessionId) {
			StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT);
			headers.setSessionId(sessionId);
			headers.setAcceptVersion("1.1,1.2");
			Message<?> message = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders());
			MessageExchangeBuilder builder = new MessageExchangeBuilder(message);
			return builder.andExpectError();
		}

		public static MessageExchangeBuilder subscribeWithReceipt(String sessionId, String subscriptionId,
				String destination, String receiptId) {

			StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
			headers.setSessionId(sessionId);
			headers.setSubscriptionId(subscriptionId);
			headers.setDestination(destination);
			headers.setReceipt(receiptId);
			Message<?> message = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders());

			MessageExchangeBuilder builder = new MessageExchangeBuilder(message);
			builder.expected.add(new StompReceiptFrameMessageMatcher(sessionId, receiptId));
			return builder;
		}

		public static MessageExchangeBuilder send(String destination, String payload) {
			SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
			headers.setDestination(destination);
			Message<?> message = MessageBuilder.createMessage(payload.getBytes(StandardCharsets.UTF_8),
					headers.getMessageHeaders());
			return new MessageExchangeBuilder(message);
		}

		public static MessageExchangeBuilder disconnectWithReceipt(String sessionId, String receiptId) {
			StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.DISCONNECT);
			headers.setSessionId(sessionId);
			headers.setReceipt(receiptId);
			Message<?> message = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders());

			MessageExchangeBuilder builder = new MessageExchangeBuilder(message);
			builder.expected.add(new StompReceiptFrameMessageMatcher(sessionId, receiptId));
			return builder;
		}

		public MessageExchangeBuilder andExpectMessage(String sessionId, String subscriptionId) {
			Assert.state(SimpMessageType.MESSAGE.equals(this.headers.getMessageType()), "MESSAGE type expected");
			String destination = this.headers.getDestination();
			Object payload = this.message.getPayload();
			this.expected.add(new StompMessageFrameMessageMatcher(sessionId, subscriptionId, destination, payload));
			return this;
		}

		public MessageExchangeBuilder andExpectError() {
			String sessionId = this.headers.getSessionId();
			Assert.state(sessionId != null, "No sessionId to match the ERROR frame to");
			return andExpectError(sessionId);
		}

		public MessageExchangeBuilder andExpectError(String sessionId) {
			this.expected.add(new StompFrameMessageMatcher(StompCommand.ERROR, sessionId));
			return this;
		}

		public MessageExchange build() {
			return new MessageExchange(this.message, this.expected.toArray(new MessageMatcher[this.expected.size()]));
		}
	}

	private interface MessageMatcher {

		boolean match(Message<?> message);
	}

	private static class StompFrameMessageMatcher implements MessageMatcher {

		private final StompCommand command;

		private final String sessionId;

		public StompFrameMessageMatcher(StompCommand command, String sessionId) {
			this.command = command;
			this.sessionId = sessionId;
		}

		@Override
		public final boolean match(Message<?> message) {
			StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
			if (!this.command.equals(headers.getCommand()) || !this.sessionId.equals(headers.getSessionId())) {
				return false;
			}
			return matchInternal(headers, message.getPayload());
		}

		protected boolean matchInternal(StompHeaderAccessor headers, Object payload) {
			return true;
		}

		@Override
		public String toString() {
			return "command=" + this.command  + ", session=\"" + this.sessionId + "\"";
		}
	}

	private static class StompReceiptFrameMessageMatcher extends StompFrameMessageMatcher {

		private final String receiptId;

		public StompReceiptFrameMessageMatcher(String sessionId, String receipt) {
			super(StompCommand.RECEIPT, sessionId);
			this.receiptId = receipt;
		}

		@Override
		protected boolean matchInternal(StompHeaderAccessor headers, Object payload) {
			return (this.receiptId.equals(headers.getReceiptId()));
		}

		@Override
		public String toString() {
			return super.toString() + ", receiptId=\"" + this.receiptId + "\"";
		}
	}

	private static class StompMessageFrameMessageMatcher extends StompFrameMessageMatcher {

		private final String subscriptionId;

		private final String destination;

		private final Object payload;

		public StompMessageFrameMessageMatcher(String sessionId, String subscriptionId, String destination, Object payload) {
			super(StompCommand.MESSAGE, sessionId);
			this.subscriptionId = subscriptionId;
			this.destination = destination;
			this.payload = payload;
		}

		@Override
		protected boolean matchInternal(StompHeaderAccessor headers, Object payload) {
			if (!this.subscriptionId.equals(headers.getSubscriptionId()) ||
					!this.destination.equals(headers.getDestination())) {

				return false;
			}
			if (payload instanceof byte[] && this.payload instanceof byte[]) {
				return Arrays.equals((byte[]) payload, (byte[]) this.payload);
			}
			else {
				return this.payload.equals(payload);
			}
		}

		@Override
		public String toString() {
			return super.toString() + ", subscriptionId=\"" + this.subscriptionId
					+ "\", destination=\"" + this.destination + "\", payload=\"" + getPayloadAsText() + "\"";
		}

		protected String getPayloadAsText() {
			return (this.payload instanceof byte[]) ?
					new String((byte[]) this.payload, StandardCharsets.UTF_8) : this.payload.toString();
		}
	}

	private static class StompConnectedFrameMessageMatcher extends StompFrameMessageMatcher {

		public StompConnectedFrameMessageMatcher(String sessionId) {
			super(StompCommand.CONNECTED, sessionId);
		}
	}

}


text: <!doctype html>