text:
body{
			padding:0;
			margin:0;
			background:#D7DF01;
		}

		#background{
			display: inline-block;
			width:100%;
			height:auto;
			background:url(../img/footer_lodyas.png);
			padding:80px 0;
		}

		.about{
			position: relative;
			display: block;
			width:1050px;
			margin:0 auto;
			height: auto;

		}

		#noticia{
			position: relative;
			width: 250px;
			height: 270px;
			float:left;
			background-color:#fff;
			margin-left:12.5px;
			border-radius:3px;
		}

		.foto{
			position: absolute;
			display:table;
			margin:0 auto;
			bottom:-40px;
			width: 100px;
			height: 100px;
			border-radius: 50%;
			margin-left: auto;
			margin-right: auto;
			left:0;
			-webkit-transition:all 1s ease;
			right:0;
			overflow:hidden;
			-webkit-transition:all 0.1s ease;
			border: 5px solid rgba(255, 255, 255, .7);
		}

		/*perfiles----------------------------------------------------------------------------------------*/
		#alex{
			background: url("http://i00.i.aliimg.com/wsphoto/v0/32237233504_1/2014-new-winter-Casual-woman-octagonal-cap-Woolen-face-lift-visors-Fashion-wild-beret-European-style.jpg_120x120.jpg");
		}

		#frant{
			background: url(http://asiacue.com/images/persons/c/Chiu,%20Man%20Cheuk_face.jpeg);
		}

		#michel{
			background: url(http://d3cdsjlahqfkbd.cloudfront.net/9306/photo_100_1426192669.jpg);
		}

		#andrew{
			background: url(https://yt3.ggpht.com/-yW6fjuwX1QU/AAAAAAAAAAI/AAAAAAAAAAA/aLHLhb4f3go/s100-c-k-no/photo.jpg);
		}

		.foto span{
			position:relative;
			display: table-cell;
			vertical-align: middle;
			text-align: center;
			border-radius: 50%;
			background-color: rgba(0,0,0,0.5);
			-webkit-transform:scale(0);
			-webkit-transition:all 0.1s ease;
		}

		/*mouse hover*/
		.foto:hover span{
			position: relative;
			text-transform: uppercase;
			font:bold 12px verdana;
			border-radius: 50%;
            -webkit-transform:scale(1);
			-webkit-transition:all 0.1s ease;
		}

		/*imagen perfiles*/
		img{
			position:relative;
			display:block;
			margin: 0 auto;
			transition:all .1s ease;
		}

		/*mouse hover imagen perfiles*/
		img:hover{
			transition:all .1s ease;
			transform:translateY(10px);
		}

		/*descripcion perfil*/
		p{
			text-align: center;
			font:14px verdana;
			margin-top:15px;
			color:#998;
			padding: 0 8px;
		}

		/*clase para el nombre*/
		.name{
			position: relative;
			display: inline;
			font:bold 12px sans-serif;
			color:#fff;
			transform:translateY(10px);
			transition:all 1s ease;
			padding-bottom:10px;
		}

		/*ver mas*/
		.more{
			display: inline-block;
			text-decoration: none;
			color:#fff;
			font-size:24px;
		}

		/*transicion y cambio de color ver mas*/
		.more:hover{
			transition:all 1s ease;
			color:red;
		}

	    /*selecionamos con target cada biografía*/
		#bio-alex:target{
			display:block;
			visibility:visible;
			transition:all 1s ease;
			opacity:1;
		}

		#bio-frant:target{
			transition:all 1s ease;
			visibility:visible;
			transition:all 1s ease;
			opacity:1;
		}

		#bio-michel:target{
			display:block;
			visibility:visible;
			transition:all 1s ease;
			opacity:1;
		}

		#bio-andrew:target{
			transition:all 1s ease;
			visibility:visible;
			transition:all 1s ease;
			opacity:1;
		}

		/*agrupamos todos los perfiles*/
		#bio-alex, #bio-frant, #bio-michel, #bio-andrew{
			display:inline-block;
			position: fixed;
			width:100%;
			height:500px;
			visibility: hidden;
			transition:all 1s ease;
			opacity:0;

		}

		.rol{
			position:relative;
			text-align: center;
			margin:10px;
			font:bold 1.2em verdana;
			color: #FE2E2E;
		}

		/*agrupamos la informacion personal*/
		.info{
			position: relative;
			width:100%;
			height:auto;
			background: green;
			margin-top: 0;
		}

		/*nombre*/
		.info-name{
			font:bold 2em calibri;
			color:#fff;
			margin:0;
			margin: 10px 0 0 135px;
		}

		/*informacion personal de los perfiles*/
		.info-text{
			color:#000;
			text-align: left;
			float:left;
			margin-left: 130px;
			width:40%;
		}

		/*imagenes que pueda tener cada perfil	*/
		.info-image{
			position: relative;
			display: block;
			float:left;
			margin-left:40px;
			width:500px;
			height:auto;
		}

		/*iconos relacionados con el manejo de software*/
		.programs{
			display: inline-block;
		}


text:
<?php

namespace Studio\Parts\Composer;

use Studio\Filesystem\Directory;
use Studio\Parts\AbstractPart;

class Part extends AbstractPart
{
    public function setupPackage($composer, Directory $target)
    {
        // Ask for package name
        $composer->name = $this->input->ask(
            'Please name this package',
            '/[[:alnum:]]+\/[[:alnum:]]+/',
            'Please enter a valid package name in the format "vendor/name".'
        );

        // Ask for the root namespace
        $namespace = $this->input->ask(
            'Please provide a default namespace (PSR-4)',
            '/([[:alnum:]]+\\\\?)+/',
            'Please enter a valid PHP namespace',
            $this->makeDefaultNamespace($composer->name)
        );

        // Normalize and store the namespace
        $namespace = str_replace('/', '\\', $namespace);
        $namespace = rtrim($namespace, '\\');
        @$composer->autoload->{'psr-4'}->{"$namespace\\"} = 'src/';

        // Create an example file
        $this->copyTo(
            __DIR__ . '/stubs/src/Example.php',
            $target,
            'src/Example.php',
            function ($content) use ($namespace) {
                return preg_replace('/namespace[^;]+;/', "namespace $namespace;", $content);
            }
        );
    }

    protected function makeDefaultNamespace($package)
    {
        list($vendor, $name) = explode('/', $package);

        return ucfirst($vendor) . '\\' . ucfirst($name);
    }
}

redpajama_set_name: RedPajamaGithub


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

# MOST OF THIS COPIED FROM native_hash_spec !!!!
# Redis::LazyHash should behave pretty much the same as Redis::LazyHash
# only, lazier...

describe Redis::LazyHash do
  before :each do
    @hash = Redis::LazyHash.new :test
    @hash.update("foo" => "bar")
    @hash.save
    @hash = Redis::LazyHash.new :test => @hash.key
  end

  describe "#loaded?" do
    it "should not be loaded when no read/write has occurred" do
      @hash.loaded?.should be_false
    end
    it "should be loaded after a read occurs" do
      @hash[:foo]
      @hash.loaded?.should be_true
    end
  end

  describe "#save" do
    it "should presist changes to existing hash key" do
      @hash["foo"] = "something else"
      @hash.save
      hash = Redis::LazyHash.find :test => @hash.key
      hash["foo"].should == "something else"
    end
    it "should persist new hash keys" do
      @hash["yin"] = "yang"
      @hash.save
      hash = Redis::LazyHash.find :test => @hash.key
      hash["yin"].should == "yang"
    end
    it "should remove deleted keys from redis" do
      @hash["yin"] = "yang"
      @hash.delete("foo")
      @hash["foo"].should == nil
      @hash.save
      hash = Redis::LazyHash.find :test => @hash.key
      hash["foo"].should == nil
    end
    it "should respect changes made since last read from redis" do
      @hash.inspect # have to touch the hash first
      concurrent_edit = Redis::LazyHash.find :test => @hash.key
      concurrent_edit["foo"] = "race value"
      concurrent_edit.save
      @hash["yin"] = "yang"
      @hash["foo"] = "bad value"
      @hash.save
      hash = Redis::LazyHash.find :test => @hash.key
      hash["foo"].should == "race value"
      hash["yin"].should == "yang"
    end
    it "should respect removed hash keys since last read" do
      @hash.inspect
      concurrent_edit = Redis::LazyHash.find :test => @hash.key
      concurrent_edit["yin"] = "yang"
      concurrent_edit.delete("foo")
      concurrent_edit.save
      @hash["foo"] = "bad value"
      @hash.save
      hash = Redis::LazyHash.find :test => @hash.key
      hash["foo"].should == nil
      hash["yin"].should == "yang"
    end
    it "should allow overwrite of concurrent edit after #reload! is called" do
      @hash.inspect
      concurrent_edit = Redis::LazyHash.find :test => @hash.key
      concurrent_edit["yin"] = "yang"
      concurrent_edit.delete("foo")
      concurrent_edit.save
      @hash.reload!
      @hash["foo"].should == nil
      @hash["foo"] = "good value"
      @hash.save
      hash = Redis::LazyHash.find :test => @hash.key
      hash["foo"].should == "good value"
    end
    it "should treat string and symbolic keys the same" do
      @hash[:foo].should == "bar"
      @hash[:test] = "good value"
      @hash["test"].should == "good value"
      @hash.save
      hash = Redis::LazyHash.find :test => @hash.key
      hash[:test].should == "good value"
      hash["test"].should == "good value"
    end
    it "should properly store nested hashes" do
      @hash[:test] = { :foo => :bar, :x => { :y => "z" } }
      @hash[:test][:x][:y].should == "z"
      @hash.save
      hash = Redis::LazyHash.find :test => @hash.key
      hash[:test][:foo].should == :bar
      hash[:test][:x][:y].should == "z"
    end
  end

  describe "#renew" do
    it "should generate a new key" do
      old_key = @hash.key
      new_key = @hash.renew_key
      @hash.key.should eq(new_key)
      @hash.key.should_not eq(old_key)
    end
    it "should remove the old hash from redis" do
      old_key   = @hash.key
      namespace = @hash.namespace
      @hash.renew_key
      hash = Redis::LazyHash.find namespace => old_key
      hash.inspect
      hash.size.should == 0
    end
    it "should not persist the hash under the new key until #save is called" do
      @hash["good key"] = "good value"
      key = @hash.renew_key
      bad_hash = Redis::LazyHash.find :test => key
      bad_hash.size.should == 0
      @hash.save
      good_hash = Redis::LazyHash.find :test => key
      good_hash["good key"].should eq("good value")
      good_hash["foo"].should      eq("bar")
    end
  end

  describe "#key=" do
    it "should allow an arbitrary key to be used" do
      @hash.key = "blah@blah.com"
      @hash.save
      a_hash = Redis::LazyHash.find :test => "blah@blah.com"
      a_hash["foo"].should eq('bar')
    end
    it "should not leave the old hash behind when the key is changed" do
      old_key = @hash.key
      @hash.key = "carl@linkleaf.com"
      @hash.save
      bad_hash = Redis::LazyHash.find :test => old_key
      bad_hash.size.should == 0
    end
  end

  describe ".find" do
    it "should find an existing redis hash" do
      hash = Redis::LazyHash.find :test => @hash.key
      hash["foo"].should == "bar"
    end
    it "should return an empty hash when hash not found" do
      hash = Redis::LazyHash.find :foo => :doesnt_exist
      hash.size.should == 0
    end
  end

  after :each do
    @hash.destroy
  end
end


text:
(function(jiglib) {

  var JIndexedTriangle = jiglib.JIndexedTriangle;
  var JOctree = jiglib.JOctree;
  var JCapsule = jiglib.JCapsule;
  var JRay = jiglib.JRay;
  var JAABox = jiglib.JAABox;
  var JTerrain = jiglib.JTerrain;
  var JPlane = jiglib.JPlane;
  var JTriangleMesh = jiglib.JTriangleMesh;
  var JTriangle = jiglib.JTriangle;
  var JSphere = jiglib.JSphere;
  var JSegment = jiglib.JSegment;
  var RigidBody = jiglib.RigidBody;
  var Matrix3D = jiglib.Matrix3D;
  var Vector3D = jiglib.Vector3D;
  var CollOutData = jiglib.CollOutData;
  var EdgeData = jiglib.EdgeData;
  var SpanData = jiglib.SpanData;
  var JMatrix3D = jiglib.JMatrix3D;
  var JMath3D = jiglib.JMath3D;
  var JNumber3D = jiglib.JNumber3D;
  var PhysicsState = jiglib.PhysicsState;

  var JBox = function(skin, width, depth, height)
  {
    this._sideLengths = null; // Vector3D
    this._points = null; // Vector3D
    this._edges =  [
      new EdgeData( 0, 1 ), new EdgeData( 0, 2 ), new EdgeData( 0, 6 ),
      new EdgeData( 2, 3 ), new EdgeData( 2, 4 ), new EdgeData( 6, 7 ),
      new EdgeData( 6, 4 ), new EdgeData( 1, 3 ), new EdgeData( 1, 7 ),
      new EdgeData( 3, 5 ), new EdgeData( 7, 5 ), new EdgeData( 4, 5 )]; // EdgeData
    this._face =  [
      [[6, 7, 1, 0]], [[5, 4, 2, 3]],
      [[3, 1, 7, 5]], [[4, 6, 0, 2]],
      [[1, 3, 2, 0]], [[7, 6, 4, 5]]]; // Vector.<Vector.<Number>>

    jiglib.RigidBody.apply(this, [ skin ]);
    this._type = "BOX";

    this._sideLengths = new Vector3D(width, height, depth);
    this._boundingSphere = 0.5 * this._sideLengths.get_length();
    this.initPoint();
    this.set_mass(1);
    this.updateBoundingBox();

  }

  jiglib.extend(JBox, RigidBody);

  JBox.prototype.initPoint = function()
  {

    var halfSide = this.getHalfSideLengths();
    this._points = [];
    this._points[0] = new Vector3D(halfSide.x, -halfSide.y, halfSide.z);
    this._points[1] = new Vector3D(halfSide.x, halfSide.y, halfSide.z);
    this._points[2] = new Vector3D(-halfSide.x, -halfSide.y, halfSide.z);
    this._points[3] = new Vector3D(-halfSide.x, halfSide.y, halfSide.z);
    this._points[4] = new Vector3D(-halfSide.x, -halfSide.y, -halfSide.z);
    this._points[5] = new Vector3D(-halfSide.x, halfSide.y, -halfSide.z);
    this._points[6] = new Vector3D(halfSide.x, -halfSide.y, -halfSide.z);
    this._points[7] = new Vector3D(halfSide.x, halfSide.y, -halfSide.z);

  }

  JBox.prototype.set_sideLengths = function(size)
  {

    this._sideLengths = size.clone();
    this._boundingSphere = 0.5 * this._sideLengths.get_length();
    this.initPoint();
    this.setInertia(this.getInertiaProperties(this.get_mass()));
    this.setActive();
    this.updateBoundingBox();

  }

  JBox.prototype.get_sideLengths = function()
  {

    return this._sideLengths;

  }

  JBox.prototype.get_edges = function()
  {

    return this._edges;

  }

  JBox.prototype.getVolume = function()
  {

    return (this._sideLengths.x * this._sideLengths.y * this._sideLengths.z);

  }

  JBox.prototype.getSurfaceArea = function()
  {

    return 2 * (this._sideLengths.x * this._sideLengths.y + this._sideLengths.x * this._sideLengths.z + this._sideLengths.y * this._sideLengths.z);

  }

  JBox.prototype.getHalfSideLengths = function()
  {

    return JNumber3D.getScaleVector(this._sideLengths, 0.5);

  }

  JBox.prototype.getSpan = function(axis)
  {

    var s, u, d, r, p;
    var cols = this.get_currentState().getOrientationCols();
    var obj = new SpanData();
    s = Math.abs(axis.dotProduct(cols[0])) * (0.5 * this._sideLengths.x);
    u = Math.abs(axis.dotProduct(cols[1])) * (0.5 * this._sideLengths.y);
    d = Math.abs(axis.dotProduct(cols[2])) * (0.5 * this._sideLengths.z);
    r = s + u + d;
    p = this.get_currentState().position.dotProduct(axis);
    obj.min = p - r;
    obj.max = p + r;

    return obj;

  }

  JBox.prototype.getCornerPoints = function(state)
  {

    var _points_length = this._points.length;
    var arr = [];

    var transform = JMatrix3D.getTranslationMatrix(state.position.x, state.position.y, state.position.z);
    transform = JMatrix3D.getAppendMatrix3D(state.orientation, transform);

    var i=0;
    for (var _points_i = 0, _points_l = this._points.length, _point; (_points_i < _points_l) && (_point = this._points[_points_i]); _points_i++){
      arr[i++] = transform.transformVector(_point);
    }

    return arr;

  }

  JBox.prototype.getCornerPointsInBoxSpace = function(thisState, boxState)
  {

    var max, orient, transform;

    max = JMatrix3D.getTransposeMatrix(boxState.orientation);
    var pos = thisState.position.subtract(boxState.position);
    pos = max.transformVector(pos);

    orient = JMatrix3D.getAppendMatrix3D(thisState.orientation, max);

    var arr = [];

    transform = JMatrix3D.getTranslationMatrix(pos.x, pos.y, pos.z);
    transform = JMatrix3D.getAppendMatrix3D(orient, transform);

    var i = 0;
    for (var _points_i = 0, _points_l = this._points.length, _point; (_points_i < _points_l) && (_point = this._points[_points_i]); _points_i++)
      arr[i++] = transform.transformVector(_point);

    return arr;

  }

  JBox.prototype.getSqDistanceToPoint = function(state, closestBoxPoint, point)
  {

    var _closestBoxPoint, halfSideLengths;
    var delta=0, sqDistance=0;

    _closestBoxPoint = point.subtract(state.position);
    _closestBoxPoint = JMatrix3D.getTransposeMatrix(state.orientation).transformVector(_closestBoxPoint);

    halfSideLengths = this.getHalfSideLengths();

    if (_closestBoxPoint.x < -halfSideLengths.x)
    {
      delta = _closestBoxPoint.x + halfSideLengths.x;
      sqDistance += (delta * delta);
      _closestBoxPoint.x = -halfSideLengths.x;
    }
    else if (_closestBoxPoint.x > halfSideLengths.x)
    {
      delta = _closestBoxPoint.x - halfSideLengths.x;
      sqDistance += (delta * delta);
      _closestBoxPoint.x = halfSideLengths.x;
    }

    if (_closestBoxPoint.y < -halfSideLengths.y)
    {
      delta = _closestBoxPoint.y + halfSideLengths.y;
      sqDistance += (delta * delta);
      _closestBoxPoint.y = -halfSideLengths.y;
    }
    else if (_closestBoxPoint.y > halfSideLengths.y)
    {
      delta = _closestBoxPoint.y - halfSideLengths.y;
      sqDistance += (delta * delta);
      _closestBoxPoint.y = halfSideLengths.y;
    }

    if (_closestBoxPoint.z < -halfSideLengths.z)
    {
      delta = _closestBoxPoint.z + halfSideLengths.z;
      sqDistance += (delta * delta);
      _closestBoxPoint.z = -halfSideLengths.z;
    }
    else if (_closestBoxPoint.z > halfSideLengths.z)
    {
      delta = (_closestBoxPoint.z - halfSideLengths.z);
      sqDistance += (delta * delta);
      _closestBoxPoint.z = halfSideLengths.z;
    }
    _closestBoxPoint = state.orientation.transformVector(_closestBoxPoint);
    closestBoxPoint[0] = state.position.add(_closestBoxPoint);
    return sqDistance;

  }

  JBox.prototype.getDistanceToPoint = function(state, closestBoxPoint, point)
  {

    return Math.sqrt(this.getSqDistanceToPoint(state, closestBoxPoint, point));

  }

  JBox.prototype.pointIntersect = function(pos)
  {

    var p, h, dirVec;

    p = pos.subtract(this.get_currentState().position);
    h = JNumber3D.getScaleVector(this._sideLengths, 0.5);

    var cols = this.get_currentState().getOrientationCols();
    for (var dir; dir < 3; dir++)
    {
      dirVec = cols[dir].clone();
      dirVec.normalize();
      if (Math.abs(dirVec.dotProduct(p)) > JNumber3D.toArray(h)[dir] + JMath3D.NUM_TINY)
      {
        return false;
      }
    }
    return true;

  }

  JBox.prototype.segmentIntersect = function(out, seg, state)
  {

    out.frac = 0;
    out.position = new Vector3D();
    out.normal = new Vector3D();

    var tiny=JMath3D.NUM_TINY, huge=JMath3D.NUM_HUGE, frac, min, max, dirMin=0, dirMax=0, dir=0, e, f, t, t1, t2, directionVectorNumber;
    var p, h;

    frac = huge;
    min = -huge;
    max = huge;
    p = state.position.subtract(seg.origin);
    h = JNumber3D.getScaleVector(this._sideLengths, 0.5);

    var orientationCol = state.getOrientationCols();
    var directionVectorArray = JNumber3D.toArray(h);
    for (dir = 0; dir < 3; dir++)
    {
      directionVectorNumber = directionVectorArray[dir];
      e = orientationCol[dir].dotProduct(p);
      f = orientationCol[dir].dotProduct(seg.delta);
      if (Math.abs(f) > tiny)
      {
        t1 = (e + directionVectorNumber) / f;
        t2 = (e - directionVectorNumber) / f;
        if (t1 > t2)
        {
        t = t1;
        t1 = t2;
        t2 = t;
        }
        if (t1 > min)
        {
        min = t1;
        dirMin = dir;
        }
        if (t2 < max)
        {
        max = t2;
        dirMax = dir;
        }
        if (min > max)
        return false;
        if (max < 0)
        return false;
      }
      else if (-e - directionVectorNumber > 0 || -e + directionVectorNumber < 0)
      {
        return false;
      }
    }

    if (min > 0)
    {
      dir = dirMin;
      frac = min;
    }
    else
    {
      dir = dirMax;
      frac = max;
    }
    if (frac < 0)
      frac = 0;
    /*if (frac > 1)
      frac = 1;*/
    if (frac > 1 - tiny)
    {
      return false;
    }
    out.frac = frac;
    out.position = seg.getPoint(frac);
    if (orientationCol[dir].dotProduct(seg.delta) < 0)
    {
      out.normal = JNumber3D.getScaleVector(orientationCol[dir], -1);
    }
    else
    {
      out.normal = orientationCol[dir];
    }
    return true;

  }

  JBox.prototype.getInertiaProperties = function(m)
  {

    return JMatrix3D.getScaleMatrix(
    (m / 12) * (this._sideLengths.y * this._sideLengths.y + this._sideLengths.z * this._sideLengths.z),
    (m / 12) * (this._sideLengths.x * this._sideLengths.x + this._sideLengths.z * this._sideLengths.z),
    (m / 12) * (this._sideLengths.x * this._sideLengths.x + this._sideLengths.y * this._sideLengths.y))

  }

  JBox.prototype.updateBoundingBox = function()
  {

    this._boundingBox.clear();
    this._boundingBox.addBox(this);

  }

  jiglib.JBox = JBox;

})(jiglib);


text:
/**
 * Created by lugty on 26/08/16.
 */
@javax.xml.bind.annotation.XmlSchema(
        namespace = "http://www.sat.gob.mx/cfd/3",
        elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED,
        xmlns = {
                @javax.xml.bind.annotation.XmlNs( prefix = "cfdi", namespaceURI = "http://www.sat.gob.mx/cfd/3" ),
                @javax.xml.bind.annotation.XmlNs( prefix = "xsi", namespaceURI = "http://www.w3.org/2001/XMLSchema-instance" )
        }
)
package com.tscfdi.comprobante;


text:
#ifndef TextRun_h
#define TextRun_h

#include "PlatformString.h"
#include "TextDirection.h"

namespace WebCore {

class RenderObject;
class RenderSVGResource;

class TextRun {
public:
    enum ExpansionBehaviorFlags {
        ForbidTrailingExpansion = 0 << 0,
        AllowTrailingExpansion = 1 << 0,
        ForbidLeadingExpansion = 0 << 1,
        AllowLeadingExpansion = 1 << 1,
    };

    typedef unsigned ExpansionBehavior;

    TextRun(const UChar* c, int len, bool allowTabs = false, float xpos = 0, float expansion = 0, ExpansionBehavior expansionBehavior = AllowTrailingExpansion | ForbidLeadingExpansion, TextDirection direction = LTR, bool directionalOverride = false)
        : m_characters(c)
        , m_len(len)
        , m_xpos(xpos)
        , m_expansion(expansion)
        , m_expansionBehavior(expansionBehavior)
#if ENABLE(SVG)
        , m_horizontalGlyphStretch(1)
#endif
        , m_allowTabs(allowTabs)
        , m_direction(direction)
        , m_directionalOverride(directionalOverride)
        , m_disableSpacing(false)
#if ENABLE(SVG_FONTS)
        , m_referencingRenderObject(0)
        , m_activePaintingResource(0)
#endif
    {
    }

    TextRun(const String& s, bool allowTabs = false, float xpos = 0, float expansion = 0, ExpansionBehavior expansionBehavior = AllowTrailingExpansion | ForbidLeadingExpansion, TextDirection direction = LTR, bool directionalOverride = false)
        : m_characters(s.characters())
        , m_len(s.length())
        , m_xpos(xpos)
        , m_expansion(expansion)
        , m_expansionBehavior(expansionBehavior)
#if ENABLE(SVG)
        , m_horizontalGlyphStretch(1)
#endif
        , m_allowTabs(allowTabs)
        , m_direction(direction)
        , m_directionalOverride(directionalOverride)
        , m_disableSpacing(false)
#if ENABLE(SVG_FONTS)
        , m_referencingRenderObject(0)
        , m_activePaintingResource(0)
#endif
    {
    }

    UChar operator[](int i) const { ASSERT(i >= 0 && i < m_len); return m_characters[i]; }
    const UChar* data(int i) const { ASSERT(i >= 0 && i < m_len); return &m_characters[i]; }

    const UChar* characters() const { return m_characters; }
    int length() const { return m_len; }

    void setText(const UChar* c, int len) { m_characters = c; m_len = len; }

#if ENABLE(SVG)
    float horizontalGlyphStretch() const { return m_horizontalGlyphStretch; }
    void setHorizontalGlyphStretch(float scale) { m_horizontalGlyphStretch = scale; }
#endif

    bool allowTabs() const { return m_allowTabs; }
    float xPos() const { return m_xpos; }
    float expansion() const { return m_expansion; }
    bool allowsLeadingExpansion() const { return m_expansionBehavior & AllowLeadingExpansion; }
    bool allowsTrailingExpansion() const { return m_expansionBehavior & AllowTrailingExpansion; }
    TextDirection direction() const { return m_direction; }
    bool rtl() const { return m_direction == RTL; }
    bool ltr() const { return m_direction == LTR; }
    bool directionalOverride() const { return m_directionalOverride; }
    bool spacingDisabled() const { return m_disableSpacing; }

    void disableSpacing() { m_disableSpacing = true; }
    void setDirection(TextDirection direction) { m_direction = direction; }
    void setDirectionalOverride(bool override) { m_directionalOverride = override; }

#if ENABLE(SVG_FONTS)
    RenderObject* referencingRenderObject() const { return m_referencingRenderObject; }
    void setReferencingRenderObject(RenderObject* object) { m_referencingRenderObject = object; }

    RenderSVGResource* activePaintingResource() const { return m_activePaintingResource; }
    void setActivePaintingResource(RenderSVGResource* object) { m_activePaintingResource = object; }
#endif

private:
    const UChar* m_characters;
    int m_len;

    // m_xpos is the x position relative to the left start of the text line, not relative to the left
    // start of the containing block. In the case of right alignment or center alignment, left start of
    // the text line is not the same as left start of the containing block.
    float m_xpos;
    float m_expansion;
    ExpansionBehavior m_expansionBehavior;
#if ENABLE(SVG)
    float m_horizontalGlyphStretch;
#endif
    bool m_allowTabs;
    TextDirection m_direction;
    bool m_directionalOverride; // Was this direction set by an override character.
    bool m_disableSpacing;

#if ENABLE(SVG_FONTS)
    RenderObject* m_referencingRenderObject;
    RenderSVGResource* m_activePaintingResource;
#endif
};

}

#endif


text:
#ifndef __G_MENU_MODEL_H__
#define __G_MENU_MODEL_H__

#include <glib-object.h>

#include <gio/giotypes.h>

G_BEGIN_DECLS

#define G_MENU_ATTRIBUTE_ACTION "action"
#define G_MENU_ATTRIBUTE_TARGET "target"
#define G_MENU_ATTRIBUTE_LABEL "label"

#define G_MENU_LINK_SUBMENU "submenu"
#define G_MENU_LINK_SECTION "section"

#define G_TYPE_MENU_MODEL                                   (g_menu_model_get_type ())
#define G_MENU_MODEL(inst)                                  (G_TYPE_CHECK_INSTANCE_CAST ((inst),                     \
                                                             G_TYPE_MENU_MODEL, GMenuModel))
#define G_MENU_MODEL_CLASS(class)                           (G_TYPE_CHECK_CLASS_CAST ((class),                       \
                                                             G_TYPE_MENU_MODEL, GMenuModelClass))
#define G_IS_MENU_MODEL(inst)                               (G_TYPE_CHECK_INSTANCE_TYPE ((inst),                     \
                                                             G_TYPE_MENU_MODEL))
#define G_IS_MENU_MODEL_CLASS(class)                        (G_TYPE_CHECK_CLASS_TYPE ((class),                       \
                                                             G_TYPE_MENU_MODEL))
#define G_MENU_MODEL_GET_CLASS(inst)                        (G_TYPE_INSTANCE_GET_CLASS ((inst),                      \
                                                             G_TYPE_MENU_MODEL, GMenuModelClass))

typedef struct _GMenuModelPrivate                           GMenuModelPrivate;
typedef struct _GMenuModelClass                             GMenuModelClass;

typedef struct _GMenuAttributeIterPrivate                   GMenuAttributeIterPrivate;
typedef struct _GMenuAttributeIterClass                     GMenuAttributeIterClass;
typedef struct _GMenuAttributeIter                          GMenuAttributeIter;

typedef struct _GMenuLinkIterPrivate                        GMenuLinkIterPrivate;
typedef struct _GMenuLinkIterClass                          GMenuLinkIterClass;
typedef struct _GMenuLinkIter                               GMenuLinkIter;

struct _GMenuModel
{
  GObject            parent_instance;
  GMenuModelPrivate *priv;
};

struct _GMenuModelClass
{
  GObjectClass parent_class;

  gboolean              (*is_mutable)                       (GMenuModel          *model);
  gint                  (*get_n_items)                      (GMenuModel          *model);
  void                  (*get_item_attributes)              (GMenuModel          *model,
                                                             gint                 item_index,
                                                             GHashTable         **attributes);
  GMenuAttributeIter *  (*iterate_item_attributes)          (GMenuModel          *model,
                                                             gint                 item_index);
  GVariant *            (*get_item_attribute_value)         (GMenuModel          *model,
                                                             gint                 item_index,
                                                             const gchar         *attribute,
                                                             const GVariantType  *expected_type);
  void                  (*get_item_links)                   (GMenuModel          *model,
                                                             gint                 item_index,
                                                             GHashTable         **links);
  GMenuLinkIter *       (*iterate_item_links)               (GMenuModel          *model,
                                                             gint                 item_index);
  GMenuModel *          (*get_item_link)                    (GMenuModel          *model,
                                                             gint                 item_index,
                                                             const gchar         *link);
};

GType                   g_menu_model_get_type                           (void) G_GNUC_CONST;

gboolean                g_menu_model_is_mutable                         (GMenuModel         *model);
gint                    g_menu_model_get_n_items                        (GMenuModel         *model);

GMenuAttributeIter *    g_menu_model_iterate_item_attributes            (GMenuModel         *model,
                                                                         gint                item_index);
GVariant *              g_menu_model_get_item_attribute_value           (GMenuModel         *model,
                                                                         gint                item_index,
                                                                         const gchar        *attribute,
                                                                         const GVariantType *expected_type);
gboolean                g_menu_model_get_item_attribute                 (GMenuModel         *model,
                                                                         gint                item_index,
                                                                         const gchar        *attribute,
                                                                         const gchar        *format_string,
                                                                         ...);
GMenuLinkIter *         g_menu_model_iterate_item_links                 (GMenuModel         *model,
                                                                         gint                item_index);
GMenuModel *            g_menu_model_get_item_link                      (GMenuModel         *model,
                                                                         gint                item_index,
                                                                         const gchar        *link);

void                    g_menu_model_items_changed                      (GMenuModel         *model,
                                                                         gint                position,
                                                                         gint                removed,
                                                                         gint                added);

#define G_TYPE_MENU_ATTRIBUTE_ITER                          (g_menu_attribute_iter_get_type ())
#define G_MENU_ATTRIBUTE_ITER(inst)                         (G_TYPE_CHECK_INSTANCE_CAST ((inst),                     \
                                                             G_TYPE_MENU_ATTRIBUTE_ITER, GMenuAttributeIter))
#define G_MENU_ATTRIBUTE_ITER_CLASS(class)                  (G_TYPE_CHECK_CLASS_CAST ((class),                       \
                                                             G_TYPE_MENU_ATTRIBUTE_ITER, GMenuAttributeIterClass))
#define G_IS_MENU_ATTRIBUTE_ITER(inst)                      (G_TYPE_CHECK_INSTANCE_TYPE ((inst),                     \
                                                             G_TYPE_MENU_ATTRIBUTE_ITER))
#define G_IS_MENU_ATTRIBUTE_ITER_CLASS(class)               (G_TYPE_CHECK_CLASS_TYPE ((class),                       \
                                                             G_TYPE_MENU_ATTRIBUTE_ITER))
#define G_MENU_ATTRIBUTE_ITER_GET_CLASS(inst)               (G_TYPE_INSTANCE_GET_CLASS ((inst),                      \
                                                             G_TYPE_MENU_ATTRIBUTE_ITER, GMenuAttributeIterClass))

struct _GMenuAttributeIter
{
  GObject parent_instance;
  GMenuAttributeIterPrivate *priv;
};

struct _GMenuAttributeIterClass
{
  GObjectClass parent_class;

  gboolean      (*get_next) (GMenuAttributeIter  *iter,
                             const gchar        **out_type,
                             GVariant           **value);
};

GType                   g_menu_attribute_iter_get_type                  (void) G_GNUC_CONST;

gboolean                g_menu_attribute_iter_get_next                  (GMenuAttributeIter  *iter,
                                                                         const gchar        **out_name,
                                                                         GVariant           **value);
gboolean                g_menu_attribute_iter_next                      (GMenuAttributeIter  *iter);
const gchar *           g_menu_attribute_iter_get_name                  (GMenuAttributeIter  *iter);
GVariant *              g_menu_attribute_iter_get_value                 (GMenuAttributeIter  *iter);

#define G_TYPE_MENU_LINK_ITER                               (g_menu_link_iter_get_type ())
#define G_MENU_LINK_ITER(inst)                              (G_TYPE_CHECK_INSTANCE_CAST ((inst),                     \
                                                             G_TYPE_MENU_LINK_ITER, GMenuLinkIter))
#define G_MENU_LINK_ITER_CLASS(class)                       (G_TYPE_CHECK_CLASS_CAST ((class),                       \
                                                             G_TYPE_MENU_LINK_ITER, GMenuLinkIterClass))
#define G_IS_MENU_LINK_ITER(inst)                           (G_TYPE_CHECK_INSTANCE_TYPE ((inst),                     \
                                                             G_TYPE_MENU_LINK_ITER))
#define G_IS_MENU_LINK_ITER_CLASS(class)                    (G_TYPE_CHECK_CLASS_TYPE ((class),                       \
                                                             G_TYPE_MENU_LINK_ITER))
#define G_MENU_LINK_ITER_GET_CLASS(inst)                    (G_TYPE_INSTANCE_GET_CLASS ((inst),                      \
                                                             G_TYPE_MENU_LINK_ITER, GMenuLinkIterClass))

struct _GMenuLinkIter
{
  GObject parent_instance;
  GMenuLinkIterPrivate *priv;
};

struct _GMenuLinkIterClass
{
  GObjectClass parent_class;

  gboolean      (*get_next) (GMenuLinkIter  *iter,
                             const gchar   **out_name,
                             GMenuModel    **value);
};

GType                   g_menu_link_iter_get_type                       (void) G_GNUC_CONST;

gboolean                g_menu_link_iter_get_next                       (GMenuLinkIter  *iter,
                                                                         const gchar   **out_link,
                                                                         GMenuModel    **value);
gboolean                g_menu_link_iter_next                           (GMenuLinkIter  *iter);
const gchar *           g_menu_link_iter_get_name                       (GMenuLinkIter  *iter);
GMenuModel *            g_menu_link_iter_get_value                      (GMenuLinkIter  *iter);

G_END_DECLS

#endif /* __G_MENU_MODEL_H__ */


text:
package presentation.ui;

import java.awt.Component;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.DSAPublicKey;
import java.security.interfaces.ECPublicKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ProgressMonitor;
import javax.swing.SwingWorker;
import javax.swing.table.DefaultTableModel;

import support.BootstrapService;
import support.Service;

import data.Configuration;
import data.ModelAccessException;
import data.TrustAssessment;
import data.TrustCertificate;
import data.TrustView;

/**
 * provide some logical functions for the GUI class
 *
 * @author Haixin Cai
 */
public class GUILogic {

	/**
	 * load a X509 certificate into program
	 * @param filepath as a string
	 * @return a X509Certificate instance
	 * @throws CertificateException
	 * @throws IOException
	 */
	public static X509Certificate LoadCert(String filepath)
			throws CertificateException, IOException {
		InputStream inStream;
		X509Certificate Cert = null;

		inStream = new FileInputStream(filepath);
		CertificateFactory cf = CertificateFactory.getInstance("X.509");

		Cert = (X509Certificate) cf.generateCertificate(inStream);
		inStream.close();
		return Cert;
	}

	/**
	 * Bootstraps the trust view using the given bootstrap file and the given
	 * security level
	 * @param bootstrapBase
	 * @param securityLevel
	 */
	public static void bootstrapTrustView(final File bootstrapBase,
			final double securityLevel, Component dialogParent) {
		final ProgressMonitor progressMonitor = new ProgressMonitor(
				dialogParent,
				"Bootstrapping the trust view using the Firefox browser history",
				"", 0, 1000);

		final SwingWorker<Void, Object> task = new SwingWorker<Void, Object>() {
			private boolean exceptionOccurred = false;

			@Override
			protected Void doInBackground() throws Exception {
				try {
					Service.getBootstrapService(bootstrapBase).bootstrap(
							securityLevel,
							new BootstrapService.Observer() {
								@Override
								public boolean update(double progress, String item) {
									if (isCancelled())
										return false;

									publish((int)(1000 * progress));
									publish(item);
									return true;
								}
							});
				}
				catch (ModelAccessException | UnsupportedOperationException e) {
					publish(e);
				}
				return null;
			}

			@Override
			public void done() {
				if (isCancelled())
					msg("Bootstrapping was aborted before it has been finished.", "Aborted");
				else if (!exceptionOccurred)
					msg("Bootstrapping was completed successfully.", "Success");
				Toolkit.getDefaultToolkit().beep();
				progressMonitor.close();
			}

			@Override
			protected void process(List<Object> chunks) {
				for (Object chunk : chunks)
					if (chunk instanceof Integer)
						progressMonitor.setProgress((int) chunk);
					else if (chunk instanceof String)
						progressMonitor.setNote((String) chunk);
					else if (chunk instanceof ModelAccessException) {
						msg("Error reading or concurrent modifying the database!");
						exceptionOccurred = true;
					}
					else if (chunk instanceof UnsupportedOperationException) {
						msg("The selected file cannot be used to bootstrap the trust view!");
						exceptionOccurred = true;
					}

				if (progressMonitor.isCanceled())
					cancel(false);
			}
		};

		task.execute();
	}

	/**
	 * @return the issuer string representation for the given certificate
	 * @param certificate
	 */
	public static String getIssuerString(TrustCertificate certificate) {
		if (certificate.getCertificate() instanceof X509Certificate) {
			X509Certificate x509cert = (X509Certificate) certificate.getCertificate();
			return x509cert.getIssuerX500Principal().toString();
		}
		return certificate.getIssuer();
	}

	/**
	 * @return the subject string representation for the given certificate
	 * @param certificate
	 */
	public static String getSubjectString(TrustCertificate certificate) {
		if (certificate.getCertificate() instanceof X509Certificate) {
			X509Certificate x509cert = (X509Certificate) certificate.getCertificate();
			return x509cert.getSubjectX500Principal().toString();
		}
		return certificate.getSubject();
	}

	/**
	 * @return the public key string representation for the given certificate
	 * @param certificate
	 */
	public static String getPublicKeyString(TrustCertificate certificate) {
		if (certificate.getCertificate() instanceof X509Certificate) {
			X509Certificate x509cert = (X509Certificate) certificate.getCertificate();

			if (x509cert.getPublicKey() instanceof RSAPublicKey) {
				RSAPublicKey key = (RSAPublicKey) x509cert.getPublicKey();
				return "[" + x509cert.getPublicKey().getAlgorithm() + "] " +
						key.getModulus().bitCount() + " bits, " +
						"modulus: " + key.getModulus().toString(16) + ", " +
						"public exponent: " + key.getPublicExponent().toString(16);
			}

			if (x509cert.getPublicKey() instanceof DSAPublicKey) {
				DSAPublicKey key = (DSAPublicKey) x509cert.getPublicKey();
				return "[" + x509cert.getPublicKey().getAlgorithm() + "] " +
						"parameters: " + key.getParams() + ", " +
						"y: " + key.getY().toString(16);
			}

			if (x509cert.getPublicKey() instanceof ECPublicKey) {
				ECPublicKey key = (ECPublicKey) x509cert.getPublicKey();
				return "[" + x509cert.getPublicKey().getAlgorithm() + "] " +
						"public x coord: " + key.getW().getAffineX().toString(16) + ", " +
						"public y coord: " + key.getW().getAffineY().toString(16) + ", " +
						"parameters: " + key.getParams();
			}

			return "[" + x509cert.getPublicKey().getAlgorithm() + "] " +
					certificate.getPublicKey();
		}

		return certificate.getPublicKey();
	}

	// /////////////////////////////////////////////////////////refresh_TC_Table/////////////////////////////////////////////////////////////////////////////////////

	/**
	 * to refresh the Trust Certificates Table in the GUI
	 */
	@SuppressWarnings("deprecation")
	public static DefaultTableModel refresh_TC_Table() {

		DefaultTableModel model = new DefaultTableModel(new Object[][] {},
				new String[] { "Serial", "Issuer", "Subject", "PublicKey",
						"NotBefore", "NotAfter" }) {

							private static final long serialVersionUID = 1L;
			@SuppressWarnings("rawtypes")
			Class[] columnTypes = new Class[] { String.class, String.class,
					String.class, String.class, String.class, String.class };

			@Override
			@SuppressWarnings({ "rawtypes", "unchecked" })
			public Class getColumnClass(int columnIndex) {
				return columnTypes[columnIndex];
			}

			boolean[] columnEditables = new boolean[] { false, false, false,
					false, false, false };

			@Override
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		};

		Collection<TrustCertificate> Certs_temp = null;

		try (TrustView view = data.Model.openTrustView()) {
			Certs_temp = view.getTrustedCertificates();

		} catch (ModelAccessException e1) {
			JOptionPane.showConfirmDialog(null,
					"Error reading or concurrent modifying the database! ",
					"Error", JOptionPane.DEFAULT_OPTION);
			e1.printStackTrace();
		}

		if (Certs_temp == null)
			return model;

		Iterator<TrustCertificate> it_cert = Certs_temp.iterator();
		TrustCertificate certificate;

		while (it_cert.hasNext()) {
			certificate = it_cert.next();
			model.addRow(new Object[] {
					certificate.getSerial(),
					getIssuerString(certificate),
					getSubjectString(certificate),
					getPublicKeyString(certificate),
					certificate.getNotBefore().toGMTString(),
					certificate.getNotAfter().toGMTString()
			});
		}

		return model;
	}

	// /////////////////////////////////////////////////////////refresh_uTC_Table/////////////////////////////////////////////////////////////////////////////////////

	/**
	 *
	 * to refresh the unTrust Certificates Table in the GUI
	 */

	@SuppressWarnings("deprecation")
	public static DefaultTableModel refresh_uTC_Table() {
		DefaultTableModel model = new DefaultTableModel(new Object[][] {},
				new String[] { "Serial", "Issuer", "Subject", "PublicKey",
						"NotBefore", "NotAfter" }) {

							private static final long serialVersionUID = 1L;
			@SuppressWarnings("rawtypes")
			Class[] columnTypes = new Class[] { String.class, String.class,
					String.class, String.class, String.class, String.class };

			@Override
			@SuppressWarnings({ "rawtypes", "unchecked" })
			public Class getColumnClass(int columnIndex) {
				return columnTypes[columnIndex];
			}

			boolean[] columnEditables = new boolean[] { false, false, false,
					false, false, false };

			@Override
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		};

		Collection<TrustCertificate> Certs_temp = null;
		try (TrustView view = data.Model.openTrustView()) {
			Certs_temp = view.getUntrustedCertificates();

		} catch (ModelAccessException e1) {
			JOptionPane.showConfirmDialog(null,
					"Error reading or concurrent modifying the database! ",
					"Error", JOptionPane.DEFAULT_OPTION);
			e1.printStackTrace();
		}

		if (Certs_temp == null)
			return model;

		Iterator<TrustCertificate> it_cert = Certs_temp.iterator();
		TrustCertificate certificate;
		while (it_cert.hasNext()) {
			certificate = it_cert.next();

			model.addRow(new Object[] {
					certificate.getSerial(),
					getIssuerString(certificate),
					getSubjectString(certificate),
					getPublicKeyString(certificate),
					certificate.getNotBefore().toGMTString(),
					certificate.getNotAfter().toGMTString()
			});
		}

		return model;
	}

	// /////////////////////////////////////////////////////////refresh_Ass_Table/////////////////////////////////////////////////////////////////////////////////////

	/**
	 *
	 * to refresh the Trust Assessment Table in the GUI
	 */

	public static DefaultTableModel refresh_Ass_Table() {
		DefaultTableModel model = new DefaultTableModel(
				new Object[][] {},
				new String[] { "PublicKey", "CA", "O_kl", "O_it_ca", "O_it_ee" }) {

					private static final long serialVersionUID = 1L;
			@SuppressWarnings("rawtypes")
			Class[] columnTypes = new Class[] { String.class, String.class,
					String.class, String.class, Object.class };

			@Override
			@SuppressWarnings({ "rawtypes", "unchecked" })
			public Class getColumnClass(int columnIndex) {
				return columnTypes[columnIndex];
			}

			boolean[] columnEditables = new boolean[] { false, false, false,
					true, true };

			@Override
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		};

		Collection<TrustAssessment> Assessments_temp = null;
		try (TrustView view = data.Model.openTrustView()) {
			Assessments_temp = view.getAssessments();

		} catch (ModelAccessException e1) {
			JOptionPane.showConfirmDialog(null,
					"Error reading or concurrent modifying the database! ",
					"Error", JOptionPane.DEFAULT_OPTION);
			e1.printStackTrace();
		}

		if (Assessments_temp == null)
			return model;

		Iterator<TrustAssessment> it_ass = Assessments_temp.iterator();
		while (it_ass.hasNext()) {
			TrustAssessment assessment = it_ass.next();
			Iterator<TrustCertificate> iterator = assessment.getS().iterator();
			TrustCertificate certificate = iterator.hasNext() ? iterator.next() : null;

			String o_kl = "";
			o_kl += assessment.getO_kl().isSet() ? "("
					+ assessment.getO_kl().get().getT() + ", "
					+ assessment.getO_kl().get().getC() + ", "
					+ assessment.getO_kl().get().getF() + ")" : "unknown";

			String o_it_ca = "(" + assessment.getO_it_ca().getT() + ", "
					+ assessment.getO_it_ca().getC() + ", "
					+ assessment.getO_it_ca().getF() + ")";
			String o_it_ee = "(" + assessment.getO_it_ee().getT() + ", "
					+ assessment.getO_it_ee().getC() + ", "
					+ assessment.getO_it_ee().getF() + ")";

			String ca = certificate != null ?
					getSubjectString(certificate) : assessment.getCa();
			String k = certificate != null ?
					getPublicKeyString(certificate) : assessment.getK();

			model.addRow(new Object[] { k, ca, o_kl, o_it_ca, o_it_ee });

		}
		return model;
	}

	// /////////////////////////////////////////////////////////getTCert_by_Click/////////////////////////////////////////////////////////////////////////////////////
	public static TrustCertificate getTCert_by_Click(JTable table)

	{
		String Serial = "";
		String Issuer = "";
		int row = table.getSelectedRow();
		if (row == -1)
			return null;
		Serial = (String) table.getValueAt(row, 0);
		Issuer = (String) table.getValueAt(row, 1);

		Collection<TrustCertificate> Certs_temp = null;

		try (TrustView view = data.Model.openTrustView()) {
			Certs_temp = view.getTrustedCertificates();

		} catch (ModelAccessException e1) {
			JOptionPane.showConfirmDialog(null,
					"Error reading or concurrent modifying the database! ",
					"Error", JOptionPane.DEFAULT_OPTION);
			e1.printStackTrace();
			return null;
		}

		Iterator<TrustCertificate> it = Certs_temp.iterator();
		while (it.hasNext()) {
			TrustCertificate it_cert = it.next();
			String it_serial = it_cert.getSerial();
			String it_issuer = getIssuerString(it_cert);

			if (it_serial.equals(Serial) && it_issuer.equals(Issuer))
				return it_cert;
		}

		return null;
	}

	// /////////////////////////////////////////////////////////getuTCert_by_Click/////////////////////////////////////////////////////////////////////////////////////
	/**
	 * @param clicked table
	 * @return a TrustCertificate instance that clicked by user
	 */
	public static TrustCertificate getuTCert_by_Click(JTable table)

	{
		String Serial = "";
		String Issuer = "";
		int row = table.getSelectedRow();
		if (row == -1)
			return null;
		Serial = (String) table.getValueAt(row, 0);
		Issuer = (String) table.getValueAt(row, 1);

		Collection<TrustCertificate> Certs_temp = null;

		try (TrustView view = data.Model.openTrustView()) {
			Certs_temp = view.getUntrustedCertificates();

		} catch (ModelAccessException e1) {
			JOptionPane.showConfirmDialog(null,
					"Error reading or concurrent modifying the database! ",
					"Error", JOptionPane.DEFAULT_OPTION);
			e1.printStackTrace();
			return null;
		}

		Iterator<TrustCertificate> it = Certs_temp.iterator();
		while (it.hasNext()) {
			TrustCertificate it_cert = it.next();
			String it_serial = it_cert.getSerial();
			String it_issuer = getIssuerString(it_cert);

			if (it_serial.equals(Serial) && it_issuer.equals(Issuer))
				return it_cert;
		}

		return null;
	}

	// /////////////////////////////////////////////////////////getAss_by_Click/////////////////////////////////////////////////////////////////////////////////////
	/**
	 * @param clicked table
	 * @return a TrustAssessment instance that clicked by user
	 */
	public static TrustAssessment getAss_by_Click(JTable table)

	{
		String k = "";
		String ca = "";
		int row = table.getSelectedRow();
		if (row == -1)
			return null;
		k = (String) table.getValueAt(row, 0);
		ca = (String) table.getValueAt(row, 1);

		Collection<TrustAssessment> Certs_temp = null;

		try (TrustView view = data.Model.openTrustView()) {
			Certs_temp = view.getAssessments();

		} catch (ModelAccessException e1) {
			JOptionPane.showConfirmDialog(null,
					"Error reading or concurrent modifying the database! ",
					"Error", JOptionPane.DEFAULT_OPTION);
			e1.printStackTrace();
			return null;
		}

		Iterator<TrustAssessment> it = Certs_temp.iterator();
		while (it.hasNext()) {
			TrustAssessment it_ass = it.next();
			Iterator<TrustCertificate> iterator = it_ass.getS().iterator();
			TrustCertificate certificate = iterator.hasNext() ? iterator.next() : null;

			String it_ca = certificate != null ?
					getSubjectString(certificate) : it_ass.getCa();
			String it_k = certificate != null ?
					getPublicKeyString(certificate) : it_ass.getK();

			if (it_ca.equals(ca) && it_k.equals(k))
				return it_ass;
		}

		return null;
	}

	/**
	 * store a k/v vaule pair for configuration
	 * @param key
	 * @param value
	 */
	public static <T> void set_Configuration(String key, T value) {
		try (Configuration conf = data.Model.openConfiguration()) {
			conf.set(key, value);
			conf.save();

		} catch (ModelAccessException e) {
			JOptionPane
					.showConfirmDialog(
							null,
							"Error reading or concurrent modifying the database! Please restart the application ",
							"Error", JOptionPane.DEFAULT_OPTION);
			e.printStackTrace();
		}
	}

	/**
	 * retrieval a k/v vaule pair for configuration
	 * @param key
	 * @param type
	 * @return
	 */
	public static <T> T get_Configuration(String key, Class<T> type) {
		try (Configuration conf = data.Model.openConfiguration()) {
			return conf.get(key, type);

		} catch (ModelAccessException e) {
			JOptionPane
					.showConfirmDialog(
							null,
							"Error reading or concurrent modifying the database! Please restart the application ",
							"Error", JOptionPane.DEFAULT_OPTION);
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * retrieval a k/v vaule pair for configuration
	 * @param key
	 * @param type
	 * @param defaultValue
	 * @return
	 */
	public static <T> T get_Configuration(String key, Class<T> type, T defaultValue) {
		try (Configuration conf = data.Model.openConfiguration()) {
			if (conf.exists(key))
				return conf.get(key, type);

		} catch (ModelAccessException e) {
			JOptionPane
					.showConfirmDialog(
							null,
							"Error reading or concurrent modifying the database! Please restart the application ",
							"Error", JOptionPane.DEFAULT_OPTION);
			e.printStackTrace();

		}
		return defaultValue;

	}

	/**
	 * pop up a error message box
	 * @param msg
	 */
	public static void msg(String msg) {
		JOptionPane.showConfirmDialog(null, msg, "Error",
				JOptionPane.DEFAULT_OPTION);
	}

	/**
	 * pop up a "type" message box
	 * @param msg
	 * @param type
	 */
	public static void msg(String msg, String type) {
		JOptionPane.showConfirmDialog(null, msg, type,
				JOptionPane.DEFAULT_OPTION);
	}
}


text:
Predication uses objects to describe predicates. That way you can store these descriptions as data and easily convert them into pre-compiled functions. This is useful if you need to store complicated predicates in a database or send them as a message, for example.

It supports common predicates and logical operators out of the box, and you can register your own predicates.

There are no external dependencies, and the umd bundle is less than 4kb uglified, and less than 1.5kb gzipped.

## installation

### npm

```bash
$ npm install predication
```

## usage

Predication takes a **description** and returns a **predicate**. So it looks like this...

```javascript
import { predication } from 'predication'

const isTrue = predication({eq: true})

isTrue(true)  // true
isTrue(false) // false
```

That example is sort of silly, but here is a more complicated description that matches numbers less than 15, and not less than 5, and divisible by either 2 or 3...

```javascript
import { predication } from 'predication'

const description = {
  and: [
    {lt: 15},
    {not: {lt: 5}},
    {or: [
      {mod: 2},
      {mod: 3}
    ]}
  ]
}

const predicate = predication(description)

const values = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

const matches = values.filter(predicate) // [6,8,9,10,12,14]
```

### Working with objects

In the likely event that your values are objects, you can use `this` to 'key' into the object...

```javascript
const predicate = predication({
  this: 'foo',
  eq: true
})

predicate({foo: true}})  // true
predicate({foo: false}}) // false
```

You can key into the object in more complicated ways. For example...

```javascript
const predicate = predication({
  this: 'foo.bar[0]',
  eq: true
})

predicate({foo: {bar: [true, false]}}) // true
predicate({foo: {bar: [false, true]}}) // false
```
You can also key into arrays starting from the end using negative indexing...

```javascript
const predicate = predication({
  this: 'foo.bar[-0]',
  eq: true
})

predicate({foo: {bar: [true, false]}}) // false
predicate({foo: {bar: [false, true]}}) // true
```

You can even specify relationships inside the object using `that`. Here is an example that matches objects whose `foo` and `bar` properties are the same...

```javascript
const predicate = predication({
  this: 'foo',
  eq: {that: 'bar'}
})

predicate({foo: true, bar: true})  // true
predicate({foo: true, bar: false}) // false
```

#### Nesting `this`

The strings provided for `this` will nest. Take, for example, Bobby and Marian...

```javascript
const Bobby = {
  body: {
    height: 60,
    age: 33
  }
}

const Marian = {
  body: {
    height: 49,
    age: 72
  }
}
```

If we wanted want to match people who are either taller than 50" or older than 65, we could do the following...

```javascript
const tall_or_old = predication({
  this: 'body',                 // <-- we select the body object
  or: [
    { this: 'height', gt: 50 }, // <-- we don't say body.height
    { this: 'age', gt: 45 }     // <-- we don't say body.age
  ]
})
```

Which would match both Bobby and Marian...

```javascript
tall_or_old(Bobby)  // true
tall_or_old(Marian) // true
```

### Registering your own predicates

If you want to add support for your own predicates, you can use `registerPredicate`. The following would add a predicate that returns `true` when a value has a given root, for example a square root...

```javascript
import { registerPredicate, predication } from 'predication'

const myHasRootPredicate = (config, value) => (
  (value > 0) && (config !== 0) && (Math.pow(value, (1 / config)) % 1 === 0)
)

registerPredicate('hasRoot', myHasRootPredicate)
```

Now that you have registered it, you can use `hasRoot` as a key in your descriptions...

```javascript
const hasSquareRoot = predication({
  hasRoot: 2
})

hasSquareRoot(4) // true
hasSquareRoot(7) // false
hasSquareRoot(9) // true
```
Because registerPredicate is used internally, you can take advantage of `this` and `that` for your predicates too...

```javascript
const fooHasCubeRoot = predication({
  this: 'foo',
  hasRoot: 3
})

fooHasCubeRoot({foo: 27}) // true
fooHasCubeRoot({foo: 9})  // false
```

If you want to validate a configuration, you can pass a predicate as the third argument to `register predicate` like so...

```javascript
const greaterThan = (v, config) => v > config
const isNumber = config => typeof config === 'number' // returns false if invalid
registerPredicate('custom_gt', greaterThan, isNumber)

predication({custom_gt: true}) // throws, because true is not a number
```

### Built-in predicates

In the above examples, `eq`, `mod`, and `lt` are examples of built-in predicate names. Here is the full list:

| Name | Example | Explanation |
| :--  | :------ | :---------- |
| `eq` | `{eq: true}` | value equals true |
| `ne` | `{ne: true}` | negation of `eq` |
| `in` | `{in: [1, 2, 3]}` | value is included in array  |
| `in` | `{in: 'abc'}` | value includes string 'abc' (case-insensitive) |
| `nin` | `{nin: ...}` | negation of `in` |

```javascript
registerPredicate('not', not);
registerPredicate('and', and);
registerPredicate('or', or);

registerPredicate('mod', c => v => (Array.isArray(c) ? modR(v, c) : mod(v, c)));

registerPredicate('ne',  c => v => v !== c);
registerPredicate('lt',  c => v => v < c);
registerPredicate('gt',  c => v => v > c);
registerPredicate('lte', c => v => v <= c);
registerPredicate('gte', c => v => v >= c);
registerPredicate('rng', c => v => (v >= c[0] && v <= c[1]));
registerPredicate('oi',  c => v => objectIncludesString(v, c));
registerPredicate('noi', c => v => !objectIncludesString(v, c));
```

### A word about `not` and missing properties

...

### More on 'this' and 'that'

... (how validation handles bad that values)


text:
package fixtures.azurespecials;

import com.microsoft.rest.ServiceResponseWithHeaders;
import fixtures.azurespecials.models.HeaderCustomNamedRequestIdHeaders;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

public class HeaderOperationsTests {
    private static AutoRestAzureSpecialParametersTestClient client;

    @BeforeClass
    public static void setup() {
        client = new AutoRestAzureSpecialParametersTestClientImpl("http://localhost.:3000");
    }

    @Test
    public void customNamedRequestId() throws Exception {
        ServiceResponseWithHeaders<Void, HeaderCustomNamedRequestIdHeaders> response = client.getHeaderOperations().customNamedRequestId("9C4D50EE-2D56-4CD3-8152-34347DC9F2B0");
        Assert.assertEquals(200, response.getResponse().code());
        Assert.assertEquals("123", response.getHeaders().getFooRequestId());
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace OAuth2.Example.Test
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}


text:
require 'waiting_on_rails/player'

module WaitingOnRails
  class Anything
    def initialize(music_player, ding_player = nil)
      @music_player = music_player
      @ding_player  = ding_player
    end

    def run(args)
      @music_player.start(loop: true)
      Process.wait(spawn_subprocess(args))
      @music_player.stop
      sleep 0.5
      @ding_player.start if @ding_player
    ensure
      @music_player.stop
    end

    private

    def spawn_subprocess(args)
      spawn *args
    end
  end
end


text:
#include "lib/nullstream.h"
#include "frontends/p4/def_use.h"

#include "inlining.h"
#include "frontends/p4/callGraph.h"
#include "frontends/p4/methodInstance.h"
#include "frontends/common/resolveReferences/resolveReferences.h"
#include "frontends/p4/parameterSubstitution.h"
#include "frontends/p4/typeChecking/typeChecker.h"
#include "frontends/p4/moveDeclarations.h"
#include "frontends/p4/resetHeaders.h"
#include "frontends/p4/toP4/toP4.h"

namespace P4 {

namespace {

class FindLocationSets : public Inspector {
    StorageMap *storageMap;
    std::map<const IR::Expression*, const LocationSet*> loc;

    const LocationSet* get(const IR::Expression* expression) const {
        auto result = ::get(loc, expression);
        BUG_CHECK(result != nullptr, "No location set known for %1%", expression);
        return result;
    }
    void set(const IR::Expression* expression, const LocationSet* ls) {
        CHECK_NULL(expression); CHECK_NULL(ls);
        loc.emplace(expression, ls);
    }

 public:
    FindLocationSets(ReferenceMap* refMap, TypeMap* typeMap) :
            storageMap(new StorageMap(refMap, typeMap)) {}

    // default behavior
    bool preorder(const IR::Expression* expression) {
        set(expression, LocationSet::empty);
        return false;
    }

    bool preorder(const IR::Slice* expression) {
        visit(expression->e0);
        auto base = get(expression->e0);
        set(expression, base);
        return false;
    }

    bool preorder(const IR::TypeNameExpression* expression) {
        set(expression, LocationSet::empty);
        return false;
    }

    bool preorder(const IR::PathExpression* expression) {
        auto decl = storageMap->refMap->getDeclaration(expression->path, true);
        auto storage = storageMap->getStorage(decl);
        const LocationSet* result;
        if (storage != nullptr)
            result = new LocationSet(storage);
        else
            result = LocationSet::empty;
        set(expression, result);
        return false;
    }

    bool preorder(const IR::Member* expression) {
        visit(expression->expr);
        auto type = storageMap->typeMap->getType(expression, true);
        if (type->is<IR::Type_Method>())
            return false;
        auto storage = get(expression->expr);

        auto basetype = storageMap->typeMap->getType(expression->expr, true);
        if (basetype->is<IR::Type_Stack>()) {
            if (expression->member.name == IR::Type_Stack::next ||
                expression->member.name == IR::Type_Stack::last) {
                set(expression, storage);
                return false;
            }
        }

        auto fields = storage->getField(expression->member);
        set(expression, fields);
        return false;
    }

    bool preorder(const IR::ArrayIndex* expression) {
        visit(expression->left);
        visit(expression->right);
        auto storage = get(expression->left);
        if (expression->right->is<IR::Constant>()) {
            auto cst = expression->right->to<IR::Constant>();
            auto index = cst->asInt();
            auto result = storage->getIndex(index);
            set(expression, result);
        } else {
            set(expression, storage->allElements());
        }
        return false;
    }

    bool preorder(const IR::Operation_Binary* expression) {
        visit(expression->left);
        visit(expression->right);
        auto l = get(expression->left);
        auto r = get(expression->right);
        auto result = l->join(r);
        set(expression, result);
        return false;
    }

    bool preorder(const IR::Mux* expression) {
        visit(expression->e0);
        visit(expression->e1);
        visit(expression->e2);
        auto e0 = get(expression->e0);
        auto e1 = get(expression->e1);
        auto e2 = get(expression->e2);
        auto result = e0->join(e1)->join(e2);
        set(expression, result);
        return false;
    }

    bool preorder(const IR::ListExpression* expression) {
        visit(expression->components, "components");
        auto l = LocationSet::empty;
        for (auto c : expression->components) {
            auto cl = get(c);
            l = l->join(cl);
        }
        set(expression, l);
        return false;
    }

    bool preorder(const IR::Operation_Unary* expression) {
        visit(expression->expr);
        auto result = get(expression->expr);
        set(expression, result);
        return false;
    }

    const LocationSet* locations(const IR::Expression* expression) {
        (void)expression->apply(*this);
        auto ls = get(expression);
        if (ls != nullptr)
            return ls->canonicalize();
        return nullptr;
    }
};

/**
This class computes new names for inlined objects.
An object's name is prefixed with the instance name that includes it.
For example:
control c() {
  table t() { ... }  apply { t.apply() }
}
control d() {
  c() cinst;
  apply { cinst.apply(); }
}
After inlining we will get:
control d() {
  @name("cinst.t") table cinst_t() { ... }
  apply { cinst_t.apply(); }
}
So the externally visible name for the table is "cinst.t"
*/
class ComputeNewNames : public Inspector {
    cstring           prefix;
    P4::ReferenceMap* refMap;
    SymRenameMap*     renameMap;

 public:
    ComputeNewNames(cstring prefix, P4::ReferenceMap* refMap, SymRenameMap* renameMap) :
            prefix(prefix), refMap(refMap), renameMap(renameMap) {
        BUG_CHECK(!prefix.isNullOrEmpty(), "Null prefix");
        CHECK_NULL(refMap); CHECK_NULL(renameMap);
    }

    void rename(const IR::Declaration* decl) {
        BUG_CHECK(decl->is<IR::IAnnotated>(), "%1%: no annotations", decl);
        cstring name = decl->externalName();
        cstring extName;
        if (name.startsWith("."))
            // Do not change the external name of objects starting with a leading dot
            extName = name;
        else
            extName = prefix + "." + name;
        cstring baseName = extName.replace('.', '_');
        cstring newName = refMap->newName(baseName);
        renameMap->setNewName(decl, newName, extName);
    }
    void postorder(const IR::P4Table* table) override { rename(table); }
    void postorder(const IR::P4ValueSet* set) override { rename(set); }
    void postorder(const IR::P4Action* action) override { rename(action); }
    void postorder(const IR::Declaration_Instance* instance) override { rename(instance); }
    void postorder(const IR::Declaration_Variable* decl) override { rename(decl); }
};

// Add a @name annotation ONLY.
static const IR::Annotations*
setNameAnnotation(cstring name, const IR::Annotations* annos) {
    if (annos == nullptr)
        annos = IR::Annotations::empty;
    return annos->addOrReplace(IR::Annotation::nameAnnotation, new IR::StringLiteral(name));
}

/**
Perform multiple substitutions and rename global objects, such as
tables, actions and instances.  Unfortunately these transformations
have to be performed at the same time, because otherwise the refMap
is invalidated.
*/
class Substitutions : public SubstituteParameters {
    P4::ReferenceMap* refMap;  // updated
    const SymRenameMap*  renameMap;  // map with new names for global objects

 public:
    Substitutions(P4::ReferenceMap* refMap,
                  P4::ParameterSubstitution* subst,
                  P4::TypeVariableSubstitution* tvs,
                  const SymRenameMap* renameMap) :
            SubstituteParameters(refMap, subst, tvs),
            refMap(refMap), renameMap(renameMap)
    { CHECK_NULL(refMap); CHECK_NULL(renameMap); }
    const IR::Node* postorder(IR::P4Table* table) override {
        auto orig = getOriginal<IR::IDeclaration>();
        cstring newName = renameMap->getName(orig);
        cstring extName = renameMap->getExtName(orig);
        LOG3("Renaming " << dbp(orig) << " to " << newName << " (" << extName << ")");
        auto annos = setNameAnnotation(extName, table->annotations);
        auto result = new IR::P4Table(table->srcInfo, newName, annos,
                                      table->properties);
        return result;
    }
    const IR::Node* postorder(IR::P4ValueSet* set) override {
        auto orig = getOriginal<IR::IDeclaration>();
        cstring newName = renameMap->getName(orig);
        cstring extName = renameMap->getExtName(orig);
        LOG3("Renaming " << dbp(orig) << " to " << newName << "(" << extName << ")");
        auto annos = setNameAnnotation(extName, set->annotations);
        auto result = new IR::P4ValueSet(set->srcInfo, newName, annos,
                                         set->elementType, set->size);
        return result;
    }
    const IR::Node* postorder(IR::P4Action* action) override {
        auto orig = getOriginal<IR::IDeclaration>();
        cstring newName = renameMap->getName(orig);
        cstring extName = renameMap->getExtName(orig);
        LOG3("Renaming " << dbp(orig) << " to " << newName << "(" << extName << ")");
        auto annos = setNameAnnotation(extName, action->annotations);
        auto result = new IR::P4Action(action->srcInfo, newName, annos,
                                       action->parameters, action->body);
        return result;
    }
    const IR::Node* postorder(IR::Declaration_Instance* instance) override {
        auto orig = getOriginal<IR::IDeclaration>();
        cstring newName = renameMap->getName(orig);
        cstring extName = renameMap->getExtName(orig);
        LOG3("Renaming " << dbp(orig) << " to " << newName << "(" << extName << ")");
        auto annos = setNameAnnotation(extName, instance->annotations);
        instance->name = newName;
        instance->annotations = annos;
        return instance;
    }
    const IR::Node* postorder(IR::Declaration_Variable* decl) override {
        auto orig = getOriginal<IR::IDeclaration>();
        cstring newName = renameMap->getName(orig);
        cstring extName = renameMap->getExtName(orig);
        LOG3("Renaming " << dbp(orig) << " to " << newName << "(" << extName << ")");
        decl->name = newName;
        return decl;
    }
    const IR::Node* postorder(IR::PathExpression* expression) override {
        LOG3("(Substitutions) visiting" << dbp(getOriginal()));
        auto decl = refMap->getDeclaration(expression->path, true);
        auto param = decl->to<IR::Parameter>();
        if (param != nullptr && subst->contains(param)) {
            // This path is the same as in SubstituteParameters
            auto value = subst->lookup(param)->expression;
            LOG3("(Substitutions) Replaced " << dbp(expression) << " for parameter "
                 << decl << " with " << dbp(value));
            return value;
        }

        cstring newName;
        if (renameMap->isRenamed(decl))
            newName = renameMap->getName(decl);
        else
            newName = expression->path->name;
        IR::ID newid(expression->path->srcInfo, newName, expression->path->name.originalName);
        auto newpath = new IR::Path(newid, expression->path->absolute);
        auto result = new IR::PathExpression(newpath);
        refMap->setDeclaration(newpath, decl);
        LOG3("(Substitutions) replaced " << dbp(getOriginal()) << " with " << dbp(result));
        return result;
    }
};
}  // namespace

template <class T>
const T* PerInstanceSubstitutions::rename(ReferenceMap* refMap, const IR::Node* node) {
    Substitutions rename(refMap, &paramSubst, &tvs, &renameMap);
    auto convert = node->apply(rename);
    CHECK_NULL(convert);
    auto result = convert->to<T>();
    CHECK_NULL(result);
    return result;
}

void InlineList::analyze() {
    P4::CallGraph<const IR::IContainer*> cg("Call-graph");

    for (auto m : inlineMap) {
        auto inl = m.second;
        if (inl->invocations.size() == 0) {
            LOG3("Callee " << inl->callee << " in " << inl->caller << " is never invoked");
            continue;
        }
        auto it = inl->invocations.begin();
        auto first = *it;
        if (!allowMultipleCalls && inl->invocations.size() > 1) {
            ++it;
            auto second = *it;
            ::error(ErrorType::ERR_UNSUPPORTED_ON_TARGET,
                    "Multiple invocations of the same object "
                    "not supported on this target: %1%, %2%",
                    first, second);
            continue;
        }
        cg.calls(inl->caller, inl->callee);
    }

    // must inline from leaves up
    std::vector<const IR::IContainer*> order;
    cg.sort(order);
    for (auto c : order) {
        // This is quadratic, but hopefully the call graph is not too large
        for (auto m : inlineMap) {
            auto inl = m.second;
            if (inl->caller == c)
                toInline.push_back(inl);
        }
    }

    std::reverse(toInline.begin(), toInline.end());
}

InlineSummary* InlineList::next() {
    if (toInline.size() == 0)
        return nullptr;
    auto result = new InlineSummary();
    std::set<const IR::IContainer*> processing;
    while (!toInline.empty()) {
        auto toadd = toInline.back();
        if (processing.find(toadd->callee) != processing.end())
            break;
        toInline.pop_back();
        result->add(toadd);
        processing.emplace(toadd->caller);
    }
    return result;
}

/////////////////////////////////////////////////////////////////////////////////////////////

void DiscoverInlining::postorder(const IR::MethodCallStatement* statement) {
    LOG4("Visiting " << dbp(statement) << statement);
    auto mi = MethodInstance::resolve(statement, refMap, typeMap);
    if (!mi->isApply())
        return;
    auto am = mi->to<P4::ApplyMethod>();
    CHECK_NULL(am);
    if (!am->applyObject->is<IR::Type_Control>() &&
        !am->applyObject->is<IR::Type_Parser>())
        return;
    auto instantiation = am->object->to<IR::Declaration_Instance>();
    if (instantiation != nullptr)
        inlineList->addInvocation(instantiation, statement);
    else
        BUG_CHECK(am->object->is<IR::Parameter>(),
                  "%1% expected a constructor parameter", am->object);
}

void DiscoverInlining::visit_all(const IR::Block* block) {
    for (auto it : block->constantValue) {
        if (it.second == nullptr)
            continue;
        if (it.second->is<IR::Block>()) {
            visit(it.second->getNode());
        }
        if (::errorCount() > 0)
            return;
    }
}

bool DiscoverInlining::preorder(const IR::ControlBlock* block) {
    LOG4("Visiting " << block);
    if (getContext()->node->is<IR::ParserBlock>()) {
        ::error(ErrorType::ERR_INVALID, "%1%: instantiation of control in parser",
                block->node);
        return false;
    } else if (getContext()->node->is<IR::ControlBlock>() && allowControls) {
        auto parent = getContext()->node->to<IR::ControlBlock>();
        LOG3("Will inline " << dbp(block) << "@" << dbp(block->node) << " into " << dbp(parent));
        auto instance = block->node->to<IR::Declaration_Instance>();
        auto callee = block->container;
        inlineList->addInstantiation(parent->container, callee, instance);
    }

    visit_all(block);
    if (::errorCount() > 0)
        return false;
    visit(block->container->body);
    return false;
}

bool DiscoverInlining::preorder(const IR::ParserBlock* block) {
    LOG4("Visiting " << block);
    if (getContext()->node->is<IR::ControlBlock>()) {
        ::error(ErrorType::ERR_INVALID, "%1%: instantiation of parser in control",
                block->node);
        return false;
    } else if (getContext()->node->is<IR::ParserBlock>()) {
        auto parent = getContext()->node->to<IR::ParserBlock>();
        LOG3("Will inline " << block << "@" << block->node << " into " << parent);
        auto instance = block->node->to<IR::Declaration_Instance>();
        auto callee = block->container;
        inlineList->addInstantiation(parent->container, callee, instance);
    }
    visit_all(block);
    if (::errorCount() > 0)
        return false;
    visit(block->container->states, "states");
    return false;
}

///////////////////////////////////////////////////////////////////////////////////////////////////

Visitor::profile_t GeneralInliner::init_apply(const IR::Node* node) {
    ResolveReferences solver(refMap);
    TypeChecking typeChecker(refMap, typeMap);
    node->apply(solver);
    (void)node->apply(typeChecker);
    return AbstractInliner::init_apply(node);
}

/* Build the substitutions needed for args and locals of the thing being inlined.
 * P4Block here may be either P4Control or P4Parser */
template<class P4Block>
void GeneralInliner::inline_subst(P4Block *caller,
                                  IR::IndexedVector<IR::Declaration> P4Block::*blockLocals) {
    LOG3("Analyzing " << dbp(caller));
    IR::IndexedVector<IR::Declaration> locals;
    for (auto s : caller->*blockLocals) {
        /* Even if we inline the block, the declaration may still be needed.
           Consider this example:
           control D() { apply { } }
           control C()(D d) { apply { d.apply(); }}
           control I() {
               D() d;  // we can't delete this instantiation after inlining, since it's used below
               C(d) c;
               apply { c.apply(); }
           }
        */
        locals.push_back(s);
        const IR::Declaration_Instance *inst = s->template to<IR::Declaration_Instance>();
        if (inst == nullptr ||
            workToDo->declToCallee.find(inst) == workToDo->declToCallee.end()) {
            // not a call
        } else {
            auto callee = workToDo->declToCallee[inst]->to<P4Block>();
            CHECK_NULL(callee);
            auto substs = new PerInstanceSubstitutions();
            workToDo->substitutions[inst] = substs;

            // Substitute constructor parameters
            substs->paramSubst.populate(callee->getConstructorParameters(), inst->arguments);
            if (auto spec = inst->type->to<IR::Type_Specialized>()) {
                substs->tvs.setBindings(callee->getNode(),
                                        callee->getTypeParameters(), spec->arguments);
            }

            // Must rename callee local objects prefixing them with their instance name.
            cstring prefix = inst->externalName();
            ComputeNewNames cnn(prefix, refMap, &substs->renameMap);
            (void)callee->apply(cnn);  // populates substs.renameMap

            // Use temporaries for these parameters
            std::set<const IR::Parameter*> useTemporary;

            const IR::MethodCallStatement *call = nullptr;
            const IR::MethodCallStatement *firstCall = nullptr;  // to get directionless parameters
            for (auto m : workToDo->callToInstance) {
                if (m.second != inst) continue;
                if (call) {
                    if (!call->equiv(*m.first)) {
                        call = nullptr;
                        break; }
                } else {
                    call = firstCall = m.first; } }
            CHECK_NULL(firstCall);
            MethodInstance *mi = MethodInstance::resolve(firstCall, refMap, typeMap);
            if (call != nullptr) {
                // All call sites are the same (call is one of them), so we use the
                // same arguments in all cases.  So we can avoid copies if args do
                // not alias
                std::map<const IR::Parameter*, const LocationSet*> locationSets;
                FindLocationSets fls(refMap, typeMap);

                for (auto param : *mi->substitution.getParametersInArgumentOrder()) {
                    auto arg = mi->substitution.lookup(param);
                    auto ls = fls.locations(arg->expression);
                    locationSets.emplace(param, ls);
                }

                for (auto param1 : *mi->substitution.getParametersInArgumentOrder()) {
                    auto ls1 = ::get(locationSets, param1);
                    for (auto param2 : *mi->substitution.getParametersInArgumentOrder()) {
                        if (param1 == param2) continue;
                        auto ls2 = ::get(locationSets, param2);
                        if (ls1->overlaps(ls2)) {
                            LOG4("Arg for " << dbp(param1) << " aliases with arg for "
                                 << dbp(param2) << ": using temp");
                            useTemporary.emplace(param1);
                            useTemporary.emplace(param2);
                        }
                    }
                }
            }

            // Substitute applyParameters
            // with fresh variable names or with the call arguments.
            for (auto param : callee->getApplyParameters()->parameters) {
                if (param->direction == IR::Direction::None) {
                    auto initializer = mi->substitution.lookup(param);
                    substs->paramSubst.add(param, initializer);
                    continue;
                }
                if (call != nullptr && (useTemporary.find(param) == useTemporary.end())) {
                    // Substitute argument directly
                    CHECK_NULL(mi);
                    auto initializer = mi->substitution.lookup(param);
                    LOG3("Substituting callee parameter " << dbp(param)
                         << " with " << dbp(initializer));
                    substs->paramSubst.add(param, initializer);
                } else {
                    // use a temporary variable
                    cstring newName = refMap->newName(param->name);
                    auto path = new IR::PathExpression(newName);
                    substs->paramSubst.add(param, new IR::Argument(path));
                    LOG3("Replacing " << param->name << " with " << newName);
                    auto vardecl = new IR::Declaration_Variable(newName,
                                                                param->annotations, param->type);
                    locals.push_back(vardecl);
                }
            }

            /* We will perform these substitutions twice: once here, to
               compute the names for the locals that we need to inline here,
               and once again at the call site (where we do additional
               substitutions, including the callee parameters). */
            auto clone = substs->rename<P4Block>(refMap, callee);
            for (auto i : clone->*blockLocals)
                locals.push_back(i);
        }
    }
    caller->*blockLocals = locals;
}

const IR::Node* GeneralInliner::preorder(IR::P4Control* caller) {
    // prepares the code to inline
    auto orig = getOriginal<IR::P4Control>();
    if (toInline->callerToWork.find(orig) == toInline->callerToWork.end()) {
        prune();
        return caller;
    }

    workToDo = &toInline->callerToWork[orig];
    inline_subst(caller, &IR::P4Control::controlLocals);
    visit(caller->body);
    list->replace(orig, caller);
    workToDo = nullptr;
    prune();
    return caller;
}

const IR::Node* GeneralInliner::preorder(IR::MethodCallStatement* statement) {
    if (workToDo == nullptr)
        return statement;
    auto orig = getOriginal<IR::MethodCallStatement>();
    if (workToDo->callToInstance.find(orig) == workToDo->callToInstance.end())
        return statement;
    LOG3("Inlining invocation " << dbp(orig));
    auto decl = workToDo->callToInstance[orig];
    CHECK_NULL(decl);

    auto called = workToDo->declToCallee[decl];
    if (!called->is<IR::P4Control>())
        // Parsers are inlined in the ParserState processor
        return statement;

    auto callee = called->to<IR::P4Control>();
    IR::IndexedVector<IR::StatOrDecl> body;
    // clone the substitution: it may be reused for multiple invocations
    auto substs = new PerInstanceSubstitutions(*workToDo->substitutions[decl]);

    auto mi = MethodInstance::resolve(statement->methodCall, refMap, typeMap);
    for (auto param : *mi->substitution.getParametersInArgumentOrder()) {
        LOG3("Looking for " << param->name);
        auto initializer = substs->paramSubst.lookup(param);
        auto arg = mi->substitution.lookup(param);
        if ((param->direction == IR::Direction::In || param->direction == IR::Direction::InOut)) {
            if (!initializer->expression->equiv(*arg->expression)) {
                auto stat = new IR::AssignmentStatement(initializer->expression, arg->expression);
                body.push_back(stat); }
        } else if (param->direction == IR::Direction::Out) {
            auto paramType = typeMap->getType(param, true);
            // This is important, since this variable may be used many times.
            DoResetHeaders::generateResets(typeMap, paramType, initializer->expression, &body);
        } else if (param->direction == IR::Direction::None) {
            // already set; the value must be the same, or else we cannot compile
            auto initializer = mi->substitution.lookup(param);
            auto prev = substs->paramSubst.lookup(param);
            if (!initializer->equiv(*prev))
                // This is a compile-time constant, since this is a non-directional
                // parameter, so the value should be independent on the context.
                ::error("%1%: non-directional parameters must be substitued with the "
                        "same value in all invocations; two different substitutions are "
                        "%2% and %3%", param, initializer, prev);
            continue;
        }
    }

    // inline actual body
    callee = substs->rename<IR::P4Control>(refMap, callee);
    body.append(callee->body->components);

    // Copy values of out and inout parameters
    for (auto param : *mi->substitution.getParametersInArgumentOrder()) {
        if (param->direction == IR::Direction::InOut || param->direction == IR::Direction::Out) {
            auto left = mi->substitution.lookup(param);
            auto arg = substs->paramSubst.lookupByName(param->name);
            if (!left->expression->equiv(*arg->expression)) {
                auto copyout = new IR::AssignmentStatement(
                    left->expression, arg->expression->clone());
                body.push_back(copyout);
            }
        }
    }

    auto annotations = callee->type->annotations->where(
        [](const IR::Annotation* a) { return a->name != IR::Annotation::nameAnnotation; });
    auto result = new IR::BlockStatement(statement->srcInfo, annotations, body);
    LOG3("Replacing " << dbp(orig) << " with " << dbp(result));
    prune();
    return result;
}

namespace {
class ComputeNewStateNames : public Inspector {
    ReferenceMap* refMap;
    cstring prefix;
    cstring acceptName;
    std::map<cstring, cstring> *stateRenameMap;
 public:
    ComputeNewStateNames(ReferenceMap* refMap, cstring prefix, cstring acceptName,
                         std::map<cstring, cstring> *stateRenameMap) :
            refMap(refMap), prefix(prefix), acceptName(acceptName), stateRenameMap(stateRenameMap)
    { CHECK_NULL(refMap); CHECK_NULL(stateRenameMap); }
    bool preorder(const IR::ParserState* state) override {
        cstring newName;
        if (state->name.name == IR::ParserState::reject) {
            newName = state->name.name;
        } else if (state->name.name == IR::ParserState::accept) {
            newName = acceptName;
        } else {
            cstring base = prefix + "_" + state->name.name;
            newName = refMap->newName(base);
        }
        stateRenameMap->emplace(state->name.name, newName);
        return false;  // prune
    }
};

/**
Renames the states in a parser for inlining.  We cannot rely on the
ReferenceMap for identifying states - it is currently inconsistent,
so we rely on the fact that state names only appear in very
specific places.
*/
class RenameStates : public Transform {
    std::map<cstring, cstring> *stateRenameMap;

 public:
    explicit RenameStates(std::map<cstring, cstring> *stateRenameMap) :
            stateRenameMap(stateRenameMap)
    { CHECK_NULL(stateRenameMap); }
    const IR::Node* preorder(IR::Path* path) override {
        // This is certainly a state name, by the way we organized the visitors
        cstring newName = ::get(stateRenameMap, path->name);
        path->name = IR::ID(path->name.srcInfo, newName, path->name.originalName);
        return path;
    }
    const IR::Node* preorder(IR::SelectExpression* expression) override {
        parallel_visit(expression->selectCases, "selectCases", 1);
        prune();
        return expression;
    }
    const IR::Node* preorder(IR::SelectCase* selCase) override {
        visit(selCase->state);
        prune();
        return selCase;
    }
    const IR::Node* preorder(IR::ParserState* state) override {
        if (state->name.name == IR::ParserState::accept ||
            state->name.name == IR::ParserState::reject) {
            prune();
            return state;
        }
        cstring newName = ::get(stateRenameMap, state->name.name);
        state->name.name = newName;
        if (state->selectExpression != nullptr)
            visit(state->selectExpression);
        prune();
        return state;
    }
    const IR::Node* preorder(IR::P4Parser* parser) override {
        visit(parser->states, "states");
        prune();
        return parser;
    }
};
}  // namespace

const IR::Node* GeneralInliner::preorder(IR::ParserState* state) {
    LOG3("Visiting state " << dbp(state));
    auto states = new IR::IndexedVector<IR::ParserState>();
    IR::IndexedVector<IR::StatOrDecl> current;

    // Scan the statements to find a parser call instruction
    auto srcInfo = state->srcInfo;
    auto annotations = state->annotations;
    IR::ID name = state->name;
    for (auto e : state->components) {
        if (!e->is<IR::MethodCallStatement>()) {
            current.push_back(e);
            continue;
        }
        auto call = e->to<IR::MethodCallStatement>();
        if (workToDo->callToInstance.find(call) == workToDo->callToInstance.end()) {
            current.push_back(e);
            continue;
        }

        LOG3("Inlining invocation " << dbp(call));
        auto decl = workToDo->callToInstance[call];
        CHECK_NULL(decl);

        auto called = workToDo->declToCallee[decl];
        auto callee = called->to<IR::P4Parser>();
        // clone the substitution: it may be reused for multiple invocations
        auto substs = new PerInstanceSubstitutions(*workToDo->substitutions[decl]);

        auto mi = MethodInstance::resolve(call->methodCall, refMap, typeMap);
        // Evaluate in and inout parameters in order.
        for (auto param : callee->getApplyParameters()->parameters) {
            auto initializer = mi->substitution.lookup(param);
            LOG3("Looking for " << param->name);
            if (param->direction == IR::Direction::In || param->direction == IR::Direction::InOut) {
                auto arg = substs->paramSubst.lookupByName(param->name);
                if (!arg->expression->equiv(*initializer->expression)) {
                    auto stat = new IR::AssignmentStatement(arg->expression,
                                                            initializer->expression);
                    current.push_back(stat); }
            } else if (param->direction == IR::Direction::Out) {
                auto arg = substs->paramSubst.lookupByName(param->name);
                auto paramType = typeMap->getType(param, true);
                // This is important, since this variable may be used many times.
                DoResetHeaders::generateResets(typeMap, paramType, arg->expression, &current);
            } else if (param->direction == IR::Direction::None) {
                // already set; the value must be the same, or else we cannot compile
                auto prev = substs->paramSubst.lookup(param);
                CHECK_NULL(prev);
                if (!initializer->equiv(*prev))
                    // This is a compile-time constant, since this is a non-directional
                    // parameter, so the value should be independent on the context.
                    ::error("%1%: non-directional parameters must be substitued with the "
                            "same value in all invocations; two different substitutions are "
                            "%2% and %3%", param, initializer, prev);
                continue;
            }
        }

        callee = substs->rename<IR::P4Parser>(refMap, callee);

        cstring nextState = refMap->newName(state->name);
        std::map<cstring, cstring> renameMap;
        ComputeNewStateNames cnn(refMap, callee->name.name, nextState, &renameMap);
        (void)callee->apply(cnn);
        RenameStates rs(&renameMap);
        auto renamed = callee->apply(rs);
        cstring newStartName = ::get(renameMap, IR::ParserState::start);
        auto transition = new IR::PathExpression(IR::ID(newStartName, nullptr));
        auto newState = new IR::ParserState(srcInfo, name, annotations, current, transition);
        states->push_back(newState);
        for (auto s : renamed->to<IR::P4Parser>()->states) {
            if (s->name == IR::ParserState::accept ||
                s->name == IR::ParserState::reject)
                continue;
            states->push_back(s);
        }

        // Prepare next state
        annotations = IR::Annotations::empty;
        name = IR::ID(nextState, nullptr);
        current.clear();

        // Copy back out and inout parameters
        for (auto param : callee->getApplyParameters()->parameters) {
            auto left = mi->substitution.lookup(param)->expression;
            if (param->direction == IR::Direction::InOut ||
                param->direction == IR::Direction::Out) {
                auto arg = substs->paramSubst.lookupByName(param->name);
                if (!left->equiv(*arg->expression)) {
                    auto copyout = new IR::AssignmentStatement(left, arg->expression->clone());
                    current.push_back(copyout); }
            }
        }
    }

    if (!states->empty()) {
        // Create final state
        auto newState = new IR::ParserState(name, annotations,
                                            current, state->selectExpression);
        states->push_back(newState);
        LOG3("Replacing with " << states->size() << " states");
        prune();
        return states;
    }
    prune();
    return state;
}

const IR::Node* GeneralInliner::preorder(IR::P4Parser* caller) {
    // prepares the code to inline
    auto orig = getOriginal<IR::P4Parser>();
    if (toInline->callerToWork.find(orig) == toInline->callerToWork.end()) {
        prune();
        return caller;
    }

    workToDo = &toInline->callerToWork[orig];
    inline_subst(caller, &IR::P4Parser::parserLocals);
    visit(caller->states, "states");
    list->replace(orig, caller);
    workToDo = nullptr;
    prune();
    return caller;
}

}  // namespace P4


text:
package com.mattunderscore.trees.linked.tree;

import com.mattunderscore.trees.mutable.MutableSettableStructuredNode;
import com.mattunderscore.trees.spi.EmptyTreeConstructor;
import com.mattunderscore.trees.spi.NodeToRelatedTreeConverter;
import com.mattunderscore.trees.tree.Tree;

/**
 * Implementation of {@link EmptyTreeConstructor} for {@link LinkedTree}.
 * @author Matt Champion on 12/08/2015
 */
public final class EmptyConstructor<E> implements EmptyTreeConstructor<E, MutableSettableStructuredNode<E>, LinkedTree<E>> {

    @Override
    public LinkedTree<E> build() {
        return new LinkedTree<>(null);
    }

    @Override
    public Class<? extends Tree> forClass() {
        return LinkedTree.class;
    }
}