text:
package org.vaadin.textfieldformatter;

import java.util.ArrayList;

import com.vaadin.flow.component.textfield.TextField;

public class CustomStringBlockFormatter extends CleaveExtension {

	/**
	 * Creates an instance of CustomStringBlockFormatter. Call extend to attach this
	 * formatter to a TextField.
	 *
	 * @param blocks      an array configuring the character blocks. The length of
	 *                    the array is the number of character blocks. The integers
	 *                    in the array are the length of the blocks.
	 * @param delimiters  the delimiter characters to be used between the character
	 *                    blocks
	 * @param forceCase   enumeration to control letter case of characters. One of
	 *                    ForceCase.NONE don't touch letter case. ForceCase.LOWER
	 *                    transform characters to lower case. ForceCase.UPPER
	 *                    transform characters to upper case.
	 * @param prefix      String prefix for the input
	 * @param numericOnly true for allowing numeric characters only. Defaults to
	 *                    false.
	 */
	public CustomStringBlockFormatter(int[] blocks, String[] delimiters, ForceCase forceCase, String prefix,
			boolean numericOnly) {
		this(blocks, delimiters, false, forceCase, prefix, true, numericOnly);
	}

	/**
	 * Creates an instance of CustomStringBlockFormatter. Call extend to attach this
	 * formatter to a TextField.
	 *
	 * @param blocks                an array configuring the character blocks. The
	 *                              length of the array is the number of character
	 *                              blocks. The integers in the array are the length
	 *                              of the blocks.
	 * @param delimiters            the delimiter characters to be used between the
	 *                              character blocks
	 * @param forceCase             enumeration to control letter case of
	 *                              characters. One of ForceCase.NONE don't touch
	 *                              letter case. ForceCase.LOWER transform
	 *                              characters to lower case. ForceCase.UPPER
	 *                              transform characters to upper case.
	 * @param prefix                String prefix for the input
	 * @param showPrefixImmediately true if you want to show prefix before value is
	 *                              entered i.e. always. Default true.
	 * @param numericOnly           true for allowing numeric characters only.
	 *                              Defaults to false.
	 */
	public CustomStringBlockFormatter(int[] blocks, String[] delimiters, ForceCase forceCase, String prefix,
			boolean showPrefixImmediately, boolean numericOnly) {
		this(blocks, delimiters, false, forceCase, prefix, showPrefixImmediately, numericOnly);
	}

	private CustomStringBlockFormatter(int[] blocks, String[] delimiters, boolean lazyDelimiter, ForceCase forceCase,
			String prefix, boolean showPrefixImmediately, boolean numericOnly) {
		getConfiguration().blocks = blocks;
		getConfiguration().delimiters = delimiters;
		getConfiguration().delimiterLazyShow = lazyDelimiter;
		if (forceCase == ForceCase.UPPER) {
			getConfiguration().lowercase = false;
			getConfiguration().uppercase = true;
		} else if (forceCase == ForceCase.LOWER) {
			getConfiguration().lowercase = true;
			getConfiguration().uppercase = false;
		}
		getConfiguration().prefix = prefix;
		getConfiguration().showPrefixImmediately = showPrefixImmediately;
		getConfiguration().numericOnly = numericOnly;
	}

	public CustomStringBlockFormatter(Options options) {
		this(options.blocks, options.delimiters, options.lazyDelimiter, options.forceCase, options.prefix,
				options.showPrefixImmediately, options.numericOnly);
	}

	/**
	 * Adds this extension to a TextField. Extension cannot be moved to another
	 * TextField again.
	 *
	 * @param textField TextField to attach this extension to
	 */
	public void extend(TextField textField) {
		super.extend(textField);
	}

	public enum ForceCase {
		NONE, UPPER, LOWER
	}

	public static class Builder {
		private String prefix;
		private boolean showPrefixImmediately = true;
		private ForceCase _case;
		private boolean numeric;
		private final ArrayList<String> delimiters = new ArrayList<>();
		private boolean lazyDelimiter = false;
		private final ArrayList<Integer> blocks = new ArrayList<>();

		/**
		 * Creates prefix as the first block and delimiter. This will replaced
		 * previously set prefix block. This will prepend any previously set normal
		 * blocks.
		 *
		 * @param prefix    String prefix to use. Cannot be null or empty.
		 * @param delimiter String delimiter after the prefix block. Cannot be null or
		 *                  empty.
		 * @return this Builder
		 */
		public Builder prefix(String prefix, String delimiter) {
			return prefix(prefix, true, delimiter);
		}

		/**
		 * Creates prefix as the first block and delimiter. This will replaced
		 * previously set prefix block. This will prepend any previously set normal
		 * blocks.
		 *
		 * @param prefix                String prefix to use. Cannot be null or empty.
		 * @param showPrefixImmediately true if the prefix should be shown even before
		 *                              user has input anything to the field. Default
		 *                              behavior is true.
		 * @param delimiter             String delimiter after the prefix block. Cannot
		 *                              be null or empty.
		 * @return this Builder
		 */
		public Builder prefix(String prefix, boolean showPrefixImmediately, String delimiter) {
			if (prefix == null || prefix.isEmpty())
				throw new IllegalArgumentException("Prefix cannot be null or empty.");
			if (delimiter == null || delimiter.isEmpty())
				throw new IllegalArgumentException("Delimiter cannot be null or empty.");
			this.prefix = prefix;
			this.showPrefixImmediately = showPrefixImmediately;
			blocks.add(0, prefix.length());
			delimiters.add(0, delimiter);
			return this;
		}

		/**
		 * Appends a block with a given block length and delimiter character. If this is
		 * the last block, the delimiter will be ignored.
		 *
		 * @param blockLength int block length
		 * @param delimiter   String delimiter after block. Cannot be null or empty.
		 * @return this Builder
		 */
		public Builder block(int blockLength, String delimiter) {
			if (delimiter == null || delimiter.isEmpty())
				throw new IllegalArgumentException("Delimiter cannot be null or empty.");
			blocks.add(blockLength);
			delimiters.add(delimiter);
			return this;
		}

		/**
		 * Appends the blocks with a given block lengths.
		 *
		 * @param blockLengths int[] block lengths
		 * @return this Builder
		 */
		public Builder blocks(int... blockLengths) {
			if (blockLengths == null)
				throw new IllegalArgumentException("Block lengths cannot be null.");
			for (int block : blockLengths) {
				blocks.add(block);
			}
			return this;
		}

		/**
		 * Appends the blocks with a given block lengths.
		 *
		 * @param delimiters String[] delimiters to be used. Cannot be null.
		 * @return this Builder
		 */
		public Builder delimiters(String... delimiters) {
			if (delimiters == null)
				throw new IllegalArgumentException("Delimiters cannot be null.");
			for (String delimiter : delimiters) {
				this.delimiters.add(delimiter);
			}
			return this;
		}

		/**
		 * Show the delimiter only when the user starts typing the next group section.
		 * Default is false.
		 *
		 * @return
		 */
		public Builder delimiterLazyShow() {
			lazyDelimiter = true;
			return this;
		}

		/**
		 * Allows only numeric characters. Default is allowing any character.
		 *
		 * @return this Builder
		 */
		public Builder numeric() {
			numeric = true;
			return this;
		}

		/**
		 * Sets the forced letter casing of characters.
		 *
		 * @param _case enumeration to control letter case of characters. ForceCase.NONE
		 *              don't touch letter case. ForceCase.LOWER transform characters to
		 *              lower case. ForceCase.UPPER transform characters to upper case.
		 * @return this Builder
		 */
		public Builder forceCase(ForceCase _case) {
			this._case = _case;
			return this;
		}

		public CustomStringBlockFormatter build() {
			return new CustomStringBlockFormatter(buildOptions());
		}

		public Options buildOptions() {
			Options options = new Options();
			options.setForceCase(_case);
			options.setNumericOnly(numeric);
			options.setPrefix(prefix, showPrefixImmediately);
			if (!blocks.isEmpty() && !delimiters.isEmpty()) {
				options.setBlocks(blocks.stream().mapToInt(Integer::valueOf).toArray());
				options.setDelimiters(delimiters.toArray(new String[delimiters.size()]));
			}
			options.setDelimiterLazyShow(lazyDelimiter);
			return options;
		}
	}

	public static class Options {
		private int[] blocks;
		private String[] delimiters = null;
		private boolean lazyDelimiter = false;
		private ForceCase forceCase = ForceCase.NONE;
		private boolean numericOnly = false;
		private String prefix;
		private boolean showPrefixImmediately = true;

		public Options(int[] blocks, String[] delimiters, ForceCase forceCase, String prefix, boolean numericOnly) {
			this(blocks, delimiters, forceCase, prefix, true, numericOnly);
		}

		public Options(int[] blocks, String[] delimiters, ForceCase forceCase, String prefix,
				boolean showPrefixImmediately, boolean numericOnly) {
			this(blocks, delimiters, false, forceCase, prefix, showPrefixImmediately, numericOnly);
		}

		public Options(int[] blocks, String[] delimiters, boolean delimiterLazyShow, ForceCase forceCase, String prefix,
				boolean showPrefixImmediately, boolean numericOnly) {
			this.blocks = blocks;
			this.delimiters = delimiters;
			this.lazyDelimiter = delimiterLazyShow;
			this.forceCase = forceCase;
			this.prefix = prefix;
			this.showPrefixImmediately = showPrefixImmediately;
			this.numericOnly = numericOnly;
		}

		public Options(Options options) {
			this(options.blocks, options.delimiters, options.lazyDelimiter, options.forceCase, options.prefix,
					options.showPrefixImmediately, options.numericOnly);
		}

		public Options() {

		}

		public int[] getBlocks() {
			return blocks;
		}

		public void setBlocks(int... blocks) {
			this.blocks = blocks;
		}

		public String[] getDelimiters() {
			return delimiters;
		}

		public void setDelimiters(String... delimiters) {
			this.delimiters = delimiters;
		}

		/**
		 *
		 * @param lazy if true, will lazy add the delimiter only when the user starting
		 *             typing the next group section. Default is false.
		 */
		public void setDelimiterLazyShow(boolean lazy) {
			this.lazyDelimiter = lazy;
		}

		public boolean isDelimiterLazyShow() {
			return lazyDelimiter;
		}

		public ForceCase getForceCase() {
			return forceCase;
		}

		public void setForceCase(ForceCase forceCase) {
			this.forceCase = forceCase;
		}

		public String getPrefix() {
			return prefix;
		}

		public void setPrefix(String prefix) {
			setPrefix(prefix, true);
		}

		/**
		 *
		 * @param prefix          Prefix to show
		 * @param showImmediately true if the prefix should be shown even before user
		 *                        has input anything to the field. Default for Options
		 *                        is true.
		 */
		public void setPrefix(String prefix, boolean showImmediately) {
			this.prefix = prefix;
			this.showPrefixImmediately = showImmediately;
		}

		public boolean isNumericOnly() {
			return numericOnly;
		}

		public void setNumericOnly(boolean numericOnly) {
			this.numericOnly = numericOnly;
		}
	}
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
J. Jap. Bot. 45:91. 1970

#### Original name
null

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace bbcsky\payment;

use yii\base\Component;

class Payment extends Component
{
    public $code;
    public $notify_url;
    public $order_pre;

}


text:
DAFTAR KEHADIRAN MT

            <?php if ($periode != "Laporan Bulan Ini") {
                ?>

Periode <?php echo $periode ?>

            <?php } else {
                ?>

<?php echo $periode ?>

                <?php
            }
            ?>

                        Nama SPG
                        Kehadiran
                        Absen
                        Gaji

                    <?php if (count($kehadirans) == 0): ?>

                            Tidak Ada Data

                        <?php
                    endif;
                    foreach ($kehadirans as $kehadiran) :
                        ?>

                            <?php echo $kehadiran->nama ?>
                            <?php echo $kehadiran->hadir ?>
                            <?php echo $kehadiran->absen ?>
                            Rp. <?php
                                $hadir = intval($kehadiran->hadir);
                                $gajiperhari = intval($kehadiran->gaji);
                                echo number_format($hadir * $gajiperhari, 0, ",", ".");
                                ?>,-

                    <?php endforeach; ?>


text:
Only call a function once.

## usage

```javascript
var once = require('once')

function load (file, cb) {
  cb = once(cb)
  loader.load('file')
  loader.once('load', cb)
  loader.once('error', cb)
}
```

Or add to the Function.prototype in a responsible way:

```javascript
// only has to be done once
require('once').proto()

function load (file, cb) {
  cb = cb.once()
  loader.load('file')
  loader.once('load', cb)
  loader.once('error', cb)
}
```

Ironically, the prototype feature makes this modul


text:
describe Medic::StatisticsOptions do

  before do
    @subject = Object.new
    @subject.extend(Medic::StatisticsOptions)
  end

  describe "#options_for_stat_query" do
    it "correctly calculates the value for options" do
      @subject.options_for_stat_query(:none).should == 0
      @subject.options_for_stat_query([:by_source, :sum]).should == 17
      @subject.options_for_stat_query([:average, :min, :max]).should == 14
    end
  end

  describe "#statistics_option" do
    it "returns the correct type identifier for symbol" do
      @subject.statistics_option(:none).should == HKStatisticsOptionNone
      @subject.statistics_option(:by_source).should == HKStatisticsOptionSeparateBySource
      @subject.statistics_option(:separate_by_source).should == HKStatisticsOptionSeparateBySource
      @subject.statistics_option(:average).should == HKStatisticsOptionDiscreteAverage
      @subject.statistics_option(:discrete_average).should == HKStatisticsOptionDiscreteAverage
      @subject.statistics_option(:min).should == HKStatisticsOptionDiscreteMin
      @subject.statistics_option(:discrete_min).should == HKStatisticsOptionDiscreteMin
      @subject.statistics_option(:max).should == HKStatisticsOptionDiscreteMax
      @subject.statistics_option(:discrete_max).should == HKStatisticsOptionDiscreteMax
      @subject.statistics_option(:sum).should == HKStatisticsOptionCumulativeSum
      @subject.statistics_option(:cumulative_sum).should == HKStatisticsOptionCumulativeSum
    end
  end

end


text:
// Identify modules.
var modules = require("../modules/modules"),
    router = modules.router,
	ObjectId = require("mongoose").Types.ObjectId,
    User = require("../modules/models/user"),
	Message = require("../modules/models/message");

/**
 * Name:	GET INFO
 * Method:	GET
 * Params:	id
 */
router.get("/info", function(req, res) {
	var id = req.param("id");

	User.findOne({
		_id: id
	}, ["_id", "email", "directs", "channels"])
	.then(function(user) {
		return res.status(200).send({
			message: user
		});
	})
	.catch(function(error) {
		return res.status(200).send({
	      message: "Something went wrong. Please try again later."
	    });
	})
});

/**
 * Name:	GET ALL USER
 * Method:	GET
 * Params:	NONE
 */
router.get("/get_user", function(req, res) {
	User.find({}, ["_id", "email"])
	.then(function(user) {
		res.status(200).send({
			message: user
		});
	})
	.then(function(error) {
		res.send(error);
	})
});

/**
 * Name:	CREATE DIRECT MESSAGE
 * Method:	POST
 * Params:	myEmail, otherEmail
 */
router.post("/direct/create", function(req, res) {
	var myEmail = req.body.myEmail,
		otherEmail = req.body.otherEmail;

	  ///////////////////////////////////////////////////
	 // Display error function.                       //
	///////////////////////////////////////////////////
	function displayError() {
		return res.status(404).send("Cannot create direct messages.");
	}

	User.find({
		email: {
			$in: [myEmail, otherEmail]
		}
	}, ["email", "directs"])
	.then(function(users) {
		(users.length > 1) ? createRoom() : displayError();

		  ///////////////////////////////////////////////////
		 // Create room function.                         //
		///////////////////////////////////////////////////
		function createRoom() {
			var check = false;

			/**Start check already created room. */
			for (var i = 0; i < users.length; i++) {
				switch (users[i].email) {
					case myEmail: {
						var directs = users[i].directs;

						/**Reset directs array to empty. */
						users[i].directs = [];

						for (var j = 0; j < directs.length; j++) {
							if (directs[j].arrEmail.indexOf(otherEmail) !== -1 && !directs[j].visible) {
								check = true;
								directs[j].visible = true;

								/**Resave directs array. */
								users[i].directs = directs;
								users[i].save();
								console.log(users[i].directs[j])
								break;
							}
						}
					}
				}
			}
			/**End check. */

			if (!check) {
				// Start create room.
				var  message = new Message();
				message
				.save()
				.then(function(msg) {
					var directID = msg._id;
					users.forEach(function(user) {
						user.directs.push({
							_id: directID,
							arrEmail: [myEmail, otherEmail],
							visible: true
						})
						user.save();
					})
					return res.status(201).send({
						message: users
					});
				})
				.catch(function(error) {
					displayError();
				});
			}else {
				return res.status(201).send({
					message: users
				});
			}
		}
	})
	.catch(function(error) {
		displayError();
	});
});

/**
 * Name:	REMOVE DIRECT MESSAGE
 * Method:	POST
 * Params:	myEmail, directID
 */
router.post("/direct/remove", function(req, res) {
	var myEmail = req.body.myEmail,
		directID = req.body.directID;

	User.findOne({
		email: myEmail
	}, ["email", "directs"])
	.then(function(user) {
		if (user === null) return res.status(404).send({
			message: "Email not found."
		});

		var directs = user.directs;
		user.directs = [];
		for (var i = 0; i < directs.length; i++) {
			if (directs[i]._id == directID) {
				directs[i].visible = false;
				user.directs = directs;
				user.save();
				break;
			}
		}

		return res.status(200).send({
			message: user
		});
	})
	.catch(function(error) {
		return res.status(200).send({
			message: "Something went wrong. Please try again later."
		});
	});
})

// Export router.
module.exports = router;


text:
#region

using System;
using WeatherNet.Model;

#endregion

namespace WeatherNet.Model
{
    /// <summary>
    ///     HistoricWeatherResult result type.
    /// </summary>
    public class HistoricWeatherResult : WeatherResult
    {
        /// <summary>
        ///     Atmospheric pressure in hPa.
        /// </summary>
        public Double Pressure { get; set; }

        /// <summary>
        ///     Wind direction in degrees (meteorological)
        /// </summary>
        public double WindDirection { get; set; }

        /// <summary>
        ///     Speed of wind gust
        /// </summary>
        public double WindGustSpeed { get; set; }

        /// <summary>
        ///     Rain volume mm .
        /// </summary>
        public Double Rain { get; set; }

        /// <summary>
        ///     Cloudiness in %
        /// </summary>
        public Double Clouds { get; set; }
    }
}


text:
namespace CodeStage.AntiCheat.Editor.Editors
{
	using Detectors;
	using UnityEditor;

	[CustomEditor(typeof (SpeedHackDetector))]
	internal class SpeedHackDetectorEditor : ActDetectorEditor
	{
		private SerializedProperty interval;
		private SerializedProperty maxFalsePositives;
		private SerializedProperty coolDown;

		protected override void FindUniqueDetectorProperties()
		{
			interval = serializedObject.FindProperty("interval");
			maxFalsePositives = serializedObject.FindProperty("maxFalsePositives");
			coolDown = serializedObject.FindProperty("coolDown");
		}

		protected override void DrawUniqueDetectorProperties()
		{
			EditorGUILayout.PropertyField(interval);
			EditorGUILayout.PropertyField(maxFalsePositives);
			EditorGUILayout.PropertyField(coolDown);
		}
	}
}


text:
[![Apache 2](http://img.shields.io/badge/license-Apache%202-blue.svg)](http://www.apache.org/licenses/LICENSE-2.0)
[![Join the chat at https://gitter.im/plesk/ext-security-advisor](https://badges.gitter.im/plesk/ext-security-advisor.svg)](https://gitter.im/plesk/ext-security-advisor?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

# Security Advisor

The Plesk Security Advisor solves three important aspects of running web sites:

   * setup free SSL certificates for all domains with Let's Encrypt (existing certificates will be kept)
   * switch all WordPress sites to https only by changing urls in WordPress and adding redirect rules to .htaccess
   * switch all websites to HTTP/2 for improved security and performance
   * scan server for vulerabilities and report them
   * offer updates for outdated packages

## How things started

When speaking to a lot of WordPress users on WordPress meet-ups and WordCamps, it turned out that everybody knows that their sites should use SSL only, but many Wordpress users do not know how to actually configure their server correctly. For sure, there are tons of blog articles describing how to switch your WordPress site to https by using the plugin "Better Search and Replace" - but honestly, that has to be easier!
And configuring Let's Encrypt for several domains is complicated and effort that nobody wants to do manually. Why not just turn it on with one click?
That was our motivation for creating an extension for Plesk at the WHD.hackathon of the largest hosting conference "World Hosting Days".
And some colleagues from Opsani were so excited about the idea that they directly joined our hackathon team and suggested adding a vulnerability scan to make Plesk users aware of vulnerabilities and mitigations.

This is how we started!

If you want to contribute, just do a pull request and we'll review your changes.

We are happy for every contributor since we care a lot for making the internet a safer place!

## Contributing

Use the virtual machine with the prepared Plesk installation:
```
vagrant up
```

Login URL: http://localhost:8880

Credentials: admin / changeme


text:
package com.dal.fingerprinting.jmx;

import com.adobe.granite.jmx.annotation.AnnotatedStandardMBean;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheStats;

import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.management.NotCompliantMBeanException;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.OpenType;
import javax.management.openmbean.TabularData;

/**
 * Guava cache MBean.
 *
 * @param <K> The cache key type.
 * @param <V> The cache value type.
 */
public abstract class AbstractGuavaCacheMBean<K, V> extends AnnotatedStandardMBean implements GenericCacheMBean {

    /**
     * One hundred.
     */
    private static final int HUNDRED = 100;

    /**
     * Construct a MBean that represents a Guava cache.
     *
     * @throws NotCompliantMBeanException If the MBean is not JMX compliant.
     */
    protected AbstractGuavaCacheMBean() throws NotCompliantMBeanException {
        super(GenericCacheMBean.class);
    }

    /**
     * Get the cache object.
     *
     * @return The cache object.
     */
    @CheckForNull
    protected abstract Cache<K, V> getCache();

    /**
     * Get the converter whereby keys are converted to {@link OpenType} values.
     *
     * @return The key converter.
     */
    @Nonnull
    protected abstract OpenTypeConverter<? extends OpenType<?>, K> getCacheKeyConverter();

    /**
     * Get the converter whereby values are converted to {@link OpenType} values.
     *
     * @return The value converter.
     */
    @Nonnull
    protected abstract OpenTypeConverter<? extends OpenType<?>, V> getCacheValueConverter();

    @Override
    public final void clearCache() {
        Cache<K, V> cache = this.getCache();
        if (cache != null) {
            cache.invalidateAll();
        }
    }

    @Override
    public final long getCacheEntriesCount() {
        Cache<K, V> cache = this.getCache();
        if (cache != null) {
            return cache.size();
        }
        return 0;
    }

    /**
     * Construct the TabularData stats for a cache.
     *
     * @return Cache stats.
     * @throws OpenDataException Error creating the TabularData.
     */
    @Nonnull
    @Override
    public final TabularData getCacheStats() throws OpenDataException {
        Cache<K, V> cache = this.getCache();
        TabularOpenTypeLinkedHashMap<String, String> lsm = new TabularOpenTypeLinkedHashMap<>(OpenTypeConverter.STRING_CONVERTER, OpenTypeConverter.STRING_CONVERTER);
        if (cache != null) {
            CacheStats cacheStats = cache.stats();
            lsm.put("Request Count", String.valueOf(cacheStats.requestCount()));
            lsm.put("Hit Count", String.valueOf(cacheStats.hitCount()));
            lsm.put("Hit Rate", String.format("%.0f%%", cacheStats.hitRate() * HUNDRED));
            lsm.put("Miss Count", String.valueOf(cacheStats.missCount()));
            lsm.put("Miss Rate", String.format("%.0f%%", cacheStats.missRate() * HUNDRED));
            lsm.put("Eviction Count", String.valueOf(cacheStats.evictionCount()));
            lsm.put("Load Count", String.valueOf(cacheStats.loadCount()));
            lsm.put("Load Exception Count", String.valueOf(cacheStats.loadExceptionCount()));
            lsm.put("Load Exception Rate", String.format("%.0f%%", cacheStats.loadExceptionRate() * HUNDRED));
            lsm.put("Load Success Count", String.valueOf(cacheStats.loadSuccessCount()));
            lsm.put("Average Load Penalty", String.valueOf(cacheStats.averageLoadPenalty()));
            lsm.put("Total Load Time", String.valueOf(cacheStats.totalLoadTime()));
        }
        return lsm.toTabularData();
    }

    @Override
    public final TabularData getCacheContents() throws OpenDataException {
        TabularOpenTypeLinkedHashMap<K, V> lsm = new TabularOpenTypeLinkedHashMap<>(this.getCacheKeyConverter(), this.getCacheValueConverter());
        Cache<K, V> cache = this.getCache();
        if (cache != null) {
            lsm.putAll(cache.asMap());
        }
        return lsm.toTabularData();
    }
}


text:
"""A simple RESTful status framework on Google App Engine

This app's API should be reasonably clean and easily targeted by other
clients, like a Flex app or a desktop program.
"""

__author__ = 'Kyle Conroy'

import string
import re
import os
import cgi
import urllib
import logging

from datetime import timedelta
from datetime import date
from datetime import datetime
from datetime import time
from dateutil.parser import parse
from google.appengine.api import memcache
from google.appengine.api import datastore_errors
from google.appengine.api import taskqueue
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from handlers import restful
from time import mktime
from utils import authorized
from utils import slugify
from models import List, Status, Event, Service, Image
from wsgiref.handlers import format_date_time

def invalidate_cache():
    all_pages = memcache.get("__all_pages__")
    if all_pages is not None:
        for page,d in all_pages.items():
            if not memcache.delete(page):
                logging.error("Memcache delete failed on %s", page)
    if not memcache.delete("__all_pages__"):
        logging.error("Memcache delete failed on __all_pages__")
    taskqueue.add(url='/', method="GET")

def aware_to_naive(d):
    """Convert an aware date to an naive date, in UTC"""
    offset = d.utcoffset()
    if offset:
        d = d.replace(tzinfo=None)
        d = d - offset
    return d

class NotFoundHandler(restful.Controller):
    def get(self):
        self.error(404, "Can't find resouce")

class ListsListHandler(restful.Controller):

    def get(self, version):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        query = List.all().order('name')
        data = [s.rest(self.base_url(version)) for s in query]
        data = {"lists": data}
        self.json(data)

    @authorized.api("admin")
    def post(self, version):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        name = self.request.get('name', default_value=None)
        description = self.request.get('description', default_value=None)

        if not name or not description:
            self.error(400, "Bad Data: Name: %s, Description: %s" \
                           % (name, description))
            return

        slug = slugify.slugify(name)
        existing_s = List.get_by_slug(slug)

        if existing_s:
            self.error(404, "A list with this name already exists")
            return

        l = List(name=name, slug=slug, description=description)
        l.put()

        invalidate_cache()

        self.response.set_status(201)
        self.json(l.rest(self.base_url(version)))

class ListInstanceHandler(restful.Controller):

    def get(self, version, list_slug):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        list = List.get_by_slug(list_slug)

        if not list:
            self.error(404, "List %s does not exist" % list_slug)
            return

        self.json(list.rest(self.base_url(version)))

    @authorized.api("admin")
    def post(self, version, list_slug):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        list = List.get_by_slug(list_slug)

        if not list:
            self.error(404, "Service %s does not exist" % list_slug)
            return

        name = self.request.get('name', default_value=None)
        description = self.request.get('description', default_value=None)

        if description:
            list.description = description

        if name:
            list.name = name

        if name or description:
            invalidate_cache()
            list.put()

        self.json(list.rest(self.base_url(version)))

    @authorized.api("admin")
    def delete(self, version, list_slug):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        list = List.get_by_slug(list_slug)

        if not list:
            self.error(404, "List %s not found" % list_slug)
            return

        query = Service.all()
        query.filter('list =', list)
        if query:
            for s in query:
                s.list = None
                s.put()

        invalidate_cache()
        list.delete()
        self.json(list.rest(self.base_url(version)))

class ServicesListHandler(restful.Controller):

    def get(self, version):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        query = Service.all().order('name')
        data = [s.rest(self.base_url(version)) for s in query]
        data = {"services": data}
        self.json(data)

    @authorized.api("admin")
    def post(self, version):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        name = self.request.get('name', default_value=None)
        description = self.request.get('description', default_value=None)
        slist = self.request.get('list', default_value=None)
        l = None

        if slist:
            l = List.all().filter("slug =", slist).get()

        if not name:
            self.error(400, "Bad name: %s" % name)
            return

        if not description:
            self.error(400, "Bad description: %s" % description)
            return

        if slist and not l:
            self.error(400, "Bad list slug: %s" % slist)
            return

        slug = slugify.slugify(name)
        existing_s = Service.get_by_slug(slug)

        if existing_s:
            self.error(404, "A sevice with this name already exists")
            return

        s = Service(name=name, slug=slug, description=description, list=l)
        s.put()

        invalidate_cache()

        self.response.set_status(201)
        self.json(s.rest(self.base_url(version)))

class ServiceInstanceHandler(restful.Controller):

    def get(self, version, service_slug):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        service = Service.get_by_slug(service_slug)

        if not service:
            self.error(404, "Service %s does not exist" % service_slug)
            return

        self.json(service.rest(self.base_url(version)))

    @authorized.api("admin")
    def post(self, version, service_slug):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        service = Service.get_by_slug(service_slug)
        if not service:
            self.error(404, "Service %s does not exist" % service_slug)
            return

        name = self.request.get('name', default_value=None)
        description = self.request.get('description', default_value=None)
        list = self.request.get('list', default_value=None)

        if description:
            service.description = description

        if name:
            service.name = name

        if list:
            l = List.all().filter("slug = ", list).get()

            if l is None:
                self.error(400, "Can't find list with slug %s" % list)
                return

            service.list = l

        if "" == list:
            service.list = None
            list = "removed"

        if name or description or list:
            invalidate_cache()
            service.put()

        self.json(service.rest(self.base_url(version)))

    @authorized.api("admin")
    def delete(self, version, service_slug):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        service = Service.get_by_slug(service_slug)

        if not service:
            self.error(404, "Service %s not found" % service_slug)
            return

        query = Event.all()
        query.filter('service =', service)
        if query:
            for e in query:
                e.delete()

        invalidate_cache()
        service.delete()
        self.json(service.rest(self.base_url(version)))

class EventsListHandler(restful.Controller):
    def get(self, version, service_slug):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        service = Service.get_by_slug(service_slug)

        if not service:
            self.error(404, "Service %s not found" % service_slug)
            return

        start = self.request.get('start', default_value=None)
        end = self.request.get('end', default_value=None)

        query = Event.all()
        query.filter('service =', service)

        if start:
            try:
                _start = aware_to_naive(parse(start))
                query.filter("start >= ", _start)
            except:
                self.error(400, "Invalid Date: %s" % start)
                return

        if end:
            try:
                _end = aware_to_naive(parse(end))
                query.filter("start <=", _end)
            except:
                self.error(400, "Invalid Date: %s" % end)
                return

        query.order('-start')

        data = [s.rest(self.base_url(version)) for s in query]
        self.json({"events": data})

    @authorized.api("admin")
    def post(self, version, service_slug):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        status_slug = self.request.get("status", default_value=None)
        message = self.request.get("message", default_value=None)
        informational = self.request.get("informational", default_value=None)

        if not message:
            self.error(400, "Event message is required")
            return

        service = Service.get_by_slug(service_slug)

        if not service:
            self.error(404, "Service %s not found" % service_slug)
            return

        if not status_slug:
            event = service.current_event()
            if event:
                status = event.status
            else:
                status = Status.get_default()
        else:
            status = Status.get_by_slug(status_slug)

        if not status:
            self.error(404, "Status %s not found" % status_slug)
            return

        e = Event(status=status, service=service, message=message)
        e.informational = informational and informational == "true"
        e.put()

        invalidate_cache()
        self.json(e.rest(self.base_url(version)))

class CurrentEventHandler(restful.Controller):
    def get(self, version, service_slug):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        service = Service.get_by_slug(service_slug)

        if not service:
            self.error(404, "Service %s not found" % service_slug)
            return

        event = service.current_event()

        if not event:
            self.error(404, "No current event for Service %s" % service_slug)
            return

        self.json(event.rest(self.base_url(version)))

class EventInstanceHandler(restful.Controller):
    def get(self, version, service_slug, sid):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        service = Service.get_by_slug(service_slug)

        if not service:
            self.error(404, "Service %s not found" % service_slug)
            return

        try:
            event = Event.get(db.Key(sid))
        except datastore_errors.BadKeyError:
            self.error(404, "Event %s not found" % sid)
            return

        if not event or service.key() != event.service.key():
            self.error(404, "No event for Service %s with sid = %s" \
                           % (service_slug, sid))
            return

        self.json(event.rest(self.base_url(version)))

    @authorized.api("admin")
    def delete(self, version, service_slug, sid):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        service = Service.get_by_slug(service_slug)

        if not service:
            self.error(404, "Service %s not found" % service_slug)
            return

        try:
            event = Event.get(db.Key(sid))
        except datastore_errors.BadKeyError:
            self.error(404, "Event %s not found" % sid)
            return

        if not event or service.key() != event.service.key():
            self.error(404, "No event for Service %s with sid = %s" \
                           % (service_slug, sid))
            return

        event.delete()
        invalidate_cache()

        # Why not JSON?
        self.success(event.rest(self.base_url(version)))

class StatusesListHandler(restful.Controller):
    def get(self, version):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        query = Status.all().order('name')

        data = [s.rest(self.base_url(version)) for s in query]
        self.json({"statuses": data})

    @authorized.api("admin")
    def post(self, version):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        name = self.request.get('name', default_value=None)
        description = self.request.get('description', default_value=None)
        image_slug = self.request.get('image', default_value=None)
        default = self.request.get('default', default_value="false")

        if default not in ["true", "false"]:
            self.error(400, "Default must be true or false")
            return

        if not name or not description or not image_slug:
            self.error(400, "Bad Data")
            return

        slug = slugify.slugify(name)
        status = Status.get_by_slug(slug)
        image = Image.get_by_slug(image_slug)

        if status is not None:
            self.error(400, "A Status with the slug %s already exists" % slug)
            return

        if image is None:
            msg = "An Image with the slug %s doesn't exist" % image_slug
            self.error(400, msg)
            return

        # Reset default status
        if default == "true":
            for stat in Status.all().filter("default", True):
                stat.default = False
                stat.put()

        default = default == "true"
        status = Status(name=name, slug=slug, description=description,
                        image=image.path, default=default)
        status.put()
        invalidate_cache()

        self.response.set_status(201)
        self.json(status.rest(self.base_url(version)))

class StatusInstanceHandler(restful.Controller):
    def get(self, version, status_slug):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        status = Status.get_by_slug(status_slug)

        if not status:
            self.error(404, "No status with the slug %s found" % status_slug)
            return

        self.json(status.rest(self.base_url(version)))

    @authorized.api("admin")
    def post(self, version, status_slug):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        status = Status.get_by_slug(status_slug)

        if not status:
            self.error(404, "No status with the slug %s found" % status_slug)
            return

        name = self.request.get('name', default_value=None)
        image_slug = self.request.get('image', default_value=None)
        image = None
        default = self.request.get('default', default_value=None)
        description = self.request.get('description', default_value=None)

        if image_slug is not None:
            image = Image.get_by_slug(image_slug)

            if image is None:
                self.error(400, "An Image with the "
                           "slug %s doesn't exist" % image_slug)
                return

            status.image = image.path

        if description is not None:
            status.description = description

        if default is not None and default in ["false", "true"]:

            # Reset default status
            if default == "true":
                for stat in Status.all().filter("default", True):
                    stat.default = False
                    stat.put()

            status.default = default == "true"

        if name is not None:
            status.name = name

        if description or name or image or default:
            status.put()
            invalidate_cache()

        self.json(status.rest(self.base_url(version)))

    @authorized.api("admin")
    def delete(self, version, status_slug):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        status = Status.get_by_slug(status_slug)

        if not status:
            self.error(404, "Status %s not found" % status_slug)
            return

        # We may want to think more about this
        events = Event.all().filter('status =', status).fetch(1000)
        for event in events:
            event.delete()

        status.delete()
        self.json(status.rest(self.base_url(version)))

class LevelListHandler(restful.Controller):

    def get(self, version):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        self.json({"levels": ["NORMAL", "WARNING", "ERROR", "CRITICAL"]})

class ImagesListHandler(restful.Controller):
    def get(self, version):
        if not self.valid_version(version):
            self.error(404, "API Version %s not supported" % version)
            return

        host = self.request.headers.get('host', 'nohost')
        images = []

        for img in Image.all().fetch(1000):
            image = {
                "url": "http://" + host + "/images/" + img.path,
                "icon_set": img.icon_set,
                "name": img.slug,
                }
            images.append(image)

        self.json({"images": images})


text:
package com.defterp.modules.accounting.entities;

import com.defterp.modules.commonClasses.BaseEntity;
import com.defterp.modules.partners.entities.Partner;
import com.defterp.validators.annotations.InDateRange;
import com.defterp.validators.annotations.StrictlyPositiveNumber;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

/**
 *
 * @author MOHAMMED BOUNAGA
 *
 * github.com/medbounaga
 */

@Entity
@Table(name = "payment")
@NamedQueries({
    @NamedQuery(name = "Payment.findByPartner", query = "SELECT p FROM Payment p WHERE p.partner.id = :partnerId AND p.partnerType = :partnerType "),
    @NamedQuery(name = "Payment.countByPartner", query = "SELECT COUNT(p) FROM Payment p WHERE p.partner.id = :partnerId AND p.partnerType = :partnerType"),
    @NamedQuery(name = "Payment.findOutstandingByPartner", query = "SELECT p FROM Payment p WHERE p.partner.id = :partnerId AND p.type = :type AND p.state = :status AND p.partnerType = :partnerType AND p.overpayment > 0"),
    @NamedQuery(name = "Payment.findAll", query = "SELECT p FROM Payment p"),
    @NamedQuery(name = "Payment.findByPartnerType", query = "SELECT p FROM Payment p WHERE p.partnerType = :partnerType"),
    @NamedQuery(name = "Payment.findById", query = "SELECT p FROM Payment p WHERE p.id = :id"),
    @NamedQuery(name = "Payment.findByDate", query = "SELECT p FROM Payment p WHERE p.date = :date"),
    @NamedQuery(name = "Payment.findByAmount", query = "SELECT p FROM Payment p WHERE p.amount = :amount"),
    @NamedQuery(name = "Payment.findByActive", query = "SELECT p FROM Payment p WHERE p.active = :active")})

public class Payment extends BaseEntity {

    private static final long serialVersionUID = 1L;

    @Column(name = "date")
    @Basic(optional = false)
    @NotNull
    @InDateRange
    @Temporal(TemporalType.TIMESTAMP)
    private Date date = new Date();
    @Basic(optional = false)
    @NotNull
    @StrictlyPositiveNumber(message = "{PositivePayment}")
    @Column(name = "amount")
    private Double amount;
    @Basic(optional = false)
    @NotNull
    @Column(name = "overpayment")
    private double overpayment;
    @Size(max = 64, message = "{LongString}")
    @Column(name = "type")
    private String type;
    @Basic(optional = false)
    @NotNull
    @Size(max = 64, message = "{LongString}")
    @Column(name = "partner_type")
    private String partnerType;
    @Size(max = 64, message = "{LongString}")
    @Column(name = "name")
    private String name;
    @Size(max = 64, message = "{LongString}")
    @Column(name = "reference")
    private String reference;
    @Size(max = 64, message = "{LongString}")
    @Column(name = "state")
    private String state;
    @Basic(optional = false)
    @NotNull
    @Column(name = "active")
    private Boolean active;
    @JoinColumn(name = "account_id", referencedColumnName = "id")
    @ManyToOne
    private Account account;
    @JoinColumn(name = "entry_id", referencedColumnName = "id")
    @OneToOne(cascade = CascadeType.PERSIST)
    private JournalEntry journalEntry;
    @JoinColumn(name = "invoice_id", referencedColumnName = "id")
    @ManyToOne
    private Invoice invoice;
    @JoinColumn(name = "journal_id", referencedColumnName = "id")
    @ManyToOne
    private Journal journal;
    @JoinColumn(name = "partner_id", referencedColumnName = "id")
    @ManyToOne
    private Partner partner;

    public Payment() {

    }

    public Payment(double amount, Date date, Partner partner, Journal journal, String type, Boolean active, Account account, JournalEntry journalEntry, Invoice invoice, String state, double overpayment, String partnerType) {
        this.type = type;
        this.active = active;
        this.account = account;
        this.journalEntry = journalEntry;
        this.invoice = invoice;
        this.amount = amount;
        this.date = date;
        this.partner = partner;
        this.journal = journal;
        this.state = state;
        this.overpayment = overpayment;
        this.partnerType = partnerType;
    }

    public Payment(double amount, Date date, Partner partner, Journal journal, String type, Boolean active, Account account, JournalEntry journalEntry, Invoice invoice, String state, String reference, double overpayment, String partnerType) {
        this.type = type;
        this.active = active;
        this.account = account;
        this.journalEntry = journalEntry;
        this.invoice = invoice;
        this.amount = amount;
        this.date = date;
        this.partner = partner;
        this.journal = journal;
        this.state = state;
        this.reference = reference;
        this.overpayment = overpayment;
        this.partnerType = partnerType;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public Double getAmount() {
        return amount;
    }

    public void setAmount(Double amount) {
        this.amount = amount;
    }

    public double getOverpayment() {
        return overpayment;
    }

    public void setOverpayment(double overpayment) {
        this.overpayment = overpayment;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getPartnerType() {
        return partnerType;
    }

    public void setPartnerType(String partnerType) {
        this.partnerType = partnerType;
    }

    public Boolean getActive() {
        return active;
    }

    public void setActive(Boolean active) {
        this.active = active;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getReference() {
        return reference;
    }

    public void setReference(String reference) {
        this.reference = reference;
    }

    public String getState() {
        return state;
    }

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

    public Account getAccount() {
        return account;
    }

    public void setAccount(Account account) {
        this.account = account;
    }

    public JournalEntry getJournalEntry() {
        return journalEntry;
    }

    public void setJournalEntry(JournalEntry journalEntry) {
        this.journalEntry = journalEntry;
    }

    public Invoice getInvoice() {
        return invoice;
    }

    public void setInvoice(Invoice invoice) {
        this.invoice = invoice;
    }

    public Journal getJournal() {
        return journal;
    }

    public void setJournal(Journal journal) {
        this.journal = journal;
    }

    public Partner getPartner() {
        return partner;
    }

    public void setPartner(Partner partner) {
        this.partner = partner;
    }

    @Override
    public String toString() {
        return "--- Payment[ id=" + super.getId() + " ] ---";
    }

}


text:
var fs = require('fs');
var cluster = require('cluster');

module.exports = {
  startPriority: 1,
  loadPriority:  110,
  initialize: function(api, next){

    api.pids = {};
    api.pids.pid = process.pid;
    api.pids.path = api.config.general.paths.pid[0]; // it would be silly to have more than one pid

    api.pids.sanitizeId = function(){
      var pidfile = api.id;
      pidfile = pidfile.replace(new RegExp(':', 'g'), '-');
      pidfile = pidfile.replace(new RegExp(' ', 'g'), '_');
      pidfile = pidfile.replace(new RegExp('\r', 'g'), '');
      pidfile = pidfile.replace(new RegExp('\n', 'g'), '');

      return pidfile;
    };

    if(cluster.isMaster){
      api.pids.title = 'actionhero-' + api.pids.sanitizeId();
    } else {
      api.pids.title = api.pids.sanitizeId();
    }

    try { fs.mkdirSync(api.pids.path); } catch(e) {}

    api.pids.writePidFile = function(){
      fs.writeFileSync(api.pids.path + '/' + api.pids.title, api.pids.pid.toString(), 'ascii');
    };

    api.pids.clearPidFile = function(){
      try {
        fs.unlinkSync(api.pids.path + '/' + api.pids.title);
      } catch(e){
        api.log('Unable to remove pidfile', 'error', e);
      }
    };

    next();
  },

  start: function(api, next){
    api.pids.writePidFile();
    api.log(['pid: %s', process.pid], 'notice');
    next();
  }
};


text:
<?php

namespace Ivory\HttpAdapter\Event\Cookie\Jar;

/**
 * Persistent cookie jar.
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
interface PersistentCookieJarInterface extends CookieJarInterface, \Serializable
{
    /**
     * Loads the cookie jar.
     *
     * @throws \Ivory\HttpAdapter\HttpAdapterException If an error occurred.
     */
    public function load();

    /**
     * Saves the cookie jar.
     *
     * @throws \Ivory\HttpAdapter\HttpAdapterException If an error occurred.
     */
    public function save();
}


text:
package org.apache.cassandra.tools.nodetool;

import io.airlift.command.Command;

import org.apache.cassandra.tools.NodeProbe;
import org.apache.cassandra.tools.NodeTool.NodeToolCmd;

@Command(name = "statusthrift", description = "Status of org.apache.cassandra.thrift.thrift server")
public class StatusThrift extends NodeToolCmd
{
    @Override
    public void execute(NodeProbe probe)
    {
        System.out.println(
                probe.isThriftServerRunning()
                ? "running"
                : "not running");
    }
}


text:
package com.gopivotal.manager.redis;

import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisConnectionException;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public final class JedisTemplateTest {

    private final Jedis jedis = mock(Jedis.class);

    private final JedisPool jedisPool = mock(JedisPool.class);

    private final JedisTemplate jedisTemplate = new JedisTemplate(this.jedisPool);

    @SuppressWarnings("unchecked")
    private final JedisTemplate.JedisOperation<String> operation = mock(JedisTemplate.JedisOperation.class);

    @Before
    public void jedis() throws Exception {
        when(this.jedisPool.getResource()).thenReturn(this.jedis);
    }

    @Test
    public void returnBrokenResourceException() throws Exception {
        JedisConnectionException expected = new JedisConnectionException("test-message");
        when(this.operation.invoke(this.jedis)).thenThrow(expected);
        doThrow(new JedisConnectionException("test-message")).when(this.jedisPool).returnBrokenResource(this.jedis);

        try {
            this.jedisTemplate.withJedis(this.operation);
            fail();
        } catch (JedisConnectionException e) {
            assertSame(expected, e);
        }

        verify(this.jedisPool).returnResource(this.jedis);
    }

    @Test
    public void returnResourceException() throws Exception {
        when(this.operation.invoke(this.jedis)).thenReturn("test-value");
        doThrow(new JedisConnectionException("test-message")).when(this.jedisPool).returnResource(this.jedis);

        String result = this.jedisTemplate.withJedis(this.operation);

        assertEquals("test-value", result);
    }

    @Test
    public void withJedis() throws Exception {
        when(this.operation.invoke(this.jedis)).thenReturn("test-value");

        String result = this.jedisTemplate.withJedis(this.operation);

        assertEquals("test-value", result);
        verify(this.jedisPool).returnResource(this.jedis);
    }

    @Test
    public void withJedisException() throws Exception {
        JedisConnectionException expected = new JedisConnectionException("test-message");
        when(this.operation.invoke(this.jedis)).thenThrow(expected);

        try {
            this.jedisTemplate.withJedis(this.operation);
            fail();
        } catch (JedisConnectionException e) {
            assertSame(expected, e);
        }

        verify(this.jedisPool).returnBrokenResource(this.jedis);
        verify(this.jedisPool).returnResource(this.jedis);
    }

    @Test
    public void withJedisResourceException() throws Exception {
        JedisConnectionException expected = new JedisConnectionException("test-message");
        when(this.jedisPool.getResource()).thenThrow(expected);

        try {
            this.jedisTemplate.withJedis(this.operation);
            fail();
        } catch (JedisConnectionException e) {
            assertSame(expected, e);
        }

        verify(this.jedisPool, times(0)).returnBrokenResource(null);
        verify(this.jedisPool, times(0)).returnResource(null);
    }
}


text:
package edu.uw.apl.commons.tsk4j.digests;

import java.util.ArrayList;
import java.util.List;

import edu.uw.apl.commons.tsk4j.filesys.FileSystem;

/**
   A unary operator for BodyFile Record.  Much like a FileFilter, when
   applied to a BodyFile Record it either accepts it or not.  A filter
   operation, reduces one set (a BodyFile) to a possibly (likely)
   smaller one (another BodyFile).
*/

public class BodyFileUnaryOperator extends BodyFileOperator {

	public interface Predicate {
		/**
		 * @param r - the particular BodyFile Record to test
		 *
		 * @param fs - the FileSystem from which the BodyFile
		 * containing r was created.  Needed when we want to at file
		 * content, since BodyFiles by themselves do not contain
		 * content.  May be null, cases when the source FileSystem is
		 * not available.
		 */

		public boolean accepts( BodyFile.Record r, FileSystem fs );
	}

	public BodyFileUnaryOperator( String name, Predicate p ) {
		super( name );
		this.predicate = p;
	}

	@Override
	public int arity() {
		return 1;
	}

	public BodyFile apply( BodyFile bf ) {
		String name = getName() + " IN (" + bf.getName() + ")";
		FileSystem fs = bf.getFileSystem();
		BodyFile result = new BodyFile( name );
		for( BodyFile.Record r : bf.records() ) {
			if( predicate.accepts( r, fs ) )
				result.add( r );
		}
		return result;

	}

	final Predicate predicate;
}

// eof


text:
module Dustbag
  class VariationSummary
    include Parser::Node

    def lowest_price
      Price.parse(subnode('LowestPrice'))
    end

    def highest_price
      Price.parse(subnode('HighestPrice'))
    end
  end
end


text:
package net.runelite.http.service.feed.osrsnews;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import lombok.extern.slf4j.Slf4j;
import net.runelite.http.api.RuneLiteAPI;
import net.runelite.http.api.feed.FeedItem;
import net.runelite.http.api.feed.FeedItemType;
import net.runelite.http.service.util.exception.InternalServerErrorException;
import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

@Service
@Slf4j
public class OSRSNewsService
{
	private static final HttpUrl RSS_URL = HttpUrl.parse("http://services.runescape.com/m=news/latest_news.rss?oldschool=true");
	private static final SimpleDateFormat PUB_DATE_FORMAT = new SimpleDateFormat("EEE, dd MMM yyyy '00:00:00 GMT'", Locale.US);

	public List<FeedItem> getNews() throws IOException
	{
		Request request = new Request.Builder()
			.url(RSS_URL)
			.build();

		try (Response response = RuneLiteAPI.CLIENT.newCall(request).execute())
		{
			if (!response.isSuccessful())
			{
				throw new IOException("Error getting OSRS news: " + response.message());
			}

			try
			{
				InputStream in = response.body().byteStream();
				Document document = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder()
					.parse(in);

				Element documentElement = document.getDocumentElement();
				NodeList documentItems = documentElement.getElementsByTagName("item");

				List<FeedItem> items = new ArrayList<>();

				for (int i = 0; i < documentItems.getLength(); i++)
				{
					Node item = documentItems.item(i);
					NodeList children = item.getChildNodes();

					String title = null;
					String description = null;
					String link = null;
					long timestamp = -1;

					for (int j = 0; j < children.getLength(); j++)
					{
						Node childItem = children.item(j);
						String nodeName = childItem.getNodeName();

						switch (nodeName)
						{
							case "title":
								title = childItem.getTextContent();
								break;
							case "description":
								description = childItem.getTextContent().replace("\n", "").trim();
								break;
							case "link":
								link = childItem.getTextContent();
								break;
							case "pubDate":
								timestamp = PUB_DATE_FORMAT.parse(childItem.getTextContent()).getTime();
								break;
						}
					}

					if (title == null || description == null || link == null || timestamp == -1)
					{
						throw new InternalServerErrorException("Failed to find title, description, link and/or timestamp in the OSRS RSS feed");
					}

					items.add(new FeedItem(FeedItemType.OSRS_NEWS, title, description, link, timestamp));
				}

				return items;
			}
			catch (ParserConfigurationException | SAXException | ParseException e)
			{
				throw new InternalServerErrorException("Failed to parse OSRS news: " + e.getMessage());
			}
		}
	}
}


text:
package com.parrot.docdown.data.markup.pegdown;

import org.parboiled.BaseParser;
import org.parboiled.Rule;
import org.parboiled.support.StringBuilderVar;
import org.pegdown.Extensions;
import org.pegdown.Parser;
import org.pegdown.ast.SimpleNode;
import org.pegdown.ast.TextNode;
import org.pegdown.ast.WikiLinkNode;
import org.pegdown.plugins.BlockPluginParser;

public class PluginParser extends Parser implements BlockPluginParser {

    public PluginParser() {
        super(Extensions.FENCED_CODE_BLOCKS | Extensions.WIKILINKS, 1000L, Parser.DefaultParseRunnerProvider);
    }

    @Override
    public Rule[] blockPluginRules() {
        return new Rule[]{includeCodeRule()};
    }

    public Rule includeCodeRule() {
        return Sequence(
                "@(",
                OneOrMore(TestNot(')'), ANY), // might have to restrict from ANY
                push(new ExternalCodeNode(match())),
                ")",Sp(),Newline()
        );
    }
}


text:
#ifndef LIB_SIGNALS_H
#define LIB_SIGNALS_H

#include <signal.h>

enum libsig_flags {
	/* Signal handler will be called later from IO loop when it's safe to
	   do any kind of work */
	LIBSIG_FLAG_DELAYED	= 0x01,
	/* Restart syscalls instead of having them fail with EINTR */
	LIBSIG_FLAG_RESTART	= 0x02
};
#define LIBSIG_FLAGS_SAFE (LIBSIG_FLAG_DELAYED | LIBSIG_FLAG_RESTART)

typedef void signal_handler_t(const siginfo_t *si, void *context);

/* Number of times a "termination signal" has been received.
   These signals are SIGINT, SIGQUIT and SIGTERM. Callers can compare this to
   their saved previous value to see if a syscall returning EINTR should be
   treated as someone wanting to end the process or just some internal signal
   that should be ignored, such as SIGCHLD.

   This is marked as volatile so that compiler won't optimize away its
   comparisons. It may not work perfectly everywhere, such as when accessing it
   isn't atomic, so you shouldn't heavily rely on its actual value. */
extern volatile unsigned int signal_term_counter;

/* Convert si_code to string */
const char *lib_signal_code_to_str(int signo, int sicode);

/* Set signal handler for specific signal. */
void lib_signals_set_handler(int signo, enum libsig_flags flags,
			     signal_handler_t *handler, void *context)
	ATTR_NULL(4);
/* Ignore given signal. */
void lib_signals_ignore(int signo, bool restart_syscalls);
void lib_signals_unset_handler(int signo,
			       signal_handler_t *handler, void *context)
	ATTR_NULL(3);

/* Remove and add the internal I/O handler back. This is necessary to get
   the delayed signals to work when using multiple I/O loops. */
void lib_signals_reset_ioloop(void);

void lib_signals_init(void);
void lib_signals_deinit(void);

#endif


text: # CaptureTheNumbers


text:
namespace supersonic {

// Contains basic page information.
struct PageHeader {
  uint64_t total_size;
  uint32_t byte_buffers_count;
};

// Contains basic byte buffer information.
// TODO(wzoltak): We may want to add something here in future (like compression
//                method), but it will kill compatibility with previous
//                versions. Consider usage of protobuf.
struct ByteBufferHeader {
  uint64_t length;
};

// Size of serialized PageHeader object in bytes.
const int kSerializedPageHeaderSize = 12;

// Size of serialized ByteBufferHeader object in bytes.
const int kSerializedByteBufferHeaderSize = 8;

// Size of serialized Page::Offset value in bytes.
const int kSerializedOffsetSize = 8;

// In-memory, raw data chunk in storage layer. Contains a set of byte buffers.
// Exposes APIs that allow reading.
class Page {
 public:
  typedef uint64_t offset_t;

  virtual ~Page() {}

  // Returns a page header.
  virtual const struct PageHeader& PageHeader() const = 0;

  // Returns a header for given byte buffer.
  virtual FailureOr<const struct ByteBufferHeader*>
      ByteBufferHeader(int byte_buffer_index) const = 0;

  // Returns a pointer to place in which data of given byte buffer is stored.
  virtual FailureOr<const void*> ByteBuffer(int byte_buffer_index) const = 0;

  // Returns a pointer to raw in-memory page representation.
  virtual const void* RawData() const = 0;

  // Returns true when page is empty (has 0 byte buffers).
  virtual bool IsEmpty() const = 0;
};

// Creates Page object from buffer containing raw data. Takes ownership over
// the buffer.
FailureOrOwned<Page> CreatePage(std::unique_ptr<const Buffer> buffer);

// Creates Page object as a temporary view on buffer containing raw data. Does
// not take ownership over the buffer.
FailureOrOwned<Page> CreatePageView(const Buffer& buffer);

}  // namespace supersonic

#endif  // SUPERSONIC_CONTRIB_STORAGE_BASE_PAGE_H_


text:
namespace eja
{
	class router_util final
	{
	private:
		static mutex m_mutex;

	private:
		router_util() { }
		~router_util() = delete;

		static std::shared_ptr<function_map_list_component> get_function_map();

	public:
		// Utility
		static entity::ptr create();
		static entity::ptr create(const entity::ptr parent);

		// Accessor
		static entity_vector::ptr get_active_servers(const entity::ptr owner);
		static entity::ptr get_active_server(const entity::ptr owner);
		static mutex& get_mutex() { return m_mutex; }
	};
}

#endif


text:
'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
  'ngRoute',
  'myApp.view1',
  'myApp.view2',
  'myApp.version',
  'chart.js',
  'btford.socket-io'
]).
config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
  $locationProvider.hashPrefix('!');

  $routeProvider.otherwise({redirectTo: '/view1'});
}]).
factory('socketInstance', function (socketFactory) {
  return socketFactory();
});


text:
layout: post
date:	2008-02-06 19:46:00
title:  One of my perennial favourites....
tags: [archived-posts]
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---
I can never hear this song enough.....oh, the pangs of unrequited love!

<param name="movie" value="http://www.youtube.com/v/ckfcAT9N-vg&rel=1"></param><param name="wmode" value="transparent"></param><lj-embed id="14" /></object>

The lyrics:

ajeeb dAsthAn hai yEh
kahAn shuru kahAn khatham
yeh manzilEin kaun see
na wOh samajh sakEy na hum

yeh rOshnee ke sAth kyOn
dhuAn utthA chirAg sEy
yeh khwAb dEkhthee hoon meyn
ki jag padi hoon khwAb sEy

mubArakEin thUmhEy ki thUm (that's the "U" pronounced as in "book")
kisee key noor hO gayEy
kiseeke ithnEy pAs hO
ki sabsEy dhoor hO gayEy

kiseeka pyAr lEyke thUm
nayA jahAn basAogEy
yeh shAm jab bhi AyEgee
thUm hamkO yAAd AogEy

Translation (if anyone has a better version do give it!)

What a weird tale this is...
Where does it begin, where does it end?
What are the destinations?
Neither of us understands

Why, with the light,
Does the smoke arise from the lamp?
I dream...
..that I have woken up from the dream

Congratulations to you..you have
Become the light of someone's life
You have become so close to someone
That you are far away from everyone else

With someone's love, you
Will create a new world
Whenever (the memory of) this evening comes
I will think of you

The heroine is <a href="http://en.wikipedia.org/wiki/Meena_Kumari"> Meena Kumari </a>, who was a great tragedienne...in her later years, she was fat, a diva in her behaviour...her life itself was very unhappy.

The Wikipaedia link is really nice...it includes some "shAyri" (couplet verse poetry) that she herself wrote.


text:
layout: page
title: Logan Gold Trade Party
date: 2016-05-24
author: Joyce Ramirez
tags: weekly links, java
status: published
summary: Nulla vel tristique dui. Sed a viverra felis. Morbi et.
banner: images/banner/office-01.jpg
booking:
  startDate: 11/12/2019
  endDate: 11/16/2019
  ctyhocn: EMVWEHX
  groupCode: LGTP
published: true
---
Sed feugiat condimentum nibh at porta. Maecenas hendrerit magna sed sem laoreet ultricies. Aliquam venenatis viverra bibendum. Donec tempor sollicitudin purus. Nam vestibulum consequat libero, sit amet tincidunt urna posuere nec. Nam fermentum lectus vel nulla porttitor dapibus. Proin vel ante ipsum. Duis pretium eget augue in tincidunt. Donec et mattis lacus, in tempus felis. Nam nec vestibulum odio. Donec condimentum ultricies arcu ut tempus. Nullam euismod odio id posuere mollis. Integer enim augue, interdum et nunc eu, tincidunt semper enim. In sodales ullamcorper blandit. Morbi tristique pellentesque pellentesque.

* Donec a massa mattis, feugiat lorem quis, dictum urna
* Quisque sit amet nisl id turpis efficitur suscipit
* Quisque et odio quis nulla mollis auctor fermentum et nulla
* Donec molestie eros at lacinia pretium
* In ac urna ut enim congue semper eu in dui.

Maecenas aliquet erat non volutpat fermentum. Integer sed velit ante. Etiam sed varius orci. Donec a finibus orci, quis consequat risus. Suspendisse potenti. Etiam vel mollis nisi, sed lobortis orci. Vestibulum nec tortor id lacus tristique pharetra sed nec massa. Vivamus feugiat ipsum in gravida pharetra. Ut iaculis tellus eget elementum sagittis. Morbi et dapibus tortor, sed tincidunt eros. Aliquam consectetur scelerisque consectetur. Duis viverra lacinia diam vel gravida. Sed ullamcorper quam ac lectus malesuada, in vestibulum tellus pretium.


text:
use strict;
use warnings;

package LucyX::Remote::SearchClient;
BEGIN { our @ISA = qw( Lucy::Search::Searcher ) }
our $VERSION = '0.005000';
$VERSION = eval $VERSION;
use Carp;
use Storable qw( nfreeze thaw );

# Inside-out member vars.
our %peer_address;
our %sock;

use IO::Socket::INET;

sub new {
    my ( $either, %args ) = @_;
    my $peer_address = delete $args{peer_address};
    my $self         = $either->SUPER::new(%args);
    $peer_address{$$self} = $peer_address;

    # Establish a connection.
    my $sock = $sock{$$self} = IO::Socket::INET->new(
        PeerAddr => $peer_address,
        Proto    => 'tcp',
    );
    confess("No socket: $!") unless $sock;
    $sock->autoflush(1);
    my %handshake_args = ( _action => 'handshake' );
    my $response = $self->_rpc( \%handshake_args );
    confess("Failed to connect") unless $response;

    return $self;
}

sub DESTROY {
    my $self = shift;
    $self->close if defined $sock{$$self};
    delete $peer_address{$$self};
    delete $sock{$$self};
    $self->SUPER::DESTROY;
}

=for comment

Make a remote procedure call.  For every call that does not close/terminate
the socket connection, expect a response back that's been serialized using
Storable.

=cut

sub _rpc {
    my ( $self, $args ) = @_;
    my $sock = $sock{$$self};

    my $serialized = nfreeze($args);
    my $packed_len = pack( 'N', length($serialized) );
    print $sock "$packed_len$serialized" or confess $!;

    # disabled
    #my $check_val = $sock->syswrite("$packed_len$serialized");
    #confess $! if $check_val != length($serialized) + 4;

    my $check_val;

    # Bail out if we're either closing or shutting down the server remotely.
    return if $args->{_action} eq 'done';
    return if $args->{_action} eq 'terminate';

    # Decode response.
    $check_val = $sock->read( $packed_len, 4 );
    confess("Failed to read 4 bytes: $!")
        unless $check_val == 4;
    my $arg_len = unpack( 'N', $packed_len );
    $check_val = $sock->read( $serialized, $arg_len );
    confess("Failed to read $arg_len bytes")
        unless $check_val == $arg_len;
    my $response = thaw($serialized);
    if ( exists $response->{retval} ) {
        return $response->{retval};
    }
    return;
}

sub top_docs {
    my $self = shift;
    my %args = ( @_, _action => 'top_docs' );
    return $self->_rpc( \%args );
}

sub terminate {
    my $self = shift;
    my %args = ( _action => 'terminate' );
    return $self->_rpc( \%args );
}

sub fetch_doc {
    my ( $self, $doc_id ) = @_;
    my %args = ( doc_id => $doc_id, _action => 'fetch_doc' );
    return $self->_rpc( \%args );
}

sub fetch_doc_vec {
    my ( $self, $doc_id ) = @_;
    my %args = ( doc_id => $doc_id, _action => 'fetch_doc_vec' );
    return $self->_rpc( \%args );
}

sub doc_max {
    my $self = shift;
    my %args = ( _action => 'doc_max' );
    return $self->_rpc( { _action => 'doc_max' } );
}

sub doc_freq {
    my $self = shift;
    my %args = ( @_, _action => 'doc_freq' );
    return $self->_rpc( \%args );
}

sub close {
    my $self = shift;
    $self->_rpc( { _action => 'done' } );
    my $sock = $sock{$$self};
    close $sock or confess("Error when closing socket: $!");
    delete $sock{$$self};
}

1;

__END__

=head1 NAME

LucyX::Remote::SearchClient - Connect to a remote SearchServer.

=head1 SYNOPSIS

    my $client = LucyX::Remote::SearchClient->new(
        peer_address => 'searchserver1:7890',
    );
    my $hits = $client->hits( query => $query );

=head1 DESCRIPTION

SearchClient is a subclass of L<Lucy::Search::Searcher> which can be
used to search an index on a remote machine made accessible via
L<SearchServer|LucyX::Remote::SearchServer>.

=head1 METHODS

=head2 new

Constructor.  Takes hash-style params.

=over

=item *

B<peer_address> - The name/IP and the port number which the client should
attempt to connect to.

=back

=cut


text:
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Common
{
  public class XPanel : Panel
  {

    #region Dependency properties

    #region AnimationLength property

    public int AnimationLength
    {
      get { return (int)GetValue(AnimationLengthProperty); }
      set { SetValue(AnimationLengthProperty, value); }
    }

    public static readonly DependencyProperty AnimationLengthProperty =
        DependencyProperty.Register("AnimationLength", typeof(int), typeof(XPanel), new PropertyMetadata(0));

    #endregion

    #region Columns property

    public int Columns
    {
      get { return (int)GetValue(ColumnsProperty); }
      set { SetValue(ColumnsProperty, value); }
    }

    public static readonly DependencyProperty ColumnsProperty =
      DependencyProperty.Register("Columns", typeof (int), typeof (XPanel),
                                  new PropertyMetadata(0, OnColumnsChanged));

    private static void OnColumnsChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
      if ((int)e.NewValue > 0)
      {
        ((XPanel)obj).Rows = 0;
        ((XPanel)obj).Orientation = Orientation.Horizontal;
      }
      ((XPanel)obj).AutoWrap = (((XPanel)obj).Columns == 0 && ((XPanel)obj).Rows == 0);
    }

    #endregion

    #region Rows property

    public int Rows
    {
      get { return (int)GetValue(RowsProperty); }
      set { SetValue(RowsProperty, value); }
    }

    public static readonly DependencyProperty RowsProperty =
        DependencyProperty.Register("Rows", typeof(int), typeof(XPanel),
          new PropertyMetadata(0, OnRowsChanged));

    private static void OnRowsChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
      if ((int)e.NewValue > 0)
      {
        ((XPanel)obj).Columns = 0;
        ((XPanel)obj).Orientation = Orientation.Vertical;
      }
      ((XPanel)obj).AutoWrap = (((XPanel)obj).Columns == 0 && ((XPanel)obj).Rows == 0);
    }

    #endregion

    #region Orientation property

    public Orientation Orientation
    {
      get { return (Orientation)GetValue(OrientationProperty); }
      set { SetValue(OrientationProperty, value); }
    }

    public static readonly DependencyProperty OrientationProperty =
        DependencyProperty.Register("Orientation", typeof(Orientation), typeof(XPanel),
          new PropertyMetadata(Orientation.Horizontal, OnOrientationChanged));

    private static void OnOrientationChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
      if ((Orientation)e.NewValue == Orientation.Horizontal)
        ((XPanel)obj).Rows = 0;
      else
        ((XPanel)obj).Columns = 0;
    }

    #endregion

    #region Uniform property

    public bool Uniform
    {
      get { return (bool)GetValue(UniformProperty); }
      set { SetValue(UniformProperty, value); }
    }

    public static readonly DependencyProperty UniformProperty =
      DependencyProperty.Register("Uniform", typeof(bool), typeof(XPanel),
        new PropertyMetadata(false));

    #endregion

    #region ItemWidth property

    public double ItemWidth
    {
      get { return (double)GetValue(ItemWidthProperty); }
      set { SetValue(ItemWidthProperty, value); }
    }

    public static readonly DependencyProperty ItemWidthProperty =
      DependencyProperty.Register("ItemWidth", typeof(double), typeof(XPanel),
        new PropertyMetadata(0.0));

    #endregion

    #region ItemHeight property

    public double ItemHeight
    {
      get { return (double)GetValue(ItemHeightProperty); }
      set { SetValue(ItemHeightProperty, value); }
    }

    public static readonly DependencyProperty ItemHeightProperty =
      DependencyProperty.Register("ItemHeight", typeof(double), typeof(XPanel),
        new PropertyMetadata(0.0));

    #endregion

    #region AutoWrap property

    public bool AutoWrap
    {
      get { return (bool)GetValue(AutoWrapProperty); }
      set { SetValue(AutoWrapProperty, value); }
    }

    public static readonly DependencyProperty AutoWrapProperty =
      DependencyProperty.Register("AutoWrap", typeof(bool), typeof(XPanel),
        new PropertyMetadata(true));

    private static void OnAutoWrapChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
      if ((bool)e.NewValue == true)
      {
        ((XPanel)obj).Columns = 0;
        ((XPanel)obj).Rows = 0;
      }
    }

    #endregion

    #endregion

    #region Attached properties

    #region Row attached property

    public static int GetRow(DependencyObject obj)
    {
      return (int)obj.GetValue(RowProperty);
    }

    private static void SetRow(DependencyObject obj, int value)
    {
      obj.SetValue(RowProperty, value);
    }

    public static readonly DependencyProperty RowProperty =
        DependencyProperty.RegisterAttached("Row", typeof(int), typeof(XPanel), new PropertyMetadata(0));

    #endregion

    #region Column attached property

    public static int GetColumn(DependencyObject obj)
    {
      return (int)obj.GetValue(ColumnProperty);
    }

    private static void SetColumn(DependencyObject obj, int value)
    {
      obj.SetValue(ColumnProperty, value);
    }

    public static readonly DependencyProperty ColumnProperty =
        DependencyProperty.RegisterAttached("Column", typeof(int), typeof(XPanel), new PropertyMetadata(0));

    #endregion

    #region XPosition attached property

    public static double GetXPosition(DependencyObject obj)
    {
      return (double)obj.GetValue(XPositionProperty);
    }

    private static void SetXPosition(DependencyObject obj, double value)
    {
      obj.SetValue(XPositionProperty, value);
    }

    public static readonly DependencyProperty XPositionProperty =
        DependencyProperty.RegisterAttached("XPosition", typeof(double), typeof(XPanel), new PropertyMetadata(0.0));

    #endregion

    #region YPosition attached property

    public static double GetYPosition(DependencyObject obj)
    {
      return (double)obj.GetValue(YPositionProperty);
    }

    private static void SetYPosition(DependencyObject obj, double value)
    {
      obj.SetValue(YPositionProperty, value);
    }

    public static readonly DependencyProperty YPositionProperty =
        DependencyProperty.RegisterAttached("YPosition", typeof(double), typeof(XPanel), new PropertyMetadata(0.0));

    #endregion

    #region IsLastCellInRow attached property

    public static bool GetIsLastCellInRow(DependencyObject obj)
    {
      return (bool)obj.GetValue(IsLastCellInRowProperty);
    }

    public static void SetIsLastCellInRow(DependencyObject obj, bool value)
    {
      obj.SetValue(IsLastCellInRowProperty, value);
    }

    public static readonly DependencyProperty IsLastCellInRowProperty =
        DependencyProperty.RegisterAttached("IsLastCellInRow", typeof(bool), typeof(XPanel), new PropertyMetadata(false));

    #endregion

    #region IsLastCellInColumn attached property

    public static bool GetIsLastCellInColumn(DependencyObject obj)
    {
      return (bool)obj.GetValue(IsLastCellInColumnProperty);
    }

    public static void SetIsLastCellInColumn(DependencyObject obj, bool value)
    {
      obj.SetValue(IsLastCellInColumnProperty, value);
    }

    public static readonly DependencyProperty IsLastCellInColumnProperty =
        DependencyProperty.RegisterAttached("IsLastCellInColumn", typeof(bool), typeof(XPanel), new PropertyMetadata(false));

    #endregion

    #endregion

    protected override Size MeasureOverride(Size availableSize)
    {
      if (this.Children == null || this.Children.Count == 0)
        return Size.Empty;

      SetChildProperties(availableSize);

      double width = 0, height = 0;

      foreach (FrameworkElement child in Children)
      {
        width = Math.Max(width, XPanel.GetXPosition(child) + child.DesiredSize.Width);
        height = Math.Max(height, XPanel.GetYPosition(child) + child.DesiredSize.Height);
      }

      return new Size(width, height);
    }

    protected override Size ArrangeOverride(Size finalSize)
    {
      if (this.Children == null || this.Children.Count == 0)
        return finalSize;

      SetChildProperties(finalSize);

      foreach (UIElement child in Children)
      {
        if (this.AnimationLength > 0)
        {
          TranslateTransform trans = child.RenderTransform as TranslateTransform;

          if (trans == null)
          {
            child.RenderTransformOrigin = new Point(0, 0);
            trans = new TranslateTransform();
            child.RenderTransform = trans;
          }

          child.Arrange(new Rect(0, 0, child.DesiredSize.Width, child.DesiredSize.Height));

          //@@@ jkt doet het niet moet via storyboard http://www.c-sharpcorner.com/UploadFile/anavijai/silverlight-translatetransform-animation-example/
          //trans.BeginAnimation(TranslateTransform.XProperty, new DoubleAnimation(XPanel.GetXPosition(child), TimeSpan.FromMilliseconds(this.AnimationLength)), HandoffBehavior.Compose);
          //trans.BeginAnimation(TranslateTransform.YProperty, new DoubleAnimation(XPanel.GetYPosition(child), TimeSpan.FromMilliseconds(this.AnimationLength)), HandoffBehavior.Compose);
        }
        else
        {
          child.Arrange(new Rect(XPanel.GetXPosition(child), XPanel.GetYPosition(child), child.DesiredSize.Width, child.DesiredSize.Height));
        }
      }

      return finalSize;
    }

    //Set the attached properties for all the childs
    private void SetChildProperties(Size availableSize)
    {

      Size infiniteSize = new Size(double.PositiveInfinity, double.PositiveInfinity);
      int curCol = 0, curRow = 0;
      double curX = 0, curY = 0, rowHeight = 0, colWidth = 0, maxWidth = 0, maxHeight = 0;
      Dictionary<int, int> maxColInRow = new Dictionary<int, int>();
      Dictionary<int, int> maxRowInCol = new Dictionary<int, int>();

      if (this.Uniform)
      {
        foreach (UIElement child in Children)
        {
          child.Measure(infiniteSize);
          maxWidth = Math.Max(maxWidth, child.DesiredSize.Width);
          maxHeight = Math.Max(maxHeight, child.DesiredSize.Height);
        }
      }
      else if (this.ItemWidth > 0 || this.ItemHeight > 0)
      {
        foreach (FrameworkElement child in Children)
        {
          if (this.ItemWidth > 0) child.Width = this.ItemWidth;
          if (this.ItemHeight > 0) child.Height = this.ItemHeight;
        }
      }

      foreach (UIElement child in Children)
      {

        child.Measure(infiniteSize);

        if (this.Columns > 0)
        {
          if (curCol == this.Columns)
          {
            curRow += 1;
            curCol = 0;
            curX = 0;
            curY += rowHeight;
            rowHeight = 0;
          }
        }
        else if (this.Rows > 0)
        {
          if (curRow == this.Rows)
          {
            curCol += 1;
            curRow = 0;
            curY = 0;
            curX += colWidth;
            colWidth = 0;
          }
        }
        else if (this.Orientation == Orientation.Horizontal)
        {
          if (curX + child.DesiredSize.Width > availableSize.Width)
          {
            curRow += 1;
            curCol = 0;
            curX = 0;
            curY += rowHeight;
            rowHeight = 0;
          }
        }
        else if (this.Orientation == Orientation.Vertical)
        {
          if (curY + child.DesiredSize.Height > availableSize.Height)
          {
            curCol += 1;
            curRow = 0;
            curY = 0;
            curX += colWidth;
            colWidth = 0;
          }
        }

        XPanel.SetXPosition(child, curX);
        XPanel.SetYPosition(child, curY);
        XPanel.SetRow(child, curRow);
        XPanel.SetColumn(child, curCol);

        if (maxColInRow.ContainsKey(curRow)) maxColInRow[curRow] = curCol; else maxColInRow.Add(curRow, curCol);
        if (maxRowInCol.ContainsKey(curCol)) maxRowInCol[curCol] = curRow; else maxRowInCol.Add(curCol, curRow);

        if (this.Columns > 0 || this.Orientation == Orientation.Horizontal)
        {
          curCol += 1;
          curX += this.Uniform ? maxWidth : child.DesiredSize.Width;
          rowHeight = this.Uniform ? maxHeight : Math.Max(rowHeight, child.DesiredSize.Height);
        }
        else if (this.Rows > 0 || this.Orientation == Orientation.Vertical)
        {
          curRow += 1;
          curY += this.Uniform ? maxHeight : child.DesiredSize.Height;
          colWidth = this.Uniform ? maxWidth : Math.Max(colWidth, child.DesiredSize.Width);
        }

      }

      foreach (UIElement child in Children)
      {
        XPanel.SetIsLastCellInColumn(child, maxRowInCol[XPanel.GetColumn(child)] == XPanel.GetRow(child));
        XPanel.SetIsLastCellInRow(child, maxColInRow[XPanel.GetRow(child)] == XPanel.GetColumn(child));
      }

    }

  }

}


text:
/*
 * Timer.h
 *
 *  Created on: May 20, 2013
 *      Author: planke
 */

#ifndef BW_TIME_H_
#define BW_TIME_H_

#include <string>

class BW_Time {
public:
	BW_Time();
	virtual ~BW_Time();
	static double getMilliSecondsCached();
	static double getMilliSeconds();
	static int getSeconds();
	static void updateCachedMilliseconds();
	static void stopCachedMilliseconds();
	static void startCachedMilliseconds();
	static void resetStopDiff();

	static double getMilliSecondsOverCached();
	static void resetStartTime(float gameSpeed = 1);

	//static std::string integerToTimeString(int time);
	static std::string integerToDayTimeString(int time);
private:
	static double _now;

	static double _stopDiff;
	static double _lastStop;
	static double _start;

	static float _gameSpeed;
};

#endif /* BW_TIME_H_ */