text:
namespace base {
class Value;
}

namespace extensions {
class RequestSender;

// Functions exposed to extension JS to implement the setIcon extension API.
class SetIconNatives : public ChromeV8Extension {
 public:
  SetIconNatives(Dispatcher* dispatcher,
                 RequestSender* request_sender,
                 ChromeV8Context* context);

 private:
  bool ConvertImageDataToBitmapValue(const v8::Local<v8::Object> image_data,
                                     Value** bitmap_value);
  bool ConvertImageDataSetToBitmapValueSet(
      const v8::FunctionCallbackInfo<v8::Value>& args,
      base::DictionaryValue* bitmap_value);
  void SetIconCommon(const v8::FunctionCallbackInfo<v8::Value>& args);

  RequestSender* request_sender_;

  DISALLOW_COPY_AND_ASSIGN(SetIconNatives);
};

}  // namespace extensions

#endif  // CHROME_RENDERER_EXTENSIONS_SET_ICON_NATIVES_H_


text:
#ifndef MULTIOBJECTIVEEVALUATION_H_
#define MULTIOBJECTIVEEVALUATION_H_

#include "Individual.h"

/**
 * A class which evaluate multiobjective individuals.
 */
class MultiObjectiveEvaluation
{

protected:

	/**
	 * Default constructor.
	 */
	MultiObjectiveEvaluation();

public:

	/**
	 * Default destructor.
	 */
	virtual ~MultiObjectiveEvaluation();

	/**
	 * A method to assing the objectives values to an individual.
	 */
	virtual void evaluate(Individual* individual);
};

#endif /*MULTIOBJECTIVEEVALUATION_H_*/

redpajama_set_name: RedPajamaGithub


text:
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'benchmark/ips'

def log_block(&block); nil; end
def log(string); nil; end

first, second, third = %w{foo bar baz}

Benchmark.ips do |x|
  x.report('interpolation no var') do
    log "so simple"
  end

  x.report('interpolation 1 var') do
    log "my #{first} var"
  end

  x.report('interpolation 2 var') do
    log "my #{first} var is #{second}"
  end

  x.report('interpolation 3 var') do
    log "my #{first} var is #{second} and #{third}"
  end

  x.report('block no var') do
    log_block { "so simple" }
  end

  x.report('block 1 var') do
    log_block { "my #{first} var" }
  end

  x.report('block 2 var') do
    log_block { "my #{first} var is #{second}" }
  end

  x.report('block 3 var') do
    log_block { "my #{first} var is #{second} and #{third}" }
  end
end


text:
App.CommentActivity = Ember.Object.extend({
  someProperty: function(){
    console.log('hello');
  }.property('hello')
});


text:
from codecs import open  # To use a consistent encoding
from os import path

from setuptools import setup

HERE = path.dirname(path.abspath(__file__))

# Get version info
ABOUT = {}
with open(path.join(HERE, 'datadog_checks', 'gatekeeper', '__about__.py')) as f:
    exec(f.read(), ABOUT)

# Get the long description from the README file
with open(path.join(HERE, 'README.md'), encoding='utf-8') as f:
    long_description = f.read()

def get_dependencies():
    dep_file = path.join(HERE, 'requirements.in')
    if not path.isfile(dep_file):
        return []

    with open(dep_file, encoding='utf-8') as f:
        return f.readlines()

def parse_pyproject_array(name):
    import os
    import re
    from ast import literal_eval

    pattern = r'^{} = (\[.*?\])$'.format(name)

    with open(os.path.join(HERE, 'pyproject.toml'), 'r', encoding='utf-8') as f:
        # Windows \r\n prevents match
        contents = '\n'.join(line.rstrip() for line in f.readlines())

    array = re.search(pattern, contents, flags=re.MULTILINE | re.DOTALL).group(1)
    return literal_eval(array)

CHECKS_BASE_REQ = parse_pyproject_array('dependencies')[0]

setup(
    name='datadog-gatekeeper',
    version=ABOUT['__version__'],
    description='The Gatekeeper check',
    long_description=long_description,
    long_description_content_type='text/markdown',
    keywords='datadog agent gatekeeper check',
    # The project's main homepage.
    url='https://github.com/DataDog/integrations-extras',
    # Author details
    author='Ara Pulido',
    author_email='ara.pulido@datadoghq.com',
    # License
    license='BSD-3-Clause',
    # See https://pypi.org/classifiers
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'Topic :: System :: Monitoring',
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.8',
    ],
    # The package we're going to ship
    packages=['datadog_checks.gatekeeper'],
    # Run-time dependencies
    install_requires=[CHECKS_BASE_REQ],
    extras_require={'deps': parse_pyproject_array('deps')},
    # Extra files to ship with the wheel package
    include_package_data=True,
)


text:
class ScheduleUpdateUserActivityWorker
  include Sidekiq::Worker
  include CronjobQueue

  def perform(batch_size = 500)
    Gitlab::UserActivities.new.each_slice(batch_size) do |batch|
      UpdateUserActivityWorker.perform_async(Hash[batch])
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="loading"
        android:padding="4dip"
        android:textSize="16sp"
        />

    <WebView
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        />

</LinearLayout>


text:
FROM openshift/origin-source

COPY *.repo /etc/yum.repos.d/
RUN INSTALL_PKGS=" \
      which git tar wget hostname sysvinit-tools util-linux bsdtar \
      socat ethtool device-mapper iptables tree findutils nmap-ncat e2fsprogs \
      xfsprogs lsof device-mapper-persistent-data ceph-common \
      " && \
    yum install -y centos-release-ceph-luminous && \
    rpm -V centos-release-ceph-luminous && \
    yum install -y ${INSTALL_PKGS} && \
    rpm -V ${INSTALL_PKGS} && \
    yum clean all && \
    mkdir -p /var/lib/origin

LABEL io.k8s.display-name="OpenShift Origin CentOS 7 Base" \
      io.k8s.description="This is the base image from which all OpenShift Origin images inherit." \
      io.openshift.tags="openshift,base"


text:
.row0{
 background:white;
 background-color: #fff;
}
.row1{
 background:black;
 background-color: #ccc;
}

table	{ margin-left: auto;	margin-right: auto;	}
table.info th, table.info td    {border: 1px solid green}
table.info thead        {color: white; background-color: rgb(20, 150, 20)}
table.info col.firstcol {background-color: rgb(255, 55, 12); width: 2%}
table.info col.dayCols  {width: 3%}
table.info thead tr     {height: 20px}
table.info tbody tr     {height: 30px}
table.info tbody td     {vertical-align: top; padding: 3px}
table.info caption      {caption-side: top; text-align: right}

.menu{
	border:none;
	border:0px;
	margin:0px;
	margin-top: -40px;
	padding:0px;
	font: 67.5% "Lucida Sans Unicode", "Bitstream Vera Sans", "Trebuchet Unicode MS", "Lucida Grande", Verdana, Helvetica, sans-serif;
	font-size:14px;
	font-weight:bold;
	}
.menu ul{
	background:#333333;
	height:35px;
	list-style:none;
	margin:0;
	padding:0;
	}
	.menu li{
		float:left;
		padding:0px;
		}
	.menu li a{
		background:#333333 url("../images/separator.gif") bottom right no-repeat;
		color:#cccccc;
		display:block;
		font-weight:normal;
		line-height:35px;
		margin:0px;
		padding:0px 25px;
		text-align:center;
		text-decoration:none;
		}
		.menu li a:hover, .menu ul li:hover a{
			background: #2580a2 url("../images/hover.gif") bottom center no-repeat;
			color:#FFFFFF;
			text-decoration:none;
			}
	.menu li ul{
		background:#333333;
		display:none;
		height:auto;
		padding:0px;
		margin:0px;
		border:0px;
		position:absolute;
		width:225px;
		z-index:200;
		/*top:1em;
		/*left:0;*/
		}
	.menu li:hover ul{
		display:block;

		}
	.menu li li {
		background:url('images/sub_sep.gif') bottom left no-repeat;
		display:block;
		float:none;
		margin:0px;
		padding:0px;
		width:225px;
		}
	.menu li:hover li a{
		background:none;

		}
	.menu li ul a{
		display:block;
		height:35px;
		font-size:12px;
		font-style:normal;
		margin:0px;
		padding:0px 10px 0px 15px;
		text-align:left;
		}
		.menu li ul a:hover, .menu li ul li:hover a{
			background:#2580a2 url('images/hover_sub.gif') center left no-repeat;
			border:0px;
			color:#ffffff;
			text-decoration:none;
			}
	.menu p{
		clear:left;
		}

.image-center{
	margin-left: 400px;
	margin-top: 130px;
}


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using System.Web.Http.OData;
using System.Web.Http.OData.Routing;
using Northwind.EF;

namespace aurelia_axel.Controllers
{
    /*
    The WebApiConfig class may require additional changes to add a route for this controller. Merge these statements into the Register method of the WebApiConfig class as applicable. Note that OData URLs are case sensitive.

    using System.Web.Http.OData.Builder;
    using System.Web.Http.OData.Extensions;
    using Northwind.EF;
    ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
    builder.EntitySet<Customer>("Customers");
    builder.EntitySet<Order>("Orders");
    config.Routes.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());
    */
    public class CustomersController : ODataController
    {
        private NorthwindEntities db = new NorthwindEntities();

        // GET: odata/Customers
        [EnableQuery(MaxExpansionDepth = 4)]
        public IQueryable<Customer> GetCustomers()
        {
            return db.Customers;
        }

        // GET: odata/Customers(5)
        [EnableQuery(MaxExpansionDepth = 4)]
        public SingleResult<Customer> GetCustomer([FromODataUri] string key)
        {
            return SingleResult.Create(db.Customers.Where(customer => customer.CustomerID == key));
        }

        // PUT: odata/Customers(5)
        public async Task<IHttpActionResult> Put([FromODataUri] string key, Delta<Customer> patch)
        {
            Validate(patch.GetEntity());

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            Customer customer = await db.Customers.FindAsync(key);
            if (customer == null)
            {
                return NotFound();
            }

            patch.Put(customer);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CustomerExists(key))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Updated(customer);
        }

        // POST: odata/Customers
        public async Task<IHttpActionResult> Post(Customer customer)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Customers.Add(customer);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (CustomerExists(customer.CustomerID))
                {
                    return Conflict();
                }
                else
                {
                    throw;
                }
            }

            return Created(customer);
        }

        // PATCH: odata/Customers(5)
        [AcceptVerbs("PATCH", "MERGE")]
        public async Task<IHttpActionResult> Patch([FromODataUri] string key, Delta<Customer> patch)
        {
            Validate(patch.GetEntity());

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            Customer customer = await db.Customers.FindAsync(key);
            if (customer == null)
            {
                return NotFound();
            }

            patch.Patch(customer);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CustomerExists(key))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Updated(customer);
        }

        // DELETE: odata/Customers(5)
        public async Task<IHttpActionResult> Delete([FromODataUri] string key)
        {
            Customer customer = await db.Customers.FindAsync(key);
            if (customer == null)
            {
                return NotFound();
            }

            db.Customers.Remove(customer);
            await db.SaveChangesAsync();

            return StatusCode(HttpStatusCode.NoContent);
        }

        // GET: odata/Customers(5)/Orders
        [EnableQuery]
        public IQueryable<Order> GetOrders([FromODataUri] string key)
        {
            return db.Customers.Where(m => m.CustomerID == key).SelectMany(m => m.Orders);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool CustomerExists(string key)
        {
            return db.Customers.Count(e => e.CustomerID == key) > 0;
        }
    }
}


text:
package net.lecousin.framework.core.tests.io;

import java.io.File;
import java.util.Collection;
import java.util.LinkedList;

import net.lecousin.framework.concurrent.threads.Task;
import net.lecousin.framework.core.test.io.TestReadWrite;
import net.lecousin.framework.core.test.runners.LCConcurrentRunner;
import net.lecousin.framework.io.FileIO;
import net.lecousin.framework.io.SubIO;

import org.junit.runner.RunWith;
import org.junit.runners.Parameterized.Parameters;

@RunWith(LCConcurrentRunner.Parameterized.class) @org.junit.runners.Parameterized.UseParametersRunnerFactory(LCConcurrentRunner.ConcurrentParameterizedRunnedFactory.class)
public class TestSubIOReadWrite extends TestReadWrite {

	@Parameters(name = "nbBuf = {1}, nbBufSkippedStart = {2}, nbBufSkippedEnd = {3}")
	public static Collection<Object[]> parameters() {
		Collection<Object[]> base = generateTestCases(false);
		LinkedList<Object[]> list = new LinkedList<>();
		for (Object[] params : base) {
			int nbBuf = ((Integer)params[1]).intValue();
			if (nbBuf <= 1000)
				list.add(createParams(params, 0, 0));
			if (nbBuf < 80) continue;
			if (nbBuf <= 100)
				list.add(createParams(params, 60, 15));
			else if (nbBuf <= 1000)
				list.add(createParams(params, 700, 50));
			else if (nbBuf <= 100000)
				list.add(createParams(params, 80000, 5000));
			else
				list.add(createParams(params, nbBuf - 50000, 20000));
		}
		return list;
	}
	private static Object[] createParams(Object[] original, int skipStart, int skipEnd) {
		return new Object[] { original[0], original[1], Integer.valueOf(skipStart), Integer.valueOf(skipEnd) };
	}

	public TestSubIOReadWrite(byte[] testBuf, int nbBuf, int nbBufSkippedStart, int nbBufSkippedEnd) {
		super(testBuf, nbBuf - nbBufSkippedStart - nbBufSkippedEnd);
		this.nbBufSkippedStart = nbBufSkippedStart;
		this.nbBufSkippedEnd = nbBufSkippedEnd;
	}

	protected int nbBufSkippedStart;
	protected int nbBufSkippedEnd;

	@SuppressWarnings("unchecked")
	@Override
	protected SubIO.ReadWrite openReadWrite() throws Exception {
		File tmpFile = File.createTempFile("test", "fileio.rw");
		tmpFile.deleteOnExit();
		FileIO.ReadWrite fio = new FileIO.ReadWrite(tmpFile, Task.Priority.NORMAL);
		long size = nbBuf * testBuf.length;
		fio.setSizeSync(size + (nbBufSkippedStart + nbBufSkippedEnd) * testBuf.length);
		return new SubIO.ReadWrite(fio, nbBufSkippedStart * testBuf.length, size, "test subio", true);
	}

}


text:
using System;
using Foundation;

[assembly: LinkerSafe]

namespace Square.SocketRocket
{
	partial class WebSocket
	{
		public void SendPing ()
		{
			SendPing (null);
		}
	}
}


text:
class ResourceFileType < ApplicationRecord
  has_many :resource_files

  validates :title, :position, presence: true
  validates :position, numericality: true
end


text:
package Debconf::Element::Dialog::Multiselect;
use strict;
use base qw(Debconf::Element::Multiselect);
use Debconf::Encoding qw(width);

sub show {
	my $this=shift;

	my ($text, $lines, $columns)=
		$this->frontend->makeprompt($this->question, -2);

	my $screen_lines=$this->frontend->screenheight - $this->frontend->spacer;
	my @params=();
	my @choices=$this->question->choices_split;
	my %value = map { $_ => 1 } $this->translate_default;

	my $menu_height=$#choices + 1;
	if ($lines + $#choices + 2 >= $screen_lines) {
		$menu_height = $screen_lines - $lines - 4;
		if ($menu_height < 3 && $#choices + 1 > 2) {
			$this->frontend->showtext($this->question, $this->question->extended_description);
			($text, $lines, $columns)=$this->frontend->sizetext($this->question->description);
			$menu_height=$#choices + 1;
			if ($lines + $#choices + 2 >= $screen_lines) {
				$menu_height = $screen_lines - $lines - 4;
			}
		}
	}

	$lines=$lines + $menu_height + $this->frontend->spacer;
	my $selectspacer = $this->frontend->selectspacer;
	my $c=1;
	foreach (@choices) {
		push @params, ($_, "");
		push @params, ($value{$_} ? 'on' : 'off');

		if ($columns < width($_) + $selectspacer) {
			$columns = width($_) + $selectspacer;
		}
	}

	if ($this->frontend->dashsep) {
		unshift @params, $this->frontend->dashsep;
	}

	@params=('--separate-output', '--checklist',
	         $text, $lines, $columns, $menu_height, @params);

	my $value=$this->frontend->showdialog($this->question, @params);

	if (defined $value) {
		$this->value(join(", ", $this->order_values(
					map { $this->translate_to_C($_) }
					split(/\n/, $value))));
	}
	else {
		my $default='';
		$default=$this->question->value
			if defined $this->question->value;
		$this->value($default);
	}
}

1


text:
  Germaine est
       un village
       situé dans le département de l'Aisne en Picardie. On dénombrait 66 habitants en 2008.

Le nombre d'habitations, à Germaine, était réparti en 2011 en zero appartements et 31 maisons soit
 un marché relativement équilibré.

À coté de Germaine sont situées les communes de
Lanchy située à 3 km, 57 habitants,
Beauvois-en-Vermandois localisée à 2 km, 283 habitants,
Étreillers à 3 km, 1 081 habitants,
Villers-Saint-Christophe située à 3 km, 456 habitants,
Aubigny-aux-Kaisnes localisée à 4 km, 247 habitants,
Douchy située à 2 km, 144 habitants,
 entre autres. De plus, Germaine est située à seulement treize km de Saint-Quentin.

Si vous pensez demenager à Germaine, vous pourrez facilement trouver une maison à vendre.


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>unescape</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="index.html" title="Smarty 3 Manual">
<link rel="up" href="language.modifiers.html"
	title="Chapter 5. Variable Modifiers">
<link rel="prev" href="language.modifier.truncate.html" title="truncate">
<link rel="next" href="language.modifier.upper.html" title="upper">

				unescape

				Prev
				Chapter 5. Variable Modifiers
				 Next

						unescape

			unescape
			is used to decode
			entity
			,
			html
			and
			htmlall
			. It counters the effects of the escape
				modifier for the given types.

				<colgroup>
					<col align="center">
					<col align="center">
					<col align="center">
					<col align="center">
					<col align="center">
					<col>
				</colgroup>

						Parameter Position
						Type
						Required
						Possible Values
						Default
						Description

						1
						string
						No
						html, htmlall, entity,

						html
						This is the escape format to use.

						2
						string
						No
						ISO-8859-1, UTF-8, and any character set supported by

								htmlentities()

						UTF-8
						The character set encoding passed to html_entity_decode()
							or htmlspecialchars_decode() or mb_convert_encoding() et. al.

				Example 5.22. escape

<?php

$smarty->assign('articleTitle',
                "Germans use &quot;&Uuml;mlauts&quot; and pay in &euro;uro"
                );

?>

					These are example
					unescape
					template lines followed by the output

{$articleTitle}
Germans use &quot;&Uuml;mlauts&quot; and pay in &euro;uro

{$articleTitle|unescape:"html"}
Germans use "&Uuml;mlauts" and pay in &euro;uro

{$articleTitle|unescape:"htmlall"}
Germans use "Ümlauts" and pay in €uro

			See also escaping smarty parsing, escape
				modifier.

				Prev
				Up
				 Next

				truncate
				Home
				 upper


text:
using System;
using System.Collections;
using System.Drawing;

#if GTK
using Gtk;
using Compatibility.Gtk;

#else
using System.Windows.Forms;
#endif

namespace SmartQuant.FinChart
{
    public enum PadScaleStyle
    {
        Arith,
        Log
    }

    public interface IChartDrawable
    {
        bool ToolTipEnabled { get; set; }
        string ToolTipFormat { get; set; }
        void Paint();
        void SetInterval(DateTime minDate, DateTime maxDate);
        Distance Distance(int x, double y);
        void Select();
        void UnSelect();
    }

    public interface IDateDrawable
    {
        DateTime DateTime { get; }
    }

    public interface IZoomable
    {
        PadRange GetPadRangeY(Pad pad);
    }

    public class Pad
    {
        private Chart chart;
        private ArrayList simplePrimitives;
        private SortedRangeList rangeList;
        private SortedRangeList intervalLeftList;
        private SortedRangeList intervalRightList;
        private object selectedObject;
        private int width;
        private int height;
        private int marginLeft;
        private int marginRight;
        private bool onPrimitive;
        private bool outlineEnabled;
        private Rectangle outlineRectangle;
        private string axisLabelFormat;

        public AxisRight Axis { get; private set; }

        internal int AxisGap { get; private set; }

        internal Chart Chart => this.chart;

        public bool DrawItems { get; set; }

        public string AxisLabelFormat
        {
            get
            {
                return this.axisLabelFormat != null ? this.axisLabelFormat : string.Format("F{0}", chart.LabelDigitsCount);
            }
            set
            {
                this.axisLabelFormat = value;
            }
        }

        internal IChartDrawable SelectedPrimitive { get; set; }

        public bool DrawGrid { get; set; }

        public PadScaleStyle ScaleStyle { get; set; }

        public int X1 { get; private set; }

        public int X2 { get; private set; }

        public int Y1 { get; private set; }

        public int Y2 { get; private set; }

        public double MaxValue { get; private set; }

        public double MinValue { get; private set; }

        internal int Width
        {
            get
            {
                return this.width;
            }
            set
            {
                this.width = value;
                X2 = X1 + this.width;
                Axis.SetBounds(X2, Y1, Y2);
            }
        }

        public ISeries Series => this.chart.Series;

        public ISeries MainSeries => this.chart.MainSeries;

        public double IntervalWidth => this.chart.IntervalWidth;

        public int FirstIndex => this.chart.FirstIndex;

        public int LastIndex => this.chart.LastIndex;

        public Graphics Graphics { get; private set; }

        public ArrayList Primitives { get; private set; }

        public Pad(Chart chart, int x1, int x2, int y1, int y2)
        {
            this.chart = chart;
            this.marginLeft = this.marginRight = 0;
            this.onPrimitive = false;
            this.outlineEnabled = false;
            this.outlineRectangle = Rectangle.Empty;
            DrawGrid = true;
            SetCanvas(x1, x2, y1, y2);
            Primitives = ArrayList.Synchronized(new ArrayList());
            this.simplePrimitives = new ArrayList();
            this.rangeList = new SortedRangeList();
            this.intervalLeftList = new SortedRangeList();
            this.intervalRightList = new SortedRangeList(true);
        }

        public void SetCanvas(int x1, int x2, int y1, int y2)
        {
            X1 = x1 + this.marginLeft;
            X2 = x2 - this.marginRight;
            Y1 = y1;
            Y2 = y2;
            this.width = X2 - X1;
            this.height = Y2 - Y1;
            if (Axis == null)
                Axis = new AxisRight(this.chart, this, x2, y1, y2);
            else
                Axis.SetBounds(x2, y1, y2);
        }

        public void AddPrimitive(IChartDrawable primitive)
        {
            Primitives.Add(primitive);
            if (primitive is IDateDrawable)
                this.rangeList.Add(primitive as IDateDrawable);
            else
                this.simplePrimitives.Add(primitive);
        }

        public void RemovePrimitive(IChartDrawable primitive)
        {
            Primitives.Remove(primitive);
            if (primitive is IDateDrawable)
                this.rangeList[(primitive as IDateDrawable).DateTime].Remove(primitive);
            else
                this.simplePrimitives.Remove(primitive);
        }

        public void ClearPrimitives()
        {
            Primitives.Clear();
            this.rangeList.Clear();
            this.simplePrimitives.Clear();
        }

        public void SetSelectedObject(object obj)
        {
            this.selectedObject = obj;
        }

        internal void Reset()
        {
            ClearPrimitives();
        }

        public int ClientX(DateTime dateTime)
        {
            double w = (double)Width / (LastIndex - FirstIndex + 1);
            return X1 + (int)((MainSeries.GetIndex(dateTime, IndexOption.Null) - FirstIndex) * w + w / 2);
        }

        public int ClientY(double worldY)
        {
            if (ScaleStyle == PadScaleStyle.Log)
                return Y1 + (int)((1.0 - (Math.Log10(worldY) - Math.Log10(MinValue)) / (Math.Log10(MaxValue) - Math.Log10(MinValue))) * this.height);
            else
                return Y1 + (int)((1.0 - (worldY - MinValue) / (MaxValue - MinValue)) * this.height);
        }

        public void SetInterval(DateTime minDate, DateTime maxDate)
        {
            foreach (IChartDrawable drawable in Primitives)
                drawable.SetInterval(minDate, maxDate);
        }

        public void DrawHorizontalGrid(Pen pen, double y)
        {
            if (DrawGrid)
            {
                var cY = ClientY(y);
                Graphics.DrawLine(pen, X1, cY, X2, cY);
            }
        }

        public void DrawHorizontalTick(Pen pen, double x, double y, int length)
        {
            var cY = ClientY(y);
            Graphics.DrawLine(pen, (int)x, cY, (int)x + length, cY);
        }

        internal void PrepareForUpdate()
        {
            if (this.chart.MainSeries == null || this.chart.MainSeries.Count == 0)
                return;
            MaxValue = double.MinValue;
            MinValue = double.MaxValue;
            ArrayList primitives;
            lock (Primitives.SyncRoot)
                primitives = new ArrayList(Primitives);
            foreach (IChartDrawable drawable in primitives)
            {
                if ((DrawItems || drawable is SeriesView) && drawable is IZoomable)
                {
                    var range = (drawable as IZoomable).GetPadRangeY(this);
                    if (range.IsValid)
                    {
                        MaxValue = Math.Max(MaxValue, range.Max);
                        MinValue = Math.Min(MinValue, range.Min);
                    }
                }
            }
            if (MinValue != double.MaxValue && MaxValue != double.MinValue)
            {
                var offset = (MaxValue - MinValue) / 10;
                MinValue -= offset;
                MaxValue += offset;
                AxisGap = Axis.GetAxisGap();
            }
            else
                AxisGap = -1;
        }

        internal void Update(Graphics g)
        {
            if (this.chart.MainSeries == null || this.chart.MainSeries.Count == 0)
                return;
            Graphics = g;
            if (MinValue != double.MaxValue && MaxValue != double.MinValue)
            {
                Axis.Paint();
                g.SetClip(new Rectangle(X1, Y1, this.width, this.height));
                foreach (IChartDrawable drawable in this.simplePrimitives)
                    if (DrawItems || drawable is SeriesView)
                        drawable.Paint();
                if (DrawItems)
                {
                    int nextIndex = this.rangeList.GetNextIndex(this.chart.MainSeries.GetDateTime(this.chart.FirstIndex));
                    int prevIndex = this.rangeList.GetPrevIndex(this.chart.MainSeries.GetDateTime(this.chart.LastIndex));
                    if (nextIndex != -1 && prevIndex != -1)
                        for (int i = nextIndex; i <= prevIndex; ++i)
                            foreach (IChartDrawable drawable in this.rangeList[i])
                                drawable.Paint();
                }
                g.ResetClip();
            }
            float num = X1 + 2f;
            string legend = null;
            foreach (IChartDrawable drawable in this.simplePrimitives)
            {
                if (drawable is SeriesView)
                {
                    var sView = drawable as SeriesView;
                    if (sView.DisplayNameEnabled)
                    {
                        legend = legend == null ? sView.DisplayName : " " + sView.DisplayName;
                        var size = g.MeasureString(legend, this.chart.Font);
                        g.FillRectangle(new SolidBrush(this.chart.CanvasColor), num + 2f, Y1 + 2f, size.Width, size.Height);
                        g.DrawString(legend, this.chart.Font, new SolidBrush(sView.Color), num + 2f, Y1 + 2f);
                        num += size.Width;
                    }
                }
            }
            if (this.outlineEnabled)
                g.DrawRectangle(new Pen(Color.Green), this.outlineRectangle);
        }

        public DateTime GetDateTime(int x) => this.chart.GetDateTime(x);

        public double WorldY(int y)
        {
            if (ScaleStyle == PadScaleStyle.Log)
                return Math.Pow(10, (double)(Y2 - y) / (double)(Y2 - Y1) * (Math.Log10(MaxValue) - Math.Log10(MinValue))) * MinValue;
            else
                return MinValue + (MaxValue - MinValue) * (double)(Y2 - y) / (double)(Y2 - Y1);
        }

        public virtual void MouseDown(MouseEventArgs evnt)
        {
            if (this.chart.MainSeries == null || this.chart.MainSeries.Count == 0 || evnt.X <= X1 || evnt.X >= X2)
                return;
            double num1 = 10.0;
            double num2 = (MaxValue - MinValue) / 20.0;
            foreach (IChartDrawable primitive in this.simplePrimitives)
            {
                if (primitive is DSView)
                {
                    var d = primitive.Distance(evnt.X, WorldY(evnt.Y));
                    if (d != null)
                    {
                        this.chart.UnSelectAll();
                        if (d.DX < num1 && d.DY < num2)
                        {
                            primitive.Select();
                            this.chart.ContentUpdated = true;
                            this.chart.Invalidate();
                            this.chart.ShowProperties(primitive as DSView, this, false);
                            SelectedPrimitive = primitive;
                            if (this.chart.ContextMenuEnabled && evnt.Button == System.Windows.Forms.MouseButtons.Right)
                                ShowContextMenu(primitive, this.chart, evnt);
                            break;
                        }
                    }
                }
            }
        }

        public virtual void MouseUp(MouseEventArgs Event)
        {
            this.chart.ContentUpdated = true;
            this.chart.Invalidate();
        }

        public virtual void MouseMove(MouseEventArgs evnt)
        {
            if (this.chart.MainSeries == null || this.chart.MainSeries.Count == 0 || evnt.X <= X1 || evnt.X >= X2)
                return;
            double num1 = 10.0;
            double num2 = (MaxValue - MinValue) / 20.0;
            int x = evnt.X;
            double y = this.WorldY(evnt.Y);
            bool flag = false;
            string caption = "";
            this.onPrimitive = false;
            foreach (IChartDrawable drawable in this.simplePrimitives)
            {
                if (DrawItems || drawable is SeriesView)
                {
                    Distance distance = drawable.Distance(x, y);
                    if (distance != null && distance.DX < num1 && distance.DY < num2)
                    {
                        if (drawable.ToolTipEnabled)
                        {
                            if (caption != "")
                                caption = caption + "\n\n";
                            caption = caption + distance.ToolTipText;
                            flag = true;
                        }
                        this.onPrimitive = true;
                        this.chart.SetCursor(ChartCursorType.Hand);
//                        #if GTK
//                        this.chart.GdkWindow.Cursor = UserControl.HandCursor;
//                        #else
//                        Cursor.Current = Cursors.Hand;
//                        #endif
                    }
                }
            }
            if (DrawItems)
            {
                int num3 = 0;
                int index1 = this.chart.MainSeries.GetIndex(GetDateTime(evnt.X), IndexOption.Null);
                DateTime dateTime1 = this.chart.MainSeries.GetDateTime(index1);
                if (index1 != 0)
                {
                    DateTime dateTime2 = this.chart.MainSeries.GetDateTime(index1 - 1);
                    num3 = this.rangeList.GetNextIndex(dateTime2);
                    if (this.rangeList.Contains(dateTime2))
                        ++num3;
                }
                int prevIndex = this.rangeList.GetPrevIndex(dateTime1);
                if (num3 != -1 && prevIndex != -1)
                {
                    for (int index2 = num3; index2 <= prevIndex; ++index2)
                    {
                        foreach (IChartDrawable drawable in this.rangeList[index2])
                        {
                            var distance = drawable.Distance(x, y);
                            if (distance != null && distance.DX < num1 && distance.DY < num2)
                            {
                                if (drawable.ToolTipEnabled)
                                {
                                    if (caption != "")
                                        caption = caption + "\n\n";
                                    caption = caption + distance.ToolTipText;
                                    flag = true;
                                }
                                this.onPrimitive = true;
                                this.chart.SetCursor(ChartCursorType.Hand);
//                                #if GTK
//                                #else
//                                Cursor.Current = Cursors.Hand;
//                                #endif
                            }
                        }
                    }
                }
            }
            if (flag)
            {
                this.chart.ToolTip.SetToolTip(this.chart, caption);
                this.chart.ToolTip.Active = true;
            }
            else
                this.chart.ToolTip.Active = false;
        }

        private void ShowContextMenu(IChartDrawable primitive, UserControl control, MouseEventArgs e)
        {
            #if GTK
            GtkWorkarounds.ShowContextMenu(InitContextMenu(primitive), control, e.GdkEventButton, Gdk.Rectangle.Zero);
            #else
            InitContextMenu(primitive).Show(control, e.Location);
            #endif
        }

        #if GTK
        private Menu InitContextMenu(IChartDrawable primitive)
        {
            string displayName = (primitive as DSView).DisplayName;
            var menu = new Menu();
            ImageMenuItem mi;
            mi = new ImageMenuItem(string.Format("Delete {0}", displayName));
            mi.Activated += OnDeleteMenuItemClick;
            menu.Append(mi);
            menu.Append(new SeparatorMenuItem());
            mi = new ImageMenuItem(string.Format("Properties {0}", displayName));
            mi.Activated += OnPropertiesMenuItemClick;
            menu.Append(mi);
            menu.ShowAll();
            return menu;
        }
        #else
        private ContextMenuStrip InitContextMenu(IChartDrawable primitive)
        {
            string displayName = (primitive as DSView).DisplayName;
            var menu = new ContextMenuStrip();
            ToolStripMenuItem mi;
            mi = new ToolStripMenuItem();
            mi.Text = string.Format("Delete {0}", displayName);
            mi.Click += OnDeleteMenuItemClick;
            mi.Image = this.chart.PrimitiveDeleteImage;
            menu.Items.Add(mi);
            menu.Items.Add(new ToolStripSeparator());
            mi = new ToolStripMenuItem();
            mi.Text = string.Format("Properties {0}", displayName);
            mi.Click += OnPropertiesMenuItemClick;
            mi.Image = this.chart.PrimitivePropertiesImage;
            menu.Items.Add(mi);
            return menu;
        }
        #endif

        private void OnPropertiesMenuItemClick(object sender, EventArgs e)
        {
            this.chart.ShowProperties(SelectedPrimitive as DSView, this, true);
        }

        private void OnDeleteMenuItemClick(object sender, EventArgs e)
        {
            Primitives.Remove(SelectedPrimitive);
            this.simplePrimitives.Remove(SelectedPrimitive);
            this.chart.ContentUpdated = true;
            this.chart.Invalidate();
        }

        public bool IsInRange(double x, double y) => X1 <= x && x <= X2 && Y1 <= y && y <= Y2;

        #region Helper Methods

        private Distance GetPrimitiveDistance(IChartDrawable primitive, Point point)
        {
            var x = point.X;
            var y = WorldY(point.Y);
            return primitive.Distance(x, y);
        }

        #endregion
    }

    [Serializable]
    public class PadList : IList
    {
        private ArrayList list = new ArrayList();

        public bool IsReadOnly => this.list.IsReadOnly;

        object IList.this[int index]
        {
            get
            {
                return this[index];
            }
            set
            {
                throw new NotSupportedException();
            }
        }

        public bool IsFixedSize => this.list.IsFixedSize;

        public bool IsSynchronized => this.list.IsSynchronized;

        public int Count => this.list.Count;

        public object SyncRoot => this.list.SyncRoot;

        public Pad this[int index] => this.list[index] as Pad;

        public void RemoveAt(int index) => this.list.RemoveAt(index);

        void IList.Insert(int index, object value)
        {
            throw new NotSupportedException();
        }

        void IList.Remove(object value) => Remove(value as Pad);

        bool IList.Contains(object value) => this.list.Contains(value);

        public void Clear() => this.list.Clear();

        int IList.IndexOf(object value) => IndexOf(value as Pad);

        int IList.Add(object value) => Add(value as Pad);

        public void CopyTo(Array array, int index) => this.list.CopyTo(array, index);

        public IEnumerator GetEnumerator() => this.list.GetEnumerator();

        public int Add(Pad pad) => this.list.Add(pad);

        public void Remove(Pad pad) => this.list.Remove(pad);

        public void Insert(int index, Pad pad) => this.list.Insert(index, pad);

        public int IndexOf(Pad pad) => this.list.IndexOf(pad);
    }

    [Serializable]
    public class PadRange
    {
        public double Min { get; set; }

        public double Max { get; set; }

        protected bool isValid;

        public bool IsValid => this.isValid;

        public PadRange(double min, double max)
        {
            this.Min = min;
            this.Max = max;
            this.isValid = max - min > double.Epsilon;
        }
    }
}


text:
/*flip tile 0.1 */
if(($.browser.name=="msie" && $.browser.version<11)  || $.browser.name=="opera"){
	$(document).on("mouseenter",".tileFlip",function(){
		$(this).removeClass("support3D").find(".flipFront, .tileLabelWrapper").stop().fadeOut(500);
	}).on("mouseleave",".tileFlip",function(){
		$(this).find(".flipFront, .tileLabelWrapper").fadeIn(500);
	})
}else{
	$(document).on("mouseenter",".tileFlip",function(){
		clearTimeout(timers["tileFlipTimer"]);
		$(this).addClass("tileFlipped");
	}).on("mouseleave",".tileFlipped",function(){
		timers["tileFlipTimer"] = setTimeout(function(){$(".tileFlipped").removeClass("tileFlipped")},600);
	})
}


text:
<?php
/**
 * Created by IntelliJ IDEA.
 *
 * @author egkim <egkim@theragenetex.com>
 * created at 30/08/2017 2:35 PM
 */

namespace Eagu\Texting;

class Gabia
{
    const SERVICE_REGION = 'KR';
    const SHORT_UPPERLIMIT = 90;

    private $agent;
    private $callback = [];
    private $validator;

    protected function scalar($x)
    {
        if ($x instanceof \SimpleXMLElement) {
            $x = (array)$x;
            if (count($x) == 0)
                return null;
            return $x[0];
        }
        return $x;
    }

    protected function token($length=40, $alphabet='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
    {
        $token = '';
        while (true) {
            $token = '';
            for ($i = 0; $i < $length; $i++)
                $token .= $alphabet[rand(0, strlen($alphabet) - 1)];
            if ($this->status($token) === false)
                break;
        }
        return $token;
    }

    public function __construct($userid, $secret)
    {
        require_once(__DIR__.'/sms.gabia.com_api_php/api.class.php');

        // Get Gabia SMS API service handle.
        $this->agent = new \gabiaSmsApi($userid, $secret);

        // This is a heck to check if authentication was a success.
        // Gabia does not provide this functionality.
        if (null === $this->agent->get_status_by_ref_all(''))
            throw new \Exception();

        $this->validator = \libphonenumber\PhoneNumberUtil::getInstance();
        $this->callback();
    }

    public function status($token)
    {
        $response = $this->agent->get_status_by_ref_all($token);
        if ($response) {
            $result = [];
            foreach ($response as $each)
                $result[] = [
                    'number' => $each['PHONE'],
                    'message' => $each['MESG'],
                ];
            return $result;
        }

        // Nothing found with this token.
        return false;
    }

    public function callback()
    {
        // Get all the registered callback numbers at Gabia.
        $this->callback = [];
        $registered = $this->agent->getCallbackNum();
        foreach ($registered as $number) {
            $proto = $this->validator->parse($number, self::SERVICE_REGION);
            $number = $this->validator->format($proto, \libphonenumber\PhoneNumberFormat::NATIONAL);
            $this->callback[] = str_replace(['-', ' '], '', $number);
        }
        return $this->callback;
    }

    public function serviceable(array $receiver)
    {
        // Check if the receiver numbers are Korean numbers.
        return array_map(function($number){
            $proto = $this->validator->parse($number, self::SERVICE_REGION);
            if (self::SERVICE_REGION != $this->validator->getRegionCodeForNumber($proto))
                return false;
            $number = $this->validator->format($proto, \libphonenumber\PhoneNumberFormat::NATIONAL);
            return str_replace(['-', ' '], '', $number);
        }, $receiver);
    }

    public function send($callback, array $receiver, $title, $text)
    {
        return $this->reserve($callback, $receiver, $title, $text);
    }

    public function reserve($callback, array $receiver, $title, $text, $sendAt='')
    {
        $callback = $this->serviceable([$callback])[0];
        $token = $this->token();
        $serviceable = $this->serviceable($receiver);
        $numbers_converted = array_combine($receiver, $serviceable);
        $filtered = array_values(array_filter($serviceable, function($number){
            return $number !== false;
        }));

        // Decide whether the text message is sent using SMS or LMS.
        $short = (strlen($text) <= self::SHORT_UPPERLIMIT and empty($title));

        if ($short)
            $response = $this->agent->multi_sms_send($filtered, $callback, $text, $token, $sendAt);
        else
            $response = $this->agent->multi_lms_send($filtered, $callback, $text, $title, $token, $sendAt);

        if ($response == \gabiaSmsApi::$RESULT_OK) {
            $success_count = $this->scalar($this->agent->get_success_cnt());
            $success_count = is_null($success_count) ? 0 : $success_count;

            $failure_count = $this->scalar($this->agent->get_fail_list());
            $failure_count = is_null($failure_count) ? 0 : $failure_count;

            return [
                'success' => true,
                'token' => $token,
                'callback' => $callback,
                'numbers_converted' => $numbers_converted,
                'success_count' => $success_count,
                'failure_count' => $failure_count,
                'credit_spent' => $this->scalar($this->agent->getBefore()) - $this->scalar($this->agent->getAfter()),
                'credit' => $this->scalar($this->agent->getAfter()),
                'unit' => 'count',
            ];
        }
        else
            return [
                'success' => false,
                'callback' => $callback,
                'numbers_converted' => $numbers_converted,
                'code' => $this->scalar($this->agent->getResultCode()),
                'message' => $this->scalar($this->agent->getResultMessage()),
                'credit' => $this->scalar($this->agent->getSmsCount()),
                'unit' => 'count',
            ];
    }

    public function cancel($token, array $receiver=[])
    {
        $serviceable = $this->serviceable($receiver);
        $numbers_converted = array_combine($receiver, $serviceable);
        $filtered = array_values(array_filter($serviceable, function($number){
            return $number !== false;
        }));

        if (!empty($receiver) and empty($filtered))
            return [
                'success' => false,
                'numbers_converted' => $numbers_converted,
            ];

        foreach (['sms', 'lms'] as $type) {
            $response = $this->agent->reservationCancel($token, $type, $filtered);
            if ($response !== false) {
                $numbers_cancelled = array_filter($numbers_converted, function ($value) {
                    return $value !== false;
                });
                return [
                    'success' => true,
                    'numbers_converted' => $numbers_converted,
                    'numbers_cancelled' => empty($receiver) ? 'all' : $numbers_cancelled,
                ];
            }
        }

        return [
            'success' => false,
            'numbers_converted' => $numbers_converted,
            'code' => $this->scalar($this->agent->getResultCode()),
            'message' => $this->scalar($this->agent->getResultMessage()),
        ];
    }

    public function credit()
    {
        $response = $this->agent->getSmsCount();
        return [
            'credit' => $this->scalar($response),
            'unit' => 'count'
        ];
    }
}


text:
package com.twitter.finatra.http.tests.integration.doeverything.main.controllers

import com.twitter.finagle.http.{Method, Request, Status}
import com.twitter.finagle.{ChannelClosedException, ChannelWriteException}
import com.twitter.finatra.annotations.CamelCaseMapper
import com.twitter.finatra.http.Controller
import com.twitter.finatra.http.exceptions._
import com.twitter.finatra.http.marshalling.mustache.MustacheService
import com.twitter.finatra.http.request.RequestUtils
import com.twitter.finatra.http.response._
import com.twitter.finatra.http.tests.integration.doeverything.main.domain._
import com.twitter.finatra.http.tests.integration.doeverything.main.exceptions._
import com.twitter.finatra.http.tests.integration.doeverything.main.filters.ForbiddenFilter
import com.twitter.finatra.http.tests.integration.doeverything.main.services.{ComplexServiceFactory, DoEverythingService, MultiService}
import com.twitter.finatra.json.FinatraObjectMapper
import com.twitter.finatra.request.{QueryParam, RouteParam}
import com.twitter.inject.annotations.Flag
import com.twitter.util.Future
import java.io.ByteArrayInputStream
import java.nio.charset.StandardCharsets
import java.util.concurrent.ThreadLocalRandom
import java.util.concurrent.atomic.AtomicInteger
import javax.inject.Inject
import scala.collection.SortedSet

class DoEverythingController @Inject()(
  @Flag("magicNum") magicNum: String,
  @Flag("moduleMagicNum") moduleMagicNum: String,
  exampleService: DoEverythingService,
  multiService: Set[MultiService],
  complexServiceFactory: ComplexServiceFactory,
  objectMapper: FinatraObjectMapper,
  @CamelCaseMapper camelCaseObjectMapper: FinatraObjectMapper,
  mustacheService: MustacheService)
  extends Controller {

  private val flakyCount = new AtomicInteger()

  get("/example/routing/always") { request: Request =>
    response.ok.body("always response")
  }

  get("/example/routing/always2") { request: Request =>
    response.ok("always response")
  }

  get("/plaintext") { request: Request =>
    "Hello, World!"
  }

  get("/bytearray") { request: Request =>
    val b = new Array[Byte](20)
    ThreadLocalRandom.current().nextBytes(b)
    b
  }

  get("/inputstream") { request: Request =>
    val b = new Array[Byte](20)
    ThreadLocalRandom.current().nextBytes(b)
    response.ok.body(new ByteArrayInputStream(b))
  }

  get("/useragent") { request: UserAgentRequest =>
    request.`user-agent`
  }

  get("/json") { request: Request =>
    response.ok.json("{}".getBytes)
  }

  get("/admin/foo") { request: Request =>
    response.ok("Hanging out on the externl interface")
  }

  get("/json2") { request: Request =>
    response.ok.json("{}")
  }

  get("/none") { request: Request =>
    response.ok.body(None)
  }

  get("/bodyunit") { request: Request =>
    response.ok.body(())
  }

  get("/bodynull") { request: Request =>
    response.ok.body(null.asInstanceOf[Any])
  }

  get("/bodyEmptyString") { request: Request =>
    response.ok.body("")
  }

  get("/example/routing/json/:id") { request: Request =>
    ExampleResponse(
      id = request.params("id"),
      name = "bob",
      magic = magicNum,
      moduleMagic = moduleMagicNum)
  }

  get("/routeParamGetAll/:id") { request: Request =>
    assert(request.params.isValid)
    request.params("id") +: request.params.getAll("id").toSeq
  }

  get("/column/:key//:*") { request: Request =>
    s"${request.params("key")}/${request.params("*")}"
  }

  post("/foo") { request: Request =>
    "bar"
  }

  post("/longer/post/path/:capture") { request: Request =>
    "bar"
  }

  post("/longer/post/path/with/name/:capture", name = "my_cool_endpoint") { request: Request =>
    "bar"
  }

  post("/formPost") { formPost: FormPostRequest =>
    formPost.name
  }

  post("/formPostView") { formPost: FormPostRequest =>
    TestUserView(
      formPost.age,
      formPost.name,
      Seq("user1", "user2"))
  }

  get("/getView") { request: Request =>
    TestUserView(
      request.params.getInt("age").get,
      request.params("name"),
      Seq("user1", "user2"))
  }

  post("/echo") { request: Request =>
    response.ok(request.contentString)
  }

  post("/formPostViewFromBuilderView") { formPost: FormPostRequest =>
    response.ok.view(
      "testuser2.mustache",
      TestUserView(formPost.age, formPost.name, Seq("user1", "user2")))
  }

  post("/formPostViewFromBuilderHtml") { formPost: FormPostRequest =>
    response.ok.html(
      TestUserView(formPost.age, formPost.name, Seq("user1", "user2")))
  }

  post("/formPostViewFromBuilderCreatedView") { formPost: FormPostRequest =>
    response.created.
      location("/foo/1").
      view(
        "testuser2.mustache",
        TestUserView(formPost.age, formPost.name, Seq("user1", "user2")))
  }

  post("/formPostViewFromBuilderCreatedHtml") { formPost: FormPostRequest =>
    response.created.
      location("/foo/1").
      html(
        TestUserView(formPost.age, formPost.name, Seq("user1", "user2")))
  }

  post("/formPostMultipart") { request: Request =>
    RequestUtils.multiParams(request)("file").contentType
  }

  post("/groups/:group_id/users") { user: TestUserWithGroupIdFromRoute =>
    response.created(user)
  }

  post("/multipleRouteParams") { r: MultipleInjectableValueParams =>
    response.created(r)
  }

  post("/caseClassWithRequestField") { r: CaseClassWithRequestField =>
    "hi"
  }

  get("/example/routing/flaky") { request: Request =>
    val num = flakyCount.incrementAndGet()
    if (num == 1)
      response.internalServerError.body("flaky error")
    else if (num == 2)
      throw new ChannelClosedException()
    else if (num == 3)
      throw new ChannelWriteException(new ChannelClosedException())
    else
      response.ok.body("flaky response")
  }

  get("/ok") { request: Request =>
    response.ok.body("ok")
  }

  get("/created") { request: Request =>
    response.created.body("created").location("/foo/123")
  }

  get("/accepted") { request: Request =>
    response.accepted.body("accepted").location("/foo/123")
  }

  get("/accepted2") { request: Request =>
    response.accepted("accepted").location("/foo/123")
  }

  get("/badrequest") { request: Request =>
    response.badRequest.body("bad")
  }

  get("/forbidden") { request: Request =>
    response.forbidden.body("forbidden")
  }

  get("/methodnotallowed") { request: Request =>
    response.methodNotAllowed.body("not allowed")
  }

  get("/unauthorized") { request: Request =>
    response.unauthorized.body("unauthorized")
  }

  get("/unavailable") { request: Request =>
    response.serviceUnavailable.body("unavail")
  }

  get("/conflict") { request: Request =>
    SimpleResponse(Status.Conflict, "conflict")
  }

  get("/redirect") { request: Request =>
    response.temporaryRedirect.location("/foo/123")
  }

  get("/found") { request: Request =>
    response.found.location("/foo/123")
  }

  get("/notfound") { request: Request =>
    response.notFound.body("notfound")
  }

  get("/notfound2") { request: Request =>
    response.notFound("notfound")
  }

  get("/future") { request: Request =>
    Future(response.ok.body("future"))
  }

  get("/true") { request: Request =>
    true
  }

  post("/post") { request: Request =>
    "post"
  }

  delete("/delete") { request: Request =>
    "delete"
  }

  put("/putJson/:id") { request: IdAndNameRequest =>
    request
  }

  put("/putAndPost") { request: Request =>
    "PUT" + request.contentString
  }

  post("/putAndPost") { request: Request =>
    "POST" + request.contentString
  }

  post("/postAndPut") { request: Request =>
    "POST" + request.contentString
  }

  put("/postAndPut") { request: Request =>
    "PUT" + request.contentString
  }

  put("/echo") { request: Request =>
    response.ok(request.contentString)
  }

  get("/testfile") { request: Request =>
    response.ok.file("/testfile.txt")
  }

  get("/testfileWhenNotfound") { request: Request =>
    response.ok.file("/doesntexist.txt")
  }

  get("/index/:*") { request: Request =>
    response.ok.fileOrIndex(
      request.params("*"),
      "testindex.html")
  }

  get("/null") { request: Request =>
    null
  }

  get("/empty") { request: Request =>
    ""
  }

  get("/unit") { request: Request =>
  }

  get("/exception") { request: Request =>
    throw new Exception("bad")
  }

  get("/complexpath/:name") { request: Request =>
    val name = request.params("name")
    complexServiceFactory.create(name).execute
  }

  get("/complexquery") { request: Request =>
    val name = request.params("name")
    complexServiceFactory.create(name).execute
  }

  get("/notfoundexception") { request: Request =>
    throw NotFoundException()
  }

  get("/notfoundexception2") { request: Request =>
    throw new NotFoundException("foo")
  }

  get("/servererrorexception") { request: Request =>
    throw InternalServerErrorException()
  }

  get("/serviceunavailableexception") { request: Request =>
    throw ServiceUnavailableException()
  }

  get("/serviceunavailableexception2") { request: Request =>
    throw ServiceUnavailableException.plainText("foo")
  }

  get("/responsebuilder_status_code") { request: Request =>
    response.status(503)
  }

  get("/responsebuilder_status") { request: Request =>
    response.status(Status.ServiceUnavailable)
  }

  get("/pathUrl") { request: Request =>
    RequestUtils.pathUrl(request)
  }

  get("/path") { request: Request =>
    RequestUtils.pathUrl(request)
  }

  put("/put/:id") { request: Request =>
    request.getParam("id") + "_" + request.contentString
  }

  put("/put_route_param/:id") { idRequest: IdRequest =>
    idRequest.id + "_" + idRequest.request.contentString
  }

  put("/put_route_param_and_name/:id") { idRequest: IdAndNameRequest =>
    idRequest.id + "_" + idRequest.name
  }

  put("/put_id_ignoring_body/:id") { req: IdRequestIgnoringBody =>
    req.id
  }

  put("/put_id_not_ignoring_body/:id") { req: IdRequestNotIgnoringBody =>
    req.id
  }

  get("/implicitOkAndException") { request: Request =>
    if (request.params.contains("hi"))
      "hello"
    else
      throw BadRequestException()
  }

  get("/BadRequestException") { request: Request =>
    throw BadRequestException.plainText("foo")
  }

  get("/slow") { request: Request =>
    println("SLOW ROUTE CALLED")
    Thread.sleep(9999)
    "slow"
  }

  get("/builderCreatedWithHeader") { request: Request =>
    response.
      created.
      header("a", "b").
      header("Location", "http://foo.com/1")
  }

  get("/requestInjectionsNotFound") { request: RequestWithNotFoundInjections =>
    request.fooClass
  }

  post("/requestInjectionsNotAvailable") { request: Request =>
    val requestWithInjections = objectMapper.parse[RequestWithInjections](request)
    requestWithInjections.id.id +
      requestWithInjections.id2.map(_.id).getOrElse(0L) +
      requestWithInjections.id3.getOrElse(0) +
      requestWithInjections.id4.getOrElse(0)
  }

  get("/requestInjection") { request: RequestWithInjections =>
    request
  }

  get("/requestInjectionsNotAvailable") { request: Request =>
    val requestWithInjections = objectMapper.parse[RequestWithInjections](request)
    requestWithInjections.id.id +
      requestWithInjections.id2.map(_.id).getOrElse(0L) +
      requestWithInjections.id3.getOrElse(0) +
      requestWithInjections.id4.getOrElse(0)
  }

  get("/users/:name") { r: Request =>
    val user = TestUser(r.params("name"))
    response.ok.body(user) // test ResponseBuilder
  }

  post("/users") { user: TestUser =>
    user.name
  }

  post("/userWithMissingField") { user: TestUser =>
    user.name
  }

  post("/userWithInvalidFieldValidation") { user: TestUserWithInvalidFieldValidation =>
    user.name
  }

  post("/userWithInvalidMethodValidation") { user: TestUserWithInvalidMethodValidation =>
    user.name
  }

  post("/userWithMessageBodyReader") { user: DomainTestUser =>
    user
  }

  get("/array") { r: Request =>
    Array("a", "b")
  }

  get("/set") { r: Request =>
    response.ok.body(SortedSet("a", "b"))
  }

  get("/seq") { r: Request =>
    Seq("a", "b")
  }

  options("/options") { r: Request =>
    "options"
  }

  head("/head") { r: Request =>
    response.conflict
  }

  patch("/patch") { r: Request =>
    "patch"
  }

  patch("/echo") { request: Request =>
    response.ok(request.contentString)
  }

  get("/HttpResponseException") { r: Request =>
    val exception = new HttpResponseException(response.conflict("conflicted"))
    warn(exception.getMessage)
    throw exception
  }

  get("/toFutureException") { r: Request =>
    response.conflict("conflicted").toFutureException
  }

  get("/admin/finatra/foo") { r: Request =>
    "bar"
  }

  get("/HttpExceptionPlain") { r: Request =>
    throw HttpException.plainText(Status.Created, "foo")
  }

  get("/HttpExceptionErrors") { r: Request =>
    val e = HttpException(Status.Created, "foo1", "foo2")
    warn(e + " " + e.hashCode)
    throw e
  }

  get("/NotFoundException") { r: Request =>
    throw NotFoundException("foo1")
  }

  get("/ConflictException") { r: Request =>
    throw ConflictException("foo1")
  }

  get("/ConflictException2") { r: Request =>
    throw ConflictException.plainText("foo1")
  }

  get("/ConflictException3") { r: Request =>
    throw new ConflictException("foo1")
  }

  get("/ForbiddenException") { r: Request =>
    throw ForbiddenException.plainText("foo1")
  }

  get("/ForbiddenException2") { r: Request =>
    throw ForbiddenException("foo1")
  }

  get("/NotAcceptableException") { r: Request =>
    throw NotAcceptableException("foo1")
  }

  get("/NotAcceptableException2") { r: Request =>
    throw NotAcceptableException.plainText("foo1")
  }

  get("/InternalServerErrorExceptionPlain") { r: Request =>
    throw InternalServerErrorException.plainText("foo1")
  }

  get("/UnserializableClassField") { r: RequestWithInjectedMapper =>
    r
  }

  get("/RequestWithQueryParamSeqString") { r: RequestWithQueryParamSeqString =>
    ResponseOfQueryParamSeqString(r.foo.map(_ + 1).seq)
  }

  get("/RequestWithQueryParamSeqLong") { r: RequestWithQueryParamSeqLong =>
    ResponseOfQueryParamSeqLong(r.foo.map(_ + 1).seq)
  }

  get("/FooException/:id") { r: Request =>
    throw new FooException(r.params("id"))
  }

  get("/BarException") { r: Request =>
    throw new BarException
  }

  get("/BazException") { r: Request =>
    throw new BazException
  }

  get("/NoSuchMethodException") { r: Request =>
    throw new NoSuchMethodException
  }

  get("/users") { r: UsersRequest =>
    r
  }

  post("/multipartParamsEcho") { r: Request =>
    RequestUtils.multiParams(r).keys
  }

  put("/multipartParamsPutEcho") { r: Request =>
    RequestUtils.multiParams(r).keys
  }

  get("/CaseClassWithIntQueryParam") { r: RequestWithIntQueryParams =>
    r.param
  }

  get("/CaseClassWithShortQueryParam") { r: RequestWithShortQueryParams =>
    r.param
  }

  get("/RequestWithBooleanQueryParams") { r: RequestWithBooleanQueryParams =>
    r.param
  }

  get("/RequestWithBooleanQueryParam") { r: RequestWithBooleanQueryParam =>
    r.param
  }

  get("/RequestWithOptionBooleanQueryParam") { r: RequestWithOptionBooleanQueryParam =>
    "Hi " + r.param
  }

  get("/CaseClassWithCaseClassQueryParam") { r: RequestWithCaseClassQueryParams =>
    r.param
  }

  post("/SomethingStreamedRequest.json") { r: SomethingStreamedRequest =>
    s"${r.somethingId}/${r.field1.get}/${r.field2.get}"
  }

  post("/SomethingStreamedRequestAsJsonResponse.json") { r: SomethingStreamedRequest =>
    SomethingStreamedResponse(r.somethingId, r.field1, r.field2)
  }

  get("/camelCaseJson") { request: Request =>
    camelCaseObjectMapper.writeValueAsString(Map("firstName" -> "Bob"))
  }

  post("/createUser") { user: CreateUserRequest =>
    response.created.location(s"/users/${user.requestId}")
  }

  post("/arrayElementValidation") { request: TestCaseClassWithSeqOfValidatedWrappedLongs =>
    s"Size of input array: ${request.seq.size}"
  }

  //needed to avoid colliding with Logging#trace :-/
  trace[Request, String]("/trace") { r: Request =>
    "trace 123"
  }

  filter[ForbiddenFilter].get("/forbiddenByFilter") { r: Request =>
    "ok!"
  }

  get("/testClassWithHtml") { r: Request =>
    val testUser = TestUserView(
      28,
      "Bob Smith",
      Seq("user1", "user2"))

    TestCaseClassWithHtml(
      address = "123 Main St. Anywhere, CA US 90210",
      phone = "+12221234567",
      renderedHtml = xml.Utility.escape(mustacheService.createString("testHtml.mustache", testUser)))
  }

  get("/non_case_class") { r: Request =>
    new NonCaseClass
  }

  get("/bytes") { r: Request =>
    "Steve".getBytes(StandardCharsets.UTF_8)
  }

  any("/anyMethod") { request: Request =>
    // only support GET, HEAD or TRACE here
    request.method match {
      case m @ (Method.Get | Method.Head | Method.Trace) =>
        response.ok
      case _ =>
        response.methodNotAllowed
    }
  }
}

case class MultipleInjectableValueParams(
  @RouteParam @QueryParam id: String)

case class CaseClassWithRequestField(
  @Inject request: Request)

class NonCaseClass {
  val name = "Bob"
  val age = 21
}


text:
package com.jblur.acme_client.command.registration;

import com.jblur.acme_client.Parameters;
import com.jblur.acme_client.command.ACMECommand;
import com.jblur.acme_client.manager.AccountManager;
import org.shredzone.acme4j.exception.AcmeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DeactivateAccountCommand extends ACMECommand {

    private static final Logger LOG = LoggerFactory.getLogger(DeactivateAccountCommand.class);
    private AccountManager registrationManagement;

    public DeactivateAccountCommand(Parameters parameters, AccountManager registrationManagement){
        super(parameters);
        this.registrationManagement = registrationManagement;
    }

    @Override
    public void commandExecution() {
        try {
            registrationManagement.deactivateAccount();
        } catch (AcmeException e) {
            LOG.error("Cannot deactivate account", e);
            error = true;
        }
    }

}


text:
//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists for the convenience
// of qapplication_*.cpp, qwidget*.cpp, qcolor_x11.cpp, qfiledialog.cpp
// and many other.  This header file may change from version to version
// without notice, or even be removed.
//
// We mean it.
//

// Private AppKit class (dumped from classdump).

#import <Cocoa/Cocoa.h>
#import "qnstitledframe_mac_p.h"

@interface NSThemeFrame : NSTitledFrame
{
    NSButton *toolbarButton;
    int toolbarVisibleStatus;
    NSImage *showToolbarTransitionImage;
    NSSize showToolbarPreWindowSize;
    NSButton *modeButton;
    int leftGroupTrackingTagNum;
    int rightGroupTrackingTagNum;
    char mouseInsideLeftGroup;
    char mouseInsideRightGroup;
    int widgetState;
    NSString *displayName;
}

+ (void)initialize;
+ (float)_windowBorderThickness:(unsigned int)fp8;
+ (float)_minXWindowBorderWidth:(unsigned int)fp8;
+ (float)_maxXWindowBorderWidth:(unsigned int)fp8;
+ (float)_minYWindowBorderHeight:(unsigned int)fp8;
+ (float)_windowTitlebarButtonSpacingWidth:(unsigned int)fp8;
+ (float)_windowFileButtonSpacingWidth:(unsigned int)fp8;
+ (float)_minXTitlebarWidgetInset:(unsigned int)fp8;
+ (float)_maxXTitlebarWidgetInset:(unsigned int)fp8;
+ (float)minFrameWidthWithTitle:fp8 styleMask:(unsigned int)fp12;
+ (float)_windowSideTitlebarTitleMinWidth:(unsigned int)fp8;
+ (float)_windowTitlebarTitleMinHeight:(unsigned int)fp8;
+ (float)_sideTitlebarWidth:(unsigned int)fp8;
+ (float)_titlebarHeight:(unsigned int)fp8;
+ (float)_resizeHeight:(unsigned int)fp8;
+ (char)_resizeFromEdge;
+ (struct _NSSize)sizeOfTitlebarButtons:(unsigned int)fp8;
+ (float)_contentToFrameMinXWidth:(unsigned int)fp8;
+ (float)_contentToFrameMaxXWidth:(unsigned int)fp8;
+ (float)_contentToFrameMinYHeight:(unsigned int)fp8;
+ (float)_contentToFrameMaxYHeight:(unsigned int)fp8;
+ (unsigned int)_validateStyleMask:(unsigned int)fp8;
- (struct _NSSize)_topCornerSize;
- (struct _NSSize)_bottomCornerSize;
- (void *)_createWindowOpaqueShape;
- (void)shapeWindow;
- (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)fp8 isVisibleRect:(char)fp24 rectIsVisibleRectForView:fp28 topView:(char)fp32;
- (void *)_regionForOpaqueDescendants:(NSRect)fp8 forMove:(char)fp24;
- (void)_drawFrameInterior:(NSRect *)fp8 clip:(NSRect)fp12;
- (void)_setTextShadow:(char)fp8;
- (void)_drawTitleBar:(NSRect)fp8;
- (void)_drawResizeIndicators:(NSRect)fp8;
- (void)_drawFrameRects:(NSRect)fp8;
- (void)drawFrame:(NSRect)fp8;
- contentFill;
- (void)viewDidEndLiveResize;
- (float)contentAlpha;
- (void)setThemeFrameWidgetState:(int)fp8;
- (char)constrainResizeEdge:(int *)fp8 withDelta:(struct _NSSize)fp12 elapsedTime:(float)fp20;
- (void)addFileButton:fp8;
- (void)_updateButtons;
- (void)_updateButtonState;
- newCloseButton;
- newZoomButton;
- newMiniaturizeButton;
- newToolbarButton;
- newFileButton;
- (void)_resetTitleBarButtons;
- (void)setDocumentEdited:(char)fp8;
- toolbarButton;
- modeButton;
- initWithFrame:(NSRect)fp8 styleMask:(unsigned int)fp24 owner:fp28;
- (void)dealloc;
- (void)setFrameSize:(struct _NSSize)fp8;
- (char)_canHaveToolbar;
- (char)_toolbarIsInTransition;
- (char)_toolbarIsShown;
- (char)_toolbarIsHidden;
- _toolbarView;
- _toolbar;
- (float)_distanceFromToolbarBaseToTitlebar;
- (unsigned int)_shadowFlags;
- (NSRect)frameRectForContentRect:(NSRect)fp8 styleMask:(unsigned int)fp24;
- (NSRect)contentRectForFrameRect:(NSRect)fp8 styleMask:(unsigned int)fp24;
- (struct _NSSize)minFrameSizeForMinContentSize:(struct _NSSize)fp8 styleMask:(unsigned int)fp16;
- (NSRect)contentRect;
- (NSRect)_contentRectExcludingToolbar;
- (NSRect)_contentRectIncludingToolbarAtHome;
- (void)_setToolbarShowHideResizeWeightingOptimizationOn:(char)fp8;
- (char)_usingToolbarShowHideWeightingOptimization;
- (void)handleSetFrameCommonRedisplay;
- (void)_startLiveResizeAsTopLevel;
- (void)_endLiveResizeAsTopLevel;
- (void)_growContentReshapeContentAndToolbarView:(int)fp8 animate:(char)fp12;
- (char)_growWindowReshapeContentAndToolbarView:(int)fp8 animate:(char)fp12;
- (void)_reshapeContentAndToolbarView:(int)fp8 resizeWindow:(char)fp12 animate:(char)fp16;
- (void)_toolbarFrameSizeChanged:fp8 oldSize:(struct _NSSize)fp12;
- (void)_syncToolbarPosition;
- (void)_showHideToolbar:(int)fp8 resizeWindow:(char)fp12 animate:(char)fp16;
- (void)_showToolbarWithAnimation:(char)fp8;
- (void)_hideToolbarWithAnimation:(char)fp8;
- (void)_drawToolbarTransitionIfNecessary;
- (void)drawRect:(NSRect)fp8;
- (void)resetCursorRects;
- (char)shouldBeTreatedAsInkEvent:fp8;
- (char)_shouldBeTreatedAsInkEventInInactiveWindow:fp8;
//- hitTest:(struct _NSPoint)fp8; // collides with hittest in qcocoasharedwindowmethods_mac_p.h
- (NSRect)_leftGroupRect;
- (NSRect)_rightGroupRect;
- (void)_updateWidgets;
- (void)_updateMouseTracking;
- (void)mouseEntered:fp8;
- (void)mouseExited:fp8;
- (void)_setMouseEnteredGroup:(char)fp8 entered:(char)fp12;
- (char)_mouseInGroup:fp8;
- (struct _NSSize)miniaturizedSize;
- (float)_minXTitlebarDecorationMinWidth;
- (float)_maxXTitlebarDecorationMinWidth;
- (struct _NSSize)minFrameSize;
- (float)_windowBorderThickness;
- (float)_windowTitlebarXResizeBorderThickness;
- (float)_windowTitlebarYResizeBorderThickness;
- (float)_windowResizeBorderThickness;
- (float)_minXWindowBorderWidth;
- (float)_maxXWindowBorderWidth;
- (float)_minYWindowBorderHeight;
- (float)_maxYWindowBorderHeight;
- (float)_minYTitlebarButtonsOffset;
- (float)_minYTitlebarTitleOffset;
- (float)_sideTitlebarWidth;
- (float)_titlebarHeight;
- (NSRect)_titlebarTitleRect;
- (NSRect)titlebarRect;
- (float)_windowTitlebarTitleMinHeight;
- (struct _NSSize)_sizeOfTitlebarFileButton;
- (struct _NSSize)sizeOfTitlebarToolbarButton;
- (float)_windowTitlebarButtonSpacingWidth;
- (float)_windowFileButtonSpacingWidth;
- (float)_minXTitlebarWidgetInset;
- (float)_maxXTitlebarWidgetInset;
- (float)_minXTitlebarButtonsWidth;
- (float)_maxXTitlebarButtonsWidth;
- (struct _NSPoint)_closeButtonOrigin;
- (struct _NSPoint)_zoomButtonOrigin;
- (struct _NSPoint)_collapseButtonOrigin;
- (struct _NSPoint)_toolbarButtonOrigin;
- (struct _NSPoint)_fileButtonOrigin;
- (void)_tileTitlebar;
- (NSRect)_commandPopupRect;
- (void)_resetDragMargins;
- (float)_maxYTitlebarDragHeight;
- (float)_minXTitlebarDragWidth;
- (float)_maxXTitlebarDragWidth;
- (float)_contentToFrameMinXWidth;
- (float)_contentToFrameMaxXWidth;
- (float)_contentToFrameMinYHeight;
- (float)_contentToFrameMaxYHeight;
- (float)_windowResizeCornerThickness;
- (NSRect)_minYResizeRect;
- (NSRect)_minYminXResizeRect;
- (NSRect)_minYmaxXResizeRect;
- (NSRect)_minXResizeRect;
- (NSRect)_minXminYResizeRect;
- (NSRect)_minXmaxYResizeRect;
- (NSRect)_maxYResizeRect;
- (NSRect)_maxYminXResizeRect;
- (NSRect)_maxYmaxXResizeRect;
- (NSRect)_maxXResizeRect;
- (NSRect)_maxXminYResizeRect;
- (NSRect)_maxXmaxYResizeRect;
- (NSRect)_minXTitlebarResizeRect;
- (NSRect)_maxXTitlebarResizeRect;
- (NSRect)_minXBorderRect;
- (NSRect)_maxXBorderRect;
- (NSRect)_maxYBorderRect;
- (NSRect)_minYBorderRect;
- (void)_setUtilityWindow:(char)fp8;
- (char)_isUtility;
- (float)_sheetHeightAdjustment;
- (void)_setSheet:(char)fp8;
- (char)_isSheet;
- (char)_isResizable;
- (char)_isClosable;
- (char)_isMiniaturizable;
- (char)_hasToolbar;
- (NSRect)_growBoxRect;
- (void)_drawGrowBoxWithClip:(NSRect)fp8;
- (char)_inactiveButtonsNeedMask;
- (void)mouseDown:fp8;
- _displayName;
- (void)_setDisplayName:fp8;

@end


text:
<!DOCTYPE html>
<html>
<head>
	<title>Button Group Sample</title>
	<!-- -->
	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
	<!-- -->
	<script src="../../../enyo/enyo.js" type="text/javascript"></script>
	<script src="../../layout/package.js" type="text/javascript"></script>
	<script src="../../onyx/package.js" type="text/javascript"></script>
	<!-- -->
	<link href="sample.css" rel="stylesheet">
	<script src="ButtonGroupSample.js" type="text/javascript"></script>
	<!-- -->
</head>
<body>
<script type="text/javascript">
	new onyx.sample.ButtonGroupSample({classes: "enyo-unselectable"}).write();
</script>
</body>
</html>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using log4net;
using Ninject;
using NUnit.Framework;
using OpenQA.Selenium;
using Sonneville.Fidelity.Shell.AppStartup.Ninject;
using Sonneville.Fidelity.Shell.Interface;
using Sonneville.Investing.Fidelity.WebDriver;
using Sonneville.Investing.Fidelity.WebDriver.Configuration;
using Sonneville.Investing.Fidelity.WebDriver.Navigation;
using Sonneville.Investing.Persistence;
using Sonneville.Investing.Persistence.EFCore.EntityFrameworkCore;
using Sonneville.Selenium.Config;
using Sonneville.Utilities.Persistence.v2;

namespace Sonneville.Fidelity.Shell.Test.AppStartup
{
    [TestFixture]
    public class ImmutableKernelTests
    {
        private static IKernel _kernel;

        [OneTimeSetUp]
        public void Setup()
        {
            _kernel = new KernelBuilder().Build();
        }

        [OneTimeTearDown]
        public void TearDown()
        {
            _kernel?.Dispose();

            LogManager.Shutdown();
        }

        [Test]
        public void ShouldGetDatabaseConnectionInfo()
        {
            Assert.Throws<NotSupportedException>(() => _kernel.Get<DatabaseConnectionInfo>());
        }

        [Test]
        public void ShouldGetPersistenceContext()
        {
            Assert.Throws<NotSupportedException>(() => _kernel.Get<IPersistenceContext>());
        }

        [Test]
        public void ShouldBindConfigStoreAsSingleton()
        {
            var dataStore = _kernel.Get<IDataStore>();

            Assert.IsNotNull(dataStore);
            Assert.AreSame(dataStore, _kernel.Get<IDataStore>());
        }

        [Test]
        public void ShouldCreateFidelityConfiguration()
        {
            var dataStore = _kernel.Get<IDataStore>();

            var config = dataStore.Load<FidelityConfiguration>();
            Assert.IsNotNull(config);
        }

        [Test]
        public void ShouldCreateSeleniumConfiguration()
        {
            var dataStore = _kernel.Get<IDataStore>();

            var config = dataStore.Load<SeleniumConfiguration>();
            Assert.IsNotNull(config);
        }

        [Test]
        public void ShouldBindApp()
        {
            using (var commandRouter = _kernel.Get<ICommandRouter>())
            {
                Assert.IsNotNull(commandRouter);
            }
        }

        [Test]
        public void ShouldBindCommands()
        {
            List<ICommand> commands = null;
            try
            {
                commands = _kernel.GetAll<ICommand>().ToList();

                Assert.IsNotEmpty(commands);
                CollectionAssert.AllItemsAreNotNull(commands);
            }
            finally
            {
                commands?.ForEach(command => command.Dispose());
            }
        }

        [Test]
        public void ShouldBindWebDriverAsSingleton()
        {
            AssertSingleton<IWebDriver>();
        }

        private static void AssertSingleton<T>() where T : IDisposable
        {
            using (var first = _kernel.Get<T>())
            {
                Assert.IsNotNull(first);
                using (var second = _kernel.Get<T>())
                {
                    Assert.AreSame(first, second);
                }
            }
        }

        [Test]
        public void ShouldGetAllPages()
        {
            var pages = _kernel.GetAll<IPage>().ToList();

            Assert.IsNotEmpty(pages);
            CollectionAssert.AllItemsAreNotNull(pages);
        }

        [Test]
        public void ShouldGetSiteNavigator()
        {
            using (var siteNavigator = _kernel.Get<ISiteNavigator>())
            {
                Assert.IsNotNull(siteNavigator);
            }
        }
    }
}


text:
module Blix::Server
  module EchoHandlerMethods
    def echo(val)
      puts "echo #{val.inspect}" if $DEBUG
      val
    end

    def self.included(mod)
      Blix::ServerMethod.new(:echo,:item)
    end
  end
end

module Blix::Server
  class EchoHandler < Handler
    include EchoHandlerMethods
  end
end


text:
package org.elasticsearch.transport;

import org.elasticsearch.ElasticSearchException;

/**
 *
 */
public class TransportException extends ElasticSearchException {

    public TransportException(String msg) {
        super(msg);
    }

    public TransportException(String msg, Throwable cause) {
        super(msg, cause);
    }
}


text:
package core.language.document.tweet;

import core.language.document.DocumentRepository;
import io.corpus.CorpusReader;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

public class TweetRepository implements DocumentRepository {

    private List<Tweet> tweets = new ArrayList<Tweet>();
    private CorpusReader corpusReader;

    public TweetRepository(CorpusReader corpusReader) {
        this.corpusReader = corpusReader;
    }

    public void loadDocuments() {
        try {
            while (corpusReader.hasNextDocument()) {
                tweets.add((Tweet) corpusReader.getNextDocument());
            }
        } catch (ParseException e) {
            System.err.println("Incorrect input format detected. Please check your input file.");
        }
    }

    public int getDocumentCount() {
        return tweets.size();
    }

    public int getToponymCount() {
        int count = 0;
        for (Tweet t : tweets) {
            count += t.getToponymCount();
        }
        return count;
    }

    public int getGeonamesIdCount() {
        int count = 0;
        for (Tweet t : tweets) {
            count += t.getGeonamesIdCount();
        }
        return count;
    }

}


text:
SET SQL_SAFE_UPDATES=0;

delete from `humbuch`.`schoolYear`;
delete from `humbuch`.`student`;
delete from `humbuch`.`studentSubject`;
delete from `humbuch`.`teachingMaterial`;
delete from `humbuch`.`teachingMaterialSubject`;
delete from `humbuch`.`borrowedMaterial`;
delete from `humbuch`.`category`;
delete from `humbuch`.`dunningDate`;
delete from `humbuch`.`dunning_has_borrowedMaterial`;
delete from `humbuch`.`dunning`;
delete from `humbuch`.`parent`;
delete from `humbuch`.`role_has_permission`;
delete from `humbuch`.`user_has_role`;
delete from `humbuch`.`permission`;
delete from `humbuch`.`role`;
delete from `humbuch`.`user`;
delete from `humbuch`.`grade`;
delete from `humbuch`.`setting`;

-- -----------------------------------------------------
-- Data for table `humbuch`.`grade`
-- -----------------------------------------------------
START TRANSACTION;
USE `humbuch`;
INSERT INTO `humbuch`.`grade` (`id`, `grade`, `suffix`, `teacher`) VALUES (1, 5, 'a', NULL);
INSERT INTO `humbuch`.`grade` (`id`, `grade`, `suffix`, `teacher`) VALUES (2, 6, 'a', NULL);
INSERT INTO `humbuch`.`grade` (`id`, `grade`, `suffix`, `teacher`) VALUES (3, 7, 'a', NULL);
INSERT INTO `humbuch`.`grade` (`id`, `grade`, `suffix`, `teacher`) VALUES (4, 8, 'a', NULL);
INSERT INTO `humbuch`.`grade` (`id`, `grade`, `suffix`, `teacher`) VALUES (5, 9, 'a', NULL);

COMMIT;

-- -----------------------------------------------------
-- Data for table `humbuch`.`parent`
-- -----------------------------------------------------
START TRANSACTION;
USE `humbuch`;
INSERT INTO `humbuch`.`parent` (`id`, `title`, `firstname`, `lastname`, `street`, `postcode`, `city`) VALUES (1, 'Herr', 'Siegfried', 'Müller', 'Musterstraße 1', 12345, 'Musterstadt');
INSERT INTO `humbuch`.`parent` (`id`, `title`, `firstname`, `lastname`, `street`, `postcode`, `city`) VALUES (2, 'Herr', 'Manfred', 'Perterson', 'Musterstraße 1', 12345, 'Musterstadt');

COMMIT;

-- -----------------------------------------------------
-- Data for table `humbuch`.`student`
-- -----------------------------------------------------
START TRANSACTION;
USE `humbuch`;
INSERT INTO `humbuch`.`student` (`id`, `gradeId`, `lastname`, `firstname`, `birthday`, `gender`, `parentId`, `leavingSchool`) VALUES (1, 1, 'Müller', 'Hans', '1998-05-01', 'm', 1, 0);
INSERT INTO `humbuch`.`student` (`id`, `gradeId`, `lastname`, `firstname`, `birthday`, `gender`, `parentId`, `leavingSchool`) VALUES (2, 1, 'Maier', 'Peter', '1998-05-01', 'm', 1, 0);
INSERT INTO `humbuch`.`student` (`id`, `gradeId`, `lastname`, `firstname`, `birthday`, `gender`, `parentId`, `leavingSchool`) VALUES (3, 3, 'Peterson', 'Alfred', '2013-12-28', 'm', 2, 0);
INSERT INTO `humbuch`.`student` (`id`, `gradeId`, `lastname`, `firstname`, `birthday`, `gender`, `parentId`, `leavingSchool`) VALUES (4, 3, 'Flick', 'Hansi', '2013-12-28', 'm', 2, 0);

COMMIT;

-- -----------------------------------------------------
-- Data for table `humbuch`.`category`
-- -----------------------------------------------------
START TRANSACTION;
USE `humbuch`;
INSERT INTO `humbuch`.`category` (`id`, `name`, `description`) VALUES (1, 'Bücher', NULL);

COMMIT;

-- -----------------------------------------------------
-- Data for table `humbuch`.`teachingMaterial`
-- -----------------------------------------------------
START TRANSACTION;
USE `humbuch`;
INSERT INTO `humbuch`.`teachingMaterial` (`id`, `categoryId`, `name`, `identifyingNumber`, `producer`, `price`, `comment`, `fromGrade`, `toGrade`, `fromTerm`, `toTerm`, `validFrom`, `validUntil`) VALUES (1, 1, 'Englisch 5', '442275214', 'Cornelsen', 0.00, NULL, 5, 5, 0, 1, '2013-12-01', NULL);
INSERT INTO `humbuch`.`teachingMaterial` (`id`, `categoryId`, `name`, `identifyingNumber`, `producer`, `price`, `comment`, `fromGrade`, `toGrade`, `fromTerm`, `toTerm`, `validFrom`, `validUntil`) VALUES (2, 1, 'Englisch 6', '136911291', 'Cornelsen', 0.00, NULL, 6, 6, 0, 1, '2013-12-01', NULL);
INSERT INTO `humbuch`.`teachingMaterial` (`id`, `categoryId`, `name`, `identifyingNumber`, `producer`, `price`, `comment`, `fromGrade`, `toGrade`, `fromTerm`, `toTerm`, `validFrom`, `validUntil`) VALUES (3, 1, 'Englisch 5-8', '226899435', 'Cornelsen', 0.00, NULL, 5, 8, 0, 1, '2013-12-01', NULL);
INSERT INTO `humbuch`.`teachingMaterial` (`id`, `categoryId`, `name`, `identifyingNumber`, `producer`, `price`, `comment`, `fromGrade`, `toGrade`, `fromTerm`, `toTerm`, `validFrom`, `validUntil`) VALUES (4, 1, 'Englisch 5 ALT', '419939614', 'Cornelsen', 0.00, NULL, 5, 5, 0, 1, '2011-10-01', '2013-10-01');
INSERT INTO `humbuch`.`teachingMaterial` (`id`, `categoryId`, `name`, `identifyingNumber`, `producer`, `price`, `comment`, `fromGrade`, `toGrade`, `fromTerm`, `toTerm`, `validFrom`, `validUntil`) VALUES (5, 1, 'Deutsch 5', '648778295', 'Cornelsen', 0.00, NULL, 5, 5, 0, 1, '2013-12-01', NULL);
INSERT INTO `humbuch`.`teachingMaterial` (`id`, `categoryId`, `name`, `identifyingNumber`, `producer`, `price`, `comment`, `fromGrade`, `toGrade`, `fromTerm`, `toTerm`, `validFrom`, `validUntil`) VALUES (6, 1, 'Latein 5', '208496904', 'Cornelsen', 0.00, NULL, 5, 5, 0, 1, '2013-12-01', NULL);
INSERT INTO `humbuch`.`teachingMaterial` (`id`, `categoryId`, `name`, `identifyingNumber`, `producer`, `price`, `comment`, `fromGrade`, `toGrade`, `fromTerm`, `toTerm`, `validFrom`, `validUntil`) VALUES (7, 1, 'Evg Reli 5', '391918769', 'Cornelsen', 0.00, NULL, 5, 5, 0, 1, '2013-12-01', NULL);
INSERT INTO `humbuch`.`teachingMaterial` (`id`, `categoryId`, `name`, `identifyingNumber`, `producer`, `price`, `comment`, `fromGrade`, `toGrade`, `fromTerm`, `toTerm`, `validFrom`, `validUntil`) VALUES (8, 1, 'Evg Reli 7', '440499670', 'Cornelsen', 0.00, NULL, 7, 7, 0, 1, '2013-12-01', NULL);
INSERT INTO `humbuch`.`teachingMaterial` (`id`, `categoryId`, `name`, `identifyingNumber`, `producer`, `price`, `comment`, `fromGrade`, `toGrade`, `fromTerm`, `toTerm`, `validFrom`, `validUntil`) VALUES (9, 1, 'Gemeinschaftskunde 5', '129991165', 'Cornelsen', 0.00, NULL, 5, 5, 0, 0, '2013-12-01', NULL);
INSERT INTO `humbuch`.`teachingMaterial` (`id`, `categoryId`, `name`, `identifyingNumber`, `producer`, `price`, `comment`, `fromGrade`, `toGrade`, `fromTerm`, `toTerm`, `validFrom`, `validUntil`) VALUES (10, 1, 'Erdkunde 5', '354180810', 'Cornelsen', 0.00, NULL, 5, 5, 1, 1, '2013-12-01', NULL);
INSERT INTO `humbuch`.`teachingMaterial` (`id`, `categoryId`, `name`, `identifyingNumber`, `producer`, `price`, `comment`, `fromGrade`, `toGrade`, `fromTerm`, `toTerm`, `validFrom`, `validUntil`) VALUES (11, 1, 'Atlas', '860937574', 'Cornelsen', 0.00, NULL, 5, 6, 1, 0, '2013-12-01', NULL);

COMMIT;

-- -----------------------------------------------------
-- Data for table `humbuch`.`user`
-- -----------------------------------------------------
START TRANSACTION;
USE `humbuch`;
INSERT INTO `humbuch`.`user` (`id`, `username`, `password`, `email`) VALUES (1, 'admin', '500:d854d1abe5e05e2e2ad4d3bde6d6c1e858ec18c1:c816e7e095abc356c27ff84ccf5c0c1275299ae4', 'test@test.com');
INSERT INTO `humbuch`.`user` (`id`, `username`, `password`, `email`) VALUES (2, 'schlager', '500:1dac1aeacf9cc190a569672bea49432f6be88d5e:45446a81139d8aca30ec3762cdf734cbb60adaf9', 'schlager@test.com');

COMMIT;

-- -----------------------------------------------------
-- Data for table `humbuch`.`role`
-- -----------------------------------------------------
START TRANSACTION;
USE `humbuch`;
INSERT INTO `humbuch`.`role` (`id`, `name`, `description`) VALUES (1, 'Admin', NULL);

COMMIT;

-- -----------------------------------------------------
-- Data for table `humbuch`.`permission`
-- -----------------------------------------------------
START TRANSACTION;
USE `humbuch`;
INSERT INTO `humbuch`.`permission` (`id`, `name`, `description`) VALUES (1, 'darf alles', NULL);

COMMIT;

-- -----------------------------------------------------
-- Data for table `humbuch`.`user_has_role`
-- -----------------------------------------------------
START TRANSACTION;
USE `humbuch`;
INSERT INTO `humbuch`.`user_has_role` (`user_id`, `role_id`) VALUES (1, 1);

COMMIT;

-- -----------------------------------------------------
-- Data for table `humbuch`.`role_has_permission`
-- -----------------------------------------------------
START TRANSACTION;
USE `humbuch`;
INSERT INTO `humbuch`.`role_has_permission` (`role_id`, `permission_id`) VALUES (1, 1);

COMMIT;

-- -----------------------------------------------------
-- Data for table `humbuch`.`schoolYear`
-- -----------------------------------------------------
START TRANSACTION;
USE `humbuch`;
INSERT INTO `humbuch`.`schoolYear` (`id`, `year`, `fromDate`, `toDate`, `endFirstTerm`, `beginSecondTerm`) VALUES (1, '2012/2013', '2012-08-01', '2013-07-31', '2013-01-31', '2013-02-01');
INSERT INTO `humbuch`.`schoolYear` (`id`, `year`, `fromDate`, `toDate`, `endFirstTerm`, `beginSecondTerm`) VALUES (2, '2013/2014', '2013-08-01', '2014-07-31', '2014-01-31', '2014-02-01');
INSERT INTO `humbuch`.`schoolYear` (`id`, `year`, `fromDate`, `toDate`, `endFirstTerm`, `beginSecondTerm`) VALUES (3, '2014/2015', '2014-08-01', '2015-07-31', '2015-01-31', '2015-02-01');

COMMIT;

-- -----------------------------------------------------
-- Data for table `humbuch`.`studentSubject`
-- -----------------------------------------------------
START TRANSACTION;
USE `humbuch`;
INSERT INTO `humbuch`.`studentSubject` (`id`, `studentId`, `subject`) VALUES (1, 1, 'STANDARD');
INSERT INTO `humbuch`.`studentSubject` (`id`, `studentId`, `subject`) VALUES (2, 1, 'LATIN');
INSERT INTO `humbuch`.`studentSubject` (`id`, `studentId`, `subject`) VALUES (3, 1, 'EVANGELIC');
INSERT INTO `humbuch`.`studentSubject` (`id`, `studentId`, `subject`) VALUES (4, 2, 'STANDARD');
INSERT INTO `humbuch`.`studentSubject` (`id`, `studentId`, `subject`) VALUES (5, 2, 'LATIN');
INSERT INTO `humbuch`.`studentSubject` (`id`, `studentId`, `subject`) VALUES (6, 2, 'EVANGELIC');
INSERT INTO `humbuch`.`studentSubject` (`id`, `studentId`, `subject`) VALUES (7, 3, 'STANDARD');
INSERT INTO `humbuch`.`studentSubject` (`id`, `studentId`, `subject`) VALUES (8, 3, 'LATIN');
INSERT INTO `humbuch`.`studentSubject` (`id`, `studentId`, `subject`) VALUES (9, 3, 'EVANGELIC');
INSERT INTO `humbuch`.`studentSubject` (`id`, `studentId`, `subject`) VALUES (10, 4, 'STANDARD');
INSERT INTO `humbuch`.`studentSubject` (`id`, `studentId`, `subject`) VALUES (11, 4, 'LATIN');
INSERT INTO `humbuch`.`studentSubject` (`id`, `studentId`, `subject`) VALUES (12, 4, 'EVANGELIC');

COMMIT;

-- -----------------------------------------------------
-- Data for table `humbuch`.`teachingMaterialSubject`
-- -----------------------------------------------------
START TRANSACTION;
USE `humbuch`;
INSERT INTO `humbuch`.`teachingMaterialSubject` (`id`, `teachingMaterialId`, `subject`) VALUES (1, 1, 'STANDARD');
INSERT INTO `humbuch`.`teachingMaterialSubject` (`id`, `teachingMaterialId`, `subject`) VALUES (2, 2, 'STANDARD');
INSERT INTO `humbuch`.`teachingMaterialSubject` (`id`, `teachingMaterialId`, `subject`) VALUES (3, 3, 'STANDARD');
INSERT INTO `humbuch`.`teachingMaterialSubject` (`id`, `teachingMaterialId`, `subject`) VALUES (4, 4, 'STANDARD');
INSERT INTO `humbuch`.`teachingMaterialSubject` (`id`, `teachingMaterialId`, `subject`) VALUES (5, 5, 'STANDARD');
INSERT INTO `humbuch`.`teachingMaterialSubject` (`id`, `teachingMaterialId`, `subject`) VALUES (6, 6, 'LATIN');
INSERT INTO `humbuch`.`teachingMaterialSubject` (`id`, `teachingMaterialId`, `subject`) VALUES (7, 7, 'EVANGELIC');
INSERT INTO `humbuch`.`teachingMaterialSubject` (`id`, `teachingMaterialId`, `subject`) VALUES (8, 8, 'EVANGELIC');
INSERT INTO `humbuch`.`teachingMaterialSubject` (`id`, `teachingMaterialId`, `subject`) VALUES (9, 9, 'STANDARD');
INSERT INTO `humbuch`.`teachingMaterialSubject` (`id`, `teachingMaterialId`, `subject`) VALUES (10, 10, 'STANDARD');
INSERT INTO `humbuch`.`teachingMaterialSubject` (`id`, `teachingMaterialId`, `subject`) VALUES (11, 11, 'STANDARD');

COMMIT;

-- -----------------------------------------------------
-- Data for table `humbuch`.`setting`
-- -----------------------------------------------------
START TRANSACTION;
USE `humbuch`;
INSERT INTO `humbuch`.`setting` (`id`, `settingKey`, `settingValue`, `settingStandardValue`) VALUES (4, 'dun_firstDunningDeadline', '14', '14');
INSERT INTO `humbuch`.`setting` (`id`, `settingKey`, `settingValue`, `settingStandardValue`) VALUES (5, 'dun_secondDunningDeadline', '14', '14');

COMMIT;


text:
import rospy
from std_msgs.msg import String
from sensor_msgs.msg import Image

import numpy as np
import sys, os

# Import superclass and helper classes
from camera_simulator import CameraSimulator
sys.path.append(os.path.abspath('../..'))
from shared.imagewindow import ImageWindow
from shared.bagreader import BagReader
from shared.action import Action

ns = '/bebop/'

class LabeledCameraSimulator(CameraSimulator):
    def __init__(self, display=False, newtopic=True):
        super(LabeledCameraSimulator, self).__init__(display=display, newtopic=newtopic)
        self.label_topic = rospy.Publisher(ns+'label', String, latch=True, queue_size=1)
        self.label_msg = String()

    def next_labeled_image(self):
        i = self.frame % self.num_images
        label = self.labels[i]
        data = self.next_image() # self.frame is incremented here
        return data, label

    def make_label_msg(self, label):
        self.label_msg.data = Action.name(label)
        return self.label_msg

    def make_labeled_image_msgs(self, (data, label)):
        label_msg = self.make_label_msg(label)
        image_msg = self.make_image_msg(data)
        return image_msg, label_msg

    def log_labeled_image(self, img, label):
        rospy.loginfo('{}: {} x {} ({})'.format(self.frame, img.width, img.height, label))

    # Similar to the superclass simulate method, but adds a label topic
    def simulate(self, bagfile, npzfile):
        # Load jpeg-encoded images from rosbag file
        self._load_bag_data(bagfile)
        # Load label data
        npz = np.load(npzfile)
        labels = self.labels = npz['labels']

        # Double check that our label and bag image counts match
        # This isn't true for "cropped" bag files
        assert self.labels.shape[0] == self.image_data.shape[0]

        # This logic belongs elsewhere
        # Initialize display window
        if self.display:
            self.iw = ImageWindow(self.width, self.height)

        # Initialize ROS node
        rospy.init_node('labeled_camera_simulator')

        # Begin 4 Hz loop
        rate = rospy.Rate(4)
        while not rospy.is_shutdown():
            img_msg, label_msg = self.make_labeled_image_msgs(self.next_labeled_image())
            self.log_labeled_image(img_msg, label_msg)
            self.camera.publish(img_msg)
            self.label_topic.publish(label_msg)
            rate.sleep()

# TODO: Add argparse support?
if __name__ == '__main__':
    bagfile = 'test.bag'
    npzfile = 'test.npz'
    drone = LabeledCameraSimulator(display=False, newtopic=False)
    try:
        drone.simulate(bagfile, npzfile)
    except rospy.ROSInterruptException:
        pass


text:
package org.jivesoftware.openfire.handler;

import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.util.cache.ExternalizableUtil;
import org.xmpp.packet.JID;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.HashSet;
import java.util.Set;

/**
 * Represents a directed presence sent from a session hosted in a cluster node
 * to another entity (e.g. user or MUC service) hosted in some other cluster
 * node.

 *
 * This information needs to be shared by all cluster nodes so that if a
 * cluster node goes down then directed presences can be correctly cleaned
 * up.

 *
 * Note that an instance of this class will be created and kept in the clustered
 * cache only when entities hosted by different cluster nodes are involved.
 *
 * @author Gaston Dombiak
 */
public class DirectedPresence implements Externalizable {
    /**
     * ID of the node that received the request to send a directed presence. This is the
     * node ID that hosts the sender.
     */
    private byte[] nodeID;
    /**
     * Full JID of the entity that received the directed presence.
     * E.g.: paul@js.com/Spark or conference.js.com
     */
    private JID handler;
    /**
     * List of JIDs with the TO value of the directed presences.
     * E.g.: paul@js.com or room1@conference.js.com
     */
    private Set<String> receivers = new HashSet<>();

    public DirectedPresence() {
    }

    public DirectedPresence(JID handlerJID) {
        this.handler = handlerJID;
        this.nodeID = XMPPServer.getInstance().getNodeID().toByteArray();
    }

    public byte[] getNodeID() {
        return nodeID;
    }

    public JID getHandler() {
        return handler;
    }

    public Set<String> getReceivers() {
        return receivers;
    }

    public void addReceiver(String receiver) {
        receivers.add(receiver);
    }

    public void removeReceiver(String receiver) {
        receivers.remove(receiver);
    }

    public boolean isEmpty() {
        return receivers.isEmpty();
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        ExternalizableUtil.getInstance().writeByteArray(out, nodeID);
        ExternalizableUtil.getInstance().writeSerializable(out, handler);
        ExternalizableUtil.getInstance().writeStrings(out, receivers);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        nodeID = ExternalizableUtil.getInstance().readByteArray(in);
        handler = (JID) ExternalizableUtil.getInstance().readSerializable(in);
        ExternalizableUtil.getInstance().readStrings(in, receivers);
    }
}