text:
.snower{
	position: absolute;
	z-index:9000;
	width:100%;
	max-width:640px;
	height:100%;
	top:0;
	left:0;
	overflow:hidden;
	pointer-events:none;
	-webkit-box-sizing:border-box;
}
.snower  > div{
	position: absolute;
	max-width: 100px;
	max-height: 100px;
	-webkit-animation-iteration-count: infinite!important;
	-webkit-animation-direction: normal!important;
	-webkit-animation-timing-function: linear, ease-in!important;
}

.snower > div > img {
	/*position: absolute;*/
	width: 100%;
	-webkit-animation-iteration-count: infinite!important;
	-webkit-animation-direction: alternate!important;
	-webkit-animation-timing-function: ease-in-out!important;
	-webkit-transform-origin: 50% -100%!important;
}

@-webkit-keyframes fade{
	0%   { opacity: 1; }
	95%  { opacity: 1; }
	100% { opacity: 0; }
}
@-webkit-keyframes drop{
	0%{ -webkit-transform: translate3d(0px, -50px, 0); }
	100% { -webkit-transform: translate3d(0px, 500px, 0); }
}
@-webkit-keyframes clockwiseSpin{
	0% { -webkit-transform: rotate(-50deg); }
	100% { -webkit-transform: rotate(50deg); }
}
@-webkit-keyframes counterclockwiseSpinAndFlip{
	0%{-webkit-transform: scale(-1, 1) rotate(50deg); }
	100% { -webkit-transform: scale(-1, 1) rotate(-50deg); }
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('doberman', '0002_auto_20150721_1431'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='failedaccessattempt',
            options={'ordering': ('-modified',), 'verbose_name': 'Access attempts', 'verbose_name_plural': 'Access attempts'},
        ),
        migrations.AlterField(
            model_name='failedaccessattempt',
            name='captcha_attempts',
            field=models.SmallIntegerField(default=0, verbose_name='Captcha failed attempts'),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='failedaccessattempt',
            name='captcha_enabled',
            field=models.BooleanField(default=False, verbose_name='Captcha protection'),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='failedaccessattempt',
            name='failed_attempts',
            field=models.PositiveIntegerField(default=0, verbose_name='Failed login attempts'),
            preserve_default=True,
        ),
        migrations.AlterModelTable(
            name='failedaccessattempt',
            table=None,
        ),
    ]

redpajama_set_name: RedPajamaGithub


text:
class VariableMinimum : public Variable {
   public:
      VariableMinimum(const Options& iOptions, const Data& iData);
      std::string getBaseVariable() const;
   private:
      std::string mBaseVariable;
      float mTimeWindow;
      float computeCore(int iDate,
            int iInit,
            float iOffset,
            const Location& iLocation,
            const Member& iMember,
            Input::Type iType = Input::typeUnspecified) const;
};
#endif


text:
package org.carlspring.strongbox.configuration;

import org.carlspring.strongbox.storage.Storage;
import org.carlspring.strongbox.storage.routing.RoutingRules;
import org.carlspring.strongbox.xml.StorageMapAdapter;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author mtodorov
 */
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Configuration extends ServerConfiguration
{

    @XmlElement
    private String version = "1.0";

    @XmlElement
    private String baseUrl = "http://localhost/";

    @XmlElement
    private int port = 48080;

    /**
     * The global proxy settings to use when no per-repository proxy settings have been defined.
     */
    @XmlElement(name = "proxy-configuration")
    private ProxyConfiguration proxyConfiguration;

    /**
     * K: storageId
     * V: storage
     */
    @XmlElement(name = "storages")
    @XmlJavaTypeAdapter(StorageMapAdapter.class)
    private Map<String, Storage> storages = new LinkedHashMap<>();

    @XmlElement(name = "routing-rules")
    private RoutingRules routingRules;

    public Configuration()
    {
    }

    public String getVersion()
    {
        return version;
    }

    public void setVersion(String version)
    {
        this.version = version;
    }

    public String getBaseUrl()
    {
        return baseUrl;
    }

    public void setBaseUrl(String baseUrl)
    {
        this.baseUrl = baseUrl;
    }

    public int getPort()
    {
        return port;
    }

    public void setPort(int port)
    {
        this.port = port;
    }

    public ProxyConfiguration getProxyConfiguration()
    {
        return proxyConfiguration;
    }

    public void setProxyConfiguration(ProxyConfiguration proxyConfiguration)
    {
        this.proxyConfiguration = proxyConfiguration;
    }

    public Map<String, Storage> getStorages()
    {
        return storages;
    }

    public void setStorages(Map<String, Storage> storages)
    {
        this.storages = storages;
    }

    public void addStorage(Storage storage)
    {
        storages.put(storage.getId(), storage);
    }

    public Storage getStorage(String storageId)
    {
        return storages.get(storageId);
    }

    public void removeStorage(Storage storage)
    {
        storages.remove(storage.getBasedir());
    }

    public RoutingRules getRoutingRules()
    {
        return routingRules;
    }

    public void setRoutingRules(RoutingRules routingRules)
    {
        this.routingRules = routingRules;
    }

}


text:
package info.ephyra.questionanalysis.atype.classifier;

import info.ephyra.questionanalysis.atype.AnswerType;
import info.ephyra.questionanalysis.atype.QuestionClassifier;
import info.ephyra.util.Properties;

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

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import edu.cmu.minorthird.classify.Feature;
import edu.cmu.minorthird.classify.Instance;

/**
 * A rule-based classifier for the answer type of a question.
 *
 * @author Justin Betteridge
 * @version 2008-02-10
 */
public class RuleBasedQuestionClassifier extends QuestionClassifier {

    private static final Logger log = Logger.getLogger(RuleBasedQuestionClassifier.class);
    private List<Rule> rules;
    private String defaultLabel;

    public RuleBasedQuestionClassifier() {}

    public void initialize() throws Exception {
        if (isInitialized()) return;
        if (languagePair == null)
            throw new Exception("languagePair must be set before calling initialize");

        super.initialize();

        Properties properties = Properties.loadFromClassName(this.getClass().getName());

        properties = properties.mapProperties().get(languagePair.getFirst()+"_"+languagePair.getSecond());

        String rulesFileName = properties.get("rulesFile");
        if (rulesFileName == null)
            throw new RuntimeException("Required property rulesFile is undefined'");

        rules = new ArrayList<Rule>();
        loadRulesFile(rulesFileName);

        setInitialized(true);
    }

    public List<AnswerType> classify(Instance instance) {
        List<AnswerType> res = new ArrayList<AnswerType>();
        for (Rule rule : rules) {
            AnswerType result = rule.matches(instance);
            if (result != null) {
                res.add(result);
                //return res;
            }
        }
        return res;
    }

    /**
     * Retrieves the value of the given feature from the given Instance.
     *
     * @param instance the Instance to consider
     * @param featName the name of the feature
     */
    public static String getFeatureValue (Instance instance, String featName) {
        for (Iterator it = instance.binaryFeatureIterator(); it.hasNext();) {
            Feature f = (Feature)it.next();
            if (f.getPart(0).equals(featName)) {
                String val = f.getPart(1).trim();
                val = val.equals("-") ? null : val;
                return val;
            }
        }
        return null;
    }

    private void loadRulesFile(String fileName){
        // PARSE XML RULES FILE
        log.debug("Parsing xml rules file");
        Document rulesDocument;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            factory.setIgnoringComments(true);
            factory.setIgnoringElementContentWhitespace(true);
            factory.setNamespaceAware(true);
            DocumentBuilder db = factory.newDocumentBuilder();
            rulesDocument = db.parse(fileName);
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse XML patterns file", e);
        }

        // EXTRACT RULE DATA.
        log.debug("Loading rules");

        NodeList ruleList = rulesDocument.getElementsByTagName("RULE");
        for (int i = 0; i < ruleList.getLength(); i++) {
            Node rule = ruleList.item(i);
            if (!rule.getNodeName().equals("RULE") ||
                rule.getNodeType() != Node.ELEMENT_NODE) continue;
            rules.add(new Rule((Element)rule));
        }
    }

    /**
     * @return the defaultLabel
     */
    public String getDefaultLabel() {
        return defaultLabel;
    }

    /**
     * @param defaultLabel the defaultLabel to set
     */
    public void setDefaultLabel(String defaultLabel) {
        this.defaultLabel = defaultLabel;
    }
}


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

import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicReference;

import javax.inject.Inject;
import javax.inject.Qualifier;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.AbstractExecutionThreadService;
import com.google.common.util.concurrent.MoreExecutors;

import org.apache.aurora.common.stats.Stats;
import org.apache.aurora.gen.ScheduleStatus;
import org.apache.aurora.scheduler.base.Conversions;
import org.apache.aurora.scheduler.mesos.Driver;
import org.apache.aurora.scheduler.state.StateChangeResult;
import org.apache.aurora.scheduler.state.StateManager;
import org.apache.aurora.scheduler.stats.CachedCounters;
import org.apache.aurora.scheduler.storage.Storage;
import org.apache.aurora.scheduler.storage.Storage.MutateWork.NoResult;
import org.apache.mesos.Protos.TaskStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.util.Objects.requireNonNull;

/**
 * A {@link TaskStatusHandler} implementation.
 */
@VisibleForTesting
public class TaskStatusHandlerImpl extends AbstractExecutionThreadService
    implements TaskStatusHandler {

  private static final Logger LOG = LoggerFactory.getLogger(TaskStatusHandlerImpl.class);

  @VisibleForTesting
  static final String MEMORY_LIMIT_DISPLAY = "Task used more memory than requested.";

  @VisibleForTesting
  static final String DISK_LIMIT_DISPLAY = "Task used more disk than requested.";

  private static final String STATUS_STAT_FORMAT = "status_update_%s_%s";

  private final Storage storage;
  private final StateManager stateManager;
  private final Driver driver;
  private final BlockingQueue<TaskStatus> pendingUpdates;
  private final int maxBatchSize;
  private final CachedCounters counters;

  private final AtomicReference<Thread> threadReference = new AtomicReference<>();

  /**
   * Binding annotation for the status update queue.
   */
  @VisibleForTesting
  @Qualifier
  @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
  public @interface StatusUpdateQueue { }

  /**
   * Binding annotation maximum size of a status update batch.
   */
  @VisibleForTesting
  @Qualifier
  @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
  public @interface MaxBatchSize { }

  @Inject
  TaskStatusHandlerImpl(
      Storage storage,
      StateManager stateManager,
      final Driver driver,
      @StatusUpdateQueue BlockingQueue<TaskStatus> pendingUpdates,
      @MaxBatchSize Integer maxBatchSize,
      CachedCounters counters) {

    this.storage = requireNonNull(storage);
    this.stateManager = requireNonNull(stateManager);
    this.driver = requireNonNull(driver);
    this.pendingUpdates = requireNonNull(pendingUpdates);
    this.maxBatchSize = requireNonNull(maxBatchSize);
    this.counters = requireNonNull(counters);

    Stats.exportSize("status_updates_queue_size", this.pendingUpdates);

    addListener(
        new Listener() {
          @Override
          public void failed(State from, Throwable failure) {
            LOG.error("TaskStatusHandler failed: ", failure);
            driver.abort();
          }
        },
        MoreExecutors.newDirectExecutorService());
  }

  @Override
  public void statusUpdate(TaskStatus status) {
    pendingUpdates.add(status);
  }

  @Override
  protected void triggerShutdown() {
    Thread thread = threadReference.get();

    if (thread != null) {
      thread.interrupt();
    }
  }

  @Override
  protected void run() {
    threadReference.set(Thread.currentThread());

    while (isRunning()) {
      final Queue<TaskStatus> updates = new ArrayDeque<>();

      try {
        updates.add(pendingUpdates.take());
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        break;
      }

      // Process all other available updates, up to the limit on batch size.
      // TODO(bmahler): Expose histogram metrics of the batch sizes.
      pendingUpdates.drainTo(updates, maxBatchSize - updates.size());

      try {
        storage.write((NoResult.Quiet) storeProvider -> {
          for (TaskStatus status : updates) {
            ScheduleStatus translatedState = Conversions.convertProtoState(status.getState());

            StateChangeResult result = stateManager.changeState(
                storeProvider,
                status.getTaskId().getValue(),
                Optional.absent(),
                translatedState,
                formatMessage(status));

            if (status.hasReason()) {
              counters.get(statName(status, result)).incrementAndGet();
            }
          }
        });

        for (TaskStatus status : updates) {
          driver.acknowledgeStatusUpdate(status);
        }
      } catch (RuntimeException e) {
        LOG.error("Failed to process status update batch " + updates, e);
      }
    }
  }

  @VisibleForTesting
  static String statName(TaskStatus status, StateChangeResult result) {
    return String.format(STATUS_STAT_FORMAT, status.getReason(), result);
  }

  private static Optional<String> formatMessage(TaskStatus status) {
    Optional<String> message = Optional.absent();
    if (status.hasMessage()) {
      message = Optional.of(status.getMessage());
    }

    if (status.hasReason()) {
      switch (status.getReason()) {
        case REASON_CONTAINER_LIMITATION_MEMORY:
          // Add a failure explanation to the user
          if (!message.isPresent()) {
            message = Optional.of(MEMORY_LIMIT_DISPLAY);
          }
          break;

        case REASON_CONTAINER_LIMITATION_DISK:
          // Add a failure explanation to the user
          if (!message.isPresent()) {
            message = Optional.of(DISK_LIMIT_DISPLAY);
          }
          break;

        case REASON_EXECUTOR_UNREGISTERED:
          // Suppress "Unregistered executor" message as it bears no meaning to the user.
          message = Optional.absent();
          break;

        default:
          // Message is already populated above.
          break;
      }
    }

    return message;
  }
}


text:
package com.juaby.labs.rpc.proxy;

import com.juaby.labs.rpc.config.ServiceConfig;
import com.juaby.labs.rpc.message.ResponseMessageBody;
import com.juaby.labs.rpc.message.RpcMessage;
import com.juaby.labs.rpc.transport.RpcTransport;
import com.juaby.labs.rpc.util.RpcCallbackHandler;
import com.juaby.labs.rpc.util.SerializeTool;

/**
 * Created by juaby on 16-3-23.
 */
public class RpcCallbackProxy<REQ, RES> {

    private String transportKey;

    public RpcCallbackProxy() {
    }

    public RpcCallbackProxy(String transportKey) {
        this.transportKey = transportKey;
    }

    public RES transport(REQ o) {
        RpcTransport transport = RpcCallbackHandler.getCallbackRpcTransport(getTransportKey());
        if (transport.isWritable()) {
            ResponseMessageBody<REQ> responseMessageBody = new ResponseMessageBody<REQ>();
            //TODO
            String[] transportKeyArray = getTransportKey().split(":");
            responseMessageBody.setService(transportKeyArray[2]);
            responseMessageBody.setMethod(transportKeyArray[3]);
            responseMessageBody.setReturnClass("V");
            responseMessageBody.setBody(o);
            byte [] body = SerializeTool.serialize(responseMessageBody);
            RpcMessage sentMessage = new RpcMessage((byte) 1, (byte) 2,
                    (byte) 0x0F, (byte) 0, body);

            sentMessage.setId(-1);
            sentMessage.setTotalLength(ServiceConfig.HEADER_SIZE + body.length);

            transport.sendMessage(sentMessage);
        }
        return null;
    }

    public String getTransportKey() {
        return transportKey;
    }

    public void setTransportKey(String transportKey) {
        this.transportKey = transportKey;
    }

}


text:
using System;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Web;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using URSA.Web.Http.Testing;

namespace Given_instance_of_the.converter_of
{
    [ExcludeFromCodeCoverage]
    [TestClass]
    public class XWwwUrlEncodedConverter_class : ComplexTypeConverterTest<URSA.Web.Http.Converters.XWwwUrlEncodedConverter>
    {
        private const string ContentType = "application/x-www-url-encoded";

        protected override string SingleEntityContentType { get { return ContentType; } }

        protected override string MultipleEntitiesContentType { get { return ContentType; } }

        protected override bool SupportsMultipleInstances { get { return false; } }

        [TestMethod]
        public override void it_should_not_acknowledge_the_converter_as_a_match_against_incompatible_type_when_deserializing()
        {
        }

        [TestMethod]
        public override void it_should_not_acknowledge_the_converter_as_a_match_against_incompatible_type_when_serializing()
        {
        }

        protected override string SerializeObject<TI>(TI obj)
        {
            StringBuilder result = new StringBuilder(1024);
            string separator = String.Empty;
            foreach (var property in obj.GetType().GetProperties())
            {
                var value = property.GetValue(obj);
                if (value == null)
                {
                    continue;
                }

                if ((value is IEnumerable) && (!(value is string)))
                {
                    foreach (var item in (IEnumerable)value)
                    {
                        result.AppendFormat("{0}{1}={2}", separator, property.Name, HttpUtility.UrlEncode(item.ToString()));
                        separator = "&";
                    }
                }
                else
                {
                    result.AppendFormat("{0}{1}={2}", separator, property.Name, HttpUtility.UrlEncode(value.ToString()));
                }

                separator = "&";
            }

            return result.ToString();
        }
    }
}


text:
import { TestBed, inject } from '@angular/core/testing';

import { FontService } from './font.service';

describe('FontService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [FontService]
    });
  });

  it('should be created', inject([FontService], (service: FontService) => {
    expect(service).toBeTruthy();
  }));
});


text:
package net.skycrown.cuteassistant.imageloader;

/**
 * Created by skycrown on 2018/6/13.
 */

public class ImageLoaderOptions {
    public static final int CENTER_CROP = 0;
    public static final int FIT_CENTER = 1;
    private int placeHolder = -1;
    private int errorDrawable = -1;
    private int cropType = CENTER_CROP;
    private boolean crossFade = false;
    private int crossDuration = 200;
    private boolean skipMemoryCache = false;
    private OverrideSize overrideSize = null;
    private boolean cropToCircle = false;
    private boolean grayScale = false;
    private BlurTransform blurTransform = null;
    private RoundedCornerTransform roundedCornerTransform = null;
    private ColorFilterTransform colorFilterTransform = null;

    public ImageLoaderOptions() {
        this(new Builder());
    }

    ImageLoaderOptions(Builder builder) {
        this.placeHolder = builder.placeHolder;
        this.errorDrawable = builder.errorDrawable;
        this.crossFade = builder.isCrossFade;
        this.crossDuration = builder.crossDuration;
        this.cropType = builder.cropType;
        this.skipMemoryCache = builder.skipMemoryCache;
        this.overrideSize = builder.overrideSize;
        this.cropToCircle = builder.cropToCircle;
        this.grayScale = builder.grayScale;
        this.blurTransform = builder.blurTransform;
        this.roundedCornerTransform = builder.roundedCornerTransform;
        this.colorFilterTransform = builder.colorFilterTransform;
    }

    public int getPlaceHolder() {
        return placeHolder;
    }

    public int getErrorDrawable() {
        return errorDrawable;
    }

    public boolean isCrossFade() {
        return crossFade;
    }

    public int getCrossDuration() {
        return crossDuration;
    }

    public int getCropType() {
        return cropType;
    }

    public boolean isSkipMemoryCache() {
        return skipMemoryCache;
    }

    public boolean isCropToCircle() {
        return cropToCircle;
    }

    public OverrideSize getOverrideSize() {
        return overrideSize;
    }

    public boolean isGrayScale() {
        return grayScale;
    }

    public BlurTransform getBlurTransform() {
        return blurTransform;
    }

    public RoundedCornerTransform getRoundedCornerTransform() {
        return roundedCornerTransform;
    }

    public ColorFilterTransform getColorFilterTransform() {
        return colorFilterTransform;
    }

    public static final class Builder {
        private int placeHolder = -1;
        private int errorDrawable = -1;
        private boolean isCrossFade = false;
        private int crossDuration = 200;
        private int cropType = CENTER_CROP;
        private boolean skipMemoryCache = false;
        private OverrideSize overrideSize = null;
        private boolean cropToCircle = false;
        private boolean grayScale = false;
        private BlurTransform blurTransform = null;
        private RoundedCornerTransform roundedCornerTransform = null;
        private ColorFilterTransform colorFilterTransform = null;

        public Builder setPlaceHolder(int placeHolder) {
            this.placeHolder = placeHolder;
            return this;
        }

        public void setErrorDrawable(int errorDrawable) {
            this.errorDrawable = errorDrawable;
        }

        public Builder setCrossFade(boolean crossFade) {
            this.isCrossFade = crossFade;
            return this;
        }

        public void setCrossDuration(int crossDuration) {
            this.crossDuration = crossDuration;
        }

        public void setCropType(int cropType) {
            this.cropType = cropType;
        }

        public Builder skipMemoryCache(boolean skipMemoryCache) {
            this.skipMemoryCache = skipMemoryCache;
            return this;
        }

        public void cropToCircle(boolean cropToCircle) {
            this.cropToCircle = cropToCircle;
        }

        public void setGrayScale(boolean grayScale) {
            this.grayScale = grayScale;
        }

        public void setSkipMemoryCache(boolean skipMemoryCache) {
            this.skipMemoryCache = skipMemoryCache;
        }

        public void setOverrideSize(OverrideSize overrideSize) {
            this.overrideSize = overrideSize;
        }

        public void setBlurTransform(BlurTransform blurTransform) {
            this.blurTransform = blurTransform;
        }

        public void setRoundedCornerTransform(RoundedCornerTransform roundedCornerTransform) {
            this.roundedCornerTransform = roundedCornerTransform;
        }

        public void setColorFilterTransform(ColorFilterTransform colorFilterTransform) {
            this.colorFilterTransform = colorFilterTransform;
        }

        public ImageLoaderOptions build() {
            return new ImageLoaderOptions(this);
        }

    }

    public static class OverrideSize {
        public int width = -1;
        public int height = -1;

        public OverrideSize(int width, int height) {
            this.width = width;
            this.height = height;
        }
    }

    public static class BlurTransform {
        public int radius = 25;

        public BlurTransform(int radius) {
            this.radius = radius;
        }

    }

    public static class RoundedCornerTransform {
        public int radius = 25;
        public int margin = 25;

        public RoundedCornerTransform(int radius, int margin) {
            this.radius = radius;
            this.margin = margin;
        }
    }

    public static class ColorFilterTransform {
        public int color;

        public ColorFilterTransform(int color) {
            this.color = color;
        }
    }

}


text:
/*! \file Asserter.h
 \brief Interface class for asserter functions

 Interface for asserter functions that can be used to validate
 the data
 */

#include <string>
#include <vector>
#include "DType.h"

#ifndef DBIngestor_Asserter_h
#define DBIngestor_Asserter_h

namespace DBAsserter {
    /*! \class Asserter
     \brief Asserter class interface

     Implement this class, if you want to build your own asserter object.
     */
	class Asserter {

	private:
        /*! \var string name
         identifier string for the asserter
         */
		std::string name;

        /*! \var vector<DBDataSchema::DType> DTypeArray
         supported DTypes that the asserter can handle
         */
        std::vector<DBDataSchema::DType> DTypeArray;

    protected:
        void setName(std::string newString);

        void setDTypeArray(DBDataSchema::DType * newDTypeArray, int size);

	public:
        Asserter();

        virtual ~Asserter();

        /*! \brief check whether DType is supporter by this asserter
         \param DBDataSchema::DType thisDType: dtype to test whether this assertion works or not
         \return 1 if ok, 0 if not

         Checks whether the DType of this data object can be handled by this asserter. If not, throw an
         error.*/
		int checkDType(DBDataSchema::DType thisDType);

        /*! \brief if the specific implementation supports parameters, this function sets the specified parameter
         \param int parNum: the number of the parameter to set
         \param void* value: value to set
         \return 1 if ok, 0 if not

         Sets the parNum-th parameter as defined by the implementor, with a specified value. This needs to be
         implemented by the assertion implementer.*/
		virtual int setParameter(int parNum, void* value) = 0;

        /*! \brief if the specific implementation supports parameters, this function returns the specified parameter
         \param int parNum: the number of the parameter to set
         \return a void pointer to the parameter variable.

         Sets the parNum-th parameter as defined by the implementor, with a specified value. This needs to be
         implemented by the assertion implementer.*/
		virtual void* getParameter(int parNum) = 0;

        /*! \brief executes the assertion for a specific data object and value
         \param DBDataSchema::DType thisDType: dtype to execute this assertion for
         \param void* value: pointer to the value that needs to be asserted
         \return 1 if assertion is passed, 0 if assertion is not passed successfully

         Runs the assertion on the specified value. Returns 1 if the assertion is passen, 0 if not. This needs to be
         implemented by the assertion implementer.*/
		virtual bool execute(DBDataSchema::DType thisDType, void* value) = 0;

        virtual std::string getName();
    };
}

#endif


text:
using System;

using NUnit.Framework;

using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.Test;

namespace Org.BouncyCastle.Crypto.Tests
{
	/**
	* Wrap Test based on RFC3211 test vectors
	*/
	[TestFixture]
	public class Rfc3211WrapTest
		: SimpleTest
	{
		// Note: These test data assume the Rfc3211WrapEngine will call SecureRandom.NextBytes

		SecureRandom r1 = FixedSecureRandom.From(
			new byte[]{ 0xC4, 0x36, 0xF5, 0x41 });

		SecureRandom r2 = FixedSecureRandom.From(
			new byte[]{ 0xFA, 0x06, 0x0A, 0x45 });

		public override string Name
		{
			get { return "RFC3211Wrap"; }
		}

		private void doWrapTest(
			int				id,
			IBlockCipher	engine,
			byte[]			kek,
			byte[]			iv,
			SecureRandom	rand,
			byte[]			inBytes,
			byte[]			outBytes)
		{
			IWrapper wrapper = new Rfc3211WrapEngine(engine);

			wrapper.Init(true, new ParametersWithRandom(
				new ParametersWithIV(new KeyParameter(kek), iv), rand));

			byte[] cText = wrapper.Wrap(inBytes, 0, inBytes.Length);
			if (!AreEqual(cText, outBytes))
			{
				Fail("failed Wrap test " + id  + " expected "
					+ Hex.ToHexString(outBytes) + " got " + Hex.ToHexString(cText));
			}

			wrapper.Init(false, new ParametersWithIV(new KeyParameter(kek), iv));

			byte[] pText = wrapper.Unwrap(outBytes, 0, outBytes.Length);
			if (!AreEqual(pText, inBytes))
			{
				Fail("rfailed Unwrap test " + id  + " expected "
					+ Hex.ToHexString(inBytes) + " got " + Hex.ToHexString(pText));
			}
		}

		private void doTestCorruption()
		{
			byte[] kek = Hex.Decode("D1DAA78615F287E6");
			byte[] iv = Hex.Decode("EFE598EF21B33D6D");

			IWrapper wrapper = new Rfc3211WrapEngine(new DesEngine());

			wrapper.Init(false, new ParametersWithIV(new KeyParameter(kek), iv));

			byte[] block = Hex.Decode("ff739D838C627C897323A2F8C436F541");
			encryptBlock(kek, iv, block);

			try
			{
				wrapper.Unwrap(block, 0, block.Length);

				Fail("bad length not detected");
			}
			catch (InvalidCipherTextException e)
			{
				if (!e.Message.Equals("wrapped key corrupted"))
				{
					Fail("wrong exception on length");
				}
			}

			block = Hex.Decode("08639D838C627C897323A2F8C436F541");
			doTestChecksum(kek, iv, block, wrapper);

			block = Hex.Decode("08736D838C627C897323A2F8C436F541");
			doTestChecksum(kek, iv, block, wrapper);

			block = Hex.Decode("08739D638C627C897323A2F8C436F541");
			doTestChecksum(kek, iv, block, wrapper);
		}

		private void doTestChecksum(
			byte[]		kek,
			byte[]		iv,
			byte[]		block,
			IWrapper	wrapper)
		{
			encryptBlock(kek, iv, block);

			try
			{
				wrapper.Unwrap(block, 0, block.Length);

				Fail("bad checksum not detected");
			}
			catch (InvalidCipherTextException e)
			{
				if (!e.Message.Equals("wrapped key fails checksum"))
				{
					Fail("wrong exception");
				}
			}
		}

		private void encryptBlock(byte[] key, byte[] iv, byte[] cekBlock)
		{
			IBlockCipher engine = new CbcBlockCipher(new DesEngine());

			engine.Init(true, new ParametersWithIV(new KeyParameter(key), iv));

			for (int i = 0; i < cekBlock.Length; i += 8)
			{
				engine.ProcessBlock(cekBlock, i, cekBlock, i);
			}

			for (int i = 0; i < cekBlock.Length; i += 8)
			{
				engine.ProcessBlock(cekBlock, i, cekBlock, i);
			}
		}

		public override void PerformTest()
		{
			doWrapTest(1, new DesEngine(), Hex.Decode("D1DAA78615F287E6"), Hex.Decode("EFE598EF21B33D6D"), r1, Hex.Decode("8C627C897323A2F8"), Hex.Decode("B81B2565EE373CA6DEDCA26A178B0C10"));
			doWrapTest(2, new DesEdeEngine(), Hex.Decode("6A8970BF68C92CAEA84A8DF28510858607126380CC47AB2D"), Hex.Decode("BAF1CA7931213C4E"), r2,
				Hex.Decode("8C637D887223A2F965B566EB014B0FA5D52300A3F7EA40FFFC577203C71BAF3B"),
				Hex.Decode("C03C514ABDB9E2C5AAC038572B5E24553876B377AAFB82ECA5A9D73F8AB143D9EC74E6CAD7DB260C"));

			doTestCorruption();

			IWrapper wrapper = new Rfc3211WrapEngine(new DesEngine());
			ParametersWithIV parameters = new ParametersWithIV(new KeyParameter(new byte[16]), new byte[16]);
			byte[] buf = new byte[16];

			try
			{
				wrapper.Init(true, parameters);

				wrapper.Unwrap(buf, 0, buf.Length);

				Fail("failed Unwrap state test.");
			}
			catch (InvalidOperationException)
			{
				// expected
			}
			catch (InvalidCipherTextException e)
			{
				Fail("unexpected exception: " + e, e);
			}

			try
			{
				wrapper.Init(false, parameters);

				wrapper.Wrap(buf, 0, buf.Length);

				Fail("failed Unwrap state test.");
			}
			catch (InvalidOperationException)
			{
				// expected
			}

			//
			// short test
			//
			try
			{
				wrapper.Init(false, parameters);

				wrapper.Unwrap(buf, 0, buf.Length / 2);

				Fail("failed Unwrap short test.");
			}
			catch (InvalidCipherTextException)
			{
				// expected
			}
		}

		public static void Main(
			string[] args)
		{
			RunTest(new Rfc3211WrapTest());
		}

		[Test]
		public void TestFunction()
		{
			string resultText = Perform().ToString();

			Assert.AreEqual(Name + ": Okay", resultText);
		}
	}
}


text:
Persistent<FunctionTemplate> Image::constructor;

void Image::Initialize(Handle<Object> target) {

    HandleScope scope;

    constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(Image::New));
    constructor->InstanceTemplate()->SetInternalFieldCount(1);
    constructor->SetClassName(String::NewSymbol("Image"));

    NODE_SET_PROTOTYPE_METHOD(constructor, "getPixel", getPixel);
    NODE_SET_PROTOTYPE_METHOD(constructor, "setPixel", setPixel);
    NODE_SET_PROTOTYPE_METHOD(constructor, "encodeSync", encodeSync);
    NODE_SET_PROTOTYPE_METHOD(constructor, "encode", encode);
    NODE_SET_PROTOTYPE_METHOD(constructor, "view", view);
    NODE_SET_PROTOTYPE_METHOD(constructor, "save", save);
    NODE_SET_PROTOTYPE_METHOD(constructor, "setGrayScaleToAlpha", setGrayScaleToAlpha);
    NODE_SET_PROTOTYPE_METHOD(constructor, "width", width);
    NODE_SET_PROTOTYPE_METHOD(constructor, "height", height);
    NODE_SET_PROTOTYPE_METHOD(constructor, "painted", painted);
    NODE_SET_PROTOTYPE_METHOD(constructor, "composite", composite);
    NODE_SET_PROTOTYPE_METHOD(constructor, "premultiplySync", premultiplySync);
    NODE_SET_PROTOTYPE_METHOD(constructor, "premultiply", premultiply);
    NODE_SET_PROTOTYPE_METHOD(constructor, "demultiplySync", demultiplySync);
    NODE_SET_PROTOTYPE_METHOD(constructor, "demultiply", demultiply);
    NODE_SET_PROTOTYPE_METHOD(constructor, "clear", clear);
    NODE_SET_PROTOTYPE_METHOD(constructor, "clearSync", clear);

    ATTR(constructor, "background", get_prop, set_prop);

    // This *must* go after the ATTR setting
    NODE_SET_METHOD(constructor->GetFunction(),
                    "open",
                    Image::open);
    NODE_SET_METHOD(constructor->GetFunction(),
                    "fromBytes",
                    Image::fromBytes);
    NODE_SET_METHOD(constructor->GetFunction(),
                    "openSync",
                    Image::openSync);
    NODE_SET_METHOD(constructor->GetFunction(),
                    "fromBytesSync",
                    Image::fromBytesSync);
    target->Set(String::NewSymbol("Image"),constructor->GetFunction());
}

Image::Image(unsigned int width, unsigned int height) :
    ObjectWrap(),
    this_(boost::make_shared<mapnik::image_32>(width,height)),
    estimated_size_(width * height * 4)
{
    V8::AdjustAmountOfExternalAllocatedMemory(estimated_size_);
}

Image::Image(image_ptr _this) :
    ObjectWrap(),
    this_(_this),
    estimated_size_(this_->width() * this_->height() * 4)
{
    V8::AdjustAmountOfExternalAllocatedMemory(estimated_size_);
}

Image::~Image()
{
    V8::AdjustAmountOfExternalAllocatedMemory(-estimated_size_);
}

Handle<Value> Image::New(const Arguments& args)
{
    HandleScope scope;
    if (!args.IsConstructCall())
        return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));

    if (args[0]->IsExternal())
    {
        //std::clog << "external!\n";
        Local<External> ext = Local<External>::Cast(args[0]);
        void* ptr = ext->Value();
        Image* im =  static_cast<Image*>(ptr);
        im->Wrap(args.This());
        return args.This();
    }

    try
    {
        if (args.Length() == 2)
        {
            if (!args[0]->IsNumber() || !args[1]->IsNumber())
                return ThrowException(Exception::Error(
                                          String::New("Image 'width' and 'height' must be a integers")));
            Image* im = new Image(args[0]->IntegerValue(),args[1]->IntegerValue());
            im->Wrap(args.This());
            return args.This();
        }
        else
        {
            return ThrowException(Exception::Error(
                                      String::New("please provide Image width and height")));
        }
    }
    catch (std::exception const& ex)
    {
        return ThrowException(Exception::Error(
                                  String::New(ex.what())));
    }
    return Undefined();
}

Handle<Value> Image::get_prop(Local<String> property,
                              const AccessorInfo& info)
{
    HandleScope scope;
    Image* im = node::ObjectWrap::Unwrap<Image>(info.Holder());
    std::string a = TOSTR(property);
    if (a == "background") {
        boost::optional<mapnik::color> c = im->get()->get_background();
        if (c)
            return scope.Close(Color::New(*c));
        else
            return Undefined();
    }
    return Undefined();
}

void Image::set_prop(Local<String> property,
                     Local<Value> value,
                     const AccessorInfo& info)
{
    HandleScope scope;
    Image* im = node::ObjectWrap::Unwrap<Image>(info.Holder());
    std::string a = TOSTR(property);
    if (a == "background") {
        if (!value->IsObject())
            ThrowException(Exception::TypeError(
                               String::New("mapnik.Color expected")));

        Local<Object> obj = value->ToObject();
        if (obj->IsNull() || obj->IsUndefined() || !Color::constructor->HasInstance(obj))
            ThrowException(Exception::TypeError(String::New("mapnik.Color expected")));
        Color *c = node::ObjectWrap::Unwrap<Color>(obj);
        im->get()->set_background(*c->get());
    }
}

Handle<Value> Image::getPixel(const Arguments& args)
{
    HandleScope scope;
    int x = 0;
    int y = 0;
    if (args.Length() >= 2) {
        if (!args[0]->IsNumber())
            return ThrowException(Exception::TypeError(
                                      String::New("first arg, 'x' must be an integer")));
        if (!args[1]->IsNumber())
            return ThrowException(Exception::TypeError(
                                      String::New("second arg, 'y' must be an integer")));
        x = args[0]->IntegerValue();
        y = args[1]->IntegerValue();
    } else {
        return ThrowException(Exception::TypeError(
                                  String::New("must supply x,y to query pixel color")));
    }
    Image* im = node::ObjectWrap::Unwrap<Image>(args.This());
    mapnik::image_data_32 const& data = im->this_->data();
    if (x >= 0 && x < static_cast<int>(data.width())
        && y >= 0 && y < static_cast<int>(data.height()))
    {
        unsigned pixel = data(x,y);
        unsigned r = pixel & 0xff;
        unsigned g = (pixel >> 8) & 0xff;
        unsigned b = (pixel >> 16) & 0xff;
        unsigned a = (pixel >> 24) & 0xff;
        return Color::New(mapnik::color(r,g,b,a));
    }
    return Undefined();
}

Handle<Value> Image::setPixel(const Arguments& args)
{
    HandleScope scope;
    if (args.Length() < 3 || (!args[0]->IsNumber() && !args[1]->IsNumber())) {
        return ThrowException(Exception::TypeError(String::New("expects three arguments: x, y, and pixel value")));
    }
    Local<Object> obj = args[2]->ToObject();
    if (obj->IsNull() || obj->IsUndefined() || !Color::constructor->HasInstance(obj))
        return ThrowException(Exception::TypeError(String::New("mapnik.Color expected as third arg")));
    Color * color = node::ObjectWrap::Unwrap<Color>(obj);
    int x = args[0]->IntegerValue();
    int y = args[1]->IntegerValue();
    Image* im = node::ObjectWrap::Unwrap<Image>(args.This());
    mapnik::image_data_32 & data = im->this_->data();
    if (x < static_cast<int>(data.width()) && y < static_cast<int>(data.height()))
    {
        data(x,y) = color->get()->rgba();
        return scope.Close(Undefined());
    }
    return ThrowException(Exception::TypeError(String::New("invalid pixel requested")));
    return scope.Close(Undefined());
}

Handle<Value> Image::clearSync(const Arguments& args)
{
    HandleScope scope;
#if MAPNIK_VERSION >= 200200
    Image* im = node::ObjectWrap::Unwrap<Image>(args.This());
    im->get()->clear();
#endif
    return Undefined();
}

typedef struct {
    uv_work_t request;
    Image* im;
    std::string format;
    bool error;
    std::string error_name;
    Persistent<Function> cb;
} clear_image_baton_t;

Handle<Value> Image::clear(const Arguments& args)
{
    HandleScope scope;
    Image* im = node::ObjectWrap::Unwrap<Image>(args.This());

    if (args.Length() == 0) {
        return clearSync(args);
    }
    // ensure callback is a function
    Local<Value> callback = args[args.Length()-1];
    if (!args[args.Length()-1]->IsFunction())
        return ThrowException(Exception::TypeError(
                                  String::New("last argument must be a callback function")));
    clear_image_baton_t *closure = new clear_image_baton_t();
    closure->request.data = closure;
    closure->im = im;
    closure->error = false;
    closure->cb = Persistent<Function>::New(Handle<Function>::Cast(callback));
    uv_queue_work(uv_default_loop(), &closure->request, EIO_Clear, (uv_after_work_cb)EIO_AfterClear);
    im->Ref();
    return Undefined();
}

void Image::EIO_Clear(uv_work_t* req)
{
#if MAPNIK_VERSION >= 200200
    clear_image_baton_t *closure = static_cast<clear_image_baton_t *>(req->data);
    try
    {
        closure->im->get()->clear();
    }
    catch(std::exception const& ex)
    {
        closure->error = true;
        closure->error_name = ex.what();
    }
#endif
}

void Image::EIO_AfterClear(uv_work_t* req)
{
    HandleScope scope;
    clear_image_baton_t *closure = static_cast<clear_image_baton_t *>(req->data);
    TryCatch try_catch;
    if (closure->error)
    {
        Local<Value> argv[1] = { Exception::Error(String::New(closure->error_name.c_str())) };
        closure->cb->Call(Context::GetCurrent()->Global(), 1, argv);
    }
    else
    {
        Local<Value> argv[1] = { Local<Value>::New(Null()) };
        closure->cb->Call(Context::GetCurrent()->Global(), 1, argv);
    }
    if (try_catch.HasCaught())
    {
        node::FatalException(try_catch);
    }
    closure->im->Unref();
    closure->cb.Dispose();
    delete closure;
}

Handle<Value> Image::setGrayScaleToAlpha(const Arguments& args)
{
    HandleScope scope;

    Image* im = node::ObjectWrap::Unwrap<Image>(args.This());
    if (args.Length() == 0) {
        im->this_->set_grayscale_to_alpha();
    } else {
        if (!args[0]->IsObject())
            return ThrowException(Exception::TypeError(
                                      String::New("optional second arg must be a mapnik.Color")));

        Local<Object> obj = args[0]->ToObject();

        if (obj->IsNull() || obj->IsUndefined() || !Color::constructor->HasInstance(obj))
            return ThrowException(Exception::TypeError(String::New("mapnik.Color expected as second arg")));

        Color * color = node::ObjectWrap::Unwrap<Color>(obj);

        mapnik::image_data_32 & data = im->this_->data();
        for (unsigned int y = 0; y < data.height(); ++y)
        {
            unsigned int* row_from = data.getRow(y);
            for (unsigned int x = 0; x < data.width(); ++x)
            {
                unsigned rgba = row_from[x];
                // TODO - big endian support
                unsigned r = rgba & 0xff;
                unsigned g = (rgba >> 8 ) & 0xff;
                unsigned b = (rgba >> 16) & 0xff;

                // magic numbers for grayscale
                unsigned a = (int)((r * .3) + (g * .59) + (b * .11));

                row_from[x] = (a << 24) |
                    (color->get()->blue() << 16) |
                    (color->get()->green() << 8) |
                    (color->get()->red()) ;
            }
        }
    }

    return Undefined();
}

typedef struct {
    uv_work_t request;
    Image* im;
    bool error;
    std::string error_name;
    Persistent<Function> cb;
} image_op_baton_t;

Handle<Value> Image::premultiplySync(const Arguments& args)
{
    HandleScope scope;
#if MAPNIK_VERSION >= 200100
    Image* im = node::ObjectWrap::Unwrap<Image>(args.This());
    im->get()->premultiply();
#endif
    return Undefined();
}

Handle<Value> Image::premultiply(const Arguments& args)
{
    HandleScope scope;
    if (args.Length() == 0) {
        return premultiplySync(args);
    }
    Image* im = node::ObjectWrap::Unwrap<Image>(args.This());

    // ensure callback is a function
    Local<Value> callback = args[args.Length()-1];
    if (!args[args.Length()-1]->IsFunction())
        return ThrowException(Exception::TypeError(
                                  String::New("last argument must be a callback function")));

    image_op_baton_t *closure = new image_op_baton_t();
    closure->request.data = closure;
    closure->im = im;
    closure->error = false;
    closure->cb = Persistent<Function>::New(Handle<Function>::Cast(callback));
    uv_queue_work(uv_default_loop(), &closure->request, EIO_Premultiply, (uv_after_work_cb)EIO_AfterMultiply);
    im->Ref();
    return Undefined();
}

void Image::EIO_Premultiply(uv_work_t* req)
{
    image_op_baton_t *closure = static_cast<image_op_baton_t *>(req->data);

    try
    {
        closure->im->get()->premultiply();
    }
    catch (std::exception const& ex)
    {
        closure->error = true;
        closure->error_name = ex.what();
    }
}

void Image::EIO_AfterMultiply(uv_work_t* req)
{
    HandleScope scope;
    image_op_baton_t *closure = static_cast<image_op_baton_t *>(req->data);
    TryCatch try_catch;
    if (closure->error)
    {
        Local<Value> argv[1] = { Exception::Error(String::New(closure->error_name.c_str())) };
        closure->cb->Call(Context::GetCurrent()->Global(), 1, argv);
    }
    else
    {
        Local<Value> argv[2] = { Local<Value>::New(Null()), Local<Value>::New(closure->im->handle_) };
        closure->cb->Call(Context::GetCurrent()->Global(), 2, argv);
    }
    if (try_catch.HasCaught()) {
        node::FatalException(try_catch);
    }
    closure->im->Unref();
    closure->cb.Dispose();
    delete closure;
}

Handle<Value> Image::demultiplySync(const Arguments& args)
{
    HandleScope scope;
#if MAPNIK_VERSION >= 200100
    Image* im = node::ObjectWrap::Unwrap<Image>(args.This());
    im->get()->demultiply();
#endif
    return Undefined();
}

Handle<Value> Image::demultiply(const Arguments& args)
{
    HandleScope scope;
    if (args.Length() == 0) {
        return demultiplySync(args);
    }
    Image* im = node::ObjectWrap::Unwrap<Image>(args.This());

    // ensure callback is a function
    Local<Value> callback = args[args.Length()-1];
    if (!args[args.Length()-1]->IsFunction())
        return ThrowException(Exception::TypeError(
                                  String::New("last argument must be a callback function")));

    image_op_baton_t *closure = new image_op_baton_t();
    closure->request.data = closure;
    closure->im = im;
    closure->error = false;
    closure->cb = Persistent<Function>::New(Handle<Function>::Cast(callback));
    uv_queue_work(uv_default_loop(), &closure->request, EIO_Demultiply, (uv_after_work_cb)EIO_AfterMultiply);
    im->Ref();
    return Undefined();
}

void Image::EIO_Demultiply(uv_work_t* req)
{
    image_op_baton_t *closure = static_cast<image_op_baton_t *>(req->data);

    try
    {
        closure->im->get()->demultiply();
    }
    catch (std::exception const& ex)
    {
        closure->error = true;
        closure->error_name = ex.what();
    }
}

Handle<Value> Image::painted(const Arguments& args)
{
    HandleScope scope;

    Image* im = node::ObjectWrap::Unwrap<Image>(args.This());
    return scope.Close(Boolean::New(im->get()->painted()));
}

Handle<Value> Image::width(const Arguments& args)
{
    HandleScope scope;

    Image* im = node::ObjectWrap::Unwrap<Image>(args.This());
    return scope.Close(Integer::New(im->get()->width()));
}

Handle<Value> Image::height(const Arguments& args)
{
    HandleScope scope;

    Image* im = node::ObjectWrap::Unwrap<Image>(args.This());
    return scope.Close(Integer::New(im->get()->height()));
}

Handle<Value> Image::openSync(const Arguments& args)
{
    HandleScope scope;

    if (args.Length() < 1) {
        return ThrowException(Exception::TypeError(
                                  String::New("must provide a string argument")));
    }

    if (!args[0]->IsString()) {
        return ThrowException(Exception::TypeError(String::New(
                                                       "Argument must be a string")));
    }

    try
    {
        std::string filename = TOSTR(args[0]);
        boost::optional<std::string> type = mapnik::type_from_filename(filename);
        if (type)
        {
            std::auto_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(filename,*type));
            if (reader.get())
            {
                boost::shared_ptr<mapnik::image_32> image_ptr(new mapnik::image_32(reader->width(),reader->height()));
                reader->read(0,0,image_ptr->data());
                Image* im = new Image(image_ptr);
                Handle<Value> ext = External::New(im);
                Handle<Object> obj = constructor->GetFunction()->NewInstance(1, &ext);
                return scope.Close(obj);
            }
            return ThrowException(Exception::TypeError(String::New(
                                                           ("Failed to load: " + filename).c_str())));
        }
        return ThrowException(Exception::TypeError(String::New(
                                                       ("Unsupported image format:" + filename).c_str())));
    }
    catch (std::exception const& ex)
    {
        return ThrowException(Exception::Error(
                                  String::New(ex.what())));
    }
}

typedef struct {
    uv_work_t request;
    image_ptr im;
    const char *data;
    size_t dataLength;
    bool error;
    std::string error_name;
    Persistent<Function> cb;
} image_mem_ptr_baton_t;

typedef struct {
    uv_work_t request;
    image_ptr im;
    std::string filename;
    bool error;
    std::string error_name;
    Persistent<Function> cb;
} image_file_ptr_baton_t;

Handle<Value> Image::open(const Arguments& args)
{
    HandleScope scope;

    if (args.Length() == 1) {
        return openSync(args);
    }

    if (args.Length() < 2) {
        return ThrowException(Exception::TypeError(
                                  String::New("must provide a string argument")));
    }

    if (!args[0]->IsString()) {
        return ThrowException(Exception::TypeError(String::New(
                                                       "Argument must be a string")));
    }

    // ensure callback is a function
    Local<Value> callback = args[args.Length()-1];
    if (!args[args.Length()-1]->IsFunction())
        return ThrowException(Exception::TypeError(
                                  String::New("last argument must be a callback function")));

    image_file_ptr_baton_t *closure = new image_file_ptr_baton_t();
    closure->request.data = closure;
    closure->filename = TOSTR(args[0]);
    closure->error = false;
    closure->cb = Persistent<Function>::New(Handle<Function>::Cast(callback));
    uv_queue_work(uv_default_loop(), &closure->request, EIO_Open, (uv_after_work_cb)EIO_AfterOpen);
    return Undefined();
}

void Image::EIO_Open(uv_work_t* req)
{
    image_file_ptr_baton_t *closure = static_cast<image_file_ptr_baton_t *>(req->data);

    try
    {
        boost::optional<std::string> type = mapnik::type_from_filename(closure->filename);
        if (!type)
        {
            closure->error = true;
            closure->error_name = "Unsupported image format: " + closure->filename;
        }
        else
        {
            std::auto_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(closure->filename,*type));
            if (reader.get())
            {
                closure->im = boost::make_shared<mapnik::image_32>(reader->width(),reader->height());
                reader->read(0,0,closure->im->data());
            }
            else
            {
                closure->error = true;
                closure->error_name = "Failed to load: " + closure->filename;
            }
        }
    }
    catch (std::exception const& ex)
    {
        closure->error = true;
        closure->error_name = ex.what();
    }
}

void Image::EIO_AfterOpen(uv_work_t* req)
{
    HandleScope scope;
    image_file_ptr_baton_t *closure = static_cast<image_file_ptr_baton_t *>(req->data);
    TryCatch try_catch;
    if (closure->error || !closure->im)
    {
        Local<Value> argv[1] = { Exception::Error(String::New(closure->error_name.c_str())) };
        closure->cb->Call(Context::GetCurrent()->Global(), 1, argv);
    }
    else
    {
        Image* im = new Image(closure->im);
        Handle<Value> ext = External::New(im);
        Local<Object> image_obj = constructor->GetFunction()->NewInstance(1, &ext);
        Local<Value> argv[2] = { Local<Value>::New(Null()), Local<Value>::New(ObjectWrap::Unwrap<Image>(image_obj)->handle_) };
        closure->cb->Call(Context::GetCurrent()->Global(), 2, argv);
    }
    if (try_catch.HasCaught()) {
        node::FatalException(try_catch);
    }
    closure->cb.Dispose();
    delete closure;
}

Handle<Value> Image::fromBytesSync(const Arguments& args)
{
    HandleScope scope;

    if (args.Length() < 1 || !args[0]->IsObject()) {
        return ThrowException(Exception::TypeError(
                                  String::New("must provide a buffer argument")));
    }

    Local<Object> obj = args[0]->ToObject();
    if (obj->IsNull() || obj->IsUndefined())
        return ThrowException(Exception::TypeError(String::New("first argument is invalid, must be a Buffer")));
    if (!node::Buffer::HasInstance(obj)) {
        return ThrowException(Exception::TypeError(String::New(
                                                       "first argument must be a buffer")));
    }

    try
    {
        std::auto_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(node::Buffer::Data(obj),node::Buffer::Length(obj)));
        if (reader.get())
        {
            boost::shared_ptr<mapnik::image_32> image_ptr(new mapnik::image_32(reader->width(),reader->height()));
            reader->read(0,0,image_ptr->data());
            Image* im = new Image(image_ptr);
            Handle<Value> ext = External::New(im);
            return scope.Close(constructor->GetFunction()->NewInstance(1, &ext));
        }
        return ThrowException(Exception::TypeError(String::New(
                                                       "Failed to load from buffer")));
    }
    catch (std::exception const& ex)
    {
        return ThrowException(Exception::Error(
                                  String::New(ex.what())));
    }
}

Handle<Value> Image::fromBytes(const Arguments& args)
{
    HandleScope scope;

    if (args.Length() == 1) {
        return fromBytesSync(args);
    }

    if (args.Length() < 2) {
        return ThrowException(Exception::TypeError(
                                  String::New("must provide a buffer argument")));
    }

    if (!args[0]->IsObject()) {
        return ThrowException(Exception::TypeError(
                                  String::New("must provide a buffer argument")));
    }

    Local<Object> obj = args[0]->ToObject();
    if (obj->IsNull() || obj->IsUndefined())
        return ThrowException(Exception::TypeError(String::New("first argument is invalid, must be a Buffer")));
    if (!node::Buffer::HasInstance(obj)) {
        return ThrowException(Exception::TypeError(String::New(
                                                       "first argument must be a buffer")));
    }
    // ensure callback is a function
    Local<Value> callback = args[args.Length()-1];
    if (!args[args.Length()-1]->IsFunction())
        return ThrowException(Exception::TypeError(
                                  String::New("last argument must be a callback function")));

    image_mem_ptr_baton_t *closure = new image_mem_ptr_baton_t();
    closure->request.data = closure;
    closure->data = node::Buffer::Data(obj);
    closure->dataLength = node::Buffer::Length(obj);
    closure->error = false;
    closure->cb = Persistent<Function>::New(Handle<Function>::Cast(callback));
    uv_queue_work(uv_default_loop(), &closure->request, EIO_FromBytes, (uv_after_work_cb)EIO_AfterFromBytes);
    return Undefined();
}

void Image::EIO_FromBytes(uv_work_t* req)
{
    image_mem_ptr_baton_t *closure = static_cast<image_mem_ptr_baton_t *>(req->data);

    try
    {
        std::auto_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(closure->data,closure->dataLength));
        if (reader.get())
        {
            closure->im = boost::make_shared<mapnik::image_32>(reader->width(),reader->height());
            reader->read(0,0,closure->im->data());
        }
        else
        {
            closure->error = true;
            closure->error_name = "Failed to load from buffer";
        }
    }
    catch (std::exception const& ex)
    {
        closure->error = true;
        closure->error_name = ex.what();
    }
}

void Image::EIO_AfterFromBytes(uv_work_t* req)
{
    HandleScope scope;
    image_mem_ptr_baton_t *closure = static_cast<image_mem_ptr_baton_t *>(req->data);
    TryCatch try_catch;
    if (closure->error || !closure->im)
    {
        Local<Value> argv[1] = { Exception::Error(String::New(closure->error_name.c_str())) };
        closure->cb->Call(Context::GetCurrent()->Global(), 1, argv);
    }
    else
    {
        Image* im = new Image(closure->im);
        Handle<Value> ext = External::New(im);
        Local<Object> image_obj = constructor->GetFunction()->NewInstance(1, &ext);
        Local<Value> argv[2] = { Local<Value>::New(Null()), Local<Value>::New(ObjectWrap::Unwrap<Image>(image_obj)->handle_) };
        closure->cb->Call(Context::GetCurrent()->Global(), 2, argv);
    }
    if (try_catch.HasCaught()) {
        node::FatalException(try_catch);
    }
    closure->cb.Dispose();
    delete closure;
}

Handle<Value> Image::encodeSync(const Arguments& args)
{
    HandleScope scope;

    Image* im = node::ObjectWrap::Unwrap<Image>(args.This());

    std::string format = "png";
    palette_ptr palette;

    // accept custom format
    if (args.Length() >= 1){
        if (!args[0]->IsString())
            return ThrowException(Exception::TypeError(
                                      String::New("first arg, 'format' must be a string")));
        format = TOSTR(args[0]);
    }

    // options hash
    if (args.Length() >= 2) {
        if (!args[1]->IsObject())
            return ThrowException(Exception::TypeError(
                                      String::New("optional second arg must be an options object")));
        Local<Object> options = args[1]->ToObject();
        if (options->Has(String::New("palette")))
        {
            Local<Value> format_opt = options->Get(String::New("palette"));
            if (!format_opt->IsObject())
                return ThrowException(Exception::TypeError(
                                          String::New("'palette' must be an object")));

            Local<Object> obj = format_opt->ToObject();
            if (obj->IsNull() || obj->IsUndefined() || !Palette::constructor->HasInstance(obj))
                return ThrowException(Exception::TypeError(String::New("mapnik.Palette expected as second arg")));
            palette = node::ObjectWrap::Unwrap<Palette>(obj)->palette();
        }
    }

    try {
        std::string s;
        if (palette.get())
        {
            s = save_to_string(*(im->this_), format, *palette);
        }
        else {
            s = save_to_string(*(im->this_), format);
        }

        // https://github.com/joyent/node/commit/3a2f273bd73bc94a6e93f342d629106a9f022f2d#src/node_buffer.h
        #if NODE_VERSION_AT_LEAST(0, 11, 0)
        return scope.Close(node::Buffer::New((char*)s.data(),s.size()));
        #else
        return scope.Close(node::Buffer::New((char*)s.data(),s.size())->handle_);
        #endif
    }
    catch (std::exception const& ex)
    {
        return ThrowException(Exception::Error(
                                  String::New(ex.what())));
    }
}

typedef struct {
    uv_work_t request;
    Image* im;
    std::string format;
    palette_ptr palette;
    bool error;
    std::string error_name;
    Persistent<Function> cb;
    std::string result;
} encode_image_baton_t;

Handle<Value> Image::encode(const Arguments& args)
{
    HandleScope scope;

    Image* im = node::ObjectWrap::Unwrap<Image>(args.This());

    std::string format = "png";
    palette_ptr palette;

    // accept custom format
    if (args.Length() >= 1){
        if (!args[0]->IsString())
            return ThrowException(Exception::TypeError(
                                      String::New("first arg, 'format' must be a string")));
        format = TOSTR(args[0]);
    }

    // options hash
    if (args.Length() >= 2) {
        if (!args[1]->IsObject())
            return ThrowException(Exception::TypeError(
                                      String::New("optional second arg must be an options object")));

        Local<Object> options = args[1]->ToObject();

        if (options->Has(String::New("palette")))
        {
            Local<Value> format_opt = options->Get(String::New("palette"));
            if (!format_opt->IsObject())
                return ThrowException(Exception::TypeError(
                                          String::New("'palette' must be an object")));

            Local<Object> obj = format_opt->ToObject();
            if (obj->IsNull() || obj->IsUndefined() || !Palette::constructor->HasInstance(obj))
                return ThrowException(Exception::TypeError(String::New("mapnik.Palette expected as second arg")));

            palette = node::ObjectWrap::Unwrap<Palette>(obj)->palette();
        }
    }

    // ensure callback is a function
    Local<Value> callback = args[args.Length()-1];
    if (!args[args.Length()-1]->IsFunction())
        return ThrowException(Exception::TypeError(
                                  String::New("last argument must be a callback function")));

    encode_image_baton_t *closure = new encode_image_baton_t();
    closure->request.data = closure;
    closure->im = im;
    closure->format = format;
    closure->palette = palette;
    closure->error = false;
    closure->cb = Persistent<Function>::New(Handle<Function>::Cast(callback));
    uv_queue_work(uv_default_loop(), &closure->request, EIO_Encode, (uv_after_work_cb)EIO_AfterEncode);
    im->Ref();

    return Undefined();
}

void Image::EIO_Encode(uv_work_t* req)
{
    encode_image_baton_t *closure = static_cast<encode_image_baton_t *>(req->data);

    try {
        if (closure->palette.get())
        {
            closure->result = save_to_string(*(closure->im->this_), closure->format, *closure->palette);
        }
        else
        {
            closure->result = save_to_string(*(closure->im->this_), closure->format);
        }
    }
    catch (std::exception const& ex)
    {
        closure->error = true;
        closure->error_name = ex.what();
    }
}

void Image::EIO_AfterEncode(uv_work_t* req)
{
    HandleScope scope;

    encode_image_baton_t *closure = static_cast<encode_image_baton_t *>(req->data);

    TryCatch try_catch;

    if (closure->error) {
        Local<Value> argv[1] = { Exception::Error(String::New(closure->error_name.c_str())) };
        closure->cb->Call(Context::GetCurrent()->Global(), 1, argv);
    }
    else
    {
        #if NODE_VERSION_AT_LEAST(0, 11, 0)
        Local<Value> argv[2] = { Local<Value>::New(Null()), Local<Value>::New(node::Buffer::New((char*)closure->result.data(),closure->result.size())) };
        #else
        Local<Value> argv[2] = { Local<Value>::New(Null()), Local<Value>::New(node::Buffer::New((char*)closure->result.data(),closure->result.size())->handle_) };
        #endif
        closure->cb->Call(Context::GetCurrent()->Global(), 2, argv);
    }

    if (try_catch.HasCaught()) {
        node::FatalException(try_catch);
    }

    closure->im->Unref();
    closure->cb.Dispose();
    delete closure;
}

Handle<Value> Image::view(const Arguments& args)
{
    HandleScope scope;

    if ( (args.Length() != 4) || (!args[0]->IsNumber() && !args[1]->IsNumber() && !args[2]->IsNumber() && !args[3]->IsNumber() ))
        return ThrowException(Exception::TypeError(
                                  String::New("requires 4 integer arguments: x, y, width, height")));

    // TODO parse args
    unsigned x = args[0]->IntegerValue();
    unsigned y = args[1]->IntegerValue();
    unsigned w = args[2]->IntegerValue();
    unsigned h = args[3]->IntegerValue();

    Image* im = node::ObjectWrap::Unwrap<Image>(args.This());
    return scope.Close(ImageView::New(im,x,y,w,h));
}

Handle<Value> Image::save(const Arguments& args)
{
    HandleScope scope;

    if (args.Length() == 0 || !args[0]->IsString()){
        return ThrowException(Exception::TypeError(
                                  String::New("filename required")));
    }

    std::string filename = TOSTR(args[0]);

    std::string format("");

    if (args.Length() >= 2) {
        if (!args[1]->IsString())
            return ThrowException(Exception::TypeError(
                                      String::New("both 'filename' and 'format' arguments must be strings")));
        format = TOSTR(args[1]);
    }
    else
    {
        format = mapnik::guess_type(filename);
        if (format == "<unknown>") {
            std::ostringstream s("");
            s << "unknown output extension for: " << filename << "\n";
            return ThrowException(Exception::Error(
                                      String::New(s.str().c_str())));
        }
    }

    Image* im = node::ObjectWrap::Unwrap<Image>(args.This());
    try
    {
        mapnik::save_to_file<mapnik::image_data_32>(im->get()->data(),filename, format);
    }
    catch (std::exception const& ex)
    {
        return ThrowException(Exception::Error(
                                  String::New(ex.what())));
    }
    return Undefined();
}

#if MAPNIK_VERSION >= 200100

typedef struct {
    uv_work_t request;
    Image* im1;
    Image* im2;
    mapnik::composite_mode_e mode;
    int dx;
    int dy;
    float opacity;
    std::vector<mapnik::filter::filter_type> filters;
    bool error;
    std::string error_name;
    Persistent<Function> cb;
} composite_image_baton_t;

Handle<Value> Image::composite(const Arguments& args)
{
    HandleScope scope;

    if (args.Length() < 1){
        return ThrowException(Exception::TypeError(
                                  String::New("requires at least one argument: an image mask")));
    }

    if (!args[0]->IsObject()) {
        return ThrowException(Exception::TypeError(
                                  String::New("first argument must be an image mask")));
    }

    Local<Object> im2 = args[0]->ToObject();
    if (im2->IsNull() || im2->IsUndefined() || !Image::constructor->HasInstance(im2))
        return ThrowException(Exception::TypeError(String::New("mapnik.Image expected as first arg")));

    // ensure callback is a function
    Local<Value> callback = args[args.Length()-1];
    if (!args[args.Length()-1]->IsFunction())
        return ThrowException(Exception::TypeError(
                                  String::New("last argument must be a callback function")));

    try
    {
        mapnik::composite_mode_e mode = mapnik::src_over;
        float opacity = 1.0;
        std::vector<mapnik::filter::filter_type> filters;
        int dx = 0;
        int dy = 0;
        if (args.Length() >= 2) {
            if (!args[1]->IsObject())
                return ThrowException(Exception::TypeError(
                                          String::New("optional second arg must be an options object")));

            Local<Object> options = args[1]->ToObject();

            if (options->Has(String::New("comp_op")))
            {
                Local<Value> opt = options->Get(String::New("comp_op"));
                if (!opt->IsNumber()) {
                    return ThrowException(Exception::TypeError(
                                              String::New("comp_op must be a mapnik.compositeOp value")));
                }
                mode = static_cast<mapnik::composite_mode_e>(opt->IntegerValue());
            }

            if (options->Has(String::New("opacity")))
            {
                Local<Value> opt = options->Get(String::New("opacity"));
                if (!opt->IsNumber()) {
                    return ThrowException(Exception::TypeError(
                                              String::New("opacity must be a floating point number")));
                }
                opacity = opt->NumberValue();
            }

            if (options->Has(String::New("dx")))
            {
                Local<Value> opt = options->Get(String::New("dx"));
                if (!opt->IsNumber()) {
                    return ThrowException(Exception::TypeError(
                                              String::New("dx must be an integer")));
                }
                dx = opt->IntegerValue();
            }

            if (options->Has(String::New("dy")))
            {
                Local<Value> opt = options->Get(String::New("dy"));
                if (!opt->IsNumber()) {
                    return ThrowException(Exception::TypeError(
                                              String::New("dy must be an integer")));
                }
                dy = opt->IntegerValue();
            }

            if (options->Has(String::New("image_filters")))
            {
                Local<Value> opt = options->Get(String::New("image_filters"));
                if (!opt->IsString()) {
                    return ThrowException(Exception::TypeError(
                                              String::New("image_filters argument must string of filter names")));
                }
                std::string filter_str = TOSTR(opt);
                bool result = mapnik::filter::parse_image_filters(filter_str, filters);
                if (!result)
                {
                    return ThrowException(Exception::TypeError(
                                              String::New("could not parse image_filters")));
                }
            }
        }

        composite_image_baton_t *closure = new composite_image_baton_t();
        closure->request.data = closure;
        closure->im1 = node::ObjectWrap::Unwrap<Image>(args.This());
        closure->im2 = node::ObjectWrap::Unwrap<Image>(im2);
        closure->mode = mode;
        closure->opacity = opacity;
        closure->filters = filters;
        closure->dx = dx;
        closure->dy = dy;
        closure->error = false;
        closure->cb = Persistent<Function>::New(Handle<Function>::Cast(callback));
        uv_queue_work(uv_default_loop(), &closure->request, EIO_Composite, (uv_after_work_cb)EIO_AfterComposite);
        closure->im1->Ref();
        closure->im2->Ref();
    }
    catch (std::exception const& ex)
    {
        return ThrowException(Exception::Error(String::New(ex.what())));
    }
    return Undefined();
}

void Image::EIO_Composite(uv_work_t* req)
{
    composite_image_baton_t *closure = static_cast<composite_image_baton_t *>(req->data);

    try
    {
        if (closure->filters.size() > 0)
        {
            mapnik::filter::filter_visitor<mapnik::image_32> visitor(*closure->im2->this_);
            BOOST_FOREACH(mapnik::filter::filter_type const& filter_tag, closure->filters)
            {
                boost::apply_visitor(visitor, filter_tag);
            }
        }
        mapnik::composite(closure->im1->this_->data(),closure->im2->this_->data(), closure->mode, closure->opacity, closure->dx, closure->dy);
    }
    catch (std::exception const& ex)
    {
        closure->error = true;
        closure->error_name = ex.what();
    }
}

void Image::EIO_AfterComposite(uv_work_t* req)
{
    HandleScope scope;

    composite_image_baton_t *closure = static_cast<composite_image_baton_t *>(req->data);

    TryCatch try_catch;

    if (closure->error) {
        Local<Value> argv[1] = { Exception::Error(String::New(closure->error_name.c_str())) };
        closure->cb->Call(Context::GetCurrent()->Global(), 1, argv);
    } else {
        Local<Value> argv[2] = { Local<Value>::New(Null()), Local<Value>::New(closure->im1->handle_) };
        closure->cb->Call(Context::GetCurrent()->Global(), 2, argv);
    }

    if (try_catch.HasCaught()) {
        node::FatalException(try_catch);
    }

    closure->im1->Unref();
    closure->im2->Unref();
    closure->cb.Dispose();
    delete closure;
}

#else

Handle<Value> Image::composite(const Arguments& args)
{
    HandleScope scope;

    return ThrowException(Exception::TypeError(
                              String::New("compositing is only supported if node-mapnik is built against >= Mapnik 2.1.x")));

}

#endif


text:
import * as Hapi from '../../';
const server = new Hapi.Server();
server.version === '8.0.0'