text:
<?php

// Written by Kevin Prigel
// (c) KDP Innovations, LLC
// Licensed under the Apache License.  See LICENSE for details
//
//
//
// You must have ImageMagick and Imagick installed for this to work properly
//  You need to have a domain name in Rackspace Cloud DNS that is inserted in
//  the ParentDomain field to create CNAMES pointing to the public CDN URL
//  of containers.  You need a Rackspace Cloud account (though this can likely
//  be modified to work with other OpenStack deployments.  Also, sign up for
//  an account at Iron.io for the message queue service (10M messages per month
//  for free!).   Libraries required include php-opencloud, Ironcore, and
//  IronMQ.

require_once('php-opencloud.php');
require_once "IronCore.class.php";
require_once "IronMQ.class.php";

$ironmq = new IronMQ(array(
    "token" => 'YOUR TOKEN HERE',
    "project_id" => 'YOUR MESSAGE ID HERE',
    'host' => 'mq-rackspace-dfw.iron.io'
));

// post test message -  comment this out once the PutFile method is implemented
// see PutFile.php for definitions
$postmessage=json_encode(array("ImageName"=>"IMG_1100.JPG",
    "CurrentContainer"=>"toprocess",
    "NewContainerName"=>"456",
    "ParentDomain"=>"YOURDOMAIN.COM",
    "SuffixFormat"=>array('','_web','_mob','_tweb','_tmob'),
    "WidthArray"=>array(2000,1200,960,500,600),
    "HeightArray"=>array(1500,900,640,500,600),
    "QualityArray"=>array(100,90,80,80,60),
    "MaintainAspect"=>array(TRUE,TRUE,TRUE,FALSE,FALSE),
    "ForceWidth"=>array(0,0,0,1,1),
    "KeepOriginal"=>0,
    "idFile"=>"578946"));

$ironmq->postMessage("iprocess",$postmessage);

//get message

$process_info=$ironmq->getMessage("iprocess",60);
while (empty($process_info)){
    sleep(10);
    $process_info=$ironmq->getMessage("iprocess",60);
}

$process_me=json_decode($process_info->body);

$toprocess=$process_me->CurrentContainer;
$imagename=$process_me->ImageName;
$container_name=$process_me->NewContainerName;
$suffixformat=$process_me->SuffixFormat;
$widtharray=$process_me->WidthArray;
$heightarray=$process_me->HeightArray;
$qualityarray=$process_me->QualityArray;
$aspectarray=$process_me->MaintainAspect;
$parent_domain=$process_me->ParentDomain;
$forcewidth=$process_me->ForceWidth;
$keeporiginal=$process_me->KeepOriginal;
$idFile=$process_me->idFile;

define('AUTHURL', RACKSPACE_US);
define('USERNAME', 'RACKSPACE USERNAME');
define('APIKEY', 'RACKSPACE APIKEY');

// establish our credentials
$connection = new \OpenCloud\Rackspace(AUTHURL,
array( 'username' => USERNAME,
'apiKey' => APIKEY));
$conn=$connection->ObjectStore('cloudFiles','DFW');

// if $containername does not exist, create it, publish it to the CDN, and
//  create a CNAME under ParentDomain that points to the container
try { $container = $conn->Container($container_name); }
catch (OpenCloud\Common\Exceptions\ContainerNotFoundError $e) {
ContAndCNAME($container_name,$parent_domain);}

/* START THE IMAGES SECTION */

$tempimagename=md5(microtime());

$container_to_process=$conn->Container($toprocess);
$file_to_process=$container_to_process->DataObject($imagename);
$file_to_process->SaveToFileName($imagename);
$basefilename=PATHINFO($imagename,PATHINFO_FILENAME);
$tempimagename=$tempimagename.".".pathinfo($imagename,PATHINFO_EXTENSION);
rename($imagename,$tempimagename);
$originalimagename=$imagename;
$imagename=$tempimagename;

$count=count($suffixformat);

$container_new=$conn->Container($container_name);

$im=new Imagick();
$im->readimage($imagename);

//  If the image is rotated, correct it

$orientation = $im->getImageOrientation();

    switch($orientation) {
        case imagick::ORIENTATION_BOTTOMRIGHT:
            $im->rotateimage("#000", 180); // rotate 180 degrees
        break;

        case imagick::ORIENTATION_RIGHTTOP:
            $im->rotateimage("#000", 90); // rotate 90 degrees CW
        break;

        case imagick::ORIENTATION_LEFTBOTTOM:
            $im->rotateimage("#000", -90); // rotate 90 degrees CCW
        break;
    }

// Get EXIF data from the original image, save it to post to the message
//    queue when processing finishes

$exif=$im->getImageProperties('exif:*') ;

// strip exif data and rewrite source image to largest dimensions for faster
//  processing of large images

$maxwidth=max($widtharray);
$maxheight=max($heightarray);
$im->resizeImage($maxwidth,$maxheight,imagick::FILTER_LANCZOS,1,TRUE);
$d = $im->getImageGeometry();
$w = $d['width'];
$h = $d['height'];

// Now that it's auto-rotated, make sure the EXIF data is correct in case the
// EXIF gets saved with the image!
$im->stripImage();
$im->setImageOrientation(imagick::ORIENTATION_TOPLEFT);
$im->setImageFormat('jpeg');
$im->setImageCompression(Imagick::COMPRESSION_JPEG);
$im->setCompressionQuality(100);
$im->writeimage($imagename);

for ($i=0;$i<$count;$i++){
    $cycletime=microtime(true);

    $newfilename[$i]=$basefilename.$suffixformat[$i].".jpg";
    $newfiletemp[$i]=MD5(microtime()).".jpg";
    //echo $newfilename[$i]."\n";
    //echo $newfiletemp[$i]."\n";

    $im->readImage($imagename);

    $readtime=microtime(true)-$cycletime;
    $cycletime=microtime(true);
    //echo "Readtime ".$readtime."\n";

    if ($aspectarray[$i]==TRUE){
        // This resizes the image, maintaining the current aspect ratio.
        // As written, it resizes the largest dimension of the image to the
        // value specified in width.
        if ($w>$h){
            $im->resizeImage($widtharray[$i],$heightarray[$i],imagick::FILTER_LANCZOS,1,TRUE);}
        else {
            $im->resizeImage($heightarray[$i],$widtharray[$i],imagick::FILTER_LANCZOS,1,TRUE);}
        }

    else {
     // processing if MaintainAspect=FALSE (for making square or other size
     // images
      if ($forcewidth[$i]=0){
          //  This creates a crop thumbnail that is exactly the width and height
          $im->cropthumbnailimage($widtharray[$i],$heightarray[$i]);}
      else {
          if ($w>$h){
         // if forcewidth=1 then the width is treated as fixed, generating an
         // image that if is a landscape style image, will generally make a
         // landscape style image, and if it is a portrait orientation image
         // will generate an square image (Usage would generally be for
         // WIDTH=HEIGHT, MaintainAspect=FALSE, ForceWidth=1).  Essentially,
         // this creates thumbnails like those in the Facebook iPhone app which
         // are square for portrait orientation images, and rectangular for
         // landscape orientation images.
              $im->resizeImage($widtharray[$i],$heightarray[$i],imagick::FILTER_LANCZOS,1,TRUE);}
          else{
              $im->cropthumbnailimage($widtharray[$i],$heightarray[$i]);
          }
          }
      }

    $im->setImageFormat('jpeg');
    $im->setImageCompression(Imagick::COMPRESSION_JPEG);
    $im->setCompressionQuality($qualityarray[$i]);
    $im->writeimage($newfiletemp[$i]);

    $im->Clear();

}

for ($j=0;$j<$count;$j++){
    // write new files to Cloud Files in NewContainerName
    $write_file=$container_new->DataObject();
    $write_file->Create(array('name' => $newfilename[$j]),$newfiletemp[$j]);

    // delete local copy of image
    unlink($newfiletemp[$j]);
}

// delete original image
unlink($imagename);

$im->destroy();

// add message to queue that file is processed with EXIF data
$postmessage=json_encode(array("idFile"=>$idFile,"FilesGenerated"=>$count,"exif"=>$exif));
$ironmq->postMessage("filesprocessed",$postmessage);

// delete message from queue
$ironmq->deleteMessage("iprocess",$process_info->id);

// now delete original image if KeepOriginal=0
if ($keeporiginal=0){
$container_to_delete_from=$conn->Container($toprocess);
$file_to_delete=$container_to_delete_from->DataObject($originalimagename);
$file_to_delete->Delete();}

flush();

exit();

Function ContAndCNAME($ContName,$BaseDomainName){

// establish our credentials
$connection = new \OpenCloud\Rackspace(AUTHURL,
array( 'username' => USERNAME,
'apiKey' => APIKEY));

// connect to Cloud Files
$objstore = $connection->ObjectStore('cloudFiles', 'DFW');

// create container
$container = $objstore->Container();
$container->Create(array('name'=>$ContName));

// publish container to cdn, get url
$cdnversion = $container->PublishToCDN();
$CNAMEResolves2 =$container->PublicURL();
$CNAMEResolves=substr($CNAMEResolves2,7);

// connect to dns
$dns = $connection->DNS();

// create new cname
$NewCNAME = $ContName . "." . $BaseDomainName;

$dlist=$dns->DomainList(array('name'=>$BaseDomainName));
$domain=$dlist->Next();

$record = $domain->Record();
$record->Create(array(
'type' => 'CNAME',
    'name' => $NewCNAME,
    'ttl' => 600,
    'data' => $CNAMEResolves));
}

?>


text:
package ru.stqa.pft.sandbox;

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

/**
 * Created by user on 30-May-16.
 */
public class Collections {

    public static void main(String[] args){
   // String[] langs = {"Java","C#","Python","PHP"};
        List<String> languages = Arrays.asList("Java","C#","Python","PHP");

        for(String l: languages){
            System.out.println("I want to learn " + l);
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.causeway.viewer.wicket.ui.actionresponse;

import org.apache.wicket.request.component.IRequestablePage;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.springframework.lang.Nullable;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.NonNull;

@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class PageRedirectRequest<T extends IRequestablePage> {

    private final @NonNull Class<T> pageClass;
    private final @Nullable PageParameters pageParameters;
    private final @Nullable IRequestablePage pageInstance;

    public static <T extends IRequestablePage> PageRedirectRequest<T> forPageClass(
            final @NonNull Class<T> pageClass,
            final @NonNull PageParameters pageParameters) {
        return new PageRedirectRequest<>(pageClass, pageParameters, null);
    }

    public static <T extends IRequestablePage> PageRedirectRequest<T> forPageClass(
            final @NonNull Class<T> pageClass) {
        return new PageRedirectRequest<>(pageClass, null, null);
    }

    public static <T extends IRequestablePage> PageRedirectRequest<T> forPage(
            final @NonNull Class<T> pageClass,
            final @NonNull T pageInstance) {
        return new PageRedirectRequest<>(pageClass, null, pageInstance);
    }

    public void applyTo(
            final @Nullable RequestCycle requestCycle) {
        if(requestCycle==null) {
            return;
        }
        if(pageParameters!=null) {
            requestCycle.setResponsePage(pageClass, pageParameters);
            return;
        }
        if(pageInstance!=null) {
            requestCycle.setResponsePage(pageInstance);
            return;
        }
        requestCycle.setResponsePage(pageClass);
    }

    @Override
    public String toString() {
        return String.format("PageRedirectRequest[pageClass=%s,pageParameters=%s]",
                pageClass.getName(), pageParameters);
    }

}


text:
class JobsController < ApplicationController
  before_action :set_job, only: [:show, :edit, :update, :destroy]

  # GET /jobs
  # GET /jobs.json
  def index
    @jobs = Job.all
  end

  # GET /jobs/1
  # GET /jobs/1.json
  def show
  end

  # GET /jobs/new
  def new
    @job = Job.new
  end

  # GET /jobs/1/edit
  def edit
  end

  # POST /jobs
  # POST /jobs.json
  def create
    @job = Job.new(job_params)

    respond_to do |format|
      if @job.save
        format.html { redirect_to @job, notice: 'Job was successfully created.' }
        format.json { render :show, status: :created, location: @job }
      else
        format.html { render :new }
        format.json { render json: @job.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /jobs/1
  # PATCH/PUT /jobs/1.json
  def update
    respond_to do |format|
      if @job.update(job_params)
        format.html { redirect_to @job, notice: 'Job was successfully updated.' }
        format.json { render :show, status: :ok, location: @job }
      else
        format.html { render :edit }
        format.json { render json: @job.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /jobs/1
  # DELETE /jobs/1.json
  def destroy
    @job.destroy
    respond_to do |format|
      format.html { redirect_to jobs_url, notice: 'Job was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_job
      @job = Job.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def job_params
      params.require(:job).permit(:title, :hirer, :compensation_type, :description, :deadline, :url, :contact, :qualifications, :start_date, :duration)
    end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="marshallingMessageConverter"
          class="org.springframework.amqp.support.converter.MarshallingMessageConverter">
        <constructor-arg ref="marshaller" />
    </bean>

<!--     <bean id="marshallingMessageConverter"  -->
<!--           class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter" /> -->

</beans>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

        <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
        <title>Plotserver</title>
        <link href="/static/favicon.png" rel="icon" type="image/png" />
        <link href="/static/client.css" rel="stylesheet" type="text/css" />

            <button id="editView" onClick="toggleEditMode()">Edit plot</button>

            <textarea id="options" class="textarea" onInput="onOptionsChanged()"></textarea>
            <textarea id="numbers" class="textarea" onKeyUp="onNumbersChanged($('#numbers').val())" onChange="onNumbersChanged($('#numbers').val())"></textarea>
            <button id="save" onClick="save($('#numbers').val(), $('#options').val())">Save</button>
            Chart options
            Example .csv data


text:
/**
 * Support for AOP-based scoping of target objects, with configurable backend.
 */
@NonNullApi
@NonNullFields
package org.springframework.aop.scope;

import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;


text:
package com.winterwell.bob.tasks;

import java.io.File;

import junit.framework.TestCase;

public class JarTaskTest extends TestCase {

	/**
	 * These jar files are giving "invalid archive" messages when examined through the Windows file explorer
	 * TODO check in Linux
	 */
	public void testWindowsWierdness() {
		File dir = new File("bin");
		File jarFile = new File("testing/test.jar");
		JarTask jt = new JarTask(jarFile, dir);
		jt.run();
	}
}


text:
namespace Common
{
	using System;
	using System.Collections.Specialized;
	using System.Windows.Data;

	#region Enumerations

	/// <summary>
	/// Enumeration used to specify what kind of change the
	/// property that is hooked to the CollectionObservationHandle
	/// instance underwent.
	/// </summary>
	public enum ChangeType
	{
		PropertyChanged = 0,
		CollectionChanged
	}

	#endregion Enumerations

	/// <summary>
	/// Arguments for the callback method of a CollectionObservationHandle.
	/// </summary>
	public class CollectionObservationCallbackArgs
	{
		#region constructors

		/// <summary>
		/// Initializes a new instance of the <see cref="CollectionObservationCallbackArgs"/> class.
		/// </summary>
		/// <param name="handle">The CollectionObservationHandle instance that is assiciated with the callback.</param>
		/// <param name="propertyChangedCallbackArgs">The PropertyChangedCallbackArgs instance that was caused by a property change.</param>
		public CollectionObservationCallbackArgs(CollectionObservationHandle handle, PropertyChangedCallbackArgs propertyChangedCallbackArgs)
		{
			this.ChangeType = ChangeType.PropertyChanged;
			this.Handle = handle;
			this.PropertyChangedCallbackArgs = propertyChangedCallbackArgs;
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="CollectionObservationCallbackArgs"/> class.
		/// </summary>
		/// <param name="handle">The CollectionObservationHandle instance that is assiciated with the callback.</param>
		/// <param name="notifyCollectionChangedEventArgs">The <see cref="System.Collections.Specialized.NotifyCollectionChangedEventArgs"/> instance containing the event data.</param>
		public CollectionObservationCallbackArgs(CollectionObservationHandle handle, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
		{
			this.ChangeType = ChangeType.CollectionChanged;
			this.Handle = handle;
			this.NotifyCollectionChangedEventArgs = notifyCollectionChangedEventArgs;
		}

		#endregion constructors

		#region properties

		/// <summary>
		/// Gets or sets the type of the property change which can be either a
		/// change in value of the property itsself or a change in the containing collection.
		/// </summary>
		public ChangeType ChangeType
		{
			get;
			private set;
		}

		/// <summary>
		/// Gets or sets the CollectionObservationHandle instance that is assiciated with the callback.
		/// </summary>
		public CollectionObservationHandle Handle
		{
			get;
			private set;
		}

		/// <summary>
		/// Gets or sets the NotifyCollectionChangedEventArgs that were given with the collection change.
		/// Is null if callback was called as a result of a property change.
		/// </summary>
		public NotifyCollectionChangedEventArgs NotifyCollectionChangedEventArgs
		{
			get;
			private set;
		}

		/// <summary>
		/// Gets or sets the PropertyChangedCallbackArgs that were given with the property change.
		/// Is null if callback was called as a result of a collection change.
		/// </summary>
		public PropertyChangedCallbackArgs PropertyChangedCallbackArgs
		{
			get;
			private set;
		}

		#endregion properties
	}

	/// <summary>
	/// Used to monitor changes in a poperty of a type that implements INotifyCollectionChanged.
	/// A callback method is called whenever the property changes to another value or the collection it contains
	/// raises the CollectionChanged event.
	/// </summary>
	public class CollectionObservationHandle : IDisposable
	{
		#region static methods

		// TODO: (PS) Comment this.
		public static CollectionObservationHandle GetDistinctInstance(Binding binding, Action<CollectionObservationCallbackArgs> callback, bool keepAlive = false)
		{
			if (callback == null)
			{
				throw new ArgumentNullException("callback");
			}

			return DistinctInstanceProvider<CollectionObservationHandle>.Instance.GetDistinctInstance(new CollectionObservationHandle(binding, callback, keepAlive));
		}

		/// <summary>
		/// Creates a new instance of this class or if one with the same parameters as the given ones allready exists returns that one.
		/// </summary>
		/// <param name="source">The source object that contains the property to monitor.</param>
		/// <param name="path">The path from the source object to the property to monitor.</param>
		/// <param name="callback">The callback method that is supposed to be called when changes happen in the property.</param>
		/// <returns>Returns a new instance of this class or if one with the same parameters as the given ones allready exists returns that one</returns>
		public static CollectionObservationHandle GetDistinctInstance(object source, string path, Action<CollectionObservationCallbackArgs> callback, bool keepAlive = false)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (String.IsNullOrWhiteSpace(path))
			{
				throw new ArgumentException("String argument 'path' must not be null or empty (incl. whitespace).", "path");
			}

			return GetDistinctInstance(new Binding(path) { Source = source }, callback);
		}

		#endregion static methods

		#region constructors

		// TODO: (PS) Comment this.
		/// <summary>
		/// Initializes a new instance of the <see cref="CollectionObservationHandle"/> class.
		/// </summary>
		/// <param name="source">The source object that contains the property to monitor.</param>
		/// <param name="path">The path from the source object to the property to monitor.</param>
		/// <param name="callback">The callback method that is supposed to be called when changes happen in the property.</param>
		private CollectionObservationHandle(Binding binding, Action<CollectionObservationCallbackArgs> callback, bool keepAlive)
		{
			this.PropertyChangedHandle = PropertyChangedHandle.GetDistinctInstance(binding, this.OnMonitoredPropertyChanged, keepAlive);
			this.UpdateCollectionChangedEventHandler(null, this.PropertyChangedHandle.PropertyValue as INotifyCollectionChanged);
			this.Callback = callback;
		}

		/// <summary>
		/// Releases unmanaged resources and performs other cleanup operations before the
		/// <see cref="CollectionObservationHandle"/> is reclaimed by garbage collection.
		/// </summary>
		~CollectionObservationHandle()
		{
			DistinctInstanceProvider<CollectionObservationHandle>.Instance.RemoveDistinctInstance(this);
			this.Dispose();
		}

		#endregion constructors

		#region properties

		/// <summary>
		/// Gets the callback method of this instance that is called whenever the property or its'
		/// containing collection change.
		/// </summary>
		public Action<CollectionObservationCallbackArgs> Callback
		{
			get;
			private set;
		}

		/// <summary>
		/// Gets or sets a value indicating whether this <see cref="CollectionObservationHandle"/> is disposed.
		/// </summary>
		/// <value><c>true</c> if disposed; otherwise, <c>false</c>.</value>
		public bool Disposed
		{
			get;
			protected set;
		}

		/// <summary>
		/// Gets the PropertyChangedHandle that is used to monitor value changes in the monitored property.
		/// </summary>
		public PropertyChangedHandle PropertyChangedHandle
		{
			get;
			private set;
		}

		#endregion properties

		#region overrideable methods

		/// <summary>
		/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
		/// </summary>
		/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
		/// <returns>
		/// 	<c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
		/// </returns>
		public override bool Equals(object obj)
		{
			CollectionObservationHandle other = obj as CollectionObservationHandle;

			return other != null &&
				this.PropertyChangedHandle.Equals(other.PropertyChangedHandle, false) &&
				this.Callback.Equals(other.Callback);
		}

		/// <summary>
		/// Returns a hash code for this instance.
		/// Used object class's GetHashCode() method.
		/// </summary>
		/// <returns>
		/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
		/// </returns>
		public override int GetHashCode()
		{
			return HashCodeOperations.Combine(this.PropertyChangedHandle, this.Callback);
		}

		#endregion overrideable methods

		#region methods

		/// <summary>
		/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
		/// </summary>
		public void Dispose()
		{
			if (!this.Disposed)
			{
				this.Disposed = true;

				this.UpdateCollectionChangedEventHandler(this.PropertyChangedHandle.PropertyValue as INotifyCollectionChanged, null);
				this.PropertyChangedHandle.Dispose();
			}
		}

		/// <summary>
		/// Called when the monitored property changes its' value.
		/// </summary>
		/// <param name="e">The callback arguments of the property change.</param>
		private void OnMonitoredPropertyChanged(PropertyChangedCallbackArgs e)
		{
			this.UpdateCollectionChangedEventHandler(e.OldValue as INotifyCollectionChanged, e.NewValue as INotifyCollectionChanged);
			this.Callback(new CollectionObservationCallbackArgs(this, e));
		}

		/// <summary>
		/// Adds/removes the CollectionChanged event handler to/from the new/old value.
		/// </summary>
		/// <param name="newValue">The new value of the monitored property.</param>
		private void UpdateCollectionChangedEventHandler(INotifyCollectionChanged oldValue, INotifyCollectionChanged newValue)
		{
			if (oldValue != null)
			{
				newValue.CollectionChanged -= WeakEventHandler.GetHandler(this.MonitoredCollection_CollectionChanged);
			}

			if (newValue != null)
			{
				newValue.CollectionChanged += WeakEventHandler.GetHandler(this.MonitoredCollection_CollectionChanged);
			}
		}

		#endregion methods

		#region event handlers

		/// <summary>
		/// Handles the CollectionChanged event of the current value of the monitored property.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.Collections.Specialized.NotifyCollectionChangedEventArgs"/> instance containing the event data.</param>
		private void MonitoredCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			this.Callback(new CollectionObservationCallbackArgs(this, e));
		}

		#endregion event handlers
	}
}


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

import java.util.Collections;
import java.util.List;

import org.apache.ibatis.type.JdbcType;
import org.flowable.cmmn.engine.impl.db.EntityDependencyOrder;
import org.flowable.engine.common.AbstractEngineConfiguration;
import org.flowable.engine.common.AbstractEngineConfigurator;
import org.flowable.engine.common.EngineDeployer;
import org.flowable.engine.common.impl.db.CustomMyBatisTypeHandlerConfig;
import org.flowable.engine.common.impl.db.CustomMybatisTypeAliasConfig;
import org.flowable.engine.common.impl.interceptor.EngineConfigurationConstants;
import org.flowable.engine.common.impl.persistence.entity.Entity;
import org.flowable.idm.engine.IdmEngineConfiguration;
import org.flowable.idm.engine.impl.cfg.StandaloneIdmEngineConfiguration;
import org.flowable.idm.engine.impl.persistence.ByteArrayRefTypeHandler;
import org.flowable.idm.engine.impl.persistence.entity.ByteArrayRef;

/**
 * @author Tijs Rademakers
 * @author Joram Barrez
 */
public class IdmEngineConfigurator extends AbstractEngineConfigurator {

    protected IdmEngineConfiguration idmEngineConfiguration;

    @Override
    public int getPriority() {
        return EngineConfigurationConstants.PRIORITY_ENGINE_IDM;
    }

    @Override
    protected List<EngineDeployer> getCustomDeployers() {
        return null;
    }

    @Override
    protected String getMybatisCfgPath() {
        return IdmEngineConfiguration.DEFAULT_MYBATIS_MAPPING_FILE;
    }

    @Override
    protected List<CustomMybatisTypeAliasConfig> getMybatisTypeAliases() {
        return Collections.singletonList(new CustomMybatisTypeAliasConfig("IdmByteArrayRefTypeHandler", ByteArrayRefTypeHandler.class));
    }

    @Override
    protected List<CustomMyBatisTypeHandlerConfig> getMybatisTypeHandlers() {
        return Collections.singletonList(new CustomMyBatisTypeHandlerConfig(
                ByteArrayRef.class,
                JdbcType.VARCHAR,
                ByteArrayRefTypeHandler.class));
    }

    @Override
    public void configure(AbstractEngineConfiguration engineConfiguration) {
        if (idmEngineConfiguration == null) {
            idmEngineConfiguration = new StandaloneIdmEngineConfiguration();
        }

        initialiseCommonProperties(engineConfiguration, idmEngineConfiguration);

        idmEngineConfiguration.buildIdmEngine();

        initServiceConfigurations(engineConfiguration, idmEngineConfiguration);
    }

    @Override
    protected List<Class<? extends Entity>> getEntityInsertionOrder() {
        return EntityDependencyOrder.INSERT_ORDER;
    }

    @Override
    protected List<Class<? extends Entity>> getEntityDeletionOrder() {
        return EntityDependencyOrder.DELETE_ORDER;
    }

    public IdmEngineConfiguration getIdmEngineConfiguration() {
        return idmEngineConfiguration;
    }

    public IdmEngineConfigurator setIdmEngineConfiguration(IdmEngineConfiguration idmEngineConfiguration) {
        this.idmEngineConfiguration = idmEngineConfiguration;
        return this;
    }

}


text:
ace.define("ace/snippets/plain_text",["require","exports","module"],function(e,t,n){"use strict";t.snippetText=undefined,t.scope="plain_text"});                (function() {
                    ace.require(["ace/snippets/plain_text"], function(m) {
                        if (typeof module == "object" && typeof exports == "object" && module) {
                            module.exports = m;
                        }
                    });
                })();


text:
<?xml version="1.0" ?>
<PrivateChannels>
	<Channel name="Tootsuki Radio Station" siteUrl="http://open.fm/play/72" streamUrl="http://gr-relay-6.gaduradio.pl/72"/>
</PrivateChannels>


text:
package ammonite.shell

import java.nio.file.NotDirectoryException
import java.nio.file.attribute.PosixFilePermission

import ammonite.ops._
import ammonite.repl.FrontEndUtils
import pprint.Renderer

import scala.util.Try

case class ShellSession() extends OpsAPI {
  var wd0 = pwd
  /**
    * The current working directory of the shell, that will get picked up by
    * any ammonite.ops commands you use
    */
  implicit def wd = wd0
  /**
    * Change the working directory `wd`; if the provided path is relative it
    * gets appended on to the current `wd`, if it's absolute it replaces.
    */
  val cd = (arg: Path) => {
    /*
     * `arg` should be a directory or a symlink to a directory
     * `realPath will be None if that is not the case,
     * otherwise - Some(realPath)
     */
    val realPath = Option(arg)
      .filter(_.isDir)
      .orElse(arg.tryFollowLinks.filter(_.isDir))

    realPath match {
      case None => throw new NotDirectoryException(arg.toString)
      case Some(path) => wd0 = arg; wd0
    }
  }

  implicit def Relativizer[T](p: T)(implicit b: Path, f: T => RelPath): Path = b/f(p)
}

trait OpsAPI{
  /**
    * The current working directory of the shell, that will get picked up by
    * any [[Relativizer]] below, and can be modified using [[cd]]
    */
  implicit def wd: Path
  /**
    * Change the working directory `wd`; if the provided path is relative it
    * gets appended on to the current `wd`, if it's absolute it replaces. It
    * returns the resultant absolute path.
    */
  val cd: ammonite.ops.Path => ammonite.ops.Path

  /**
    * Allows you to use relative paths (and anything convertible to a relative
    * path) as absolute paths when working in the REPL. Note that this isn't
    * available when using Ammonite-Ops in a standalone project! In such cases,
    * it's good practice to convert paths from relative to absolute explicitly.
    */
  implicit def Relativizer[T](p: T)(implicit b: Path, f: T => RelPath): Path

}


text:
using NBitcoin.Crypto;
using NBitcoin.DataEncoders;
using NBitcoin.Protocol;
using NBitcoin.RPC;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NBitcoin
{
	public class OutPoint : IBitcoinSerializable
	{
		public bool IsNull
		{
			get
			{
				return (hash == 0 && n == uint.MaxValue);
			}
		}
		private uint256 hash;
		private uint n;

		public uint256 Hash
		{
			get
			{
				return hash;
			}
			set
			{
				hash = value;
			}
		}
		public uint N
		{
			get
			{
				return n;
			}
			set
			{
				n = value;
			}
		}

		public static bool TryParse(string str, out OutPoint result)
		{
			result = null;
			if(str == null)
				throw new ArgumentNullException("str");
			var splitted = str.Split('-');
			if(splitted.Length != 2)
				return false;

			uint256 hash;
			if(!uint256.TryParse(splitted[0], out hash))
				return false;

			uint index;
			if(!uint.TryParse(splitted[1], out index))
				return false;
			result = new OutPoint(hash, index);
			return true;
		}

		public static OutPoint Parse(string str)
		{
			OutPoint result;
			if(TryParse(str, out result))
				return result;
			throw new FormatException("The format of the outpoint is incorrect");
		}

		public OutPoint()
		{
			SetNull();
		}
		public OutPoint(uint256 hashIn, uint nIn)
		{
			hash = hashIn;
			n = nIn;
		}
		public OutPoint(uint256 hashIn, int nIn)
		{
			hash = hashIn;
			this.n = nIn == -1 ? n = uint.MaxValue : (uint)nIn;
		}

		public OutPoint(Transaction tx, uint i)
			: this(tx.GetHash(), i)
		{
		}

		public OutPoint(Transaction tx, int i)
			: this(tx.GetHash(), i)
		{
		}

		public OutPoint(OutPoint outpoint)
		{
			this.FromBytes(outpoint.ToBytes());
		}
		//IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )

		public void ReadWrite(BitcoinStream stream)
		{
			stream.ReadWrite(ref hash);
			stream.ReadWrite(ref n);
		}

		void SetNull()
		{
			hash = 0;
			n = uint.MaxValue;
		}

		public static bool operator <(OutPoint a, OutPoint b)
		{
			return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
		}
		public static bool operator >(OutPoint a, OutPoint b)
		{
			return (a.hash > b.hash || (a.hash == b.hash && a.n > b.n));
		}

		public static bool operator ==(OutPoint a, OutPoint b)
		{
			if(Object.ReferenceEquals(a, null))
			{
				return Object.ReferenceEquals(b, null);
			}
			if(Object.ReferenceEquals(b, null))
			{
				return false;
			}
			return (a.hash == b.hash && a.n == b.n);
		}

		public static bool operator !=(OutPoint a, OutPoint b)
		{
			return !(a == b);
		}
		public override bool Equals(object obj)
		{
			OutPoint item = obj as OutPoint;
			if(object.ReferenceEquals(null, item))
				return false;
			return item == this;
		}

		public override int GetHashCode()
		{
			unchecked
			{
				return 17 + hash.GetHashCode() * 31 + n.GetHashCode() * 31 * 31;
			}
		}

		public override string ToString()
		{
			return Hash + "-" + N;
		}
	}

	public class TxIn : IBitcoinSerializable
	{
		public TxIn()
		{

		}
		public TxIn(Script scriptSig)
		{
			this.scriptSig = scriptSig;
		}
		public TxIn(OutPoint prevout, Script scriptSig)
		{
			this.prevout = prevout;
			this.scriptSig = scriptSig;
		}
		public TxIn(OutPoint prevout)
		{
			this.prevout = prevout;
		}
		OutPoint prevout = new OutPoint();
		Script scriptSig = Script.Empty;
		uint nSequence = uint.MaxValue;

		public Sequence Sequence
		{
			get
			{
				return nSequence;
			}
			set
			{
				nSequence = value.Value;
			}
		}
		public OutPoint PrevOut
		{
			get
			{
				return prevout;
			}
			set
			{
				prevout = value;
			}
		}

		public Script ScriptSig
		{
			get
			{
				return scriptSig;
			}
			set
			{
				scriptSig = value;
			}
		}

		WitScript witScript = WitScript.Empty;

		/// <summary>
		/// The witness script (Witness script is not serialized and deserialized at the TxIn level, but at the Transaction level)
		/// </summary>
		public WitScript WitScript
		{
			get
			{
				return witScript;
			}
			set
			{
				witScript = value;
			}
		}

		#region IBitcoinSerializable Members

		public void ReadWrite(BitcoinStream stream)
		{
			stream.ReadWrite(ref prevout);
			stream.ReadWrite(ref scriptSig);
			stream.ReadWrite(ref nSequence);
		}

		#endregion

		public bool IsFrom(PubKey pubKey)
		{
			var result = PayToPubkeyHashTemplate.Instance.ExtractScriptSigParameters(ScriptSig);
			return result != null && result.PublicKey == pubKey;
		}

		public bool IsFinal
		{
			get
			{
				return (nSequence == uint.MaxValue);
			}
		}

		public TxIn Clone()
		{
			var txin = BitcoinSerializableExtensions.Clone(this);
			txin.WitScript = (witScript ?? WitScript.Empty).Clone();
			return txin;
		}

		public static TxIn CreateCoinbase(int height)
		{
			var txin = new TxIn();
			txin.ScriptSig = new Script(Op.GetPushOp(height)) + OpcodeType.OP_0;
			return txin;
		}
	}

	public class TxOutCompressor : IBitcoinSerializable
	{
		// Amount compression:
		// * If the amount is 0, output 0
		// * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
		// * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
		//   * call the result n
		//   * output 1 + 10*(9*n + d - 1) + e
		// * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
		// (this is decodable, as d is in [1-9] and e is in [0-9])

		ulong CompressAmount(ulong n)
		{
			if(n == 0)
				return 0;
			int e = 0;
			while(((n % 10) == 0) && e < 9)
			{
				n /= 10;
				e++;
			}
			if(e < 9)
			{
				int d = (int)(n % 10);
				n /= 10;
				return 1 + (n * 9 + (ulong)(d - 1)) * 10 + (ulong)e;
			}
			else
			{
				return 1 + (n - 1) * 10 + 9;
			}
		}

		ulong DecompressAmount(ulong x)
		{
			// x = 0  OR  x = 1+10*(9*n + d - 1) + e  OR  x = 1+10*(n - 1) + 9
			if(x == 0)
				return 0;
			x--;
			// x = 10*(9*n + d - 1) + e
			int e = (int)(x % 10);
			x /= 10;
			ulong n = 0;
			if(e < 9)
			{
				// x = 9*n + d - 1
				int d = (int)((x % 9) + 1);
				x /= 9;
				// x = n
				n = (x * 10 + (ulong)d);
			}
			else
			{
				n = x + 1;
			}
			while(e != 0)
			{
				n *= 10;
				e--;
			}
			return n;
		}

		private TxOut _TxOut = new TxOut();
		public TxOut TxOut
		{
			get
			{
				return _TxOut;
			}
		}
		public TxOutCompressor()
		{

		}
		public TxOutCompressor(TxOut txOut)
		{
			_TxOut = txOut;
		}

		#region IBitcoinSerializable Members

		public void ReadWrite(BitcoinStream stream)
		{
			if(stream.Serializing)
			{
				ulong val = CompressAmount((ulong)_TxOut.Value.Satoshi);
				stream.ReadWriteAsCompactVarInt(ref val);
			}
			else
			{
				ulong val = 0;
				stream.ReadWriteAsCompactVarInt(ref val);
				_TxOut.Value = new Money(DecompressAmount(val));
			}
			ScriptCompressor cscript = new ScriptCompressor(_TxOut.ScriptPubKey);
			stream.ReadWrite(ref cscript);
			if(!stream.Serializing)
				_TxOut.ScriptPubKey = new Script(cscript.ScriptBytes);
		}

		#endregion
	}

	public class ScriptCompressor : IBitcoinSerializable
	{
		// make this static for now (there are only 6 special scripts defined)
		// this can potentially be extended together with a new nVersion for
		// transactions, in which case this value becomes dependent on nVersion
		// and nHeight of the enclosing transaction.
		const uint nSpecialScripts = 6;
		byte[] _Script;
		public byte[] ScriptBytes
		{
			get
			{
				return _Script;
			}
		}
		public ScriptCompressor(Script script)
		{
			_Script = script.ToBytes(true);
		}
		public ScriptCompressor()
		{

		}

		public Script GetScript()
		{
			return new Script(_Script);
		}

		private KeyId GetKeyId()
		{
			if(_Script.Length == 25 && _Script[0] == (byte)OpcodeType.OP_DUP && _Script[1] == (byte)OpcodeType.OP_HASH160
								&& _Script[2] == 20 && _Script[23] == (byte)OpcodeType.OP_EQUALVERIFY
								&& _Script[24] == (byte)OpcodeType.OP_CHECKSIG)
			{
				return new KeyId(_Script.SafeSubarray(3, 20));
			}
			return null;
		}

		private ScriptId GetScriptId()
		{
			if(_Script.Length == 23 && _Script[0] == (byte)OpcodeType.OP_HASH160 && _Script[1] == 20
								&& _Script[22] == (byte)OpcodeType.OP_EQUAL)
			{
				return new ScriptId(_Script.SafeSubarray(2, 20));
			}
			return null;
		}

		private PubKey GetPubKey()
		{
			return PayToPubkeyTemplate.Instance.ExtractScriptPubKeyParameters(new Script(_Script));
		}

		byte[] Compress()
		{
			byte[] result = null;
			KeyId keyID = GetKeyId();
			if(keyID != null)
			{
				result = new byte[21];
				result[0] = 0x00;
				Array.Copy(keyID.ToBytes(), 0, result, 1, 20);
				return result;
			}
			ScriptId scriptID = GetScriptId();
			if(scriptID != null)
			{
				result = new byte[21];
				result[0] = 0x01;
				Array.Copy(scriptID.ToBytes(), 0, result, 1, 20);
				return result;
			}
			PubKey pubkey = GetPubKey();
			if(pubkey != null)
			{
				result = new byte[33];
				var pubBytes = pubkey.ToBytes();
				Array.Copy(pubBytes, 1, result, 1, 32);
				if(pubBytes[0] == 0x02 || pubBytes[0] == 0x03)
				{
					result[0] = pubBytes[0];
					return result;
				}
				else if(pubBytes[0] == 0x04)
				{
					result[0] = (byte)(0x04 | (pubBytes[64] & 0x01));
					return result;
				}
			}
			return null;
		}

		Script Decompress(uint nSize, byte[] data)
		{
			switch(nSize)
			{
				case 0x00:
					return new Script(OpcodeType.OP_DUP, OpcodeType.OP_HASH160, Op.GetPushOp(data.SafeSubarray(0, 20)), OpcodeType.OP_EQUALVERIFY, OpcodeType.OP_CHECKSIG);
				case 0x01:
					return new Script(OpcodeType.OP_HASH160, Op.GetPushOp(data.SafeSubarray(0, 20)), OpcodeType.OP_EQUAL);
				case 0x02:
				case 0x03:
					return new Script(Op.GetPushOp(new byte[] { (byte)nSize }.Concat(data.SafeSubarray(0, 32)).ToArray()), OpcodeType.OP_CHECKSIG);
				case 0x04:
				case 0x05:
					byte[] vch = new byte[33];
					vch[0] = (byte)(nSize - 2);
					Array.Copy(data, 0, vch, 1, 32);
					PubKey pubkey = new PubKey(vch);
					pubkey = pubkey.Decompress();
					return new Script(Op.GetPushOp(pubkey.ToBytes()), OpcodeType.OP_CHECKSIG);
			}
			return null;
		}

		#region IBitcoinSerializable Members

		public void ReadWrite(BitcoinStream stream)
		{
			if(stream.Serializing)
			{
				var compr = Compress();
				if(compr != null)
				{
					stream.ReadWrite(ref compr);
					return;
				}
				uint nSize = (uint)_Script.Length + nSpecialScripts;
				stream.ReadWriteAsCompactVarInt(ref nSize);
				stream.ReadWrite(ref _Script);
			}
			else
			{
				uint nSize = 0;
				stream.ReadWriteAsCompactVarInt(ref nSize);
				if(nSize < nSpecialScripts)
				{
					byte[] vch = new byte[GetSpecialSize(nSize)];
					stream.ReadWrite(ref vch);
					_Script = Decompress(nSize, vch).ToBytes();
					return;
				}
				nSize -= nSpecialScripts;
				_Script = new byte[nSize];
				stream.ReadWrite(ref _Script);
			}
		}

		private int GetSpecialSize(uint nSize)
		{
			if(nSize == 0 || nSize == 1)
				return 20;
			if(nSize == 2 || nSize == 3 || nSize == 4 || nSize == 5)
				return 32;
			return 0;
		}

		#endregion
	}

	public class TxOut : IBitcoinSerializable, IDestination
	{
		Script publicKey = Script.Empty;
		public Script ScriptPubKey
		{
			get
			{
				return this.publicKey;
			}
			set
			{
				this.publicKey = value;
			}
		}

		private long value = -1;
		Money _MoneyValue;
		public bool IsNull
		{
			get
			{
				return value == -1;
			}
		}

		public TxOut()
		{

		}

		public TxOut(Money value, IDestination destination)
		{
			Value = value;
			if(destination != null)
				ScriptPubKey = destination.ScriptPubKey;
		}

		public TxOut(Money value, Script scriptPubKey)
		{
			Value = value;
			ScriptPubKey = scriptPubKey;
		}

		public Money Value
		{
			get
			{
				if(_MoneyValue == null)
					_MoneyValue = new Money(value);
				return _MoneyValue;
			}
			set
			{
				if(value == null)
					throw new ArgumentNullException("value");
				_MoneyValue = value;
				this.value = (long)_MoneyValue.Satoshi;
			}
		}

		public bool IsDust(FeeRate minRelayTxFee)
		{
			return (Value < GetDustThreshold(minRelayTxFee));
		}

		public Money GetDustThreshold(FeeRate minRelayTxFee)
		{
			if(minRelayTxFee == null)
				throw new ArgumentNullException("minRelayTxFee");
			int nSize = this.GetSerializedSize() + 148;
			return 3 * minRelayTxFee.GetFee(nSize);
		}

		#region IBitcoinSerializable Members

		public void ReadWrite(BitcoinStream stream)
		{
			stream.ReadWrite(ref value);
			stream.ReadWrite(ref publicKey);
			_MoneyValue = null; //Might been updated
		}

		#endregion

		public bool IsTo(IDestination destination)
		{
			return ScriptPubKey == destination.ScriptPubKey;
		}

		internal void SetNull()
		{
			value = -1;
		}

		public static TxOut Parse(string hex)
		{
			var ret = new TxOut();
			ret.FromBytes(Encoders.Hex.DecodeData(hex));
			return ret;
		}
	}

	public class IndexedTxIn
	{
		public TxIn TxIn
		{
			get;
			set;
		}

		/// <summary>
		/// The index of this TxIn in its transaction
		/// </summary>
		public uint Index
		{
			get;
			set;
		}

		public OutPoint PrevOut
		{
			get
			{
				return TxIn.PrevOut;
			}
			set
			{
				TxIn.PrevOut = value;
			}
		}

		public Script ScriptSig
		{
			get
			{
				return TxIn.ScriptSig;
			}
			set
			{
				TxIn.ScriptSig = value;
			}
		}

		public WitScript WitScript
		{
			get
			{
				return TxIn.WitScript;
			}
			set
			{
				TxIn.WitScript = value;
			}
		}
		public Transaction Transaction
		{
			get;
			set;
		}

		public bool VerifyScript(Script scriptPubKey, ScriptVerify scriptVerify = ScriptVerify.Standard)
		{
			ScriptError unused;
			return VerifyScript(scriptPubKey, scriptVerify, out unused);
		}
		public bool VerifyScript(Script scriptPubKey, out ScriptError error)
		{
			return Script.VerifyScript(scriptPubKey, Transaction, (int)Index, null, out error);
		}
		public bool VerifyScript(Script scriptPubKey, ScriptVerify scriptVerify, out ScriptError error)
		{
			return Script.VerifyScript(scriptPubKey, Transaction, (int)Index, null, scriptVerify, SigHash.Undefined, out error);
		}
		public bool VerifyScript(Script scriptPubKey, Money value, ScriptVerify scriptVerify, out ScriptError error)
		{
			return Script.VerifyScript(scriptPubKey, Transaction, (int)Index, value, scriptVerify, SigHash.Undefined, out error);
		}

		public bool VerifyScript(ICoin coin, ScriptVerify scriptVerify = ScriptVerify.Standard)
		{
			ScriptError error;
			return VerifyScript(coin, scriptVerify, out error);
		}

		public bool VerifyScript(ICoin coin, ScriptVerify scriptVerify, out ScriptError error)
		{
			return Script.VerifyScript(coin.TxOut.ScriptPubKey, Transaction, (int)Index, coin.TxOut.Value, scriptVerify, SigHash.Undefined, out error);
		}
		public bool VerifyScript(ICoin coin, out ScriptError error)
		{
			return VerifyScript(coin, ScriptVerify.Standard, out error);
		}

		public TransactionSignature Sign(Key key, ICoin coin, SigHash sigHash)
		{
			var hash = GetSignatureHash(coin, sigHash);
			return key.Sign(hash, sigHash);
		}

		public uint256 GetSignatureHash(ICoin coin, SigHash sigHash = SigHash.All)
		{
			return Script.SignatureHash(coin.GetScriptCode(), Transaction, (int)Index, sigHash, coin.TxOut.Value, coin.GetHashVersion());
		}

	}
	public class TxInList : UnsignedList<TxIn>
	{
		public TxInList()
		{

		}
		public TxInList(Transaction parent)
			: base(parent)
		{

		}
		public TxIn this[OutPoint outpoint]
		{
			get
			{
				return this[outpoint.N];
			}
			set
			{
				this[outpoint.N] = value;
			}
		}

		public IEnumerable<IndexedTxIn> AsIndexedInputs()
		{
			// We want i as the index of txIn in Intputs[], not index in enumerable after where filter
			return this.Select((r, i) => new IndexedTxIn()
			{
				TxIn = r,
				Index = (uint)i,
				Transaction = Transaction
			});
		}
	}

	public class IndexedTxOut
	{
		public TxOut TxOut
		{
			get;
			set;
		}
		public uint N
		{
			get;
			set;
		}

		public Transaction Transaction
		{
			get;
			set;
		}
		public Coin ToCoin()
		{
			return new Coin(this);
		}
	}

	public class TxOutList : UnsignedList<TxOut>
	{
		public TxOutList()
		{

		}
		public TxOutList(Transaction parent)
			: base(parent)
		{

		}
		public IEnumerable<TxOut> To(IDestination destination)
		{
			return this.Where(r => r.IsTo(destination));
		}
		public IEnumerable<TxOut> To(Script scriptPubKey)
		{
			return this.Where(r => r.ScriptPubKey == scriptPubKey);
		}

		public IEnumerable<IndexedTxOut> AsIndexedOutputs()
		{
			// We want i as the index of txOut in Outputs[], not index in enumerable after where filter
			return this.Select((r, i) => new IndexedTxOut()
			{
				TxOut = r,
				N = (uint)i,
				Transaction = Transaction
			});
		}

		public IEnumerable<Coin> AsCoins()
		{
			var txId = Transaction.GetHash();
			for(int i = 0; i < Count; i++)
			{
				yield return new Coin(new OutPoint(txId, i), this[i]);
			}
		}
	}

	public enum RawFormat
	{
		Satoshi,
		BlockExplorer,
	}

	public class WitScript
	{
		byte[][] _Pushes;
		public WitScript(string script)
		{
			var parts = script.Split(new[] { '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries);
			_Pushes = new byte[parts.Length][];
			for(int i = 0; i < parts.Length; i++)
			{
				_Pushes[i] = Encoders.Hex.DecodeData(parts[i]);
			}
		}

		/// <summary>
		/// Create a new WitnessScript
		/// </summary>
		/// <param name="script">Scripts</param>
		/// <param name="unsafe">If false, make a copy of the input script array</param>
		public WitScript(byte[][] script, bool @unsafe = false)
		{
			if(@unsafe)
				_Pushes = script;
			else
			{
				_Pushes = script.ToArray();
				for(int i = 0; i < _Pushes.Length; i++)
					_Pushes[i] = script[i].ToArray();
			}
		}

		/// <summary>
		/// Create a new WitnessScript
		/// </summary>
		/// <param name="script">Scripts</param>
		public WitScript(IEnumerable<byte[]> script, bool @unsafe = false)
			: this(script.ToArray(), @unsafe)
		{

		}

		public WitScript(params Op[] ops)
		{
			List<byte[]> pushes = new List<byte[]>();
			foreach(var op in ops)
			{
				if(op.PushData == null)
					throw new ArgumentException("Non push operation unsupported in WitScript", "ops");
				pushes.Add(op.PushData);
			}
			_Pushes = pushes.ToArray();
		}

		public WitScript(byte[] script)
		{
			if(script == null)
				throw new ArgumentNullException("script");
			var ms = new MemoryStream(script);
			BitcoinStream stream = new BitcoinStream(ms, false);
			ReadCore(stream);
		}
		WitScript()
		{

		}

		public WitScript(Script scriptSig)
		{
			List<byte[]> pushes = new List<byte[]>();
			foreach(var op in scriptSig.ToOps())
			{
				if(op.PushData == null)
					throw new ArgumentException("A WitScript can only contains push operations", "script");
				pushes.Add(op.PushData);
			}
			_Pushes = pushes.ToArray();
		}

		public static WitScript Load(BitcoinStream stream)
		{
			WitScript script = new WitScript();
			script.ReadCore(stream);
			return script;
		}
		void ReadCore(BitcoinStream stream)
		{
			List<byte[]> pushes = new List<byte[]>();
			uint pushCount = 0;
			stream.ReadWriteAsVarInt(ref pushCount);
			for(int i = 0; i < (int)pushCount; i++)
			{
				byte[] push = ReadPush(stream);
				pushes.Add(push);
			}
			_Pushes = pushes.ToArray();
		}
		private static byte[] ReadPush(BitcoinStream stream)
		{
			byte[] push = null;
			stream.ReadWriteAsVarString(ref push);
			return push;
		}

		public byte[] this[int index]
		{
			get
			{
				return _Pushes[index];
			}
		}

		public IEnumerable<byte[]> Pushes
		{
			get
			{
				return _Pushes;
			}
		}

		static WitScript _Empty = new WitScript(new byte[0][], true);

		public static WitScript Empty
		{
			get
			{
				return _Empty;
			}
		}

		public override bool Equals(object obj)
		{
			WitScript item = obj as WitScript;
			if(item == null)
				return false;
			return EqualsCore(item);
		}

		private bool EqualsCore(WitScript item)
		{
			if(_Pushes.Length != item._Pushes.Length)
				return false;
			for(int i = 0; i < _Pushes.Length; i++)
			{
				if(!Utils.ArrayEqual(_Pushes[i], item._Pushes[i]))
					return false;
			}
			return true;
		}
		public static bool operator ==(WitScript a, WitScript b)
		{
			if(System.Object.ReferenceEquals(a, b))
				return true;
			if(((object)a == null) || ((object)b == null))
				return false;
			return a.EqualsCore(b);
		}

		public static bool operator !=(WitScript a, WitScript b)
		{
			return !(a == b);
		}
		public static WitScript operator +(WitScript a, WitScript b)
		{
			if(a == null)
				return b;
			if(b == null)
				return a;
			return new WitScript(a._Pushes.Concat(b._Pushes).ToArray());
		}
		public static implicit operator Script(WitScript witScript)
		{
			if(witScript == null)
				return null;
			return witScript.ToScript();
		}
		public override int GetHashCode()
		{
			return Utils.GetHashCode(ToBytes());
		}

		public byte[] ToBytes()
		{
			var ms = new MemoryStream();
			BitcoinStream stream = new BitcoinStream(ms, true);
			uint pushCount = (uint)_Pushes.Length;
			stream.ReadWriteAsVarInt(ref pushCount);
			foreach(var push in Pushes)
			{
				var localpush = push;
				stream.ReadWriteAsVarString(ref localpush);
			}
			return ms.ToArrayEfficient();
		}

		public override string ToString()
		{
			return ToScript().ToString();
		}

		public Script ToScript()
		{
			return new Script(_Pushes.Select(p => Op.GetPushOp(p)).ToArray());
		}

		public int PushCount
		{
			get
			{
				return _Pushes.Length;
			}
		}

		public byte[] GetUnsafePush(int i)
		{
			return _Pushes[i];
		}

		public WitScript Clone()
		{
			return new WitScript(ToBytes());
		}
	}

	[Flags]
	public enum TransactionOptions : uint
	{
		None = 0x00000000,
		Witness = 0x40000000,
		All = Witness
	}
	class Witness
	{
		TxInList _Inputs;
		public Witness(TxInList inputs)
		{
			_Inputs = inputs;
		}

		internal bool IsNull()
		{
			return _Inputs.All(i => i.WitScript.PushCount == 0);
		}

		internal void ReadWrite(BitcoinStream stream)
		{
			for(int i = 0; i < _Inputs.Count; i++)
			{
				if(stream.Serializing)
				{
					var bytes = (_Inputs[i].WitScript ?? WitScript.Empty).ToBytes();
					stream.ReadWrite(ref bytes);
				}
				else
				{
					_Inputs[i].WitScript = WitScript.Load(stream);
				}
			}

			if(IsNull())
				throw new FormatException("Superfluous witness record");
		}
	}

	//https://en.bitcoin.it/wiki/Transactions
	//https://en.bitcoin.it/wiki/Protocol_specification
	public class Transaction : IBitcoinSerializable
	{
		public bool RBF
		{
			get
			{
				return Inputs.Any(i => i.Sequence < 0xffffffff - 1);
			}
		}

		uint nVersion = 1;

		public uint Version
		{
			get
			{
				return nVersion;
			}
			set
			{
				nVersion = value;
			}
		}
		TxInList vin;
		TxOutList vout;
		LockTime nLockTime;

		public Transaction()
		{
			vin = new TxInList(this);
			vout = new TxOutList(this);
		}

		public Transaction(string hex, ProtocolVersion version = ProtocolVersion.PROTOCOL_VERSION)
			: this()
		{
			this.FromBytes(Encoders.Hex.DecodeData(hex), version);
		}

		public Transaction(byte[] bytes)
			: this()
		{
			this.FromBytes(bytes);
		}

		public Money TotalOut
		{
			get
			{
				return Outputs.Sum(v => v.Value);
			}
		}

		public LockTime LockTime
		{
			get
			{
				return nLockTime;
			}
			set
			{
				nLockTime = value;
			}
		}

		public TxInList Inputs
		{
			get
			{
				return vin;
			}
		}
		public TxOutList Outputs
		{
			get
			{
				return vout;
			}
		}

		//Since it is impossible to serialize a transaction with 0 input without problems during deserialization with wit activated, we fit a flag in the version to workaround it
		const uint NoDummyInput = (1 << 27);

		#region IBitcoinSerializable Members

		public virtual void ReadWrite(BitcoinStream stream)
		{
			var witSupported = (((uint)stream.TransactionOptions & (uint)TransactionOptions.Witness) != 0) &&
								stream.ProtocolVersion >= ProtocolVersion.WITNESS_VERSION;

			byte flags = 0;
			if(!stream.Serializing)
			{
				stream.ReadWrite(ref nVersion);
				/* Try to read the vin. In case the dummy is there, this will be read as an empty vector. */
				stream.ReadWrite<TxInList, TxIn>(ref vin);

				var hasNoDummy = (nVersion & NoDummyInput) != 0 && vin.Count == 0;
				if(hasNoDummy)
					nVersion = nVersion & ~NoDummyInput;

				if(vin.Count == 0 && witSupported && !hasNoDummy)
				{
					/* We read a dummy or an empty vin. */
					stream.ReadWrite(ref flags);
					if(flags != 0)
					{
						/* Assume we read a dummy and a flag. */
						stream.ReadWrite<TxInList, TxIn>(ref vin);
						vin.Transaction = this;
						stream.ReadWrite<TxOutList, TxOut>(ref vout);
						vout.Transaction = this;
					}
					else
					{
						/* Assume read a transaction without output. */
						vout = new TxOutList();
						vout.Transaction = this;
					}
				}
				else
				{
					/* We read a non-empty vin. Assume a normal vout follows. */
					stream.ReadWrite<TxOutList, TxOut>(ref vout);
					vout.Transaction = this;
				}
				if(((flags & 1) != 0) && witSupported)
				{
					/* The witness flag is present, and we support witnesses. */
					flags ^= 1;
					Witness wit = new Witness(Inputs);
					wit.ReadWrite(stream);
				}
				if(flags != 0)
				{
					/* Unknown flag in the serialization */
					throw new FormatException("Unknown transaction optional data");
				}
			}
			else
			{
				var version = vin.Count == 0 && vout.Count > 0 ? nVersion | NoDummyInput : nVersion;
				stream.ReadWrite(ref version);

				if(witSupported)
				{
					/* Check whether witnesses need to be serialized. */
					if(HasWitness)
					{
						flags |= 1;
					}
				}
				if(flags != 0)
				{
					/* Use extended format in case witnesses are to be serialized. */
					TxInList vinDummy = new TxInList();
					stream.ReadWrite<TxInList, TxIn>(ref vinDummy);
					stream.ReadWrite(ref flags);
				}
				stream.ReadWrite<TxInList, TxIn>(ref vin);
				vin.Transaction = this;
				stream.ReadWrite<TxOutList, TxOut>(ref vout);
				vout.Transaction = this;
				if((flags & 1) != 0)
				{
					Witness wit = new Witness(this.Inputs);
					wit.ReadWrite(stream);
				}
			}
			stream.ReadWriteStruct(ref nLockTime);
		}

		#endregion

		public uint256 GetHash()
		{
			MemoryStream ms = new MemoryStream();
			this.ReadWrite(new BitcoinStream(ms, true)
			{
				TransactionOptions = TransactionOptions.None
			});
			return Hashes.Hash256(ms.ToArrayEfficient());
		}
		public uint256 GetWitHash()
		{
			MemoryStream ms = new MemoryStream();
			this.ReadWrite(new BitcoinStream(ms, true)
			{
				TransactionOptions = TransactionOptions.Witness
			});
			return Hashes.Hash256(ms.ToArrayEfficient());
		}
		public uint256 GetSignatureHash(ICoin coin, SigHash sigHash = SigHash.All)
		{
			return Inputs.AsIndexedInputs().ToArray()[GetIndex(coin)].GetSignatureHash(coin, sigHash);
		}
		public TransactionSignature SignInput(ISecret secret, ICoin coin, SigHash sigHash = SigHash.All)
		{
			return SignInput(secret.PrivateKey, coin, sigHash);
		}
		public TransactionSignature SignInput(Key key, ICoin coin, SigHash sigHash = SigHash.All)
		{
			return Inputs.AsIndexedInputs().ToArray()[GetIndex(coin)].Sign(key, coin, sigHash);
		}

		private int GetIndex(ICoin coin)
		{
			for(int i = 0; i < Inputs.Count; i++)
			{
				if(Inputs[i].PrevOut == coin.Outpoint)
					return i;
			}
			throw new ArgumentException("The coin is not being spent by this transaction", "coin");
		}

		public bool IsCoinBase
		{
			get
			{
				return (Inputs.Count == 1 && Inputs[0].PrevOut.IsNull);
			}
		}

		public static uint CURRENT_VERSION = 2;
		public static uint MAX_STANDARD_TX_SIZE = 100000;

		public TxOut AddOutput(Money money, IDestination destination)
		{
			return AddOutput(new TxOut(money, destination));
		}
		public TxOut AddOutput(Money money, Script scriptPubKey)
		{
			return AddOutput(new TxOut(money, scriptPubKey));
		}
		public TxOut AddOutput(TxOut @out)
		{
			this.vout.Add(@out);
			return @out;
		}
		public TxIn AddInput(TxIn @in)
		{
			this.vin.Add(@in);
			return @in;
		}

		public TxIn AddInput(Transaction prevTx, int outIndex)
		{
			if(outIndex >= prevTx.Outputs.Count)
				throw new InvalidOperationException("Output " + outIndex + " is not present in the prevTx");
			var @in = new TxIn();
			@in.PrevOut.Hash = prevTx.GetHash();
			@in.PrevOut.N = (uint)outIndex;
			AddInput(@in);
			return @in;
		}

		/// <summary>
		/// Sign a specific coin with the given secret
		/// </summary>
		/// <param name="secrets">Secrets</param>
		/// <param name="coins">Coins to sign</param>
		public void Sign(ISecret[] secrets, params ICoin[] coins)
		{
			Sign(secrets.Select(s => s.PrivateKey).ToArray(), coins);
		}

		/// <summary>
		/// Sign a specific coin with the given secret
		/// </summary>
		/// <param name="key">Private keys</param>
		/// <param name="coins">Coins to sign</param>
		public void Sign(Key[] keys, params ICoin[] coins)
		{
			TransactionBuilder builder = new TransactionBuilder();
			builder.AddKeys(keys);
			builder.AddCoins(coins);
			builder.SignTransactionInPlace(this);
		}
		/// <summary>
		/// Sign a specific coin with the given secret
		/// </summary>
		/// <param name="secret">Secret</param>
		/// <param name="coins">Coins to sign</param>
		public void Sign(ISecret secret, params ICoin[] coins)
		{
			Sign(new[] { secret }, coins);
		}

		/// <summary>
		/// Sign a specific coin with the given secret
		/// </summary>
		/// <param name="key">Private key</param>
		/// <param name="coins">Coins to sign</param>
		public void Sign(Key key, params ICoin[] coins)
		{
			Sign(new[] { key }, coins);
		}

		/// <summary>
		/// Sign the transaction with a private key
		/// <para>ScriptSigs should be filled with previous ScriptPubKeys</para>
		/// <para>For more complex scenario, use TransactionBuilder</para>
		/// </summary>
		/// <param name="secret"></param>
		public void Sign(ISecret secret, bool assumeP2SH)
		{
			Sign(secret.PrivateKey, assumeP2SH);
		}

		/// <summary>
		/// Sign the transaction with a private key
		/// <para>ScriptSigs should be filled with either previous scriptPubKeys or redeem script (for P2SH)</para>
		/// <para>For more complex scenario, use TransactionBuilder</para>
		/// </summary>
		/// <param name="secret"></param>
		public void Sign(Key key, bool assumeP2SH)
		{
			List<Coin> coins = new List<Coin>();
			for(int i = 0; i < Inputs.Count; i++)
			{
				var txin = Inputs[i];
				if(Script.IsNullOrEmpty(txin.ScriptSig))
					throw new InvalidOperationException("ScriptSigs should be filled with either previous scriptPubKeys or redeem script (for P2SH)");
				if(assumeP2SH)
				{
					var p2shSig = PayToScriptHashTemplate.Instance.ExtractScriptSigParameters(txin.ScriptSig);
					if(p2shSig == null)
					{
						coins.Add(new ScriptCoin(txin.PrevOut, new TxOut()
						{
							ScriptPubKey = txin.ScriptSig.PaymentScript,
						}, txin.ScriptSig));
					}
					else
					{
						coins.Add(new ScriptCoin(txin.PrevOut, new TxOut()
						{
							ScriptPubKey = p2shSig.RedeemScript.PaymentScript
						}, p2shSig.RedeemScript));
					}
				}
				else
				{
					coins.Add(new Coin(txin.PrevOut, new TxOut()
					{
						ScriptPubKey = txin.ScriptSig
					}));
				}

			}
			Sign(key, coins.ToArray());
		}

		public TxPayload CreatePayload()
		{
			return new TxPayload(this.Clone());
		}

		public static Transaction Parse(string tx, RawFormat format, Network network = null)
		{
			return GetFormatter(format, network).ParseJson(tx);
		}

		public static Transaction Parse(string hex)
		{
			return new Transaction(Encoders.Hex.DecodeData(hex));
		}

		public string ToHex()
		{
			return Encoders.Hex.EncodeData(this.ToBytes());
		}

		public override string ToString()
		{
			return ToString(RawFormat.BlockExplorer);
		}

		public string ToString(RawFormat rawFormat, Network network = null)
		{
			var formatter = GetFormatter(rawFormat, network);
			return ToString(formatter);
		}

		static private RawFormatter GetFormatter(RawFormat rawFormat, Network network)
		{
			RawFormatter formatter = null;
			switch(rawFormat)
			{
				case RawFormat.Satoshi:
					formatter = new SatoshiFormatter();
					break;
				case RawFormat.BlockExplorer:
					formatter = new BlockExplorerFormatter();
					break;
				default:
					throw new NotSupportedException(rawFormat.ToString());
			}
			formatter.Network = network ?? formatter.Network;
			return formatter;
		}

		internal string ToString(RawFormatter formatter)
		{
			if(formatter == null)
				throw new ArgumentNullException("formatter");
			return formatter.ToString(this);
		}

		/// <summary>
		/// Calculate the fee of the transaction
		/// </summary>
		/// <param name="spentCoins">Coins being spent</param>
		/// <returns>Fee or null if some spent coins are missing or if spentCoins is null</returns>
		public Money GetFee(ICoin[] spentCoins)
		{
			if(IsCoinBase)
				return Money.Zero;
			spentCoins = spentCoins ?? new ICoin[0];

			Money fees = -TotalOut;
			foreach(var input in this.Inputs)
			{
				var coin = spentCoins.FirstOrDefault(s => s.Outpoint == input.PrevOut);
				if(coin == null)
					return null;
				fees += coin.TxOut.Value;
			}
			return fees;
		}

		/// <summary>
		/// Calculate the fee rate of the transaction
		/// </summary>
		/// <param name="spentCoins">Coins being spent</param>
		/// <returns>Fee or null if some spent coins are missing or if spentCoins is null</returns>
		public FeeRate GetFeeRate(ICoin[] spentCoins)
		{
			var fee = GetFee(spentCoins);
			if(fee == null)
				return null;
			return new FeeRate(fee, this.GetSerializedSize());
		}

		public bool IsFinal(ChainedBlock block)
		{
			if(block == null)
				return IsFinal(Utils.UnixTimeToDateTime(0), 0);
			return IsFinal(block.Header.BlockTime, block.Height);
		}
		public bool IsFinal(DateTimeOffset blockTime, int blockHeight)
		{
			var nBlockTime = Utils.DateTimeToUnixTime(blockTime);
			if(nLockTime == 0)
				return true;
			if((long)nLockTime < ((long)nLockTime < LockTime.LOCKTIME_THRESHOLD ? (long)blockHeight : nBlockTime))
				return true;
			foreach(var txin in Inputs)
				if(!txin.IsFinal)
					return false;
			return true;
		}

		[Flags]
		public enum LockTimeFlags : int
		{
			None = 0,
			/// <summary>
			/// Interpret sequence numbers as relative lock-time constraints.
			/// </summary>
			VerifySequence = (1 << 0),

			/// <summary>
			///  Use GetMedianTimePast() instead of nTime for end point timestamp.
			/// </summary>
			MedianTimePast = (1 << 1),
		}

		/// <summary>
		/// Calculates the block height and time which the transaction must be later than
		/// in order to be considered final in the context of BIP 68.  It also removes
		/// from the vector of input heights any entries which did not correspond to sequence
		/// locked inputs as they do not affect the calculation.
		/// </summary>
		/// <param name="prevHeights">Previous Height</param>
		/// <param name="block">The block being evaluated</param>
		/// <param name="flags">If VerifySequence is not set, returns always true SequenceLock</param>
		/// <returns>Sequence lock of minimum SequenceLock to satisfy</returns>
		public bool CheckSequenceLocks(int[] prevHeights, ChainedBlock block, LockTimeFlags flags = LockTimeFlags.VerifySequence)
		{
			return CalculateSequenceLocks(prevHeights, block, flags).Evaluate(block);
		}

		/// <summary>
		/// Calculates the block height and time which the transaction must be later than
		/// in order to be considered final in the context of BIP 68.  It also removes
		/// from the vector of input heights any entries which did not correspond to sequence
		/// locked inputs as they do not affect the calculation.
		/// </summary>
		/// <param name="prevHeights">Previous Height</param>
		/// <param name="block">The block being evaluated</param>
		/// <param name="flags">If VerifySequence is not set, returns always true SequenceLock</param>
		/// <returns>Sequence lock of minimum SequenceLock to satisfy</returns>
		public SequenceLock CalculateSequenceLocks(int[] prevHeights, ChainedBlock block, LockTimeFlags flags = LockTimeFlags.VerifySequence)
		{
			if(prevHeights.Length != Inputs.Count)
				throw new ArgumentException("The number of element in prevHeights should be equal to the number of inputs", "prevHeights");

			// Will be set to the equivalent height- and time-based nLockTime
			// values that would be necessary to satisfy all relative lock-
			// time constraints given our view of block chain history.
			// The semantics of nLockTime are the last invalid height/time, so
			// use -1 to have the effect of any height or time being valid.
			int nMinHeight = -1;
			long nMinTime = -1;

			// tx.nVersion is signed integer so requires cast to unsigned otherwise
			// we would be doing a signed comparison and half the range of nVersion
			// wouldn't support BIP 68.
			bool fEnforceBIP68 = Version >= 2
							  && (flags & LockTimeFlags.VerifySequence) != 0;

			// Do not enforce sequence numbers as a relative lock time
			// unless we have been instructed to
			if(!fEnforceBIP68)
			{
				return new SequenceLock(nMinHeight, nMinTime);
			}

			for(var txinIndex = 0; txinIndex < Inputs.Count; txinIndex++)
			{
				TxIn txin = Inputs[txinIndex];

				// Sequence numbers with the most significant bit set are not
				// treated as relative lock-times, nor are they given any
				// consensus-enforced meaning at this point.
				if((txin.Sequence & Sequence.SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
				{
					// The height of this input is not relevant for sequence locks
					prevHeights[txinIndex] = 0;
					continue;
				}

				int nCoinHeight = prevHeights[txinIndex];

				if((txin.Sequence & Sequence.SEQUENCE_LOCKTIME_TYPE_FLAG) != 0)
				{
					long nCoinTime = (long)Utils.DateTimeToUnixTimeLong(block.GetAncestor(Math.Max(nCoinHeight - 1, 0)).GetMedianTimePast());

					// Time-based relative lock-times are measured from the
					// smallest allowed timestamp of the block containing the
					// txout being spent, which is the median time past of the
					// block prior.
					nMinTime = Math.Max(nMinTime, nCoinTime + (long)((txin.Sequence & Sequence.SEQUENCE_LOCKTIME_MASK) << Sequence.SEQUENCE_LOCKTIME_GRANULARITY) - 1);
				}
				else
				{
					// We subtract 1 from relative lock-times because a lock-
					// time of 0 has the semantics of "same block," so a lock-
					// time of 1 should mean "next block," but nLockTime has
					// the semantics of "last invalid block height."
					nMinHeight = Math.Max(nMinHeight, nCoinHeight + (int)(txin.Sequence & Sequence.SEQUENCE_LOCKTIME_MASK) - 1);
				}
			}

			return new SequenceLock(nMinHeight, nMinTime);
		}

		private DateTimeOffset Max(DateTimeOffset a, DateTimeOffset b)
		{
			return a > b ? a : b;
		}

		/// <summary>
		/// Create a transaction with the specified option only. (useful for stripping data from a transaction)
		/// </summary>
		/// <param name="options">Options to keep</param>
		/// <returns>A new transaction with only the options wanted</returns>
		public Transaction WithOptions(TransactionOptions options)
		{
			var instance = new Transaction();
			var ms = new MemoryStream();
			var bms = new BitcoinStream(ms, true);
			bms.TransactionOptions = options;
			this.ReadWrite(bms);
			ms.Position = 0;
			bms = new BitcoinStream(ms, false);
			bms.TransactionOptions = options;
			instance.ReadWrite(bms);
			return instance;
		}

		public bool HasWitness
		{
			get
			{
				return Inputs.Any(i => i.WitScript != WitScript.Empty && i.WitScript != null);
			}
		}
	}
}


text:
Pentaho Cassandra Plugin
=======================

The Pentaho Cassandra Plugin Project provides support for the Cassandra database. It is a plugin for the Pentaho Kettle engine which can be used within Pentaho Data Integration (Kettle), Pentaho Reporting, and the Pentaho BI Platform.

Building
--------
The Pentaho Cassandra Plugin is built with Apache Ant and uses Apache Ivy for dependency management. All you'll need to get started is Ant 1.7.0 or newer to build the project. The build scripts will download Ivy if you do not already have it installed.

    $ git clone git://github.com/pentaho/pentaho-cassandra-plugin.git
    $ cd big-data-plugin
    $ ant

This will produce a plugin archive in dist/pentaho-cassandra-plugin-${project.revision}.tar.gz (and .zip). This archive can then be extracted into your Pentaho Data Integration plugin directory.

Further Reading
---------------
Additional documentation is available on the Community wiki: [Big Data Plugin for Java Developers](http://wiki.pentaho.com/display/BAD/Getting+Started+for+Java+Developers)

License
-------
Licensed under the Apache License, Version 2.0. See LICENSE.txt for more information.


text:
tinyMCE.addToLang('table',{
general_tab : 'General',
advanced_tab : 'Advanced',
general_props : 'General properties',
advanced_props : 'Advanced properties',
desc : 'Inserts a new table',
row_before_desc : 'Insert row before',
row_after_desc : 'Insert row after',
delete_row_desc : 'Delete row',
col_before_desc : 'Insert column before',
col_after_desc : 'Insert column after',
delete_col_desc : 'Remove column',
rowtype : 'Row in table part',
title : 'Insert/Modify table',
width : 'Width',
height : 'Height',
cols : 'Columns',
rows : 'Rows',
cellspacing : 'Cellspacing',
cellpadding : 'Cellpadding',
border : 'Border',
align : 'Alignment',
align_default : 'Default',
align_left : 'Left',
align_right : 'Right',
align_middle : 'Center',
row_title : 'Table row properties',
cell_title : 'Table cell properties',
cell_type : 'Cell type',
row_desc : 'Table row properties',
cell_desc : 'Table cell properties',
valign : 'Vertical alignment',
align_top : 'Top',
align_bottom : 'Bottom',
props_desc : 'Table properties',
bordercolor : 'Border color',
bgcolor : 'Background color',
merge_cells_title : 'Merge table cells',
split_cells_desc : 'Split table cells',
merge_cells_desc : 'Merge table cells',
cut_row_desc : 'Cut table row',
copy_row_desc : 'Copy table row',
paste_row_before_desc : 'Paste table row before',
paste_row_after_desc : 'Paste table row after',
id : 'Id',
style: 'Style',
langdir : 'Language direction',
langcode : 'Language code',
mime : 'Target MIME type',
ltr : 'Left to right',
rtl : 'Right to left',
bgimage : 'Background image',
summary : 'Summary',
td : "Data",
th : "Header",
cell_cell : 'Update current cell',
cell_row : 'Update all cells in row',
cell_all : 'Update all cells in table',
row_row : 'Update current row',
row_odd : 'Update odd rows in table',
row_even : 'Update even rows in table',
row_all : 'Update all rows in table',
thead : 'Table Head',
tbody : 'Table Body',
tfoot : 'Table Foot',
del : 'Delete table',
scope : 'Scope',
row : 'Row',
col : 'Col',
rowgroup : 'Row Group',
colgroup : 'Col Group',
col_limit : 'You\'ve exceeded the maximum number of columns of {$cols}.',
row_limit : 'You\'ve exceeded the maximum number of rows of {$rows}.',
cell_limit : 'You\'ve exceeded the maximum number of cells of {$cells}.',
missing_scope: 'Are you sure you want to continue without specifying a scope for this table header cell. Without it, it may be difficult for some users with disabilities to understand the content or data displayed of the table.'
});


text:
#include <stdlib.h>
#include <string.h>

#include "system.h"

extern void *mem_alloc(long long size)
{
    void *p = malloc(size);
    if (p == NULL)
        sys_die("OOM: cannot allocate %lld, exiting\n", size);

    return p;
}

extern void *mem_realloc(void *p, long long nsize)
{
    void *res = realloc(p, nsize);
    if (res == NULL) {
        free(p);
        sys_die("OOM: cannot realloc %p nsize=%lld\n", p, nsize);
    }

    return res;
}

extern void mem_free(void *p)
{
    free(p);
}

extern void mem_cpy(void *dest, const void *src, long long size)
{
    memcpy(dest, src, size);
}

extern void mem_set(void *dest, int val, long long size)
{
    memset(dest, val, size);
}

extern int mem_cmp(const void *l, const void *r, long long size)
{
    return memcmp(l, r, size);
}


text:
package asobu.dsl

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import scala.concurrent.Await
import org.specs2.specification.{After, Scope}
import scala.concurrent.duration.Duration

trait WithSystem extends Scope with After {
  implicit val system = ActorSystem()
  implicit val mat = ActorMaterializer()
  def after = Await.result(system.terminate(), Duration.Inf)
}


text:
#include <aws/support/model/DescribeTrustedAdvisorCheckRefreshStatusesResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::Support::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

DescribeTrustedAdvisorCheckRefreshStatusesResult::DescribeTrustedAdvisorCheckRefreshStatusesResult()
{
}

DescribeTrustedAdvisorCheckRefreshStatusesResult::DescribeTrustedAdvisorCheckRefreshStatusesResult(const AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

DescribeTrustedAdvisorCheckRefreshStatusesResult& DescribeTrustedAdvisorCheckRefreshStatusesResult::operator =(const AmazonWebServiceResult<JsonValue>& result)
{
  const JsonValue& jsonValue = result.GetPayload();
  if(jsonValue.ValueExists("statuses"))
  {
    Array<JsonValue> statusesJsonList = jsonValue.GetArray("statuses");
    for(unsigned statusesIndex = 0; statusesIndex < statusesJsonList.GetLength(); ++statusesIndex)
    {
      m_statuses.push_back(statusesJsonList[statusesIndex].AsObject());
    }
  }

  return *this;
}


text: default_app_config = 'cmdbox.api.apps.ApiConfig'


text:
#ifndef CIRCLEFIT_H__
#define CIRCLEFIT_H__

#include "common/types.h"
#include "geometry/Sphere.h"
#include "PlaneFit3D.h"

namespace singleeyefitter {

    template<typename Scalar>
    class CircleOnSphereFitter {

    public:
            CircleOnSphereFitter( const Sphere<Scalar> sphere ) : mSphere(sphere)
            {
                mPlaneFitter = PlaneFitter3D<Scalar>();
            }

            bool fit(const std::vector<Vector3>& points)
            {

                if (!mPlaneFitter.fit(points)) {
                    return false;
                }

                Vector3 normal = mPlaneFitter.getNormal();
                Vector3 planePoint = mPlaneFitter.getPlanePoint();

                // check if the normal points outwards or inwards
                // the plane normal must lie in the same direction as the planepoint from sphere center
                if( (planePoint - mSphere.center).dot(normal) < 0 )
                    normal *= -1.0;

                // calculate circle radius and circle center

                //first calculate the distance from sphere center to plane
                double d = std::abs((mSphere.center - planePoint ).dot(normal) /  normal.norm() );
                // than calculate intersection of normal and plane
                Vector3 circle_center = mSphere.center + d * normal;
                // calculate circle radius  r = sqrt(R^2 - d^2) // R is sphere radius
                double r = sqrt( mSphere.radius*mSphere.radius - d * d);

                mCircle = {circle_center, normal, r};
                return true;

            }

            Scalar calculateResidual(const std::vector<Vector3>& points) const
            {
                return  mPlaneFitter.calculateResidual(points);
            }
            const Circle& getCircle() { return mCircle;};

        private:
            Circle mCircle;
            Sphere<Scalar> mSphere;
            PlaneFitter3D<Scalar> mPlaneFitter;

    };

} // singleeyefitter

#endif /* end of include guard: CIRCLEFIT_H__ */


text:
.. _vSphere API 4.1: ../../vim/version.rst#vimversionversion6

.. _HostDirectoryStoreInfo: ../../vim/host/DirectoryStoreInfo.rst

.. _vim.host.AuthenticationStoreInfo: ../../vim/host/AuthenticationStoreInfo.rst

vim.host.DirectoryStoreInfo
===========================
   `HostDirectoryStoreInfo`_ is a base class for objects that provide information about directory-based authentication stores.
:extends: vim.host.AuthenticationStoreInfo_
:since: `vSphere API 4.1`_

Attributes:


text:
/* tslint:disable no-empty */
import { Injectable } from '@angular/core';

@Injectable()
export class FakePlayerService {
  play() { }
  pause() { }
  playTrackList() { }
  playAlbum() { }
  playAlbumWithID() { }
  playArtistWithID() { }
}


text:
cd $(dirname $0)

ENV_DIR="__venv__"

if [[ ! -d "$ENV_DIR" ]]; then
  virtualenv "$ENV_DIR"
fi

source "$ENV_DIR/bin/activate"

pip install -r requirements.txt

python3 build.py $*


text:
import com.google.inject.AbstractModule;
import components.execution.ExecutionSystemInitialization;

/**
 * Created by daniel on 19.07.16.
 */
public class InitModule extends AbstractModule {
    @Override protected void configure() {
        bind(ExecutionSystemInitialization.class);
        bind(InitialData.class);
        bind(OnStartClass.class).asEagerSingleton();
    }
}


text:
#include <iomanip>

#ifdef __unix__
  #include <cxxabi.h>
#endif

#include "LIEF/MachO/hash.hpp"

#include "LIEF/MachO/Symbol.hpp"
#include "LIEF/MachO/EnumToString.hpp"
#include "MachO/Structures.hpp"

namespace LIEF {
namespace MachO {

Symbol::~Symbol() = default;

Symbol::Symbol() = default;

Symbol& Symbol::operator=(Symbol other) {
  swap(other);
  return *this;
}

Symbol::Symbol(const Symbol& other) :
  LIEF::Symbol{other},
  type_{other.type_},
  numberof_sections_{other.numberof_sections_},
  description_{other.description_},
  origin_{other.origin_}
{}

Symbol::Symbol(const details::nlist_32& cmd) :
  type_{cmd.n_type},
  numberof_sections_{cmd.n_sect},
  description_{static_cast<uint16_t>(cmd.n_desc)},
  origin_{SYMBOL_ORIGINS::SYM_ORIGIN_LC_SYMTAB}
{
  value_ = cmd.n_value;
}

Symbol::Symbol(const details::nlist_64& cmd) :
  type_{cmd.n_type},
  numberof_sections_{cmd.n_sect},
  description_{cmd.n_desc},
  origin_{SYMBOL_ORIGINS::SYM_ORIGIN_LC_SYMTAB}
{
  value_ = cmd.n_value;
}

Symbol::Symbol(CATEGORY cat) :
  category_{cat}
{}

void Symbol::swap(Symbol& other) {
  LIEF::Symbol::swap(other);

  std::swap(type_,              other.type_);
  std::swap(numberof_sections_, other.numberof_sections_);
  std::swap(description_,       other.description_);
  std::swap(binding_info_,      other.binding_info_);
  std::swap(export_info_,       other.export_info_);
  std::swap(origin_,            other.origin_);
}

uint8_t Symbol::type() const {
  return type_;
}

uint8_t  Symbol::numberof_sections() const {
  return numberof_sections_;
}

uint16_t Symbol::description() const {
  return description_;
}

SYMBOL_ORIGINS Symbol::origin() const {
  return origin_;
}

void Symbol::type(uint8_t type) {
  type_ = type;
}

void Symbol::numberof_sections(uint8_t nbsections) {
  numberof_sections_ = nbsections;
}

void Symbol::description(uint16_t desc) {
  description_ = desc;
}

bool Symbol::is_external() const {
  static constexpr size_t N_TYPE = 0x0e;
  return static_cast<N_LIST_TYPES>(type_ & N_TYPE) == N_LIST_TYPES::N_UNDF;
    //(type_ & MACHO_SYMBOL_TYPES::N_EXT) == MACHO_SYMBOL_TYPES::N_EXT;
    //(type_ & MACHO_SYMBOL_TYPES::N_PEXT) == 0;
}

bool Symbol::has_export_info() const {
  return export_info_ != nullptr;
}

const ExportInfo* Symbol::export_info() const {
  return export_info_;
}

ExportInfo* Symbol::export_info() {
  return const_cast<ExportInfo*>(static_cast<const Symbol*>(this)->export_info());
}

bool Symbol::has_binding_info() const {
  return binding_info_ != nullptr;
}

const BindingInfo* Symbol::binding_info() const {
  return binding_info_;
}

BindingInfo* Symbol::binding_info() {
  return const_cast<BindingInfo*>(static_cast<const Symbol*>(this)->binding_info());
}

std::string Symbol::demangled_name() const {
#if defined(__unix__)
  int status;
  const std::string& name = this->name().c_str();
  char* demangled_name = abi::__cxa_demangle(name.c_str(), 0, 0, &status);

  if (status == 0) {
    std::string realname = demangled_name;
    free(demangled_name);
    return realname;
  }
  return name;
#else
  return "";
#endif
}

void Symbol::accept(Visitor& visitor) const {
  visitor.visit(*this);
}

bool Symbol::operator==(const Symbol& rhs) const {
  if (this == &rhs) {
    return true;
  }
  size_t hash_lhs = Hash::hash(*this);
  size_t hash_rhs = Hash::hash(rhs);
  return hash_lhs == hash_rhs;
}

bool Symbol::operator!=(const Symbol& rhs) const {
  return !(*this == rhs);
}

const Symbol& Symbol::indirect_abs() {
  static Symbol abs(CATEGORY::INDIRECT_ABS);
  return abs;
}

const Symbol& Symbol::indirect_local() {
  static Symbol local(CATEGORY::INDIRECT_LOCAL);
  return local;
}

std::ostream& operator<<(std::ostream& os, const Symbol& symbol) {
  std::string type;

  //if ((symbol.type_ & MACHO_SYMBOL_TYPES::N_TYPE) == MACHO_SYMBOL_TYPES::N_TYPE) {
  //  type = to_string(
  //      static_cast<N_LIST_TYPES>(symbol.type_ & MACHO_SYMBOL_TYPES::N_TYPE));
  //} else if((symbol.type_ & MACHO_SYMBOL_TYPES::N_STAB) > 0) {
  //  type = to_string(MACHO_SYMBOL_TYPES::N_STAB);
  //} else if((symbol.type_ & MACHO_SYMBOL_TYPES::N_PEXT) == MACHO_SYMBOL_TYPES::N_PEXT) {
  //  type = to_string(MACHO_SYMBOL_TYPES::N_PEXT);
  //}  else if((symbol.type_ & MACHO_SYMBOL_TYPES::N_EXT) == MACHO_SYMBOL_TYPES::N_EXT) {
  //  type = to_string(MACHO_SYMBOL_TYPES::N_EXT);
  //}

  os << std::hex;
  os << std::left;
  os << std::setw(30) << symbol.name()
     << std::setw(10) << type
     << std::setw(10) << symbol.description()
     << std::setw(20) << symbol.value();
  return os;

}
} // namespace MachO
} // namespace LIEF


text:
require 'rubygems' if RUBY_VERSION < '1.9.0'
require 'sensu-plugin/metric/cli'
require 'redis'

class RedisListLengthMetric < Sensu::Plugin::Metric::CLI::Graphite

  option :host,
    :short => "-h HOST",
    :long => "--host HOST",
    :description => "Redis Host to connect to",
    :default  => '127.0.0.1'

  option :port,
    :short => "-p PORT",
    :long => "--port PORT",
    :description => "Redis Port to connect to",
    :proc => proc {|p| p.to_i },
    :default => 6379

  option :password,
    :short => "-P PASSWORD",
    :long => "--password PASSWORD",
    :description => "Redis Password to connect with"

  option :scheme,
    :description => "Metric naming scheme, text to prepend to metric",
    :short => "-s SCHEME",
    :long => "--scheme SCHEME",
    :default => "#{Socket.gethostname}.redis"

  option :key,
    :short => "-k KEY",
    :long => "--key KEY",
    :description => "Redis list KEY to check",
    :required => true

  def run
    options = {:host => config[:host], :port => config[:port]}
    options[:password] = config[:password] if config[:password]
    redis = Redis.new(options)

    output "#{config[:scheme]}.#{config[:key]}.items", redis.llen(config[:key])
    ok

  end
end


text:
@class DDMathStringTokenizer;
@class DDMathOperatorSet;
@class DDExpression;

@interface DDParser : NSObject

@property (readonly) DDMathOperatorSet *operatorSet;

+ (id)parserWithTokenizer:(DDMathStringTokenizer *)tokenizer error:(NSError **)error;
- (id)initWithTokenizer:(DDMathStringTokenizer *)tokenizer error:(NSError **)error;

+ (id)parserWithString:(NSString *)string error:(NSError **)error;
- (id)initWithString:(NSString *)string error:(NSError **)error;

- (DDExpression *)parsedExpressionWithError:(NSError **)error;
- (DDOperatorAssociativity)associativityForOperatorFunction:(NSString *)function;

@end


text:
package com.example.winged_elite.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class Menu extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);
        Intent mainIntent = new Intent(Menu.this, testPost.class);
        Menu.this.startActivity(mainIntent);
        Menu.this.finish();
    }

}


text:
//		Image.js

module.exports = {
    /**
    Image
    Images collection
        List images
    Image
        Retrieve an image
        Replace properties of an image
        Partially update an image
        Remove an image

        Complete

    **/
    listImages: function (callback) {
        req.is_get(["images"], callback)
    },

    getImage: function (image_id, callback) {
        req.is_get(["images", image_id], callback)
    },

    updateImage: function (image_id, jason, callback) {
        req.is_put(["images", image_id], jason, callback)
    },

    patchImage: function (image_id, jason, callback) {
        req.is_patch(["images", image_id], jason, callback)
    },

    deleteImage: function (image_id, callback) {
        req.is_del(["images", image_id], callback)
    }
}


text:
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import {WelcomeComponent} from './welcome/welcome.component';
import {PageNotFoundComponent} from './error/page-not-found.component';
import { SharedModule } from 'app/shared/shared.module';
import { RoutingModule } from 'app/routing.module';

@NgModule({
  declarations: [
    AppComponent,
    WelcomeComponent,
    PageNotFoundComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    RoutingModule,
    HttpModule,
    SharedModule,
    BrowserAnimationsModule
  ],
  providers: [
    {provide: 'API_URL', useValue: 'http://localhost:5000/api/'}

  ],
  bootstrap: [AppComponent]
})
export class AppModule { }


text:
package com.bitplan.vzjava.resources;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.util.Date;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.apache.commons.lang3.time.DateUtils;

import com.bitplan.vzjava.PowerValuePlotManager;

@SuppressWarnings("rawtypes")
@Path("/plot")
public class PowerPlotResource extends VZResource {
  protected static Logger LOGGER = Logger
      .getLogger("com.bitplan.vzjava.resources");

  /**
   * Power Plot Resource constructor
   */
  public PowerPlotResource() {
    super.prepareRootMap("Plot", "Plot");
  }

  @GET
  @Path("/range/{isoFrom}/{isoTo}/plot")
  @Produces("image/png")
  public Response getPlotFileForRange(
      @HeaderParam("If-Modified-Since") String modified,
      @QueryParam("width") @DefaultValue("1024") int width,
      @QueryParam("height") @DefaultValue("768") int height,
      @QueryParam("channelnos") String channelNos,
      @PathParam("isoFrom") String isoFrom, @PathParam("isoTo") String isoTo)
          throws Exception {
    File pngFile=PowerValuePlotManager.getInstance().getPlot(channelNos,isoFrom, isoTo, width, height);
    Response result = returnFile(pngFile, modified);
    return result;
  }

  @GET
  @Path("/file/{filename}")
  public Response getPlotFileForRange(
      @HeaderParam("If-Modified-Since") String modified,
      @PathParam("filename") String filename)
          throws Exception {
    File pngFile=PowerValuePlotManager.getInstance().getPlotFile(filename);
    Response result = returnFile(pngFile, modified);
    return result;
  }

  @GET
  @Path("/range/{isoFrom}/{isoTo}")
  public Response getPlotForRange(
      @QueryParam("width") @DefaultValue("1024") int width,
      @QueryParam("height") @DefaultValue("768") int height,
      @QueryParam("channelnos") String channelNos,
      @PathParam("isoFrom") String isoFrom, @PathParam("isoTo") String isoTo)
          throws Exception {
    File pngFile=PowerValuePlotManager.getInstance().getPlot(channelNos,isoFrom, isoTo, width, height);
    rootMap.put("isoFrom", isoFrom);
    rootMap.put("isoTo", isoTo);
    rootMap.put("pngFile", pngFile.getName());
    return super.templateResponse("plot.rythm");
  }

  /**
   * http://stackoverflow.com/a/10257341/1497139
   * Sends the file if modified and "not modified" if not modified
   * future work may put each file with a unique id in a separate folder in
   * tomcat
   * * use that static URL for each file
   * * if file is modified, URL of file changes
   * * -> client always fetches correct file
   *
   * method header for calling method public Response
   * getXY(@HeaderParam("If-Modified-Since") String modified) {
   *
   * @param file
   *          to send
   * @param modified
   *          - HeaderField "If-Modified-Since" - may be "null"
   * @return Response to be sent to the client
   */
  public static Response returnFile(File file, String modified) {
    if (!file.exists()) {
      return Response.status(Status.NOT_FOUND).build();
    }

    // do we really need to send the file or can send "not modified"?
    if (modified != null) {
      Date modifiedDate = null;

      // we have to switch the locale to ENGLISH as parseDate parses in the
      // default locale
      Locale old = Locale.getDefault();
      Locale.setDefault(Locale.ENGLISH);
      try {
        modifiedDate = DateUtils.parseDate(modified, DEFAULT_PATTERNS);
      } catch (ParseException e) {
        LOGGER.log(Level.WARNING, e.getMessage());
      }
      Locale.setDefault(old);

      if (modifiedDate != null) {
        // modifiedDate does not carry milliseconds, but fileDate does
        // therefore we have to do a range-based comparison
        // 1000 milliseconds = 1 second
        if (file.lastModified()
            - modifiedDate.getTime() < DateUtils.MILLIS_PER_SECOND) {
          return Response.status(Status.NOT_MODIFIED).build();
        }
      }
    }
    // we really need to send the file

    try {
      Date fileDate = new Date(file.lastModified());
      return Response.ok(new FileInputStream(file)).lastModified(fileDate)
          .build();
    } catch (FileNotFoundException e) {
      return Response.status(Status.NOT_FOUND).build();
    }
  }

  /**
   * Date format pattern used to parse HTTP date headers in RFC 1123 format.
   */
  public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";

  /**
   * Date format pattern used to parse HTTP date headers in RFC 1036 format.
   */
  public static final String PATTERN_RFC1036 = "EEEE, dd-MMM-yy HH:mm:ss zzz";

  /**
   * Date format pattern used to parse HTTP date headers in ANSI C
   * asctime() format.
   */
  public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy";

  public static final String[] DEFAULT_PATTERNS = new String[] {
      PATTERN_RFC1036, PATTERN_RFC1123, PATTERN_ASCTIME };

}


text:
namespace v2 {

template<typename T>
auto clone(const T& object) -> std::unique_ptr<T>
{
    return std::unique_ptr<T>(object.clone());
}

struct Figure
{
    using base_type = Figure;

    virtual ~Figure() = default;
    virtual double  area()  const = 0;

    virtual Figure* clone() const = 0;
};

struct Square : Figure
{
    double a = 0;

    Square() = default;
    Square(double a) : a{a}{}

    double  area()  const override
    {
        return a * a;
    }

    Square* clone() const override     // return type is Square* instead of Figure* (Covariant Return Type)
    {
        return new Square(*this);
    }
};

using namespace ::testing;

TEST(FigureTests_v2, square_clone_method_called_directly_return_pointer_of_type_Square)
{
    auto square = Square{};
    auto figure = clone(square);

    ASSERT_TRUE((std::is_same<std::unique_ptr<Square>, decltype(figure)>::value));
}

TEST(FigureTests_v2, square_clone_method_called_via_base_class_return_pointer_of_type_Figure)
{
    auto  square = Square{};
    auto& square_figure = static_cast<Figure&>(square);
    auto  figure = clone(square_figure);

    ASSERT_TRUE((std::is_same<std::unique_ptr<Figure>, decltype(figure)>::value));
}

TEST(FigureTests_v2, cloned_square_via_base_pointer_should_return_same_area)
{
    auto  a = 4.;
    auto  square = Square{a};
    auto& square_figure = static_cast<Figure&>(square);
    auto  figure = clone(square_figure);

    ASSERT_THAT( square.area(), Eq(a*a));
    ASSERT_THAT(figure->area(), Eq(square.area()));
}

TEST(FigureTests_v2, clonning_rvalue)
{
    auto square = Square{};
    auto figure = clone(Square{});

    ASSERT_TRUE((std::is_same<std::unique_ptr<Square>, decltype(figure)>::value));
}

TEST(FigureTests_v2, clonning_const_figure)
{
    const auto square = Square{};
    auto figure = clone(square);

    ASSERT_TRUE((std::is_same<std::unique_ptr<Square>, decltype(figure)>::value));
}

} // v2 namespace


text:
/*
 * ----------------------------------------
 *           Json Upgrading and
 *        Persistence Architecture
 * ----------------------------------------
 *          Produced by Dan Grew
 *                 2016
 * ----------------------------------------
 */
package uk.dangrew.jupa.json.io;

import java.io.File;

import org.json.JSONException;
import org.json.JSONObject;

import uk.dangrew.sd.logging.io.BasicStringIO;

/**
 * {@link JsonIO} provides basic read and write functionality for files.
 */
public class JsonIO {

   private final BasicStringIO stringIO;
   private final JsonIODigest digest;

   /**
    * Constructs a new {@link JsonIO}.
    */
   public JsonIO() {
      this( new JsonIODigest() );
   }//End Constructor

   /**
    * Constructs a new {@link JsonIO} with the given {@link JsonIODigest}.
    * @param digest the {@link JsonIODigest} to use.
    */
   JsonIO( JsonIODigest digest ) {
      this.stringIO = new BasicStringIO();
      this.digest = digest;
      this.digest.attachSource( this );
   }//End Constructor

   /**
    * Method to read json data from the given {@link File}.
    * @param file the {@link File} to read from.
    * @return the {@link JSONObject} read, or null if anything goes wrong.
    */
   public JSONObject read( File file ) {
      String parsedString = stringIO.read( file );
      if ( parsedString == null ) {
         return null;
      }
      try {
         return new JSONObject( parsedString );
      } catch ( JSONException exception ) {
         digest.failedToParseInput( file );
         return null;
      }
   }//End Method

   /**
    * Method to write the given {@link JSONObject} to the given {@link File}.
    * @param file the {@link File} to write to.
    * @param object the {@link JSONObject} to write.
    * @return true if written successfully.
    */
   public boolean write( File file, JSONObject object ) {
      if ( file == null ) {
         throw new NullPointerException( "File must not be null." );
      }
      String stringToWrite = object.toString( 3 );
      return stringIO.write( file, stringToWrite, false );
   }//End Method

}//End Class