text:
$(document).ready(function(){
    var pos;
    var points = new Array();
    var canvas;
    var startTime = -1;
    var selectedPointIndex = -1;
	var maxPoints = 200;

    //set up action listeners
    canvas = document.getElementById('voronoiCanvas');
	var clearButton = document.getElementById('voronoiClear');
	clearButton.onclick=function(){clearVoronoiCanvas()};
    canvas.addEventListener('mousedown', function(){ mouseDown()}, false);
    canvas.addEventListener('mouseup', function(){ mouseUp()}, false);
    canvas.addEventListener('mousemove', function(e) {
        pos = getCanvasPos(e);
        mouseMove();
        redraw();
    }, false);

    function getCanvasPos(e){
        var rect = canvas.getBoundingClientRect();
        return {x: e.clientX - rect.left, y: e.clientY - rect.top};
    }

    function mouseDown(){
        startTime = new Date().getTime();
        selectedPointIndex = -1;
        for(i = 0; i < points.length; i++){
            if(Math.abs(points[i].x - pos.x) <= 4 && Math.abs(points[i].y - pos.y) <= 4){
                selectedPointIndex = i;
            }
        }
    }

    function mouseUp(){
        addPoint();
        startTime = -1;
        selectedPointIndex = -1;
    }

    function addPoint()
    {
        if(selectedPointIndex < 0){
			if(points.length < maxPoints){
				points[points.length] = pos;
			}
        } else {
            endTime = new Date().getTime();
            if(startTime > 0){
                if(endTime - startTime < 250){
                    points.splice(selectedPointIndex, 1);
                }
            }
        }
        //remove duplicate points
        var selectedPoint = selectedPointIndex;
        if(selectedPoint < 0){
            //ignore newly added point
            selectedPoint = points.length - 1
        }
        for(i = points.length - 1; i >= 0; i--){
            if(i != selectedPoint && Math.abs(points[i].x - pos.x) <= 8 && Math.abs(points[i].y - pos.y) <= 8){
                points.splice(i, 1);
            }
        }
        redraw();
    }

    function mouseMove(){
        endTime = new Date().getTime();
        if(startTime > 0){
            movePoint();
        }
    }

    function movePoint(){
        if(selectedPointIndex >= 0){
            points[selectedPointIndex] = pos;
        }
    }

    function redraw()
    {
		fixScale();
        var ctx=canvas.getContext("2d");
        ctx.save();
        clearCanvas();
        for(i = 0; i < points.length; i++){
            if(Math.abs(points[i].x - pos.x) <= 4 && Math.abs(points[i].y - pos.y) <= 4){
                if(selectedPointIndex < 0 || i == selectedPointIndex){
					ctx.fillStyle="#FF0000";
                    ctx.fillRect(points[i].x - 2,points[i].y - 2,5,5);
                }
            } else {
				ctx.fillStyle="#000000";
                ctx.fillRect(points[i].x - 1,points[i].y - 1,3,3);
            }
        }
        ctx.restore();
    }

	function fixScale(){
		//fix the canvas scaling problems
		canvas.height = canvas.getContext("2d").canvas.clientHeight;
		canvas.width = canvas.getContext("2d").canvas.clientWidth;
	}

    function clearVoronoiCanvas(){
        points = new Array();
        redraw();
    }

    function clearCanvas()
    {
        //var c=$(".panes div:not(:hidden) canvas")[0];
        var ctx=canvas.getContext("2d");
        ctx.clearRect(0, 0, canvas.width, canvas.height);
    }
});

redpajama_set_name: RedPajamaGithub


text:
var props = require('props');
var unique = require('uniq');
var cache = {};

function Expression(str) {
  this.str = str;
  this.props = unique(props(str));
  this.fn = compile(str, this.props);
}

Expression.prototype.exec = function(scope, context){
  scope = scope || {};
  var args = scope ? values(scope, this.props) : [];
  return this.fn.apply(context, args);
};

Expression.prototype.toString = function(){
  return this.str;
};

function values(obj, keys) {
  return keys.map(function(key){
    return obj[key];
  });
}

function compile(str, props){
  if(cache[str]) return cache[str];
  var args = props.slice();
  args.push('return ' + str);
  var fn = Function.apply(null, args);
  cache[str] = fn;
  return fn;
}

module.exports = Expression;


text:
from http.server import BaseHTTPRequestHandler, HTTPServer
from http import cookies
from socketserver import ThreadingMixIn
import dataManagement
import time
import math

dataStor = None
_timeP = 0

def start(port, data):
    global dataStor
    dataStor = data
    serverAddress = ('', port)
    httpd = HTTPServerThread(serverAddress, HTTPHandler)
    httpd.serve_forever()

def timeF(lable):
    global _timeP
    timeR = math.floor(((time.perf_counter() - _timeP) * 1000000))
    print(lable + ": " + str(timeR))
    _timeP = time.perf_counter()
    return timeR

def timeCalibrate():
    global _timeP
    _timeP = time.perf_counter()

class HTTPHandler(BaseHTTPRequestHandler):

    content = "Server/Website/"
    defaultTitle = "Day of Sagittarius III"
    paths = {"home": "cHome", "user":None, "static":"cStatic", "sagittarius":"cSag"}
    mimes = {
        "jpg": "image/jpeg",
        "jpeg": "image/jpeg",
        "html": "text/html",
        "htm": "text/html",
        "txt": "text/plain",
        "png": "image/png",
        "gif": "image/gif",
        "css": "text/css",
        "js": "application/javascript",
        "json": "application/json",
        "mp4": "video/mp4",
        "ico": "image/x-icon",
        "ts": "application/typescript"}

    def do_HEAD(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.handleCookies()
        self.end_headers()
    def do_GET(self):
        #self.totalTime = 0
        #timeCalibrate()
        self.statusCode = 200
        self.mime = "text/html"
        self.sendCookies = True
        body = bytes(self.route(), "utf8")
        #self.totalTime += timeF("Body")
        self.send_response(self.statusCode)
        self.send_header("Content-type", self.mime)
        if self.sendCookies: self.handleCookies()
        #self.totalTime += timeF("Cookies")
        self.end_headers()
        self.wfile.write(body)
        #self.totalTime += timeF("Write")
        #print("Total: " + str(self.totalTime))
        #print()

    def handleCookies(self):
        global dataStor
        cook = cookies.SimpleCookie()
        if "Cookie" in self.headers:
            cook.load(self.headers["Cookie"])
            if "session" in cook:
                print("session")
                self.user = dataStor.getUser(cook["session"].value)
                if self.user != None:
                    print(self.user)
                    return
        user = dataStor.makeUser()
        cook["session"] = user.getSession()
        cook["session"]["path"] = "/"
        cook["session"]["max-age"] = 259200
        self.send_header("Set-Cookie", str(cook["session"])[12:])
        self.user = user

    def log_message(self, format, *args):
        return

    def route(self):
        path = self.path.split('/')
        if self.path == "/":
            return self.cHome()
        elif path[1] in self.paths:
            if len(path) == 2 or path[2] == "":
                return getattr(self, self.paths[path[1]])()
            else:
                return getattr(self, self.paths[path[1]])(path[2])
        else:
            self.statusCode = 404
            return self.cHome("error")

    def cHome(self, view = "index"):
        if view == "index":
            return self.layout(self.readFile("home/index.html"))
        elif view == "about":
            return self.layout(self.readFile("home/about.html"))
        else:
            fContent = self.readFile("home/error.html")
            if(self.statusCode == 200):
                self.statusCode = 403
            fContent = fContent.format(error = self.statusCode)
            return self.layout(fContent)

    def cSag(self, view = "game"):
        if view == "game":
            return self.layout(self.readFile("sagittarius/game.html"))
        else:
            return self.cHome("error")

    def cStatic(self, unused):
        self.sendCookies = False
        path = self.path[len("/"):]
        try:
            print(path + str(path.rindex(".") + 1))
            fContent = self.readFile(path)
            self.mime = self.mimes[path[path.rindex(".") + 1:]]
            return fContent
        except (IOError, KeyError) as e:
            print("error: " + path)
            return self.cHome("error")

    def readFile(self, fPath):
        with open(self.content + fPath) as f:
            fContent = f.read()
            f.close()
            return fContent

    def layout(self, pContent = None, pTitle = None):
        pTitle = pTitle or self.defaultTitle
        with open(self.content + "layout.html") as f:
                fLayout = f.read()
                f.close()
                fLayout = fLayout.format(title = pTitle, content = pContent)
                return fLayout

class HTTPServerThread(ThreadingMixIn, HTTPServer):
    '''Use this to handle concurent connections for now'''


text:
@interface KKCategoriesVC ()<KKDropDownMenuDelegate>
@property (weak, nonatomic)KKDropDownMenu *menu;

@end

@implementation KKCategoriesVC

#pragma mark - lifecycle
-(void)loadView{

    KKDropDownMenu *menu = [KKDropDownMenu dropDownMenu];
    self.menu = menu;
    self.menu.delegate = self;
    self.view = menu;
    NSArray *categories = [KKMetaDataTool sharedMetaDataTool].categories;
    menu.items = categories;
}

- (void)viewDidLoad {

    [super viewDidLoad];

    self.preferredContentSize = CGSizeMake(350, 480);
}

#pragma mark - KKDropDownMenuDelegate

-(void)dropDownMenu:(KKDropDownMenu *)dpMenu mainRow:(NSInteger)row{

    KKCategory *category = self.menu.items[row];

    if(category.subcategories.count == 0){

        //sent notification
        [KKNotificationCenter postNotificationName:KKCategoryDidSelectNotification object:nil userInfo:@{KKSelectedCategory:category}];
    }else{//category.subcategories.count>0

        //控制再次点击方才选中的主category时, subCategory 可以显示方才选中的
        if(self.selectedCategory == category){

            self.selectedSubCategory = self.selectedSubCategory;
        }
    }
}

-(void)dropDownMenu:(KKDropDownMenu *)dpMenu subRow:(NSInteger)subRow ofMain:(NSInteger)mainRow{

    KKCategory *category = dpMenu.items[mainRow];
    NSArray *subCategorys = category.subcategories;
    NSString *subCategory = subCategorys[subRow];

    //sent notification
    [KKNotificationCenter postNotificationName:KKCategoryDidSelectNotification object:nil userInfo:@{KKSelectedSubCategory:subCategory,KKSelectedCategory:category}];
}

#pragma mark - public methods
-(void)setSelectedCategory:(KKCategory *)selectedCategory{

    _selectedCategory = selectedCategory;
    NSInteger mainRow = [self.menu.items indexOfObject:selectedCategory];
    [self.menu selectedMainRow:mainRow];
}

-(void)setSelectedSubCategory:(NSString *)selectedSubCategory{

    _selectedSubCategory = selectedSubCategory;
    NSArray *subCategories = self.selectedCategory.subcategories;
    NSInteger subRow = [subCategories indexOfObject:selectedSubCategory];
    [self.menu selectedSubRow:subRow];
}
@end


text:
import CustomTitleInput from './CustomTitleInput'

export default CustomTitleInput


text: export { default } from 'ember-cli-uniq/components/uni-modal';


text:
<?php
namespace Ds\Bundle\CommunicationBundle\Model;

use Ds\Bundle\CommunicationBundle\Entity\Content;
use Ds\Bundle\CommunicationBundle\Entity\Message;
use Ds\Bundle\TransportBundle\Model\AbstractMessageEvent;

interface MessageContentBuilderInterface
{

    /**
     * @param Message $message
     * @param Content $content
     *
     * @return boolean
     */
    public function compileMessage(Message $message , $recipient, ContentTemplate $contentTemplate );

}


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>has_trivial_default_constructor</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.TypeTraits">
<link rel="up" href="../reference.html" title="Alphabetical Reference">
<link rel="prev" href="has_trivial_cp_cons.html" title="has_trivial_copy_constructor">
<link rel="next" href="has_trivial_destructor.html" title="has_trivial_destructor">

Home
Libraries
People
FAQ
More

has_trivial_default_constructor

        See has_trivial_constructor.

Copyright © 2000, 2011 Adobe Systems Inc, David Abrahams,
      Frederic Bron, Steve Cleary, Beman Dawes, Glen Fernandes, Aleksey Gurtovoy,
      Howard Hinnant, Jesse Jones, Mat Marcus, Itay Maman, John Maddock, Alexander
      Nasonov, Thorsten Ottosen, Roman Perepelitsa, Robert Ramey, Jeremy Siek, Robert
      Stewart and Steven Watanabe

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.ApiManagement;

namespace Azure.ResourceManager.ApiManagement.Models
{
    /// <summary> Paged Diagnostic list representation. </summary>
    internal partial class DiagnosticListResult
    {
        /// <summary> Initializes a new instance of DiagnosticListResult. </summary>
        internal DiagnosticListResult()
        {
            Value = new ChangeTrackingList<DiagnosticContractData>();
        }

        /// <summary> Initializes a new instance of DiagnosticListResult. </summary>
        /// <param name="value"> Page values. </param>
        /// <param name="count"> Total record count number across all pages. </param>
        /// <param name="nextLink"> Next page link if any. </param>
        internal DiagnosticListResult(IReadOnlyList<DiagnosticContractData> value, long? count, string nextLink)
        {
            Value = value;
            Count = count;
            NextLink = nextLink;
        }

        /// <summary> Page values. </summary>
        public IReadOnlyList<DiagnosticContractData> Value { get; }
        /// <summary> Total record count number across all pages. </summary>
        public long? Count { get; }
        /// <summary> Next page link if any. </summary>
        public string NextLink { get; }
    }
}


text:
import fluff
from custom.m4change.constants import PNC_CHILD_IMMUNIZATION_AND_REG_HOME_DELIVERED_FORMS, \
    BOOKING_FORMS, BOOKED_AND_UNBOOKED_DELIVERY_FORMS, BOOKING_FOLLOW_UP_AND_LAB_RESULTS_FORMS

class AncRegistrationCalculator(fluff.Calculator):

    @fluff.date_emitter
    def total(self, form):
        if form.xmlns in BOOKING_FORMS:
            yield [form.received_on.date(), 1]

class Anc4VisitsCalculator(fluff.Calculator):

    @fluff.date_emitter
    def total(self, form):
        if form.xmlns in BOOKING_FOLLOW_UP_AND_LAB_RESULTS_FORMS:
            visits = form.form.get("visits", "")
            if len(visits) > 0 and visits.isdigit() and int(visits) == 4:
                yield [form.received_on.date(), 1]

class FacilityDeliveryCctCalculator(fluff.Calculator):

    @fluff.date_emitter
    def total(self, form):
        if form.xmlns in BOOKED_AND_UNBOOKED_DELIVERY_FORMS:
            yield [form.received_on.date(), 1]

class PncAttendanceWithin6WeeksCalculator(fluff.Calculator):

    @fluff.date_emitter
    def total(self, form):
        if form.form.get("date_delivery", None) is not None:
            date_received_on = form.received_on.date()
            if form.xmlns in PNC_CHILD_IMMUNIZATION_AND_REG_HOME_DELIVERED_FORMS \
                    and (date_received_on - form.form["date_delivery"]).days < 42:
                yield [date_received_on, 1]

class NumberOfFreeSimsGivenCalculator(fluff.Calculator):

    @fluff.date_emitter
    def total(self, form):
        if form.xmlns in BOOKING_FORMS and form.form.get("free_sim", "") == 'yes':
                yield [form.received_on.date(), 1]

class MnoCalculator(fluff.Calculator):

    def __init__(self, value):
        super(MnoCalculator, self).__init__()
        self.mno_type_value = value

    @fluff.date_emitter
    def total(self, form):
        if form.xmlns in BOOKING_FORMS and self.mno_type_value == form.form.get("mno", ""):
            yield [form.received_on.date(), 1]


text:
package org.efaps.esjp.jms.actions;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import org.efaps.db.PrintQuery;
import org.efaps.esjp.jms.AbstractObject;
import org.efaps.esjp.jms.annotation.Attribute;
import org.efaps.esjp.jms.annotation.Type;
import org.efaps.esjp.jms.attributes.AttrSetting;
import org.efaps.esjp.jms.attributes.IAttribute;
import org.efaps.util.EFapsException;

/**
 * TODO comment!
 *
 * @author The eFaps Team
 * @version $Id$
 */
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "print")
@XmlType(name = "action.print")
public class Print
    extends AbstractAction
{

    /**
     * {@inheritDoc}
     */
    @Override
    public Object execute()
        throws EFapsException
    {
        for (final AbstractObject object : getObjects()) {
            final Type typeAnno = object.getClass().getAnnotation(Type.class);
            if (typeAnno != null) {
                final PrintQuery print = new PrintQuery(object.getOid());
                final Method[] methods = object.getClass().getDeclaredMethods();
                final Map<Attribute, IAttribute<?>> attributes = new HashMap<Attribute, IAttribute<?>>();
                for (final Method method : methods) {
                    final Attribute attributeAnno = method.getAnnotation(Attribute.class);
                    if (attributeAnno != null) {
                        try {
                            final IAttribute<?> value = (IAttribute<?>) method.invoke(object);
                            if (value.hasSetting(AttrSetting.PRINT_INCLUDE)) {
                                print.addAttribute(attributeAnno.name());
                                attributes.put(attributeAnno, value);
                            }
                        } catch (final IllegalArgumentException e) {
                            throw new EFapsException("IllegalArgumentException", e);
                        } catch (final IllegalAccessException e) {
                            throw new EFapsException("IllegalAccessException", e);
                        } catch (final InvocationTargetException e) {
                            throw new EFapsException("InvocationTargetException", e);
                        }
                    }
                }
                if (print.execute()) {
                    for (final Entry<Attribute, IAttribute<?>> entry : attributes.entrySet()) {
                        final Object value = print.getAttribute(entry.getKey().name());
                        entry.getValue().setValue(value);
                    }
                }
            }
        }
        return this;
    }

}


text:
require "jquery/masonry/rails/version"

module Jquery
  module Masonry
      module Rails
        class Engine < ::Rails::Engine
        end
      end
  end
end


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

<title>PutOperationContext (Apache Geode 1.0.0-incubating.M2)</title>
<meta name="date" content="2016-04-13">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.gemstone.gemfire.cache.operations

Class PutOperationContext

java.lang.Object

com.gemstone.gemfire.cache.operations.OperationContext

com.gemstone.gemfire.cache.operations.KeyOperationContext

com.gemstone.gemfire.cache.operations.KeyValueOperationContext

com.gemstone.gemfire.cache.operations.PutOperationContext

public class PutOperationContext
extends KeyValueOperationContext

Encapsulates an OperationContext.OperationCode.PUT region operation having both key
 and value objects for for both the pre-operation case and for post-operation
 updates.

Since:

5.5

Nested Class Summary

Nested classes/interfaces inherited from class com.gemstone.gemfire.cache.operations.OperationContext

OperationContext.OperationCode

Field Summary

Fields

Modifier and Type
Field and Description

static byte
CREATE

Indicates that the operation results in a create of the key.

static byte
UNKNOWN

Indicates that it is not known whether the operation results in a create or
 in an update.

static byte
UPDATE

Indicates that the operation results in an update of the key.

Constructor Summary

Constructors

Constructor and Description

PutOperationContext(java.lang.Object key,
                   java.lang.Object value,
                   boolean isObject)

Constructor for the operation.

PutOperationContext(java.lang.Object key,
                   java.lang.Object value,
                   boolean isObject,
                   boolean postOperation)

Constructor for the operation.

PutOperationContext(java.lang.Object key,
                   java.lang.Object value,
                   boolean isObject,
                   byte opType,
                   boolean isPostOperation)

Constructor for the operation.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

OperationContext.OperationCode
getOperationCode()

Return the operation associated with the OperationContext
 object.

byte
getOpType()

Return whether the operation is a create or update or unknown.

Methods inherited from class com.gemstone.gemfire.cache.operations.KeyValueOperationContext

getDeserializedValue, getSerializedValue, getValue, isObject, setSerializedValue, setValue

Methods inherited from class com.gemstone.gemfire.cache.operations.KeyOperationContext

getCallbackArg, getKey, isPostOperation, setCallbackArg, setPostOperation

Methods inherited from class com.gemstone.gemfire.cache.operations.OperationContext

isClientUpdate, isClientUpdate

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

UNKNOWN

public static final byte UNKNOWN

Indicates that it is not known whether the operation results in a create or
 in an update. The authorization callback should explicitly use the
 Region.containsKey(java.lang.Object) method to determine it when required.

See Also:

Constant Field Values

CREATE

public static final byte CREATE

Indicates that the operation results in a create of the key.

See Also:

Constant Field Values

UPDATE

public static final byte UPDATE

Indicates that the operation results in an update of the key.

See Also:

Constant Field Values

Constructor Detail

PutOperationContext

public PutOperationContext(java.lang.Object key,
                           java.lang.Object value,
                           boolean isObject)

Constructor for the operation.

Parameters:

key - the key for this operation

value - the value for this operation

isObject - true when the value is an object; false when it is a raw
                byte array

Since:

6.5

PutOperationContext

public PutOperationContext(java.lang.Object key,
                           java.lang.Object value,
                           boolean isObject,
                           boolean postOperation)

Constructor for the operation.

Parameters:

key - the key for this operation

value - the value for this operation

isObject - true when the value is an object; false when it is a raw
                byte array

postOperation - true if the context is at the time of sending updates

Since:

6.5

PutOperationContext

public PutOperationContext(java.lang.Object key,
                           java.lang.Object value,
                           boolean isObject,
                           byte opType,
                           boolean isPostOperation)

Constructor for the operation.

Parameters:

key - the key for this operation

value - the value for this operation

isObject - true when the value is an object; false when it is a raw
                byte array

opType - flag to indicate whether the operation is create/update or
                unknown

isPostOperation - true if the context is at the time of sending updates

Since:

6.5

Method Detail

getOperationCode

public OperationContext.OperationCode getOperationCode()

Return the operation associated with the OperationContext
 object.

Specified by:

getOperationCode in class KeyOperationContext

Returns:

OperationCode.PUT.

getOpType

public byte getOpType()

Return whether the operation is a create or update or unknown.

 The user should check against CREATE,
 UPDATE, UNKNOWN.
 For the UNKNOWN case, the authorization
 callback should explicitly invoke Region.containsKey(java.lang.Object) to determine
 if it is create or update when required.

Returns:

one of CREATE,
         UPDATE,
         UNKNOWN

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
import os
import numpy as np

from nose.plugins.attrib import attr
from numpy.testing.decorators import skipif
from nose.tools import ok_, eq_, raises, assert_raises

import scitran.data as scidata
import scitran.data.tempdir as tempfile

# data is stored separately in data_testdata
# located at the top level of the testing directory
DATADIR = os.path.join(os.path.dirname(__file__), 'testdata')
if not os.path.isdir(DATADIR):
    DATADIR = None

class Test_Montage(object):

    @skipif(not DATADIR)
    def setUp(self):
        self.ds = scidata.parse(os.path.join(DATADIR, 'ge_dcm_mr_localizer.tgz'), load_data=True)

    @skipif(not DATADIR)
    def test001_write_png(self):
        """flat png montage"""
        with tempfile.TemporaryDirectory() as tempdir:
            outbase = os.path.join(tempdir, 'trashme')
            ok_(scidata.write(self.ds, self.ds.data, outbase=outbase, filetype='montage', mtype='png'))

    @skipif(not DATADIR)
    def test002_write_dir(self):
        """directory jpeg montage"""
        with tempfile.TemporaryDirectory() as tempdir:
            outbase = os.path.join(tempdir, 'trashme')
            ok_(scidata.write(self.ds, self.ds.data, outbase=outbase, filetype='montage', mtype='dir'))

    @skipif(not DATADIR)
    def test003_write_pyrdb(self):
        with tempfile.TemporaryDirectory() as tempdir:
            outbase = os.path.join(tempdir, 'trashme')
            ok_(scidata.write(self.ds, self.ds.data, outbase=outbase, filetype='montage', mtype='sqlite'))

    @skipif(not DATADIR)
    def test004_get_size(self):
        with tempfile.TemporaryDirectory() as tempdir:
            outbase = os.path.join(tempdir, 'trashme')
            scidata.write(self.ds, self.ds.data, outbase=outbase, filetype='montage')
            outfile = os.path.join(tempdir, os.listdir(tempdir)[0])
            ok_(scidata.medimg.montage.get_info(outfile))              # gets made?

    @skipif(not DATADIR)
    def test005_get_tile(self):
        with tempfile.TemporaryDirectory() as tempdir:
            outbase = os.path.join(tempdir, 'trashme')
            scidata.write(self.ds, self.ds.data, outbase=outbase, filetype='montage')
            outfile = os.path.join(tempdir, os.listdir(tempdir)[0])
            ok_(scidata.medimg.montage.get_tile(outfile, 0, 0, 0))     # all montage have 0, 0, 0


text:
This intention converts selected integer literal (written in either decimal or octal notation)
into hexadecimal notation.


text:
csv2sql
=======

CSV to SQL converter.

Installation
------------

.. code::

    $ ./setup.py install


text:
import {OperationOps, PairingString, AggFuncName, OrderingCondition
        } from './index'
import * as Catalog from './Catalog'

// literals are strings
export type OperandType = string | Operation | Column
export type Ordering = [Column | string, OrderingCondition]
export type ColumnValueType = Catalog.Column | RelFunction | string
export type Columnish = Column | RelFunction | string
export type Joinish = Join | PairingOperation
export type HighLevelRelationish = Relation | Join | Restriction | Projection |
                                   Rename | Operation | Aggregation

/* enumerated strings attached to class instances.
 * Useful for JSON output.
 * CAN be used for quick comparison, but **instanceof should be prefered**.
 */
export const enum TypeString {
  Aggregation = "aggregation",
  Restriction = "restriction",
  Projection = "projection",
  Rename = "rename",
  Relation = "relation",
  Column = "column",
  Conditional = "conditional",
  Join = "join",
  Function = "funct",
  Operation = "op"
}

export const enum HLRTypeString {
  Aggregation = TypeString.Aggregation,
  Restriction = TypeString.Restriction,
  Projection = TypeString.Projection,
  Rename = TypeString.Rename,
  Relation = TypeString.Relation,
  Join = TypeString.Join,
  Operation = TypeString.Operation
}

export abstract class HLR {
  readonly abstract type: HLRTypeString

  constructor() {}
}

export class Operation extends HLR {
  readonly type = HLRTypeString.Operation
  op: OperationOps | PairingString
  lhs: OperandType | HighLevelRelationish
  rhs: OperandType | HighLevelRelationish

  constructor(op: OperationOps | PairingString,
              lhs: OperandType | HighLevelRelationish,
              rhs: OperandType | HighLevelRelationish) {
    super()
    this.op = op
    this.lhs = lhs
    this.rhs = rhs
  }
}

export interface PairingOperation extends Operation {
  op: PairingString
  lhs: HighLevelRelationish
  rhs: HighLevelRelationish
}

export class Column {
  readonly type = TypeString.Column
  relation: Relation | null
  target: ColumnValueType
  as: string | null

  constructor(relation: Relation | null,
              target: ColumnValueType,
              As: string | null = null) {
    this.relation = relation
    this.target = target
    this.as = As || null
  }

  alias(alias?: string) {
    if (!alias)
      return this
    return new Column(this.relation, this.target, alias)
  }
}

export class RelFunction {
  readonly type = TypeString.Function
  fname: AggFuncName
  expr: '*' | Column // TODO: support correct args
  hlr?: HighLevelRelationish

  constructor(fname: AggFuncName,
              expr: '*' | Column,
              hlr?: HighLevelRelationish) {
    this.fname = fname
    this.expr = expr
    if (hlr)
      this.hlr = hlr
  }

  getName(): string {
    if (this.expr === '*')
      return `${this.fname}_*`
    else if (this.expr.as)
      return `${this.fname}_${this.expr.as}`
    else {
      console.error("Failure to name RelFunction", this)
      throw new Error("Couldn't produce name for RelFunction")
    }
  }
}

export class Aggregation extends HLR {
  readonly type = HLRTypeString.Aggregation
  attributes: Column[]
  functions: RelFunction[]
  relation: HighLevelRelationish
  renames: string[]

  constructor(attributes: Column[], functions: RelFunction[],
              relation: HighLevelRelationish, renames: string[]) {
    super()
    this.attributes = attributes
    this.functions = functions
    this.relation = relation
    this.renames = renames

    if (renames.length &&
        renames.length !== (attributes.length + functions.length)) {
      const [rl, al, fl] = [renames.length, attributes.length, functions.length]
      console.error("Bad number of renames;", renames, attributes, functions)
      throw new Error(`Bad number of renames; ${rl} != ${al} + ${fl}`)
    }
  }
}

export type ThetaOp = 'eq' | 'neq' | 'leq' | 'geq' | '<' | '>' | 'and' | 'or' |
                      'in'
export type ConditionalArgumentType = OperandType | RelFunction | Conditional

export class Conditional {
  readonly type = TypeString.Conditional
  operation: ThetaOp
  lhs: ConditionalArgumentType
  rhs: ConditionalArgumentType | OperandType[]

  constructor(op: ThetaOp,
              lhs: ConditionalArgumentType,
              rhs: ConditionalArgumentType | OperandType[]) {
    this.operation = op.toLowerCase() as ThetaOp
    this.lhs = lhs
    this.rhs = rhs
  }
}

export class Restriction extends HLR {
  readonly type = HLRTypeString.Restriction
  conditions: Conditional
  args: HighLevelRelationish

  constructor(conditions: Conditional, args: HighLevelRelationish) {
    super()
    this.conditions = conditions
    this.args = args
  }
}

export class Projection extends HLR {
  readonly type = HLRTypeString.Projection
  columns: Array<string|Column>
  args: HighLevelRelationish

  constructor(columns: Array<string|Column>, args: HighLevelRelationish) {
    super()
    this.columns = columns
    this.args = args
  }
}

type _RenameInputType = Relation | Column | RelFunction |
                           Rename | string

export class Rename extends HLR {
  readonly type = HLRTypeString.Rename
  input: _RenameInputType
  output: string
  args: HighLevelRelationish

  constructor(input: _RenameInputType,
              output: string,
              args: HighLevelRelationish) {
    super()
    this.input = input
    this.output = output
    this.args = args
  }
}

export class Relation extends HLR {
  static fromCata(target: Catalog.Relation): Relation {
    return new Relation(target.name, target)
  }

  readonly type = HLRTypeString.Relation
  readonly name: string
  readonly target: Catalog.Relation

  constructor(name: string, target: Catalog.Relation) {
    super()
    this.name = name
    this.target = target
  }
}

export type JoinCond = "cross" | "left" | "right" | Conditional

// cross
// natural (no condition)
// theta join (with condition)
// semi (left and right)
export class Join extends HLR {
  readonly type = HLRTypeString.Join
  lhs: HighLevelRelationish
  rhs: HighLevelRelationish
  condition: JoinCond

  constructor(lhs: HighLevelRelationish,
              rhs: HighLevelRelationish,
              cond: JoinCond) {
    super()
    this.lhs = lhs
    this.rhs = rhs
    this.condition = cond
  }
}


text:
package com.example.component;

import arez.annotations.ArezComponent;
import arez.annotations.Priority;
import arez.annotations.SuppressArezWarnings;

// This uses the CLASS retention suppression
@SuppressArezWarnings( "Arez:UnnecessaryDefaultPriority" )
@ArezComponent( allowEmpty = true, defaultPriority = Priority.LOW )
public abstract class Suppressed2UnnecessaryDefaultPriorityPresentComponent
{
}


text:
package net.liftweb
package actor

import java.util.concurrent._

/**
 * Rules for dealing with thread pools, both in lift-actor and
 * in lift-util
 */
object ThreadPoolRules {
  /**
   * When threads are created in the thread factories, should
   * they null the context class loader.  By default false,
   * but it you set it to true, Tomcat complains less about stuff.
   * Must be set in the first line of Boot.scala
   */
  @volatile var nullContextClassLoader: Boolean = false
}

/**
 * LAPinger is for scheduling LiftActors to be pinged with an arbitrary message at some point
 * in the future.
 */
object LAPinger {

  /**The underlying java.util.concurrent.ScheduledExecutor */
  private var service = Executors.newSingleThreadScheduledExecutor(TF)

  /**
   * Re-create the underlying SingleThreadScheduledExecutor
   */
  def restart: Unit = synchronized {
    if ((service eq null) || service.isShutdown)
      service = Executors.newSingleThreadScheduledExecutor(TF)
  }

  /**
   * Shut down the underlying SingleThreadScheduledExecutor
   */
  def shutdown: Unit = synchronized {
    service.shutdown
  }

  /**
   * Schedules the sending of a message to occur after the specified delay.
   *
   * @param to The LiftActor to send the message to.
   * @param msg The message to send.
   * @param delay The number of milliseconds to delay before sending msg
   * @return a ScheduledFuture which sends the msg to
   * the to Actor after the specified TimeSpan delay.
   */
  def schedule[T](to: SpecializedLiftActor[T], msg: T, delay: Long): ScheduledFuture[Unit] = {
    val r = new Callable[Unit] {
      def call: Unit = {
        to ! msg
      }
    }
    try {
      service.schedule(r, delay, TimeUnit.MILLISECONDS)
    } catch {
      case e: RejectedExecutionException => throw PingerException(msg + " could not be scheduled on " + to, e)
    }
  }

}

/**
 * Exception thrown if a ping can't be scheduled.
 */
case class PingerException(msg: String, e: Throwable) extends RuntimeException(msg, e)

private object TF extends ThreadFactory {
  val threadFactory = Executors.defaultThreadFactory()

  def newThread(r: Runnable): Thread = {
    val d: Thread = threadFactory.newThread(r)
    d setName "ActorPinger"
    d setDaemon true
    if (ThreadPoolRules.nullContextClassLoader) {
      d setContextClassLoader null
    }
    d
  }
}


text:
import {
  base64DecodeToBytes,
  base64EncodeFromBytes,
  base64UrlDecodeToBytes,
  base64UrlEncodeFromBytes,
} from '../../../src/utils/base64';
import {
  stringToBytes,
  utf8Decode,
  utf8Encode,
} from '../../../src/utils/bytes';

describe('base64 <> utf-8 encode/decode', () => {
  const testCases = [
    'SimplyFoo',
    'Unicode௵Z加䅌ਇ☎Èʘغޝ',
    'Symbols/.,+-_()*&^%$#@!`~:="\'',
  ];
  const scenarios = ['NativeTextEncoding', 'PolyfillTextEncoding', 'Mixed'];

  scenarios.forEach(scenario => {
    describe(scenario, () => {
      const oldTextEncoder = window.TextEncoder;
      const oldTextDecoder = window.TextDecoder;
      beforeEach(() => {
        // Forces use of the TextEncoding polyfill
        if (scenario == 'PolyfillTextEncoding') {
          window.TextEncoder = undefined;
          window.TextDecoder = undefined;
        }
        // Tests a mixture where encoding is done by the polyfill but decoding
        // is done by the native TextDecoder
        if (scenario == 'Mixed') {
          window.TextEncoder = undefined;
        }
      });

      afterEach(() => {
        window.TextEncoder = oldTextEncoder;
        window.TextDecoder = oldTextDecoder;
      });

      describe('base64Encode/base64Decode', () => {
        testCases.forEach(testCase => {
          it(testCase, () => {
            const utf8Bytes = utf8Encode(testCase);
            const encoded = base64EncodeFromBytes(utf8Bytes);
            expect(encoded).not.to.equal(testCase);
            const decodedUtf8Bytes = base64DecodeToBytes(encoded);
            const decoded = utf8Decode(decodedUtf8Bytes);
            expect(decoded).to.equal(testCase);
          });
        });
      });

      describe('base64UrlEncode/base64UrlDecode', () => {
        testCases.forEach(testCase => {
          it(testCase, () => {
            const utf8Bytes = utf8Encode(testCase);
            const encoded = base64UrlEncodeFromBytes(utf8Bytes);
            expect(encoded).not.to.equal(testCase);
            expect(encoded).not.to.match(/[+/=]/g);
            const decodedUtf8Bytes = base64UrlDecodeToBytes(encoded);
            const decoded = utf8Decode(decodedUtf8Bytes);
            expect(decoded).to.equal(testCase);
          });
        });
      });
    });
  });
});

describe('base64UrlDecodeToBytes', () => {
  it('should map a sample string appropriately', () => {
    expect(base64UrlDecodeToBytes('AQAB'))
        .to.deep.equal(new Uint8Array([1, 0, 1]));
    expect(base64UrlDecodeToBytes('_-..'))
        .to.deep.equal(new Uint8Array([255]));
  });

  it('should handle padded and unpadded input', () => {
    expect(base64UrlDecodeToBytes('cw')).to.deep.equal(stringToBytes('s'));
    expect(base64UrlDecodeToBytes('cw'))
        .to.deep.equal(base64UrlDecodeToBytes('cw..'));
    expect(base64UrlDecodeToBytes('c3U')).to.deep.equal(stringToBytes('su'));
    expect(base64UrlDecodeToBytes('c3U'))
        .to.deep.equal(base64UrlDecodeToBytes('c3U.'));
    expect(base64UrlDecodeToBytes('c3Vy')).to.deep.equal(stringToBytes('sur'));
  });

  it('should signal an error with bad input characters', () => {
    expect(() => base64UrlDecodeToBytes('@#*#')).to.throw();
  });

  it('should signal an error with bad padding', () => {
    expect(() => base64UrlDecodeToBytes('c3Vy.')).to.throw();
  });
});

describe('base64DecodeToBytes', () => {
  it('should map a sample string appropriately', () => {
    expect(base64DecodeToBytes('AQAB'))
        .to.deep.equal(new Uint8Array([1, 0, 1]));
    expect(base64DecodeToBytes('/+=='))
        .to.deep.equal(new Uint8Array([255]));
  });

  it('should handle padded and unpadded input', () => {
    expect(base64DecodeToBytes('cw')).to.deep.equal(stringToBytes('s'));
    expect(base64DecodeToBytes('cw'))
        .to.deep.equal(base64DecodeToBytes('cw=='));
    expect(base64DecodeToBytes('c3U')).to.deep.equal(stringToBytes('su'));
    expect(base64DecodeToBytes('c3U'))
        .to.deep.equal(base64DecodeToBytes('c3U='));
    expect(base64DecodeToBytes('c3Vy')).to.deep.equal(stringToBytes('sur'));
  });

  it('should signal an error with bad input characters', () => {
    expect(() => base64DecodeToBytes('@#*#')).to.throw();
  });

  it('should signal an error with bad padding', () => {
    expect(() => base64DecodeToBytes('c3Vy=')).to.throw();
  });
});

describe('base64EncodeFromBytes', () => {
  it('should encode a bytes array to base64url string correctly', () => {
    expect(base64UrlEncodeFromBytes(new Uint8Array()))
        .to.equal('');
    expect(base64UrlEncodeFromBytes(stringToBytes('s')))
        .to.equal('cw..');
    expect(base64UrlEncodeFromBytes(stringToBytes('su')))
        .to.equal('c3U.');
    expect(base64UrlEncodeFromBytes(stringToBytes('sur')))
        .to.equal('c3Vy');
    expect(base64UrlEncodeFromBytes(new Uint8Array([255, 239])))
        .to.equal('_-8.');
  });

  it('should encode a bytes array to base64 string correctly', () => {
    expect(base64EncodeFromBytes(new Uint8Array()))
        .to.equal('');
    expect(base64EncodeFromBytes(stringToBytes('s')))
        .to.equal('cw==');
    expect(base64EncodeFromBytes(stringToBytes('su')))
        .to.equal('c3U=');
    expect(base64EncodeFromBytes(stringToBytes('sur')))
        .to.equal('c3Vy');
    expect(base64EncodeFromBytes(new Uint8Array([255, 239])))
        .to.equal('/+8=');
  });
});


text:
<?php
/**
 * funciones helpers ejemplos
 *
 * snake_case
 * camel_case
 *
 * Nota este archivo se debe cargar al iniciar el framework
 */

use ForeverPHP\Core\Helpers\{ArrayHelpers, RouteHelpers, StringHelpers};

if (!function_exists('array_add')) {
    /**
     * [array_add description]
     *
     * @param  [type] $array [description]
     * @param  [type] $key   [description]
     * @param  [type] $value [description]
     * @return [type]        [description]
     */
    function array_add($array, $key, $value) {
        return ArrayHelpers::arrayAdd($array, $key, $value);
    }
}

if (!function_exists('camel_case')) {
    function camel_case() {

    }
}

if (!function_exists('length')) {
    function length($string) {
        return StringHelpers::length($string);
    }
}

if (!function_exists('lower')) {
    function lower($string) {
        return StringHelpers::lower($string);
    }
}

if (!function_exists('snake_case')) {
    function snake_case() {

    }
}

if (!function_exists('upper')) {
    function upper($string) {
        return StringHelpers::upper($string);
    }
}


text:
/* Take a fresh API dump and bake it into the sources */

var apiDumpURL = 'http://api.highcharts.com/highcharts/option/dump.json',
    request = require('request'),
    fs = require('fs'),
    apiSorted = {},
    license = fs.readFileSync(__dirname + '/../LICENSE'),
    ignores = {
        'chart--spacing': true,
        'chart--margin': true,
        // 'chart--marginLeft': true,
        // 'chart--marginBottom': true,
        // 'chart--marginTop': true,
        // 'chart--marginRight': true,
        'data': true,
        'responsive': true,
        'responsive--rules': true
    }
;

require('colors');

console.log('Higcharts Advanced Options Updater'.green);
console.log('Fetching latest API dump...'.bold);

function extractType(str) {
    var s = str.indexOf('<'),
        st
    ;

    if (s >= 0) {
        return str.substr(s + 1, str.indexOf('>') - s - 1);
    }

    return false;
}

function removeType(str) {
    var t = extractType(str);

    if (t) {
        return str.replace('<' + t + '>', '');
    }
    return str;
}

function sortAPI(api) {
    // api.sort(function (a, b) {
    //     return a.name.replace(/\-/g, ' ').localeCompare(b.name.replace(/\-/g, ''));
    // });

    api.forEach(function (entry) {
        var st = extractType(entry.name);
        entry.name = removeType(entry.name);

        if (!apiSorted[entry.name]) {

            apiSorted[entry.name] = entry;

            if (st !== false) {
                entry.subType = {};
                entry.subType[st] = true;
            }
        } else if (st) {
            apiSorted[entry.name].subType = apiSorted[entry.name].subType || {};
            //apiSorted[entry.name].subType.push(st);
            apiSorted[entry.name].subType[st] = true;
            apiSorted[entry.name].values = apiSorted[entry.name].values || entry.values;
            apiSorted[entry.name].defaults = apiSorted[entry.name].defaults || entry.defaults;

            apiSorted[entry.name].subTypeDefaults = apiSorted[entry.name].subTypeDefaults || {};
            apiSorted[entry.name].subTypeDefaults[st] = entry.defaults;
        }

        if (entry.name === 'series') {
            //Hack
            apiSorted[entry.name].filteredBy = entry.filteredBy = 'series--type';

        }
    });
}

function writeMeta(data) {
    var body = [
        license,
        'highed.meta.optionsAdvanced = ',
        data,
        ';'
    ].join('\n');

   fs.writeFile(__dirname + '/../src/meta/highed.meta.options.advanced.js', body, function (err) {
        return err && console.log('[error]'.red, err);
   });
}

function process(data) {
    var tree = {
        children: {},
        entries: []
    };

    try {
        data = JSON.parse(data);
    } catch(e) {
        console.log('[error]'.red, e);
        return false;
    }

    data.sort(function (a, b) {
        return a.name.toUpperCase().localeCompare(b.name.toUpperCase());
    });

    sortAPI(data);

    fs.writeFileSync(__dirname + '/../api.js', JSON.stringify(data, undefined, '  '));

    data.forEach(function (entry) {
        var parent = entry.parent || removeType(entry.name),
            current = tree,
            path,
            nitm
        ;

        //For now we skip functions and multi-types
        if (entry.returnType === 'Function' || entry.deprecated) {
            return;
        }

        //Temp
        entry.name = removeType(entry.name);

        parent = removeType(parent);
        path = parent.replace(/\-\-/g, '.').replace(/\-/g, '.').split('.');

        if (entry.name.indexOf('series') !== 0) {
           // return;
        }

        if (ignores[entry.name]) {
            return false;
        }

        if (ignores[path[0]]) {
            return false;
        }

        // if (path.length === 1) {

        //     current.children[path[0]] = current.children[path[0]] || {
        //         entries: [],
        //         children: {}
        //     };

        //     current.children[path[0]].id = entry.name;

        //     return;
        // }

        path.forEach(function(p, i) {
            var c;

            if (ignores[p]) {
                return;
            }

            if (i === path.length - 1) {

                current.children[p] = current.children[p] || {
                    entries: {},
                    children: {}
                };

                c = {
                    id: entry.name,
                    shortName: entry.name.substr(entry.name.lastIndexOf('-') + 1),
                    dataType: (entry.returnType || '').toLowerCase(),
                    description: entry.description,
                    values: entry.values || undefined,
                    defaults: entry.defaults,
                    subType: apiSorted[entry.name].subType,
                    filteredBy: entry.filteredBy
                };

                if (c.dataType.indexOf('array') >= 0 && entry.isParent) {
                    //current.children[p] = c;
                    if (current.children[p]) {
                        current.children[p].isInstancedArray = true;
                        current.children[p].shortName = p;
                        current.children[p].id = p;
                    } //else {
                    //     c.isInstancedArray = true;
                    //     current.children[p].entries[c.id] = c;
                    // }
                    //c.entries = [];
                    //c.children = {};

                //If it's an object, skip it. It will appear as a leaf.
                } else if (!entry.isParent) {
                    //current.children[p].entries[c.id] = c;
                    current.children[p].entries[c.id] = c;

                }  else if (entry.isParent) {
                    current.id = current.id || entry.name;
                    current.dataType = (entry.returnType || '').toLowerCase();
                } else if (c.dataType.indexOf('object') >= 0) {
                    //console.log('found object', entry.name, 'current', current.id);

                    // entry.attributes = [];

                    // data.forEach(function (child) {
                    //     if (child.parent === entry.name) {
                    //         console.log('found child to', entry.name, child.title);
                    //         entry.attributes.push({
                    //             dataType: (child.returnType || '').toLowerCase(),
                    //             name: child.title,
                    //             title: child.title,
                    //             tooltipText: child.description,
                    //             defaults: child.defaults,
                    //             values: child.values
                    //         });
                    //     }
                    // });
                }

            } else {
                if (typeof current.children[p] === 'undefined') {

                    current.children[p] = {
                        entries: {},
                        children: {}
                    };

                    current = current.children[p];
                } else {
                    current = current.children[p];
                }
            }
        });

    });

    return JSON.stringify(tree, undefined, 2);
}

request(apiDumpURL, function (error, response, body) {
    console.log('API Fetched, transforming...'.bold);
    if (error) {
        console.log('[error]'.red, error);
    } else {

        writeMeta(process(body));
    }
});


text:
package resources

import (
	"fmt"

	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/ec2"
)

type EC2CustomerGateway struct {
	svc   *ec2.EC2
	id    string
	state string
}

func init() {
	register("EC2CustomerGateway", ListEC2CustomerGateways)
}

func ListEC2CustomerGateways(sess *session.Session) ([]Resource, error) {
	svc := ec2.New(sess)

	params := &ec2.DescribeCustomerGatewaysInput{}
	resp, err := svc.DescribeCustomerGateways(params)
	if err != nil {
		return nil, err
	}

	resources := make([]Resource, 0)
	for _, out := range resp.CustomerGateways {
		resources = append(resources, &EC2CustomerGateway{
			svc:   svc,
			id:    *out.CustomerGatewayId,
			state: *out.State,
		})
	}

	return resources, nil
}

func (c *EC2CustomerGateway) Filter() error {
	if c.state == "deleted" {
		return fmt.Errorf("already deleted")
	}
	return nil
}

func (c *EC2CustomerGateway) Remove() error {
	params := &ec2.DeleteCustomerGatewayInput{
		CustomerGatewayId: &c.id,
	}

	_, err := c.svc.DeleteCustomerGateway(params)
	if err != nil {
		return err
	}

	return nil
}

func (c *EC2CustomerGateway) String() string {
	return c.id
}


text:
function A = mrdivide_my(C,B,varargin)
%MRDIVIDE Lag operator polynomial right division
%
% Syntax:
%
%   A = C/B
%	A = mrdivide(C,B,param1,val1,param2,val2,...)
%
% Description:
%
%   Given two lag operator polynomials, C(L) and B(L), perform a right
%   division so that C(L) = A(L)*B(L), or A(L) = C(L)/B(L). Right division
%   requires invertibility of the coefficient matrix associated with lag 0
%   of the denominator polynomial B(L).
%
% Input Arguments:
%
%   C - Numerator (dividend) lag operator polynomial object, as produced by
%     LagOp, in the quotient C(L)/B(L).
%
%	B - Denominator (divisor) lag operator polynomial object, as produced
%	  by LagOp, in the quotient C(L)/B(L).
%
%   If at least one of C or B is a lag operator polynomial object, the
%   other can be a cell array of matrices (initial lag operator
%   coefficients), or a single matrix (zero-degree lag operator).
%
% Optional Input Parameter Name/Value Pairs:
%
%   'AbsTol'  Positive scalar absolute tolerance used as part of the
%             termination criterion of the calculation of the quotient
%             coefficients and, subsequently, to determine which
%             coefficients to include in the quotient. Specifying an
%             absolute tolerance allows for customization of the
%             termination criterion (see notes below). Once the algorithm
%             has terminated, 'AbsTol' is used to exclude polynomial lags
%             with near-zero coefficients. A coefficient matrix for a given
%             lag is excluded if the magnitudes of all elements of the
%             matrix are less than or equal to the absolute tolerance. The
%             default is 1e-12.
%
%   'RelTol'  Positive scalar relative tolerance used as part of the
%             termination criterion of the calculation of the quotient
%             coefficients. At each lag, a coefficient matrix is
%             calculated and its 2-norm compared to the largest coefficient
%             2-norm. If the ratio of the current norm to the largest norm
%             is less than or equal to 'RelTol', then the relative
%             termination criterion is satisfied. The default is 0.01.
%
%   'Window'  Positive integer indicating the size of the window used to
%             check termination tolerances. Window represents the number of
%             consecutive lags for which coefficients must satisfy a
%             tolerance-based termination criterion in order to terminate
%             the calculation of the quotient coefficients. If coefficients
%             remain below tolerance for the length of the specified
%             tolerance window, they are assumed to have died out
%             sufficiently to terminate the algorithm (see notes below).
%             The default is 20.
%
%   'Degree'  Nonnegative integer indicating the maximum degree of the
%             quotient polynomial. For stable denominators, the default is
%             the power to which the magnitude of the largest eigenvalue of
%             the denominator must be raised to equal the relative
%             termination tolerance 'RelTol'; for unstable denominators,
%             the default is the power to which the magnitude of the
%             largest eigenvalue must be raised to equal the largest
%             positive floating point number (see REALMAX). The default is
%             1000, regardless of the stability of the denominator.
%
% Output Argument:
%
%   A - Quotient lag operator polynomial object, with A(L) = C(L)/B(L).
%
% Notes:
%
%   o The right division operator (/) invokes MRDIVIDE, but the optional
%     inputs are available only by calling MRDIVIDE directly.
%
%   o To right-invert a stable B(L), set C(L) = eye(B.Dimension).
%
%   o Lag operator polynomial division generally results in infinite-degree
%     polynomials. MRDIVIDE imposes a termination criterion to truncate the
%     degree of the quotient polynomial.
%
%     If 'Degree' is unspecified, the maximum degree of the quotient is
%     determined by the stability of the denominator. Stable denominator
%     polynomials usually result in quotients whose coefficients exhibit
%     geometric decay in absolute value. (When coefficients change sign, it
%     is the coefficient envelope which decays geometrically.) Unstable
%     denominators usually result in quotients whose coefficients exhibit
%     geometric growth in absolute value. In either case, maximum degree
%     will not exceed the value of 'Degree'.
%
%     To control truncation error by terminating the coefficient sequence
%     too early, the termination criterion involves three steps:
%
%      (1) At each lag in the quotient polynomial, a coefficient matrix is
%          calculated and tested against both a relative and an absolute
%          tolerance (see 'RelTol' and 'AbsTol' inputs above).
%
%      (2) If the current coefficient matrix is below either tolerance,
%          then a tolerance window is opened to ensure that all subsequent
%          coefficients remain below tolerance for a number of lags
%          determined by 'Window'.
%
%      (3) If any subsequent coefficient matrix within the window is above
%          both tolerances, then the tolerance window is closed and
%          additional coefficients are calculated, repeating steps (1) and
%          (2) until a subsequent coefficient matrix is again below either
%          tolerance, and a new window is opened.
%
%     Steps (1)-(3) are repeated until a coefficient is below tolerance and
%     subsequent coefficients remains below tolerance for 'Window' lags, or
%     until the maximum 'Degree' is encountered, or until a coefficient
%     becomes numerically unstable (NaN or +/-Inf).
%
% References:
%
%   [1] Box, G.E.P., Jenkins, G.M., and Reinsel, G.C. Time Series Analysis:
%       Forecasting and Control. 3rd ed. Upper Saddle River, NJ: Prentice-
%       Hall, 1994.
%
%   [2] Hayashi, F. Econometrics. Princeton, NJ: Princeton University
%       Press, 2000.
%
%   [3] Hamilton, J. D. Time Series Analysis. Princeton, NJ: Princeton
%       University Press, 1994.
%
% See also LagOp/LagOp, LagOp/mtimes, LagOp/mldivide.

% Copyright 2010 The MathWorks, Inc.
% $Revision: 1.1.6.2 $   $Date: 2009/11/05 16:58:34 $

% Check input arguments:

if nargin > 10

   error('econ:LagOp:mrdivide:TooManyInputs',...
         'Too many inputs.')

end

parser = inputParser;
parser.addRequired('C');
parser.addRequired('B');
parser.addParamValue('AbsTol',LagOp.ZeroTolerance,@LagOp.checkTolerance);
parser.addParamValue('RelTol',0.01,@LagOp.checkTolerance);
parser.addParamValue('Window',20,@LagOp.checkWindow);
parser.addParamValue('Degree',[],@LagOp.checkDegree);
parser.parse(C,B,varargin{:});

C          = parser.Results.C;
B          = parser.Results.B;
absTol     = parser.Results.AbsTol;
relTol     = parser.Results.RelTol;
windowSize = parser.Results.Window;
maxDegree  = parser.Results.Degree;

if isempty(C) || isempty(B)

   error('econ:LagOp:mrdivide:MissingInputs',...
         'Lag operator polynomials must not be empty.')

end

% Allow either input to be a matrix, a cell array, or some other object,
% and attempt a LagOp conversion. The tolerance is not applied here.

if ~isa(C,'LagOp')
   C = LagOp(C,'Tolerance',0); % Convert C(L) to a LagOp object
elseif ~isa(B,'LagOp')
   B = LagOp(B,'Tolerance',0); % Convert B(L) to a LagOp object
end

if C.Dimension ~= B.Dimension

   error('econ:LagOp:mrdivide:InconsistentDimension',...
         'Polynomials must have the same dimension.')

end

% Test the 0-lag coefficient matrix of B(L) for singularity/invertibility.
% If this matrix is noninvertible (or nearly so), then issue a single
% warning and disable the core MATLAB warnings that would otherwise be
% issued repeatedly inside the FOR loop when the "/" operator is evaluated.

wState = warning; % Save warning state

if cond(B.Coefficients{0}) > LagOp.SingularTolerance
   wString = cat(2, 'Zero-lag coefficient of denominator polynomial is \n', ...
                    '         singular or badly scaled. Results may be inaccurate.');

   warning('off','MATLAB:nearlySingularMatrix')
   warning('off','MATLAB:singularMatrix')
   warning('econ:LagOp:mrdivide:NearSingularMatrix',wString)

end

% Determine the number of quotient coefficients to calculate, and, if
% necessary, the default maximum degree of the quotient polynomial:

if isempty(maxDegree)

   % The stability of the quotient is typically determined by the stability
   % of the denominator. If stable, there is a reasonable expectation of
   % geometric decay in absolute value of the quotient coefficient
   % sequence. For well-conditioned denominators, the eigenvalue of the
   % largest magnitude (the "spectral radius") is often a good indication
   % of the number of lags required for the coefficient sequence to decay
   % to some small value before termination.

  [isDenominatorStable,eigenvalues] = isStable(B);

   if isDenominatorStable

      % A zero-degree denominator involves division by a constant, and the
      % degree of the quotient is that of the numerator (no 1000 degree
      % limit imposed):

      if isempty(eigenvalues)
         maxDegree = C.Degree;
         degree    = maxDegree;
      else
         maxDegree = min(ceil(log(relTol) / log(max(abs(eigenvalues)))), 1000);
         degree    = maxDegree + windowSize;
      end
   else
      maxDegree = min(ceil(log(realmax) / log(max(abs(eigenvalues)))), 1000);
      degree    = maxDegree;
   end

else
   degree = maxDegree + windowSize; % Allow for the termination window
end

% Initialize some parameters for performance and convenience, as well as a
% convergence warning flag, but only for non-zero-degree denominators. If
% the degree of the denominator is zero, then just scale coefficients, and
% the termination algorithm is unnecessary.

p = B.Degree;                   % Degree of the denominator
isNonZeroDegree = p > 0;        % Is the denominator degree non-zero?
issueWarning = isNonZeroDegree; % Issue a convergence warning?

% Compute the quotient polynomial coefficients:

coefficients = cell(1,degree+1);     % Create an empty cell array
coefficients{1} = C.Coefficients{0} / B.Coefficients{0};
maximumNorm = norm(coefficients{1}); % Initialize largest norm so far
iCount = 0;                          % Number of consecutive lags <= termination tolerance

for i = 2:numel(coefficients)

    % The algorithm for polynomial division is derived from the convolution
    % formula designed to multiply two polynomials A(L) and B(L). See [2],
    % p. 373, equation 6.1.16, subject to the modifications discussed on
    % the bottom of p. 381 and the top of p. 382, and also allow for the
    % possibility that A0, B0, and C0 are not identity matrices.
    %
    % To illustrate the approach, define A(L), B(L) and C(L) as polynomials
    % of degree p, d, and q, respectively:
    %
    %   A(L) = A(0) + A(1)*L + ... A(p)*L^p
    %   B(L) = B(0) + B(1)*L + ... B(p)*L^d
    %   C(L) = C(0) + C(1)*L + ... C(q)*L^q
    %
    % The modified equations are:
    %
    %   A(0)*B(0)                                                               = C(0)
    %   A(0)*B(1)   + A(1)*B(0)                                                 = C(1)
    %   A(0)*B(2)   + A(1)*B(1)   + A(2)*B(0)                                   = C(2)
    %       .                     .                        .                    =  .
    %       .                     .                        .                    =  .
    %       .                     .                        .                    =  .
    %   A(0)*B(p-1) + A(1)*B(p-2) + A(2)*B(p-3) + ... + A(p-1)*B(0)             = C(p-1)
    %   A(0)*B(p)   + A(1)*B(p-1) + A(2)*B(p-2) + ... + A(p-1)*B(1) + A(p)*B(0) = C(p)
    %   A(0)*B(p+1) + A(1)*B(p)   + A(2)*B(p-1) + ... + A(p-1)*B(2) + A(p)*B(1) = C(p+1)
    %   A(0)*B(p+2) + A(1)*B(p+2) + A(2)*B(p)   + ... + A(p-1)*B(3) + A(p)*B(2) = C(p+2)
    %       .                     .                        .                    =  .
    %       .                     .                        .                    =  .
    %       .                     .                        .                    =  .
    %
    % In the above sequence of equations, C(i) = 0 for all i > q.
    %
    % MRDIVIDE iteratively solves for the coefficients of A(L).

    coefficients{i} = C.Coefficients{i-1}; % Also handles 0-matrix initialization

    for j = 1:(i-1)
        if j <= p
           coefficients{i} = coefficients{i} - coefficients{i-j}*B.Coefficients{j};
        end
    end

    coefficients{i} = coefficients{i} / B.Coefficients{0};

%     if isNonZeroDegree % Nonzero degree denominator?
%
%        % Assess termination criterion for nonzero degree denominators:
%
%        currentNorm = norm(coefficients{i});
%
%        % Apply the relative and absolute tolerance tests:
%        %
%        % o The norm of the current coefficient matrix is compared to the
%        %   largest coefficient norm found so far. If the ratio of the norms
%        %   is less than or equal to the relative tolerance, then the
%        %   relative termination criterion is satisfied.
%        %
%        % o If the magnitudes of all elements of the current coefficient
%        %   matrix are less than or equal to the absolute tolerance, then
%        %   the near-zero absolute termination criterion is satisfied.
%
%        if ((currentNorm / maximumNorm) <= relTol) || all(abs(coefficients{i}(:)) <= absTol)
%
%        % If this is the first lag of a window of consecutive lags that
%        % satisfies the termination tolerance, record the last lag whose
%        % coefficient was above tolerance. This identifies the beginning of
%        % a new tolerance window, and opens a window.
%
%           if iCount == 0
%              degree = i-2;
%           end
%
%           % Begin or continue counting the number of below-tolerance
%           % coefficients to satisfy the tolerance window:
%
%           iCount = iCount+1;
%
%           if iCount >= windowSize
%              issueWarning = false;
%              break % Tolerance window is complete, so stop
%           end
%
%        else
%
%           iCount = 0; % Reset the below-tolerance counter
%
%           if currentNorm > maximumNorm
%              maximumNorm = currentNorm; % Record the new relative tolerance threshold
%           end
%
%        end
%
%     end

    % Check for nonfinite coefficients and numerical instabilities:

    if isnan(coefficients{i})

       warning('econ:LagOp:mrdivide:NaNEncountered',...
               'NaN-valued coefficients found. Terminating.')

       degree = i-2;
       issueWarning = false;
       break
    end

    if isinf(coefficients{i})

       warning('econ:LagOp:mrdivide:InfEncountered',...
               'Infinite-valued coefficients found. Terminating.')

       degree = i-2;
       issueWarning = false;
       break
    end

end

% Issue a warning about non-convergence, if necessary:

% if issueWarning
%    if iCount == 0
%
%       wString = cat(2, 'Termination window not currently open and coefficients \n', ...
%                        '         are not below tolerance.');
%       warning('econ:LagOp:mrdivide:WindowNotOpen', wString)
%
%    else
%       if iCount < windowSize
%
%          warning('econ:LagOp:mrdivide:WindowIncomplete',...
%                  'Window component of termination \ncriterion not fully satisfied.')
%
%       end
%    end
% end

warning(wState); % Restore warning state

% Enforce the maximum polynomial degree, apply the absolute tolerance, and
% create the LagOp object:

degree = min(degree,maxDegree);
A = LagOp(coefficients(1:(degree+1)),'Lags',0:degree,'Tolerance',absTol);

end


text:
package com.izforge.izpack.event;

import com.izforge.izpack.Pack;
import com.izforge.izpack.installer.AutomatedInstallData;
import com.izforge.izpack.installer.InstallerException;
import com.izforge.izpack.installer.UninstallData;
import com.izforge.izpack.util.*;
import com.izforge.izpack.adaptator.IXMLElement;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;

/**
 * Installer listener for performing ANT actions. The definition what should be done will be made in
 * a specification file which is referenced by the resource id "AntActionsSpec.xml". There should be
 * an entry in the install.xml file in the sub ELEMENT "res" of ELEMENT "resources" which references
 * it. The specification of the xml file is done in the DTD antaction.dtd. The xml file specifies,
 * for what pack what ant call should be performed at what time of installation.
 *
 * @author Thomas Guenter
 * @author Klaus Bartz
 */
public class AntActionInstallerListener extends SimpleInstallerListener
{

    // ------------------------------------------------------------------------
    // Constant Definitions
    // ------------------------------------------------------------------------
    // --------String constants for parsing the XML specification ------------
    // -------- see class AntAction -----------------------------------------
    /**
     * Name of the specification file
     */
    public static final String SPEC_FILE_NAME = "AntActionsSpec.xml";

    private HashMap<String, HashMap<Object, ArrayList<AntAction>>> actions = null;

    private ArrayList<AntAction> uninstActions = null;

    /**
     * Default constructor
     */
    public AntActionInstallerListener()
    {
        super(true);
        actions = new HashMap<String, HashMap<Object, ArrayList<AntAction>>>();
        uninstActions = new ArrayList<AntAction>();
    }

    /**
     * Returns the actions map.
     *
     * @return the actions map
     */
    public HashMap<String, HashMap<Object, ArrayList<AntAction>>> getActions()
    {
        return (actions);
    }

    /*
     * (non-Javadoc)
     *
     * @see com.izforge.izpack.installer.InstallerListener#beforePacks(com.izforge.izpack.installer.AutomatedInstallData,
     * java.lang.Integer, com.izforge.izpack.util.AbstractUIProgressHandler)
     */
    public void beforePacks(AutomatedInstallData idata, Integer npacks,
                            AbstractUIProgressHandler handler) throws Exception
    {
        super.beforePacks(idata, npacks, handler);

        getSpecHelper().readSpec(SPEC_FILE_NAME, new VariableSubstitutor(idata.getVariables()));

        if (getSpecHelper().getSpec() == null)
        {
            return;
        }

        // Selected packs.
        Iterator iter = idata.selectedPacks.iterator();
        Pack p = null;
        while (iter != null && iter.hasNext())
        {
            p = (Pack) iter.next();

            // Resolve data for current pack.
            IXMLElement pack = getSpecHelper().getPackForName(p.name);
            if (pack == null)
            {
                continue;
            }

            // Prepare the action cache
            HashMap<Object, ArrayList<AntAction>> packActions = new HashMap<Object, ArrayList<AntAction>>();
            packActions.put(ActionBase.BEFOREPACK, new ArrayList<AntAction>());
            packActions.put(ActionBase.AFTERPACK, new ArrayList<AntAction>());
            packActions.put(ActionBase.BEFOREPACKS, new ArrayList<AntAction>());
            packActions.put(ActionBase.AFTERPACKS, new ArrayList<AntAction>());

            // Get all entries for antcalls.
            Vector<IXMLElement> antCallEntries = pack.getChildrenNamed(AntAction.ANTCALL);
            if (antCallEntries != null && antCallEntries.size() >= 1)
            {
                Iterator<IXMLElement> entriesIter = antCallEntries.iterator();
                while (entriesIter != null && entriesIter.hasNext())
                {
                    AntAction act = readAntCall(entriesIter.next(), idata);
                    if (act != null)
                    {
                        (packActions.get(act.getOrder())).add(act);
                    }
                }
                // Set for progress bar interaction.
                if ((packActions.get(ActionBase.AFTERPACKS)).size() > 0)
                {
                    this.setProgressBarCaller();
                }
            }

            actions.put(p.name, packActions);
        }
        iter = idata.availablePacks.iterator();
        while (iter.hasNext())
        {
            String currentPack = ((Pack) iter.next()).name;
            performAllActions(currentPack, ActionBase.BEFOREPACKS, null);
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see com.izforge.izpack.installer.InstallerListener#beforePack(com.izforge.izpack.Pack,
     * java.lang.Integer, com.izforge.izpack.util.AbstractUIProgressHandler)
     */
    public void beforePack(Pack pack, Integer i, AbstractUIProgressHandler handler)
            throws Exception
    {
        performAllActions(pack.name, ActionBase.BEFOREPACK, handler);
    }

    /*
     * (non-Javadoc)
     *
     * @see com.izforge.izpack.installer.InstallerListener#afterPack(com.izforge.izpack.Pack,
     * java.lang.Integer, com.izforge.izpack.util.AbstractUIProgressHandler)
     */
    public void afterPack(Pack pack, Integer i, AbstractUIProgressHandler handler) throws Exception
    {
        performAllActions(pack.name, ActionBase.AFTERPACK, handler);
    }

    /*
     * (non-Javadoc)
     *
     * @see com.izforge.izpack.compiler.InstallerListener#afterPacks(com.izforge.izpack.installer.AutomatedInstallData,
     * com.izforge.izpack.util.AbstractUIProgressHandler)
     */
    public void afterPacks(AutomatedInstallData idata, AbstractUIProgressHandler handler)
            throws Exception
    {
        if (informProgressBar())
        {
            handler.nextStep(getMsg("AntAction.pack"), getProgressBarCallerId(), getActionCount(
                    idata, ActionBase.AFTERPACKS));
        }
        Iterator iter = idata.selectedPacks.iterator();
        while (iter.hasNext())
        {
            String currentPack = ((Pack) iter.next()).name;
            performAllActions(currentPack, ActionBase.AFTERPACKS, handler);
        }
        if (uninstActions.size() > 0)
        {
            UninstallData.getInstance().addAdditionalData("antActions", uninstActions);
        }
    }

    private int getActionCount(AutomatedInstallData idata, String order)
    {
        int retval = 0;
        Iterator iter = idata.selectedPacks.iterator();
        while (iter.hasNext())
        {
            String currentPack = ((Pack) iter.next()).name;
            ArrayList<AntAction> actList = getActions(currentPack, order);
            if (actList != null)
            {
                retval += actList.size();
            }
        }
        return (retval);
    }

    /**
     * Returns the defined actions for the given pack in the requested order.
     *
     * @param packName name of the pack for which the actions should be returned
     * @param order    order to be used; valid are beforepack and afterpack
     * @return a list which contains all defined actions for the given pack and order
     */
    // -------------------------------------------------------
    protected ArrayList<AntAction> getActions(String packName, String order)
    {
        if (actions == null)
        {
            return null;
        }

        HashMap<Object, ArrayList<AntAction>> packActions = actions.get(packName);
        if (packActions == null || packActions.size() == 0)
        {
            return null;
        }

        return packActions.get(order);
    }

    /**
     * Performs all actions which are defined for the given pack and order.
     *
     * @param packName name of the pack for which the actions should be performed
     * @param order    order to be used; valid are beforepack and afterpack
     * @throws InstallerException
     */
    private void performAllActions(String packName, String order, AbstractUIProgressHandler handler)
            throws InstallerException
    {
        ArrayList<AntAction> actList = getActions(packName, order);
        if (actList == null || actList.size() == 0)
        {
            return;
        }

        Debug.trace("******* Executing all " + order + " actions of " + packName + " ...");
        for (AntAction act : actList)
        {
            // Inform progress bar if needed. Works only
            // on AFTER_PACKS
            if (informProgressBar() && handler != null
                    && handler instanceof ExtendedUIProgressHandler
                    && order.equals(ActionBase.AFTERPACKS))
            {
                ((ExtendedUIProgressHandler) handler)
                        .progress((act.getMessageID() != null) ? getMsg(act.getMessageID()) : "");
            }
            try
            {
                act.performInstallAction();
            }
            catch (Exception e)
            {
                throw new InstallerException(e);
            }
            if (act.getUninstallTargets().size() > 0)
            {
                uninstActions.add(act);
            }
        }
    }

    /**
     * Returns an ant call which is defined in the given XML element.
     *
     * @param el XML element which contains the description of an ant call
     * @param idata The installation data
     * @return an ant call which is defined in the given XML element
     * @throws InstallerException
     */
    private AntAction readAntCall(IXMLElement el, AutomatedInstallData idata) throws InstallerException
    {
        String buildFile = null;
        String buildResource = null;

        if (el == null)
        {
            return null;
        }
        SpecHelper spec = getSpecHelper();
        AntAction act = new AntAction();
        try
        {
            act.setOrder(spec.getRequiredAttribute(el, ActionBase.ORDER));
            act.setUninstallOrder(el.getAttribute(ActionBase.UNINSTALL_ORDER,
                    ActionBase.BEFOREDELETION));
        }
        catch (Exception e)
        {
            throw new InstallerException(e);
        }

        act.setQuiet(spec.isAttributeYes(el, ActionBase.QUIET, false));
        act.setVerbose(spec.isAttributeYes(el, ActionBase.VERBOSE, false));
        buildFile = el.getAttribute(ActionBase.BUILDFILE);
        buildResource = processBuildfileResource(spec, idata, el);
        if (null == buildFile && null == buildResource)
        {
            throw new InstallerException("Invalid " + SPEC_FILE_NAME + ": either buildfile or buildresource must be specified");
        }
        if (null != buildFile && null != buildResource)
        {
            throw new InstallerException("Invalid " + SPEC_FILE_NAME + ": cannot specify both buildfile and buildresource");
        }
        if (null != buildFile)
        {
            act.setBuildFile(buildFile);
        }
        else
        {
            act.setBuildFile(buildResource);
        }
        String str = el.getAttribute(ActionBase.LOGFILE);
        if (str != null)
        {
            act.setLogFile(str);
        }
        String msgId = el.getAttribute(ActionBase.MESSAGEID);
        if (msgId != null && msgId.length() > 0)
        {
            act.setMessageID(msgId);
        }

        // read propertyfiles
        Iterator<IXMLElement> iter = el.getChildrenNamed(ActionBase.PROPERTYFILE).iterator();
        while (iter.hasNext())
        {
            IXMLElement propEl = iter.next();
            act.addPropertyFile(spec.getRequiredAttribute(propEl, ActionBase.PATH));
        }

        // read properties
        iter = el.getChildrenNamed(ActionBase.PROPERTY).iterator();
        while (iter.hasNext())
        {
            IXMLElement propEl = iter.next();
            act.setProperty(spec.getRequiredAttribute(propEl, ActionBase.NAME), spec
                    .getRequiredAttribute(propEl, ActionBase.VALUE));
        }

        // read targets
        iter = el.getChildrenNamed(ActionBase.TARGET).iterator();
        while (iter.hasNext())
        {
            IXMLElement targEl = iter.next();
            act.addTarget(spec.getRequiredAttribute(targEl, ActionBase.NAME));
        }

        // read uninstall rules
        iter = el.getChildrenNamed(ActionBase.UNINSTALL_TARGET).iterator();
        while (iter.hasNext())
        {
            IXMLElement utargEl = iter.next();
            act.addUninstallTarget(spec.getRequiredAttribute(utargEl, ActionBase.NAME));
        }

        // see if this was an build_resource and there were uninstall actions
        if (null != buildResource &&  act.getUninstallTargets().size() > 0)
        {
            // We need to add the build_resource file to the uninstaller
            addBuildResourceToUninstallerData(buildResource);
        }

        return act;
    }

    private String processBuildfileResource(SpecHelper spec, AutomatedInstallData idata, IXMLElement el) throws InstallerException
    {
        String buildResource = null;

        // See if the build file is a resource
        String attr = el.getAttribute(ActionBase.BUILDRESOURCE);
        if (null != attr)
        {
            // Get the resource
            BufferedInputStream bis = new BufferedInputStream(spec.getResource(attr));
            if (null == bis)
            {
                // Resource not found
                throw new InstallerException("Failed to find buildfile_resource: " + attr);
            }
            BufferedOutputStream bos = null;
            try
            {
                // Write the resource to a temporary file
                File tempFile = File.createTempFile("buildfile_resource", "xml");
                tempFile.deleteOnExit();
                bos = new BufferedOutputStream(new FileOutputStream(tempFile));
                int c;
                while (-1 != (c = bis.read()))
                {
                    bos.write(c);
                }
                bis.close();
                bos.close();
                buildResource = tempFile.getAbsolutePath();
            }
            catch (Exception x)
            {
                throw new InstallerException("Failed to write buildfile_resource", x);
            }
            finally
            {
                if (bos != null)
                {
                    try
                    {
                        bos.close();
                    }
                    catch (Exception x)
                    {
                        // Ignore this exception
                    }
                }
            }
        }
        return buildResource;
    }

    private void addBuildResourceToUninstallerData(String buildResource) throws InstallerException {
        byte[] content = null;
        File buildFile = new File(buildResource);
        ByteArrayOutputStream bos = new ByteArrayOutputStream((int) buildFile.length());
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(buildFile));
            int c;
            while (-1 != (c = bis.read())) {
                bos.write(c);
            }
            content = bos.toByteArray();
            UninstallData.getInstance().addAdditionalData("build_resource", content);
        } catch (Exception x) {
            throw new InstallerException("Failed to add buildfile_resource to uninstaller", x);
        } finally {
            try {
                bis.close();
                bos.close();
            } catch (IOException iOException) {
                // Ignore the error
            }
        }
    }
}


text:
namespace Microsoft.Azure.Management.WebSites.Models
{
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Routing rules in production experiments.
    /// </summary>
    public partial class Experiments
    {
        /// <summary>
        /// Initializes a new instance of the Experiments class.
        /// </summary>
        public Experiments()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the Experiments class.
        /// </summary>
        /// <param name="rampUpRules">List of ramp-up rules.</param>
        public Experiments(IList<RampUpRule> rampUpRules = default(IList<RampUpRule>))
        {
            RampUpRules = rampUpRules;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets list of ramp-up rules.
        /// </summary>
        [JsonProperty(PropertyName = "rampUpRules")]
        public IList<RampUpRule> RampUpRules { get; set; }

    }
}


text:
import sys
import os

#Put lib on path, once Google App Engine does not allow doing it directly
sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))

import settings
from tekton.gae import middleware
import webapp2

class BaseHandler(webapp2.RequestHandler):
    def get(self):
        self.make_convetion()

    def post(self):
        self.make_convetion()

    def make_convetion(self):
        middleware.execute_2(settings.MIDDLEWARES, self)

app = webapp2.WSGIApplication([("/.*", BaseHandler)], debug=False)


text:
layout: page
title: Emerald Peace Solutions Show
date: 2016-05-24
author: Aaron Montoya
tags: weekly links, java
status: published
summary: Nunc aliquam massa eget lobortis vehicula. Class aptent taciti.
banner: images/banner/leisure-02.jpg
booking:
  startDate: 09/28/2016
  endDate: 10/02/2016
  ctyhocn: UFAHXHX
  groupCode: EPSS
published: true
---
Aenean dapibus bibendum eros. Aenean mollis gravida lacus rutrum auctor. Nullam vitae risus eros. Sed ut viverra risus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Mauris at tempor sem. Sed ultricies iaculis ligula nec elementum. Maecenas ut fermentum sapien. Phasellus eget libero efficitur, euismod turpis a, finibus orci. Vivamus vehicula consequat pulvinar. Vivamus feugiat sagittis sem sed placerat. Donec scelerisque ligula sit amet nulla bibendum, vitae elementum eros dignissim. Curabitur viverra mauris ac turpis pulvinar commodo. Cras eget viverra nunc. Curabitur mollis mauris arcu, ut varius massa imperdiet quis. Nulla facilisi.

1 Etiam sed ligula sed odio volutpat accumsan id vel arcu
1 Phasellus eu tortor vel mi aliquet varius.

Mauris vulputate vitae lorem sit amet lobortis. Vivamus at tincidunt dui, eu vulputate libero. Pellentesque vel quam at nisi volutpat tincidunt et eu urna. Sed quis tellus iaculis, lacinia turpis et, porttitor purus. Etiam malesuada odio id faucibus pellentesque. Ut interdum, justo non vulputate cursus, lectus metus suscipit ligula, in volutpat felis magna sed urna. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce tincidunt dui turpis, vel ullamcorper elit cursus ac. Aenean et ante sagittis, malesuada ex at, semper dolor. Nullam elementum rutrum ultricies. Nunc orci ipsum, varius quis mauris sit amet, vulputate pulvinar leo. Sed volutpat placerat sem. Nulla sodales nunc mauris, eu rutrum urna tincidunt non.


text:
namespace Azure.Communication.JobRouter
{
    /// <summary> Trigger for an exception action on exceeding queue length. </summary>
    public partial class QueueLengthExceptionTrigger : JobExceptionTrigger
    {
        /// <summary> Initializes a new instance of QueueLengthExceptionTrigger. </summary>
        /// <param name="threshold"> Threshold of number of jobs queued to for this trigger. Must be greater than 0</param>
        public QueueLengthExceptionTrigger(int threshold)
            : this(null, threshold)
        {
        }
    }
}


text:
namespace tesla
{

namespace base
{

__thread int t_numOpenedFiles = 0;
__thread std::vector<pid_t>* t_pids = NULL;

Timestamp g_startTime = Timestamp::now();

// assume those won't change during the life time of a process.
int g_clockticks = static_cast<int>(::sysconf(_SC_CLK_TCK));
int g_pagesize = static_cast<int>(::sysconf(_SC_PAGE_SIZE));

int fdDirFilter(const struct dirent* d)
{
    if (::isdigit(d->d_name[0]))
    {
        ++t_numOpenedFiles;
    }
    return 0;
}

int taskDirFilter(const struct dirent* d)
{
    if (::isdigit(d->d_name[0]))
    {
        t_pids->push_back(atoi(d->d_name));
    }
    return 0;
}

int scanDir(const char *dirpath, int (*filter)(const struct dirent *))
{
    struct dirent** namelist = NULL;
    int result = ::scandir(dirpath, &namelist, filter, alphasort);
    assert(namelist == NULL);
    return result;
}

pid_t ProcessInfo::pid()
{
    return ::getpid();
}

string ProcessInfo::pidString()
{
    char buf[32];
    snprintf(buf, sizeof buf, "%d", pid());
    return buf;
}

uid_t ProcessInfo::uid()
{
    return ::getuid();
}

string ProcessInfo::username()
{
    struct passwd pwd;
    struct passwd* result = NULL;
    char buf[8192];
    const char* name = "unknownuser";

    getpwuid_r(uid(), &pwd, buf, sizeof buf, &result);
    if (result)
    {
        name = pwd.pw_name;
    }
    return name;
}

uid_t ProcessInfo::euid()
{
    return ::geteuid();
}

Timestamp ProcessInfo::startTime()
{
    return g_startTime;
}

int ProcessInfo::clockticksPerSecond()
{
    return g_clockticks;
}

int ProcessInfo::pagesize()
{
    return g_pagesize;
}

bool ProcessInfo::debugBuild()
{
#ifdef NDEBUG
    return false;
#else
    return true;
#endif // NDEBUG
}

string ProcessInfo::hostName()
{
    // HOST_NAME_MAX 64
    // _POSIX_HOST_NAME_MAX 255
    char buf[256];
    if (::gethostname(buf, sizeof buf) == 0)
    {
        buf[sizeof(buf)-1] = '\0';
        return buf;
    }
    else
    {
        return "unknownhost";
    }
}

string ProcessInfo::procName()
{
    return procName(procStat()).as_string();
}

StringPiece ProcessInfo::procName(const string& stat)
{
    StringPiece name;
    size_t lp = stat.find('(');
    size_t rp = stat.rfind(')');
    if (lp != string::npos && rp != string::npos && lp < rp)
    {
        name.set(stat.data()+lp+1, static_cast<int>(rp-lp-1));
    }
    return name;
}

string ProcessInfo::procStatus()
{
    string result;
    readFile("/proc/self/status", 65536, &result);
    return result;
}

string ProcessInfo::procStat()
{
    string result;
    readFile("/proc/self/stat", 65536, &result);
    return result;
}

string ProcessInfo::threadStat()
{
    char buf[64];
    snprintf(buf, sizeof buf, "/proc/self/task/%d/stat", CurrentThread::tid());
    string result;
    readFile(buf, 65536, &result);
    return result;
}

string ProcessInfo::exePath()
{
    string result;
    char buf[1024];
    ssize_t n = ::readlink("/proc/self/exe", buf, sizeof buf);
    if (n > 0)
    {
        result.assign(buf, n);
    }
    return result;
}

int ProcessInfo::openedFiles()
{
    t_numOpenedFiles = 0;
    scanDir("/proc/self/fd", fdDirFilter);
    return t_numOpenedFiles;
}

int ProcessInfo::maxOpenFiles()
{
    struct rlimit rl;
    if (::getrlimit(RLIMIT_NOFILE, &rl))
    {
        return openedFiles();
    }
    else
    {
        return static_cast<int>(rl.rlim_cur);
    }
}

ProcessInfo::CpuTime ProcessInfo::cpuTime()
{
    CpuTime t;
    struct tms tms;
    if (::times(&tms) >= 0)
    {
        const double hz = static_cast<double>(clockticksPerSecond());
        t.userSeconds = static_cast<double>(tms.tms_utime) / hz;
        t.systemSeconds = static_cast<double>(tms.tms_stime) / hz;
    }
    return t;
}

int ProcessInfo::numOfThreads()
{
    int result = 0;
    string status = procStatus();
    size_t pos = status.find("Threads:");
    if (pos != string::npos)
    {
        result = ::atoi(status.c_str() + pos + 8);
    }
    return result;
}

std::vector<pid_t> ProcessInfo::threads()
{
    std::vector<pid_t> result;
    t_pids = &result;
    scanDir("/proc/self/task", taskDirFilter);
    t_pids = NULL;
    std::sort(result.begin(), result.end());
    return result;
}

} // namespace base

} // namespace tesla


text:
\lipsum[3]

\keywords{Keywords} random, generator, land whales.


text:
{{ site.t.contact.header[page.lang] }}

{{ site.t.contact.description[page.lang] }}

                <form action="https://formspree.io/contact@solutionscanada.com" method="POST">
                    <fieldset class="form-group">
                        <input type="text" class="form-control" id="exampleInputPassword1" name="name" placeholder="{{ site.t.form.name[page.lang] }}">
                    </fieldset>
                    <fieldset class="form-group">
                        <input type="email" class="form-control form-control-lg" name="_replyto" id="exampleInputEmail1" placeholder="{{ site.t.form.email[page.lang] }}" >
                    </fieldset>
                    <fieldset class="form-group">
                        <textarea class="form-control" id="exampleTextarea" rows="3" name="message" placeholder="{{ site.t.form.message[page.lang] }}"></textarea>
                    </fieldset>
                    <input type="submit" value="{{ site.t.form.submit[page.lang] }}" class="btn btn-default btn-xl page-scroll">
                </form>

{{ site.t.contact.description2[page.lang] }}

{{ site.email }}


text:
(() => {
  const plot = document.body.querySelector('tfma-gain-chart');
  const input = [];
  const count = 1000;

  let totalPositive = 3 * count;
  let totalNegative = count;
  let truePositives = 0;
  let falsePositives = 0;

  for (let i = 0; i <= count; i++) {
    input.push({
      'truePositives': truePositives,
      'falsePositives': falsePositives,
      'trueNegatives': totalNegative - falsePositives,
      'falseNegatives': totalPositive - truePositives,
      'threshold': (count - i) / count,
    });

    truePositives = Math.min(
        totalPositive, truePositives + Math.round((1 + Math.random()) * 30));
    falsePositives = Math.min(
        totalNegative, 1 + falsePositives + Math.round(Math.random() * 5));
  }

  plot.data = input;
})();