text:
<?php

namespace Oqq\Minc\Filesystem;

use Oqq\Minc\Filesystem\Exception\AdapterDoesNotHaveDirectoriesException;

/**
 * @author Eric Braun <eb@oqq.be>
 */
class Directory
{
    /** @var string */
    protected $path;

    /** @var FilesystemInterface */
    protected $filesystem;

    /**
     * @param string $path
     * @param FilesystemInterface $filesystem
     */
    public function __construct($path, FilesystemInterface $filesystem)
    {
        $this->path = $path;
        $this->filesystem = $filesystem;
    }

    /**
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * @return FilesystemInterface
     */
    public function getFilesystem()
    {
        return $this->filesystem;
    }

    /**
     * @param string $relativePath
     *
     * @return File
     */
    public function getFile($relativePath)
    {
        $fileKey = $this->getFileKey($this->getAbsolutePath($relativePath));

        return new File($fileKey, $this);
    }

    /**
     * @param string $relativePath
     *
     * @return Directory
     */
    public function getDirectory($relativePath)
    {
        return new Directory($this->getAbsolutePath($relativePath), $this->filesystem);
    }

    /**
     * @return bool
     * @throws AdapterDoesNotHaveDirectoriesException
     */
    public function exists()
    {
        return $this->getFilesystem()->directoryExists($this->path);
    }

    /**
     * @param string $fullPath
     *
     * @return FileKey
     */
    protected function getFileKey($fullPath)
    {
        return new FileKey($fullPath);
    }

    /**
     * @param $relativePath
     *
     * @return string
     */
    protected function getAbsolutePath($relativePath)
    {
        return rtrim($this->path, DIRECTORY_SEPARATOR)
             . DIRECTORY_SEPARATOR
             . ltrim($relativePath, DIRECTORY_SEPARATOR);
    }
}


text:
<?php
require __DIR__. '/../../../vendor/autoload.php';

use FluffycatCom\Mediator\BookMediator;

class MediatorTest extends \PHPUnit_Framework_TestCase {

    public function testA()
    {

        $mediator = new BookMediator('Gamma, Helm, Johnson, and Vlissides','Design Patterns');

        $author = $mediator->getAuthor();
        $title = $mediator->getTitle();

        print('Original Author and Title: ');
        $this->assertEquals('Design Patterns' , $title->getTitle());
        $this->assertEquals('Gamma, Helm, Johnson, and Vlissides' , $author->getAuthor());

        $author->setAuthorLowerCase();
        $this->assertEquals('design patterns' , $title->getTitle());
        $this->assertEquals('gamma, helm, johnson, and vlissides' , $author->getAuthor());

        $title->setTitleUpperCase();
        $this->assertEquals('DESIGN PATTERNS' , $title->getTitle());
        $this->assertEquals('GAMMA, HELM, JOHNSON, AND VLISSIDES' , $author->getAuthor());

    }
}

redpajama_set_name: RedPajamaGithub


text:
{
  "title": "Now you can easily create blogs & websites from R/RStudio with blogdown pkg #rstats https://t.co/9MEesPtlCs",
  "date": "2017-05-12"
}

# blogdown

> **Ines Garmendia** (@inesgn; 4/3): Now you can easily create blogs & websites from R/RStudio with blogdown pkg #rstats https://t.co/9MEesPtlCs  [↪](https://twitter.com/xieyihui/status/862934010670047232)

<!-- -->

> **Ines Garmendia** (@inesgn; 3/1): Building a Blog with Blogdown and GitHub by @TylerSaville https://t.co/UlsKR43KIh  [↪](https://twitter.com/xieyihui/status/862933496586805248)

<!-- -->

> **Warwick R User Group** (@WarwickRUG; 0/1): Slides on unit testing & continuous integration w/ @travisci, and on publishing with bookdown & blogdown are now up: https://t.co/mpbch3Nbjw  [↪](https://twitter.com/xieyihui/status/863036599537463297)

<!-- -->

> **Alvin Thomas** (@alvinthomas13; 0/0): @rdpeng @xieyihui @simplystats It took some learning to move from Hubpress, but I decided to take the dive and try… https://t.co/O7AL469yX1  [↪](https://twitter.com/xieyihui/status/863134935313518592)

<!-- -->

> **Laurens van Duijn** (@LaurensvanDuijn; 0/0): #BlogDown #Thanks2ThePowerCompanyMaintenance  [↪](https://twitter.com/xieyihui/status/862998950051282944)

<!-- -->

# bookdown

> **N(σ x σ, μ)** (@hoxo_m; 3/0): caret のホームページ久々に見たら bookdown になってた / "The caret Package" https://t.co/zKjuJmOaEk  [↪](https://twitter.com/xieyihui/status/862928035690840064)

<!-- -->

> **Warwick R User Group** (@WarwickRUG; 0/1): Slides on unit testing & continuous integration w/ @travisci, and on publishing with bookdown & blogdown are now up: https://t.co/mpbch3Nbjw  [↪](https://twitter.com/xieyihui/status/863036599537463297)

<!-- -->

# knitr

> **Carson Sievert** (@cpsievert; 3/0): @bhaskar_vk widgetframe is neat! I think u can use `knitr:::is_html_output()` to avoid some of the extra options? https://t.co/b6F1Vrc295  [↪](https://twitter.com/xieyihui/status/862853017309253633)

<!-- -->

> **AUR updates bot** (@AUR_updates; 0/1): AUR Package Update: "nodejs-dicy-cli" (A JavaScript based builder for LaTeX, knitr and literate Haskell that autom… https://t.co/KI5lrEy4vT  [↪](https://twitter.com/xieyihui/status/862835493842673665)

<!-- -->

# xaringan

> **Carson Sievert** (@cpsievert; 1/0): @bhaskar_vk well, it's an internal function...and it looks like @xieyihui might be missing some HTML formats? Would… https://t.co/AtJgI1TeL8  [↪](https://twitter.com/xieyihui/status/862854846747168768)

<!-- -->


text:
set -o errexit
set -o nounset
set -o pipefail

ORG="kubernetes"

mkdir -p "${GOPATH}"/src/k8s.io
cd "${GOPATH}"/src/k8s.io

# to restore the dependencies
git clone "https://github.com/kubernetes/kubernetes"
pushd kubernetes
    ./hack/godep-restore.sh
popd

for repo in "apimachinery" "client-go" "apiserver" "kube-aggregator" "sample-apiserver" "apiextensions-apiserver" "api"
do
    git clone "https://github.com/${ORG}/${repo}"
done


text:
package com.mocircle.cidrawing.core;

import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Xfermode;

import com.mocircle.android.logging.CircleLog;
import com.mocircle.cidrawing.persistence.Persistable;
import com.mocircle.cidrawing.persistence.PersistenceException;

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

import java.lang.reflect.Field;
import java.util.Map;

public class CiPaint extends Paint implements Persistable {

    private static final String TAG = "CiPaint";

    private static final String KEY_COLOR = "color";
    private static final String KEY_STROKE_WIDTH = "strokeWidth";
    private static final String KEY_FLAGS = "flags";
    private static final String KEY_ALPHA = "alpha";
    private static final String KEY_STYLE = "style";
    private static final String KEY_SECONDARY_COLOR = "secondaryColor";
    private static final String KEY_XFERMODE = "xfermode";

    private Integer secondaryColor;

    public CiPaint() {
        super();
    }

    public CiPaint(int flags) {
        super(flags);
    }

    public CiPaint(Paint paint) {
        super(paint);
        if (paint instanceof CiPaint) {
            CiPaint p = (CiPaint) paint;
            secondaryColor = p.secondaryColor;
        }
    }

    public Integer getSecondaryColor() {
        return secondaryColor;
    }

    public void setSecondaryColor(Integer color) {
        secondaryColor = color;
    }

    @Override
    public JSONObject generateJson() {
        JSONObject object = new JSONObject();
        try {
            object.put(KEY_COLOR, this.getColor());
            object.put(KEY_STROKE_WIDTH, this.getStrokeWidth());
            object.put(KEY_FLAGS, this.getFlags());
            object.put(KEY_ALPHA, this.getAlpha());
            object.put(KEY_STYLE, this.getStyle().toString());
            object.put(KEY_SECONDARY_COLOR, this.getSecondaryColor());
            object.put(KEY_XFERMODE, getXfermodeAsInt(this.getXfermode()));
        } catch (JSONException e) {
            throw new PersistenceException(e);
        }
        return object;
    }

    @Override
    public Map<String, byte[]> generateResources() {
        return null;
    }

    @Override
    public void loadFromJson(JSONObject object, Map<String, byte[]> resources) {
        if (object != null) {
            try {
                setColor(object.getInt(KEY_COLOR));
                setStrokeWidth((float) object.getDouble(KEY_STROKE_WIDTH));
                setFlags(object.getInt(KEY_FLAGS));
                setAlpha(object.getInt(KEY_ALPHA));
                setStyle(Style.valueOf(object.getString(KEY_STYLE)));
                if (object.has(KEY_SECONDARY_COLOR)) {
                    secondaryColor = object.getInt(KEY_SECONDARY_COLOR);
                }
                if (object.has(KEY_XFERMODE)) {
                    setXfermode(getXfermodeFromInt(object.getInt(KEY_XFERMODE)));
                }
            } catch (JSONException e) {
                throw new PersistenceException(e);
            }
        }
    }

    @Override
    public void afterLoaded() {
    }

    private int getXfermodeAsInt(Xfermode mode) {
        if (mode == null) {
            return -1;
        }
        try {
            Field field = Xfermode.class.getDeclaredField("porterDuffMode");
            field.setAccessible(true);
            return field.getInt(mode);
        } catch (NoSuchFieldException e) {
            CircleLog.w(TAG, e);
        } catch (IllegalAccessException e) {
            CircleLog.w(TAG, e);
        }
        return -1;
    }

    private Xfermode getXfermodeFromInt(int mode) {
        if (mode < 0) {
            return null;
        } else {
            PorterDuffXfermode xfermode = new PorterDuffXfermode(PorterDuff.Mode.values()[mode]);
            return xfermode;
        }
    }
}


text:
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public class DataController : Singleton<DataController>
{
    #region Constructor & Variables

    protected DataController() { }

    private const string DEFAULT_SAVE_NAME = "SketchTracy_";

    [HideInInspector]
    public string fileName;

    #endregion

    #region New Game

    public void NewGame()
    {
        int saveSlotIndex = GetNextAvailableSaveSlot();
        fileName = DEFAULT_SAVE_NAME + saveSlotIndex;
        SaveGame();
        Debug.Log("File " + fileName + " created successfully!");
        Application.LoadLevel("Level 1");
    }

    private int GetNextAvailableSaveSlot()
    {
        bool saveSlotFound = false;
        int saveSlot = 0;

        while (!saveSlotFound)
        {
            if (!File.Exists(Application.persistentDataPath + "/" + DEFAULT_SAVE_NAME + saveSlot + ".dat"))
            {
                saveSlotFound = true;
            }
            else
            {
                saveSlot++;
            }
        }

        return saveSlot;
    }

    #endregion

    #region Save Game

    public void SaveGame()
    {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(Application.persistentDataPath + "/" + fileName + ".dat");

        GameData data = new GameData();
        data.fileName = fileName;

        bf.Serialize(file, data);
        file.Close();
    }

    #endregion

    #region Load Game

    public void LoadGame(int pSaveSlotIndex)
    {
        string fileToLoad = DEFAULT_SAVE_NAME + pSaveSlotIndex;

        if (File.Exists(Application.persistentDataPath + "/" + fileToLoad + ".dat"))
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/" + fileToLoad + ".dat", FileMode.Open);

            GameData data = (GameData)bf.Deserialize(file);
            file.Close();

            fileName = data.fileName;
            Debug.Log("File " + fileName + " loaded successfully!");
        }
        else
        {
            Debug.Log("File " + fileName + " does not exist!");
        }
    }

    #endregion
}

[Serializable]
class GameData
{
    public string fileName;
}


text:
package org.dasein.cloud.aws.network;

import org.apache.log4j.Logger;
import org.dasein.cloud.CloudException;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.Tag;
import org.dasein.cloud.aws.AWSCloud;
import org.dasein.cloud.aws.compute.EC2Exception;
import org.dasein.cloud.aws.compute.EC2Method;
import org.dasein.cloud.identity.ServiceAction;
import org.dasein.cloud.network.*;
import org.dasein.cloud.util.APITrace;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TreeSet;

/**
 * Implements support for AWS VPC network ACLs as Dasein Cloud network firewall support.
 *
Created by George Reese: 2/4/13 9:52 AM

 * @author George Reese
 * @since 2013.04
 * @version 2013.04 initial version (issue #8)
 */
public class NetworkACL extends AbstractNetworkFirewallSupport {
    static private final Logger logger = AWSCloud.getLogger(NetworkACL.class);

    private NetworkACLCapabilities capabilities;

    NetworkACL(AWSCloud cloud) {
        super(cloud);
    }

    @Override
    public void associateWithSubnet(@Nonnull String firewallId, @Nonnull String withSubnetId) throws CloudException, InternalException {
        APITrace.begin(getProvider(), "NetworkFirewall.associateWithSubnet");
        try {
            String currentAssociation = getCurrentAssociation(withSubnetId);

            if( currentAssociation == null ) {
                throw new CloudException("Unable to identify subnet association for " + withSubnetId);
            }
            Map<String,String> parameters = ((AWSCloud)getProvider()).getStandardParameters(getContext(), EC2Method.REPLACE_NETWORK_ACL_ASSOC);
            EC2Method method;
            NodeList blocks;
            Document doc;

            parameters.put("AssociationId", currentAssociation);
            parameters.put("NetworkAclId", firewallId);
            method = new EC2Method((AWSCloud)getProvider(), ((AWSCloud)getProvider()).getEc2Url(), parameters);
            try {
                doc = method.invoke();
            }
            catch( EC2Exception e ) {
                logger.error(e.getSummary());
                throw new CloudException(e);
            }
            String id = null;

            blocks = doc.getElementsByTagName("newAssociationId");
            if( blocks.getLength() > 0 ) {
                id = blocks.item(0).getFirstChild().getNodeValue().trim();
            }
            if( id == null ) {
                throw new CloudException("Association failed without explanation");
            }
        }
        finally {
            APITrace.end();
        }

    }

    @Override
    public @Nonnull String authorize(@Nonnull String firewallId, @Nonnull Direction direction, @Nonnull Permission permission, @Nonnull RuleTarget sourceEndpoint, @Nonnull Protocol protocol, @Nonnull RuleTarget destinationEndpoint, int beginPort, int endPort, int precedence) throws CloudException, InternalException {
        APITrace.begin(getProvider(), "NetworkFirewall.authorize");
        try {
            FirewallRule currentRule = null;

            for( FirewallRule rule : listRules(firewallId) ) {
                if( rule.getDirection().equals(direction) && rule.getPrecedence() == precedence ) {
                    currentRule = rule;
                }
            }

            Map<String,String> parameters = ((AWSCloud)getProvider()).getStandardParameters(getContext(), currentRule == null ? EC2Method.CREATE_NETWORK_ACL_ENTRY : EC2Method.REPLACE_NETWORK_ACL_ENTRY);
            EC2Method method;
            NodeList blocks;
            Document doc;

            parameters.put("NetworkAclId", firewallId);
            parameters.put("Egress", String.valueOf(direction.equals(Direction.EGRESS)));
            parameters.put("RuleNumber", String.valueOf(precedence));
            parameters.put("Protocol", toProtocolNumber(protocol));
            parameters.put("RuleAction", permission.name().toLowerCase());
            String cidr;

            if( direction.equals(Direction.INGRESS) ) {
                cidr = sourceEndpoint.getCidr();
            }
            else {
                cidr = destinationEndpoint.getCidr();
            }
            if( cidr == null ) {
                throw new CloudException("No CIDR was specified for " + (direction.equals(Direction.INGRESS) ? "the source endpoint" : "the destination endpoint"));
            }
            parameters.put("CidrBlock", cidr);
            if( !protocol.equals(Protocol.ICMP) ) {
                parameters.put("PortRange.From", String.valueOf(beginPort));
                parameters.put("PortRange.To", String.valueOf(endPort));
            }
            else {
                parameters.put("Icmp.Code", "-1");
                parameters.put("Icmp.Type", "-1");
            }
            method = new EC2Method((AWSCloud)getProvider(), ((AWSCloud)getProvider()).getEc2Url(), parameters);
            try {
                doc = method.invoke();
            }
            catch( EC2Exception e ) {
                logger.error(e.getSummary());
                throw new CloudException(e);
            }
            blocks = doc.getElementsByTagName("return");
            if( blocks.getLength() > 0 ) {
                if( !blocks.item(0).getFirstChild().getNodeValue().equalsIgnoreCase("true") ) {
                    throw new CloudException("Failed to delete security group without explanation.");
                }
            }
            return (firewallId + ":" + direction.name() + ":" + String.valueOf(precedence));
        }
        finally {
            APITrace.end();
        }
    }

    @Override
    public @Nonnull String createFirewall(@Nonnull FirewallCreateOptions options) throws InternalException, CloudException {
        APITrace.begin(getProvider(), "NetworkFirewall.createFirewall");
        try {
            Map<String,String> parameters = ((AWSCloud)getProvider()).getStandardParameters(getContext(), EC2Method.CREATE_NETWORK_ACL);
            EC2Method method;
            NodeList blocks;
            Document doc;

            String vlanId = options.getProviderVlanId();

            if( vlanId != null ) {
                parameters.put("VpcId", vlanId);
            }
            else {
                throw new CloudException("You must specify a VLAN with which to associate your network ACL");
            }
            method = new EC2Method((AWSCloud)getProvider(), ((AWSCloud)getProvider()).getEc2Url(), parameters);
            try {
                doc = method.invoke();
            }
            catch( EC2Exception e ) {
                logger.error(e.getSummary());
                throw new CloudException(e);
            }
            String firewallId;

            blocks = doc.getElementsByTagName("networkAclId");
            if( blocks.getLength() > 0 ) {
                String id = blocks.item(0).getFirstChild().getNodeValue().trim();
                Map<String,String> metaData = options.getMetaData();

                metaData.put("Name", options.getName());
                metaData.put("Description", options.getDescription());

                ArrayList<Tag> tags = new ArrayList<Tag>();

                for( Map.Entry<String,String> entry : metaData.entrySet() ) {
                    String key = entry.getKey();
                    String value = entry.getValue();

                    if( value != null ) {
                        tags.add(new Tag(key, value));
                    }
                }
                ((AWSCloud)getProvider()).createTags(id, tags.toArray(new Tag[tags.size()]));
                firewallId = id;
            }
            else {
                throw new CloudException("Failed to create network ACL without explanation.");
            }
            FirewallRuleCreateOptions[] ruleOptions = options.getInitialRules();

            if( ruleOptions != null && ruleOptions.length > 0 ) {
                for( FirewallRuleCreateOptions option : ruleOptions ) {
                    authorize(firewallId, option);
                }
            }
            return firewallId;
        }
        finally {
            APITrace.end();
        }
    }

    @Override
    public @Nonnull Map<FirewallConstraints.Constraint, Object> getActiveConstraintsForFirewall(@Nonnull String firewallId) throws CloudException, InternalException {
        return new HashMap<FirewallConstraints.Constraint, Object>();
    }

    @Nonnull
    @Override
    public NetworkFirewallCapabilities getCapabilities() {
        if( capabilities == null ) {
            capabilities = new NetworkACLCapabilities((AWSCloud) getProvider());
        }
        return capabilities;
    }

    private @Nullable String getCurrentAssociation(@Nonnull String subnetId) throws InternalException, CloudException {
        APITrace.begin(getProvider(), "NetworkFirewall.getCurrentACLAssociation");
        try {
            Map<String,String> parameters = ((AWSCloud)getProvider()).getStandardParameters(getContext(), EC2Method.DESCRIBE_NETWORK_ACLS);
            EC2Method method;
            NodeList blocks;
            Document doc;

            parameters.put("Filter.1.Name", "association.subnet-id");
            parameters.put("Filter.1.Value.1", subnetId);
            method = new EC2Method((AWSCloud)getProvider(), ((AWSCloud)getProvider()).getEc2Url(), parameters);
            try {
                doc = method.invoke();
            }
            catch( EC2Exception e ) {
                logger.error(e.getSummary());
                throw new CloudException(e);
            }
            blocks = doc.getElementsByTagName("associationSet");
            for( int i=0; i<blocks.getLength(); i++ ) {
                NodeList items = blocks.item(i).getChildNodes();

                for( int j=0; j<items.getLength(); j++ ) {
                    Node item = items.item(j);

                    if( item.getNodeName().equals("item") ) {
                        NodeList attributes = item.getChildNodes();
                        String aid = null;
                        String sid = null;

                        for( int k=0; k<attributes.getLength(); k++ ) {
                            Node attribute = attributes.item(k);

                            if( attribute.getNodeName().equalsIgnoreCase("subnetId") && attribute.hasChildNodes() ) {
                                sid = attribute.getFirstChild().getNodeValue().trim();
                            }
                            else if( attribute.getNodeName().equalsIgnoreCase("networkAclAssociationId") && attribute.hasChildNodes() ) {
                                aid = attribute.getFirstChild().getNodeValue().trim();
                            }
                        }
                        if( sid != null && sid.equals(subnetId) ) {
                            if( aid != null ) {
                                return aid;
                            }
                        }
                    }
                }
            }
            return null;
        }
        finally {
            APITrace.end();
        }
    }

    @Override
    public @Nullable Firewall getFirewall(@Nonnull String firewallId) throws InternalException, CloudException {
        APITrace.begin(getProvider(), "NetworkFirewall.getFirewall");
        try {
            Map<String,String> parameters = ((AWSCloud)getProvider()).getStandardParameters(getContext(), EC2Method.DESCRIBE_NETWORK_ACLS);
            EC2Method method;
            NodeList blocks;
            Document doc;

            parameters.put("NetworkAclId.1", firewallId);
            method = new EC2Method((AWSCloud)getProvider(), ((AWSCloud)getProvider()).getEc2Url(), parameters);
            try {
                doc = method.invoke();
            }
            catch( EC2Exception e ) {
                if( "InvalidNetworkAclID.NotFound".equalsIgnoreCase(e.getCode()) ) {
                    return null;
                }
                throw new CloudException(e);
            }
            blocks = doc.getElementsByTagName("networkAclSet");
            for( int i=0; i<blocks.getLength(); i++ ) {
                NodeList items = blocks.item(i).getChildNodes();

                for( int j=0; j<items.getLength(); j++ ) {
                    Node item = items.item(j);

                    if( item.getNodeName().equals("item") ) {
                        Firewall firewall = toFirewall(item);

                        if( firewall != null ) {
                            return firewall;
                        }
                    }
                }
            }
            return null;
        }
        finally {
            APITrace.end();
        }
    }

    @Override
    public @Nonnull FirewallConstraints getFirewallConstraintsForCloud() throws CloudException, InternalException {
        return getCapabilities().getFirewallConstraintsForCloud();
    }

    @Override
    public @Nonnull String getProviderTermForNetworkFirewall(@Nonnull Locale locale) {
        return getCapabilities().getProviderTermForNetworkFirewall(locale);
    }

    @Override
    public boolean isSubscribed() throws CloudException, InternalException {
        APITrace.begin(getProvider(), "NetworkFirewall.isSubscribed");
        try {
            NetworkServices services = getProvider().getNetworkServices();

            if( services != null ) {
                VLANSupport support = services.getVlanSupport();

                return (support != null && support.isSubscribed());
            }
            return false;
        }
        finally {
            APITrace.end();
        }
    }

    @Override
    public @Nonnull Collection<Firewall> listFirewalls() throws InternalException, CloudException {
        APITrace.begin(getProvider(), "NetworkFirewall.listFirewalls");
        try {
            Map<String,String> parameters = ((AWSCloud)getProvider()).getStandardParameters(getContext(), EC2Method.DESCRIBE_NETWORK_ACLS);
            ArrayList<Firewall> list = new ArrayList<Firewall>();
            EC2Method method;
            NodeList blocks;
            Document doc;

            method = new EC2Method((AWSCloud)getProvider(), ((AWSCloud)getProvider()).getEc2Url(), parameters);
            try {
                doc = method.invoke();
            }
            catch( EC2Exception e ) {
                logger.error(e.getSummary());
                throw new CloudException(e);
            }
            blocks = doc.getElementsByTagName("networkAclSet");
            for( int i=0; i<blocks.getLength(); i++ ) {
                NodeList items = blocks.item(i).getChildNodes();

                for( int j=0; j<items.getLength(); j++ ) {
                    Node item = items.item(j);

                    if( item.getNodeName().equals("item") ) {
                        Firewall firewall = toFirewall(item);

                        if( firewall != null ) {
                            list.add(firewall);
                        }
                    }
                }
            }
            return list;
        }
        finally {
            APITrace.end();
        }
    }

    @Override
    public @Nonnull Iterable<FirewallRule> listRules(@Nonnull String firewallId) throws InternalException, CloudException {
        APITrace.begin(getProvider(), "NetworkFirewall.listRules");
        try {
            Map<String,String> parameters = ((AWSCloud)getProvider()).getStandardParameters(getContext(), EC2Method.DESCRIBE_NETWORK_ACLS);
            EC2Method method;
            NodeList blocks;
            Document doc;

            parameters.put("NetworkAclId.1", firewallId);
            method = new EC2Method((AWSCloud)getProvider(), ((AWSCloud)getProvider()).getEc2Url(), parameters);
            try {
                doc = method.invoke();
            }
            catch( EC2Exception e ) {
                logger.error(e.getSummary());
                throw new CloudException(e);
            }
            ArrayList<FirewallRule> rules = new ArrayList<FirewallRule>();

            blocks = doc.getElementsByTagName("networkAclSet");
            for( int i=0; i<blocks.getLength(); i++ ) {
                NodeList items = blocks.item(i).getChildNodes();

                for( int j=0; j<items.getLength(); j++ ) {
                    Node item = items.item(j);

                    if( item.getNodeName().equals("item") ) {
                        NodeList attributes = item.getChildNodes();

                        for( int k=0; k<attributes.getLength(); k++ ) {
                            Node attribute = attributes.item(k);

                            if( attribute.getNodeName().equalsIgnoreCase("entrySet") && attribute.hasChildNodes() ) {
                                NodeList entryItems = attribute.getChildNodes();

                                for( int l=0; l<entryItems.getLength(); l++ ) {
                                    FirewallRule rule = toRule(firewallId, entryItems.item(l));

                                    if( rule != null ) {
                                        rules.add(rule);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return rules;
        }
        finally {
            APITrace.end();
        }
    }

    @Override
    public @Nonnull Iterable<RuleTargetType> listSupportedDestinationTypes() throws InternalException, CloudException {
        return getCapabilities().listSupportedDestinationTypes();
    }

    @Override
    public @Nonnull Iterable<Direction> listSupportedDirections() throws InternalException, CloudException {
        return getCapabilities().listSupportedDirections();
    }

    @Override
    public @Nonnull Iterable<Permission> listSupportedPermissions() throws InternalException, CloudException {
        return getCapabilities().listSupportedPermissions();
    }

    @Override
    public @Nonnull Iterable<RuleTargetType> listSupportedSourceTypes() throws InternalException, CloudException {
        return getCapabilities().listSupportedSourceTypes();
    }

    @Override
    public @Nonnull String[] mapServiceAction(@Nonnull ServiceAction action) {
        if( action.equals(FirewallSupport.ANY) ) {
            return new String[] { EC2Method.EC2_PREFIX + "*" };
        }
        else if( action.equals(NetworkFirewallSupport.ASSOCIATE) ) {
            return new String[] { EC2Method.EC2_PREFIX + EC2Method.REPLACE_NETWORK_ACL_ASSOC };
        }
        else if( action.equals(NetworkFirewallSupport.AUTHORIZE) ) {
            return new String[] { EC2Method.EC2_PREFIX + EC2Method.CREATE_NETWORK_ACL_ENTRY, EC2Method.EC2_PREFIX + EC2Method.REPLACE_NETWORK_ACL_ENTRY };
        }
        else if( action.equals(NetworkFirewallSupport.CREATE_FIREWALL) ) {
            return new String[] { EC2Method.EC2_PREFIX + EC2Method.CREATE_NETWORK_ACL };
        }
        else if( action.equals(NetworkFirewallSupport.GET_FIREWALL) || action.equals(FirewallSupport.LIST_FIREWALL) ) {
            return new String[] { EC2Method.EC2_PREFIX + EC2Method.DESCRIBE_NETWORK_ACLS };
        }
        else if( action.equals(NetworkFirewallSupport.REMOVE_FIREWALL) ) {
            return new String[] { EC2Method.EC2_PREFIX + EC2Method.DELETE_NETWORK_ACL };
        }
        else if( action.equals(NetworkFirewallSupport.REVOKE) ) {
            return new String[] { EC2Method.EC2_PREFIX + EC2Method.DELETE_NETWORK_ACL_ENTRY };
        }
        return new String[0];
    }

    @Override
    public void removeFirewall(@Nonnull String... firewallIds) throws InternalException, CloudException {
        APITrace.begin(getProvider(), "NetworkFirewall.removeFirewall");
        try {
            for( String id : firewallIds ) {
                Firewall fw = getFirewall(id);

                if( fw != null ) {
                    String vlanId = fw.getProviderVlanId();
                    String newFw = null;

                    for( Firewall current : listFirewalls() ) {
                        if( current.getProviderVlanId().equals(vlanId) ) {
                            boolean pass = false;

                            for( String testId : firewallIds ) {
                                if( id.equals(testId) ) {
                                    pass = true;
                                }
                            }
                            if( !pass ) {
                                newFw = current.getProviderFirewallId();
                                if( current.getName().contains("default") ) {
                                    break;
                                }
                            }
                        }
                    }
                    if( newFw != null ) {
                        for( String subnetId : fw.getSubnetAssociations() ) {
                            associateWithSubnet(newFw, subnetId);
                        }
                    }

                    Map<String,String> parameters = ((AWSCloud)getProvider()).getStandardParameters(getContext(), EC2Method.DELETE_NETWORK_ACL);
                    EC2Method method;
                    NodeList blocks;
                    Document doc;

                    parameters.put("NetworkAclId", id);
                    method = new EC2Method((AWSCloud)getProvider(), ((AWSCloud)getProvider()).getEc2Url(), parameters);
                    try {
                        doc = method.invoke();
                    }
                    catch( EC2Exception e ) {
                        logger.error(e.getSummary());
                        throw new CloudException(e);
                    }
                    blocks = doc.getElementsByTagName("return");
                    if( blocks.getLength() > 0 ) {
                        if( !blocks.item(0).getFirstChild().getNodeValue().equalsIgnoreCase("true") ) {
                            throw new CloudException("Failed to delete security group without explanation.");
                        }
                    }
                }
            }
        }
        finally {
            APITrace.end();
        }
    }

    @Override
    public void removeTags(@Nonnull String firewallId, @Nonnull Tag... tags) throws CloudException, InternalException {
        removeTags(new String[] { firewallId }, tags);
    }

    @Override
    public void removeTags(@Nonnull String[] firewallIds, @Nonnull Tag... tags) throws CloudException, InternalException {
        APITrace.begin(getProvider(), "NetworkFirewall.removeTags");
        try {
            ((AWSCloud)getProvider()).removeTags(firewallIds, tags);
        }
        finally {
            APITrace.end();
        }
    }

    @Override
    public void revoke(@Nonnull String providerFirewallRuleId) throws InternalException, CloudException {
        APITrace.begin(getProvider(), "NetworkFirewall.revoke");
        try {
            Map<String,String> parameters = ((AWSCloud)getProvider()).getStandardParameters(getContext(), EC2Method.DELETE_NETWORK_ACL_ENTRY);
            EC2Method method;
            NodeList blocks;
            Document doc;

            String[] parts = providerFirewallRuleId.split(":");
            if( parts.length != 3 ) {
                throw new CloudException("Invalid network ACL entry: " + providerFirewallRuleId);
            }
            parameters.put("NetworkAclId", parts[0]);
            parameters.put("Egress", String.valueOf(parts[1].equalsIgnoreCase(Direction.EGRESS.name())));
            parameters.put("RuleNumber", parts[2]);
            method = new EC2Method((AWSCloud)getProvider(), ((AWSCloud)getProvider()).getEc2Url(), parameters);
            try {
                doc = method.invoke();
            }
            catch( EC2Exception e ) {
                logger.error(e.getSummary());
                throw new CloudException(e);
            }
            blocks = doc.getElementsByTagName("return");
            if( blocks.getLength() > 0 ) {
                if( !blocks.item(0).getFirstChild().getNodeValue().equalsIgnoreCase("true") ) {
                    throw new CloudException("Failed to delete security group without explanation.");
                }
            }
        }
        finally {
            APITrace.end();
        }
    }

    @Override
    public void updateTags(@Nonnull String firewallId, @Nonnull Tag... tags) throws CloudException, InternalException {
        updateTags(new String[] { firewallId }, tags);
    }

    @Override
    public void updateTags(@Nonnull String[] firewallIds, @Nonnull Tag... tags) throws CloudException, InternalException {
        APITrace.begin(getProvider(), "NetworkFirewall.updateTags");
        try {
            ((AWSCloud)getProvider()).createTags(firewallIds, tags);
        }
        finally {
            APITrace.end();
        }
    }

    private @Nullable Firewall toFirewall(@Nullable Node networkAcl) throws CloudException, InternalException {
        if( networkAcl == null ) {
            return null;
        }
        Firewall firewall = new Firewall();

        firewall.setActive(true);
        firewall.setAvailable(true);

        String regionId = getContext().getRegionId();

        if( regionId == null ) {
            throw new CloudException("No region was specified for this context");
        }
        firewall.setRegionId(regionId);

        NodeList attributes = networkAcl.getChildNodes();

        for( int i=0; i<attributes.getLength(); i++ ) {
            Node attribute = attributes.item(i);

            if( attribute.getNodeName().equalsIgnoreCase("networkAclId") && attribute.hasChildNodes() ) {
                firewall.setProviderFirewallId(attribute.getFirstChild().getNodeValue().trim());
            }
            else if( attribute.getNodeName().equalsIgnoreCase("vpcId") && attribute.hasChildNodes() ) {
                firewall.setProviderVlanId(attribute.getFirstChild().getNodeValue().trim());
            }
            else if( attribute.getNodeName().equalsIgnoreCase("associationSet") && attribute.hasChildNodes() ) {
                TreeSet<String> subnets = new TreeSet<String>();
                NodeList items = attribute.getChildNodes();

                for( int j=0; j<items.getLength(); j++ ) {
                    Node item = items.item(j);

                    if( item.hasChildNodes() ) {
                        NodeList iaList = item.getChildNodes();

                        for( int k=0; k<iaList.getLength(); k++ ) {
                            Node ia = iaList.item(k);

                            if( ia.getNodeName().equalsIgnoreCase("subnetId") && ia.hasChildNodes() ) {
                                subnets.add(ia.getFirstChild().getNodeValue().trim());
                            }
                        }
                    }
                }
                firewall.setSubnetAssociations(subnets.toArray(new String[subnets.size()]));
            }
            else if ( attribute.getNodeName().equalsIgnoreCase("tagSet")) {
                ((AWSCloud)getProvider()).setTags( attribute, firewall );
            }
        }

        String id = firewall.getProviderFirewallId();

        if( id == null ) {
            return null;
        }

        String name = firewall.getName();

        if( name == null ) {
            name = firewall.getTags().get("Name");
            if( name == null ) {
                name = id;
            }
            firewall.setName(name);
        }
        String description = firewall.getDescription();

        if( description == null ) {
            description = firewall.getTags().get("Description");
            if( description == null ) {
                description = name;
            }
            firewall.setDescription(description);
        }
        return firewall;
    }

    private @Nonnull String toProtocolNumber(@Nonnull Protocol protocol) {
        switch( protocol ) {
            case TCP: return "6";
            case UDP: return "17";
            case ANY: return "-1";
            case ICMP: return "1";
            default: return "-1";
        }
    }

    private @Nullable FirewallRule toRule(@Nonnull String firewallId, @Nullable Node aclEntry) throws CloudException, InternalException {
        if( aclEntry == null ) {
            return null;
        }
        NodeList attributes = aclEntry.getChildNodes();
        Permission permission = Permission.ALLOW;
        Direction direction = null;
        Protocol protocol = null;
        int precedence = -1;
        int startPort = -1;
        int endPort = -1;
        String cidr = null;

        for( int i=0; i<attributes.getLength(); i++ ) {
            Node attribute = attributes.item(i);

            if( attribute.getNodeName().equalsIgnoreCase("ruleNumber") && attribute.hasChildNodes() ) {
                precedence = Integer.parseInt(attribute.getFirstChild().getNodeValue().trim());
            }
            if( attribute.getNodeName().equalsIgnoreCase("protocol") && attribute.hasChildNodes() ) {
                String proto = attribute.getFirstChild().getNodeValue().trim();

                if( proto.equalsIgnoreCase("tcp") || proto.equals("6") ) {
                    protocol = Protocol.TCP;
                }
                else if( proto.equalsIgnoreCase("udp") || proto.equals("17") ) {
                    protocol = Protocol.UDP;
                }
                else if( proto.equalsIgnoreCase("icmp") || proto.equals("1") || proto.equals("58") ) {
                    protocol = Protocol.ICMP;
                }
//                else if( proto.equals("-1") || proto.equals("4") || proto.equals("41") ) {
//                    protocol = Protocol.ANY;
//                }
                else {
                    protocol = Protocol.ANY;
                }
            }
            if( attribute.getNodeName().equalsIgnoreCase("ruleAction") && attribute.hasChildNodes() ) {
                String action = attribute.getFirstChild().getNodeValue().trim();

                if( action.equalsIgnoreCase("allow") ) {
                    permission = Permission.ALLOW;
                }
                else {
                    permission = Permission.DENY;
                }
            }
            if( attribute.getNodeName().equalsIgnoreCase("egress") && attribute.hasChildNodes() ) {
                boolean egress = attribute.getFirstChild().getNodeValue().trim().equalsIgnoreCase("true");

                if( egress ) {
                    direction = Direction.EGRESS;
                }
                else {
                    direction = Direction.INGRESS;
                }
            }
            if( attribute.getNodeName().equalsIgnoreCase("cidrBlock") && attribute.hasChildNodes() ) {
                cidr = attribute.getFirstChild().getNodeValue().trim();
            }
            if( attribute.getNodeName().equalsIgnoreCase("portRange") && attribute.hasChildNodes() ) {
                NodeList parts = attribute.getChildNodes();

                for( int j=0; j<parts.getLength(); j++ ) {
                    Node part = parts.item(j);

                    if( part.getNodeName().equalsIgnoreCase("from") && part.hasChildNodes() ) {
                        startPort = Integer.parseInt(part.getFirstChild().getNodeValue().trim());
                    }
                    else if( part.getNodeName().equalsIgnoreCase("to") && part.hasChildNodes() ) {
                        endPort = Integer.parseInt(part.getFirstChild().getNodeValue().trim());
                    }
                }
            }
        }
        if( direction == null || cidr == null ) {
            return null;
        }
        RuleTarget sourceEndpoint, destinationEndpoint;

        if( direction.equals(Direction.INGRESS) ) {
            sourceEndpoint = RuleTarget.getCIDR(cidr);
            destinationEndpoint = RuleTarget.getGlobal(firewallId);
        }
        else {
            destinationEndpoint = RuleTarget.getCIDR(cidr);
            sourceEndpoint = RuleTarget.getGlobal(firewallId);
        }
        if( startPort == -1 && endPort != -1 ) {
            startPort = endPort;
        }
        else if( startPort != -1 && endPort == -1 ) {
            endPort = startPort;
        }
        else if( startPort > endPort ) {
            int x = startPort;

            startPort = endPort;
            endPort = x;
        }
        FirewallRule rule = FirewallRule.getInstance(firewallId + ":" + direction.name() + ":" + String.valueOf(precedence), firewallId, sourceEndpoint, direction, protocol, permission, destinationEndpoint, startPort, endPort);

        rule.withPrecedence(precedence);
        return rule;
    }
}


text:
package org.kie.bc.client;

import com.google.gwtmockito.GwtMockitoTestRunner;
import org.dashbuilder.client.cms.screen.explorer.NavigationExplorerScreen;
import org.dashbuilder.client.navigation.NavigationManager;
import org.dashbuilder.client.navigation.event.NavTreeLoadedEvent;
import org.dashbuilder.client.navigation.impl.NavigationManagerImpl;
import org.dashbuilder.client.navigation.widget.editor.NavTreeEditor;
import org.dashbuilder.navigation.NavGroup;
import org.dashbuilder.navigation.NavItem;
import org.dashbuilder.navigation.NavTree;
import org.dashbuilder.navigation.service.NavigationServices;
import org.guvnor.common.services.shared.config.AppConfigService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.bc.client.home.HomeConfiguration;
import org.kie.bc.client.navigation.NavTreeDefinitions;
import org.kie.bc.client.resources.i18n.NavigationConstants;
import org.kie.workbench.common.workbench.client.admin.DefaultAdminPageHelper;
import org.kie.workbench.common.workbench.client.authz.PermissionTreeSetup;
import org.kie.workbench.common.workbench.client.error.DefaultWorkbenchErrorCallback;
import org.kie.workbench.common.workbench.client.menu.DefaultWorkbenchFeaturesMenusHelper;
import org.mockito.Mock;
import org.uberfire.backend.fs.FileSystemService;
import org.uberfire.client.mvp.ActivityBeansCache;
import org.uberfire.client.workbench.Workbench;
import org.uberfire.client.workbench.widgets.menu.megamenu.WorkbenchMegaMenuPresenter;
import org.uberfire.ext.security.management.client.ClientUserSystemManager;
import org.uberfire.jsbridge.client.AppFormerJsBridge;
import org.uberfire.mocks.CallerMock;
import org.uberfire.mocks.EventSourceMock;
import org.uberfire.mvp.Command;
import org.uberfire.workbench.model.menu.MenuFactory;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(GwtMockitoTestRunner.class)
public class KieWorkbenchEntryPointTest {

    @Mock
    private AppConfigService appConfigService;

    @Mock
    private ActivityBeansCache activityBeansCache;

    @Mock
    private DefaultWorkbenchFeaturesMenusHelper menusHelper;

    @Mock
    protected ClientUserSystemManager userSystemManager;

    @Mock
    protected WorkbenchMegaMenuPresenter menuBar;

    @Mock
    protected Workbench workbench;

    @Mock
    protected PermissionTreeSetup permissionTreeSetup;

    @Mock
    private DefaultAdminPageHelper adminPageHelper;

    private NavTreeDefinitions navTreeDefinitions;

    private NavigationManager navigationManager;

    @Mock
    protected NavigationExplorerScreen navigationExplorerScreen;

    @Mock
    protected NavigationConstants navigationConstants;

    @Mock
    protected NavigationServices navigationServices;

    @Mock
    protected NavTreeEditor navTreeEditor;

    @Mock
    protected EventSourceMock<NavTreeLoadedEvent> navTreeLoadedEvent;

    @Mock
    private DefaultWorkbenchErrorCallback defaultWorkbenchErrorCallback;

    @Mock
    private FileSystemService fileSystemService;

    @Mock
    private HomeConfiguration homeConfiguration;

    private KieWorkbenchEntryPoint kieWorkbenchEntryPoint;

    @Before
    public void setup() {
        doReturn(true).when(this.fileSystemService).isGitDefaultFileSystem();
        navTreeDefinitions = new NavTreeDefinitions();
        navigationManager = new NavigationManagerImpl(new CallerMock<>(navigationServices),
                                                      null,
                                                      navTreeLoadedEvent,
                                                      null,
                                                      null);

        doAnswer(invocationOnMock -> {
            ((Command) invocationOnMock.getArguments()[0]).execute();
            return null;
        }).when(userSystemManager).waitForInitialization(any(Command.class));

        doReturn(mock(MenuFactory.TopLevelMenusBuilder.class)).when(menusHelper).buildMenusFromNavTree(any());

        CallerMock<AppConfigService> appConfigServiceCallerMock = new CallerMock<>(appConfigService);

        kieWorkbenchEntryPoint = spy(new KieWorkbenchEntryPoint(appConfigServiceCallerMock,
                                                                activityBeansCache,
                                                                menusHelper,
                                                                userSystemManager,
                                                                menuBar,
                                                                workbench,
                                                                permissionTreeSetup,
                                                                adminPageHelper,
                                                                navTreeDefinitions,
                                                                navigationManager,
                                                                navigationExplorerScreen,
                                                                defaultWorkbenchErrorCallback,
                                                                mock(AppFormerJsBridge.class),
                                                                homeConfiguration));

        doNothing().when(kieWorkbenchEntryPoint).hideLoadingPopup();
        when(navigationExplorerScreen.getNavTreeEditor()).thenReturn(navTreeEditor);
    }

    @Test
    public void initTest() {
        kieWorkbenchEntryPoint.init();

        verify(workbench).addStartupBlocker(KieWorkbenchEntryPoint.class);
        verify(navTreeEditor).setMaxLevels(NavTreeDefinitions.GROUP_WORKBENCH,
                                           2);
    }

    @Test
    public void testInitializeWorkbench() {
        kieWorkbenchEntryPoint.initializeWorkbench();

        verify(permissionTreeSetup).configureTree();
    }

    @Test
    public void setupMenuTest() {
        kieWorkbenchEntryPoint.setupMenu();

        verify(menuBar).addMenus(any());
        verify(menusHelper).addUtilitiesMenuItems();

        verify(workbench).removeStartupBlocker(KieWorkbenchEntryPoint.class);
    }

    @Test
    public void defaultNavTreeTest() {
        kieWorkbenchEntryPoint.setupMenu();

        NavTree navTree = navigationManager.getNavTree();

        NavGroup workbench = (NavGroup) navTree.getItemById(NavTreeDefinitions.GROUP_WORKBENCH);

        NavGroup deploy = (NavGroup) navTree.getItemById(NavTreeDefinitions.GROUP_DEPLOY);
        NavItem execServers = navTree.getItemById(NavTreeDefinitions.ENTRY_EXECUTION_SERVERS);

        NavGroup manage = (NavGroup) navTree.getItemById(NavTreeDefinitions.GROUP_MANAGE);
        NavItem processDef = navTree.getItemById(NavTreeDefinitions.ENTRY_PROCESS_DEFINITIONS);
        NavItem processInst = navTree.getItemById(NavTreeDefinitions.ENTRY_PROCESS_INSTANCES);
        NavItem taskAdmin = navTree.getItemById(NavTreeDefinitions.ENTRY_ADMINISTRATION_TASKS);
        NavItem jobs = navTree.getItemById(NavTreeDefinitions.ENTRY_JOBS);
        NavItem executionErrors = navTree.getItemById(NavTreeDefinitions.ENTRY_EXECUTION_ERRORS);

        NavGroup track = (NavGroup) navTree.getItemById(NavTreeDefinitions.GROUP_TRACK);
        NavItem tasks = navTree.getItemById(NavTreeDefinitions.ENTRY_TASKS_LIST);
        NavItem processDashboard = navTree.getItemById(NavTreeDefinitions.ENTRY_PROCESS_DASHBOARD);
        NavItem taskDashboard = navTree.getItemById(NavTreeDefinitions.ENTRY_TASK_DASHBOARD);

        assertNotNull(workbench);
        assertNotNull(deploy);
        assertNotNull(manage);
        assertNotNull(track);
        assertEquals(deploy.getParent(),
                     workbench);
        assertEquals(manage.getParent(),
                     workbench);
        assertEquals(track.getParent(),
                     workbench);

        assertNotNull(execServers);
        assertEquals(execServers.getParent(),
                     deploy);

        assertNotNull(processDef);
        assertNotNull(processInst);
        assertNotNull(taskAdmin);
        assertNotNull(jobs);
        assertNotNull(executionErrors);
        assertEquals(processDef.getParent(),
                     manage);
        assertEquals(processInst.getParent(),
                     manage);
        assertEquals(taskAdmin.getParent(),
                     manage);
        assertEquals(jobs.getParent(),
                     manage);
        assertEquals(executionErrors.getParent(),
                     manage);

        assertNotNull(tasks);
        assertNotNull(processDashboard);
        assertNotNull(taskDashboard);
        assertEquals(tasks.getParent(),
                     track);
        assertEquals(processDashboard.getParent(),
                     track);
        assertEquals(taskDashboard.getParent(),
                     track);

    }

    @Test
    public void testSetupAdminPage() {
        kieWorkbenchEntryPoint.setupAdminPage();

        verify(adminPageHelper).setup(false,
                                      true,
                                      false);
    }
}


text:
using System.Collections.Generic;
using System.Linq;
using Zenject;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
using Object = UnityEngine.Object;
using ModestTree;

namespace Zenject
{
    [CustomEditor(typeof(ProjectCompositionRoot))]
    public class ProjectCompositionRootEditor : CompositionRootEditor
    {
    }
}


text:
void MustInitializeWinInet();
void UnInitializeWinInet();

int WinHttpGet(const std::string& strUrl, std::string* outData, std::string* outErr);
int WinHttpPost(const std::string& strUrl, const std::string& postData, std::string* outData, std::string* outErr);

#endif


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.Messaging.EventGrid.SystemEvents
{
    public partial class MapsGeofenceGeometry
    {
        internal static MapsGeofenceGeometry DeserializeMapsGeofenceGeometry(JsonElement element)
        {
            Optional<string> deviceId = default;
            Optional<float> distance = default;
            Optional<string> geometryId = default;
            Optional<float> nearestLat = default;
            Optional<float> nearestLon = default;
            Optional<string> udId = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("deviceId"))
                {
                    deviceId = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("distance"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    distance = property.Value.GetSingle();
                    continue;
                }
                if (property.NameEquals("geometryId"))
                {
                    geometryId = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("nearestLat"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    nearestLat = property.Value.GetSingle();
                    continue;
                }
                if (property.NameEquals("nearestLon"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    nearestLon = property.Value.GetSingle();
                    continue;
                }
                if (property.NameEquals("udId"))
                {
                    udId = property.Value.GetString();
                    continue;
                }
            }
            return new MapsGeofenceGeometry(deviceId.Value, Optional.ToNullable(distance), geometryId.Value, Optional.ToNullable(nearestLat), Optional.ToNullable(nearestLon), udId.Value);
        }
    }
}


text:
import {handleActions} from 'redux-actions'

import * as project from '../project'

describe('reducers > project', () => {
  const reducer = handleActions(project.reducers, project.initialState)
  const mockIdObject = {_id: '1'}
  const mockModification = {_id: '1', type: 'adjust-dwell-time'}

  // Default State Test
  it('should handle default state', () => {
    expect(reducer(undefined, {type: 'blah', payload: {}})).toMatchSnapshot()
  })

  // Specific Handler Tests
  it('should handle add bundle', () => {
    const action = {type: 'add bundle', payload: mockIdObject}
    expect(reducer(undefined, action)).toMatchSnapshot()
  })

  it('should handle add project', () => {
    const action = {type: 'add project', payload: mockIdObject}
    expect(reducer(undefined, action)).toMatchSnapshot()
  })

  it('should handle delete bundle', () => {
    const action = {type: 'delete bundle', payload: '1'}
    const beginState = {bundles: [mockIdObject]}
    expect(reducer(beginState, action)).toMatchSnapshot()
  })

  it('should handle delete modification', () => {
    const action = {type: 'delete modification', payload: '1'}
    const beginState = {modifications: [mockModification]}
    expect(reducer(beginState, action)).toMatchSnapshot()
  })

  it('should handle delete project', () => {
    const action = {type: 'delete project', payload: '1'}
    const beginState = {projects: [mockIdObject]}
    expect(reducer(beginState, action)).toMatchSnapshot()
  })

  it('should handle log out', () => {
    expect(reducer(undefined, {type: 'log out', payload: {}})).toMatchSnapshot()
  })

  it('should handle set bundle', () => {
    const action = {type: 'set bundle', payload: '1'}
    const beginState = {
      bundles: [mockIdObject],
      currentProject: {}
    }
    expect(reducer(beginState, action)).toMatchSnapshot()
  })

  it('should handle set bundles', () => {
    const action = {type: 'set bundles', payload: [mockIdObject]}
    const beginState = {
      currentProject: {
        bundleId: '1'
      }
    }
    expect(reducer(beginState, action)).toMatchSnapshot()
  })

  it('should handle set feeds', () => {
    const action = {type: 'set feeds', payload: [mockIdObject]}
    expect(reducer(undefined, action)).toMatchSnapshot()
  })

  it('should handle set modification', () => {
    const action = {type: 'set modification', payload: mockModification}
    expect(reducer(undefined, action)).toMatchSnapshot()
  })

  it('should handle set modifications', () => {
    const action = {type: 'set modifications', payload: [mockModification]}
    expect(reducer(undefined, action)).toMatchSnapshot()
  })

  it('should handle set project', () => {
    const mockProject = {_id: '1', bundleId: '1'}
    const action = {type: 'set project', payload: mockProject}
    const beginState = {bundles: [mockIdObject], projects: []}
    expect(reducer(beginState, action)).toMatchSnapshot()
  })

  it('should handle set projects', () => {
    const action = {type: 'set projects', payload: [mockIdObject]}
    expect(reducer(undefined, action)).toMatchSnapshot()
  })

  it('should handle show variant', () => {
    const action = {type: 'show variant', payload: 1}
    const beginState = {
      modifications: [
        {
          _id: '1',
          variants: [],
          type: 'adjust-dwell-time'
        }
      ]
    }
    expect(reducer(beginState, action)).toMatchSnapshot()
  })
})


text:
package org.mifos.framework.util.helpers;

import org.mifos.application.accounts.persistence.AccountPersistence;

public class TestGeneralLedgerCode {
    static AccountPersistence accountPersistence = new AccountPersistence();

    public static final Short ASSETS = accountPersistence.getAccountIdFromGlCodeDuringInitialization("10000");
    public static final Short CASH_AND_BANK_BALANCES = accountPersistence
            .getAccountIdFromGlCodeDuringInitialization("11000");
    public static final Short BANK_ACCOUNT_ONE = accountPersistence.getAccountIdFromGlCodeDuringInitialization("11201");
    public static final Short LOANS_TO_CLIENTS = accountPersistence.getAccountIdFromGlCodeDuringInitialization("13101");
    public static final Short FEES = accountPersistence.getAccountIdFromGlCodeDuringInitialization("31301");
    public static final Short INTEREST_ON_LOANS = accountPersistence
            .getAccountIdFromGlCodeDuringInitialization("31101");
    public static final Short MARGIN_MONEY_ONE = accountPersistence.getAccountIdFromGlCodeDuringInitialization("4602");
    public static final Short INTEREST_CLIENT_MANDATORY_SAVINGS = accountPersistence
            .getAccountIdFromGlCodeDuringInitialization("41102");
    public static final Short MANAGED_ICICI_SPLOAN = accountPersistence
            .getAccountIdFromGlCodeDuringInitialization("1504");
    public static final Short INTEREST = accountPersistence.getAccountIdFromGlCodeDuringInitialization("5001");
    public static final Short COST_OF_FUNDS = accountPersistence.getAccountIdFromGlCodeDuringInitialization("41100");
}


text:
// Copyright 2018 The Bazel Authors. All rights reserved.
//
// 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 com.google.devtools.build.lib.skylarkinterface.processor.testsources;

import com.google.devtools.build.lib.skylarkinterface.Param;
import com.google.devtools.build.lib.skylarkinterface.SkylarkCallable;

/**
 * Test case for a SkylarkCallable method which has more arguments than are declared by the
 * annotation.
 */
public class TooManyArguments {

  @SkylarkCallable(
    name = "method_with_too_many_arguments",
    documented = false,
    parameters = {
      @Param(name = "parameter_one", type = String.class, named = true),
    })
  public String methodWithTooManyArguments(String parameterOne, String parameterTwo) {
    return "dolphin";
  }
}


text:
<?xml version="1.0"?>

<!--
   Copyright 2008 University of Rochester

   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.
-->

<!DOCTYPE hibernate-mapping SYSTEM
			"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
	Mapping for file download info

	@author Sharmila Ranganathan
	@author Nathan Sarr
-->
<hibernate-mapping package="edu.ur.ir.statistics">
	<class name="FileDownloadInfo" schema="ir_statistics" table="file_download_info"
		lazy="true">

		<!-- Common id property. -->
		<id name="id" type="long" column="file_download_info_id"
			unsaved-value="0" access="field">
			<generator class="sequence">
				<param name="sequence">ir_statistics.file_download_info_seq</param>
			</generator>
		</id>

		<!-- A versioned entity. -->
		<version name="version" column="version"
			access="org.hibernate.property.DirectPropertyAccessor" />

		<property name="ipAddress" column="ip_address" type="text"
			access="field" />

		<property name="ipAddressPart1" column="ip_address_part1" type="int"
			access="field" />

		<property name="ipAddressPart2" column="ip_address_part2" type="int"
			access="field" />

		<property name="ipAddressPart3" column="ip_address_part3" type="int"
			access="field" />

		<property name="ipAddressPart4" column="ip_address_part4" type="int"
			access="field" />

		<property name="irFileId" column="ir_file_id" type="long"
			access="field" />

		<property name="downloadCount" column="count" type="int"
			access="field" />

		<property name="downloadDate" column="download_date" type="date"
			access="field" />

	</class>

	<!-- named query for getting ip address count -->
	<query name="fileDownloadInfoCount">
		select count(*) from FileDownloadInfo
	</query>

    <!-- named query for getting a the download info -->
	<query name="getDownloadInfo">
		from FileDownloadInfo as fileDownloadInfo where
		fileDownloadInfo.ipAddress = ? AND
		fileDownloadInfo.irFileId = ? AND
		fileDownloadInfo.downloadDate  = ?
	</query>

	<!-- named query for getting a count of all the downloads in the repository -->
	<query name="getIrFileDownloadCount">
		select sum(fileDownloadInfo.downloadCount) from FileDownloadInfo fileDownloadInfo
		where fileDownloadInfo.irFileId = ?
		and (select count(*) from IgnoreIpAddress as ignore
		       where fileDownloadInfo.ipAddressPart1 = ignore.fromAddress1
		       and fileDownloadInfo.ipAddressPart2 = ignore.fromAddress2
		       and fileDownloadInfo.ipAddressPart3 = ignore.fromAddress3
		       and fileDownloadInfo.ipAddressPart4 between ignore.fromAddress4 and ignore.toAddress4) = 0
	</query>

	<!-- named query for getting the ignored file info  records in the repository repository -->
	<query name="getFileDownloadsIgnored">
		select fileDownloadInfo  from FileDownloadInfo fileDownloadInfo
		where (select count(*) from IgnoreIpAddress as ignore
		       where fileDownloadInfo.ipAddressPart1 = ignore.fromAddress1
		       and fileDownloadInfo.ipAddressPart2 = ignore.fromAddress2
		       and fileDownloadInfo.ipAddressPart3 = ignore.fromAddress3
		       and fileDownloadInfo.ipAddressPart4 between ignore.fromAddress4 and ignore.toAddress4) != 0
	    order by fileDownloadInfo.ipAddress,
	             fileDownloadInfo.downloadDate desc
	</query>

	<!--  named query to delete download counts that should not be kept (store counts = false) -->
	<query name="deleteIgnoredFileDownloadInfoCounts">
	    delete from FileDownloadInfo fileDownloadInfo
		where (select count(*) from IgnoreIpAddress as ignore
		where fileDownloadInfo.ipAddressPart1 = ignore.fromAddress1
		and fileDownloadInfo.ipAddressPart2 = ignore.fromAddress2
		and fileDownloadInfo.ipAddressPart3 = ignore.fromAddress3
		and ignore.storeCounts = false
		and fileDownloadInfo.ipAddressPart4 between ignore.fromAddress4 and ignore.toAddress4) != 0
	</query>

	<!-- named query for getting the ignored file info  records in the repository repository -->
	<query name="getFileDownloadsIgnoredCount">
		select count(*) from FileDownloadInfo fileDownloadInfo
		where (select count(*) from IgnoreIpAddress as ignore
		       where fileDownloadInfo.ipAddressPart1 = ignore.fromAddress1
		       and fileDownloadInfo.ipAddressPart2 = ignore.fromAddress2
		       and fileDownloadInfo.ipAddressPart3 = ignore.fromAddress3
		       and fileDownloadInfo.ipAddressPart4 between ignore.fromAddress4 and ignore.toAddress4) != 0
	</query>

	<!-- named query for getting a count of all the downloads in the repository -->
	<query name="getDownloadInfoCountSumAsc">
		select new edu.ur.ir.statistics.IpDownloadCount (fileDownloadInfo.ipAddress, sum(fileDownloadInfo.downloadCount))
		from FileDownloadInfo fileDownloadInfo
		group by fileDownloadInfo.ipAddress
		order by sum(fileDownloadInfo.downloadCount) asc
	</query>

     <!-- named query for getting a count of the number of results that would be produced for the grouping by filedownload ip address -->
	<query name="getDownloadInfoIpSumCount">
		select count(distinct fileDownloadInfo.ipAddress )
		from FileDownloadInfo fileDownloadInfo
	</query>

	<!-- named query for getting a count of all the downloads in the repository -->
	<query name="getDownloadInfoCountSumDesc">
		select new edu.ur.ir.statistics.IpDownloadCount (fileDownloadInfo.ipAddress, sum(fileDownloadInfo.downloadCount))
		from FileDownloadInfo fileDownloadInfo
		group by fileDownloadInfo.ipAddress
		order by sum(fileDownloadInfo.downloadCount) desc
	</query>

</hibernate-mapping>


text:
package com.android.printservice.recommendation.plugin.hp;

import android.net.nsd.NsdServiceInfo;

import java.util.HashMap;

final class PrinterHashMap extends HashMap<String, NsdServiceInfo> {
    public static String getKey(NsdServiceInfo serviceInfo) {
        return serviceInfo.getServiceName();
    }
    public NsdServiceInfo addPrinter(NsdServiceInfo device) {
        return put(getKey(device), device);
    }
    public NsdServiceInfo removePrinter(NsdServiceInfo device) {
        return remove(getKey(device));
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/setObservable_container"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/save_Observable"
        style="@style/FAB"
        app:backgroundTint="@color/colorAccent"
        app:elevation="5dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintDimensionRatio="h,1:1"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0"
        app:srcCompat="@android:drawable/ic_menu_save"/>

</android.support.constraint.ConstraintLayout>


text:
#pragma checksum "C:\Users\rober\onedrive\documents\visual studio 2017\Projects\Examples.CSharp\Examples.CSharp.UWP\MainPage.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "1905826551DA4BFA16EAB106524F54A4"
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace StackOverflow.Playground.UWP
{
    partial class MainPage :
        global::Windows.UI.Xaml.Controls.Page,
        global::Windows.UI.Xaml.Markup.IComponentConnector,
        global::Windows.UI.Xaml.Markup.IComponentConnector2
    {
        /// <summary>
        /// Connect()
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public void Connect(int connectionId, object target)
        {
            this._contentLoaded = true;
        }

        /// <summary>
        /// GetBindingConnector(int connectionId, object target)
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public global::Windows.UI.Xaml.Markup.IComponentConnector GetBindingConnector(int connectionId, object target)
        {
            global::Windows.UI.Xaml.Markup.IComponentConnector returnValue = null;
            return returnValue;
        }
    }
}


text:
struct cm_bearer * cm_modem_obj_create_bearer_internal(MMBearer *mm_bearer,
						       cm_err_t *err)
{
	assert(mm_bearer);
	struct cm_bearer_properties *properties = NULL;
	struct cm_bearer *bearer = NULL;
	MMBearerProperties * mm_bearer_properties =
		mm_bearer_get_properties(mm_bearer);

	properties = cm_bearer_properties_obj_new_internal(mm_bearer_properties);
	bearer = cm_bearer_new(properties, err);
	cm_bearer_obj_set_mm_bearer(bearer, mm_bearer);
	g_object_unref(mm_bearer_properties);
	properties->put(properties);
	return bearer;
}

struct cm_bearer *cm_modem_obj_connect(struct cm_modem *self,
				       struct cm_modem_connect_properties *properties,
				       cm_err_t *err)
{
	assert(self && self->priv && self->priv->mm_simple_modem
	       && properties && err);
	struct cm_bearer *bearer = NULL;
	GError *gerr = NULL;
	MMBearer *mm_bearer =
		mm_modem_simple_connect_sync(self->priv->mm_simple_modem,
					     properties->
					     priv->mm_simple_connect_properties,
					     NULL, &gerr);
	if (gerr) {
		cm_error("Error in connecting the modem %s", gerr->message);
		*err = CM_ERR_MODEM_MM_CONNECT;
		g_error_free(gerr);
		return NULL;
	}
	cm_info("CMModem connected");
	bearer = cm_modem_obj_create_bearer_internal(mm_bearer, err);
	cm_object_add(&bearer->cmobj, &self->cmobj, self->priv->bearers,
		      err, "%s-%d", CM_BEARER_CLASS_NAME,
		      cm_atomic_inc_and_read(&self->priv->num_bearers));

	g_object_unref(mm_bearer);
	return bearer;
}

void cm_modem_obj_disconnect(struct cm_modem *self,
			     const char *bearer_path,
				       cm_err_t *err)
{
	assert(self && self->priv && self->priv->mm_simple_modem
	       && bearer_path && bearer_path[0] && err);
	GError *gerr = NULL;
	struct cm_bearer *bearer = NULL;
	struct cm_object *bearer_obj = cm_set_find_object(self->priv->bearers,
							  basename(bearer_path));
	if (!bearer_obj) {
		cm_warn("Could not find bearer %s", bearer_path);
		*err = CM_ERR_MODEM_MM_BEARER_NOT_FOUND;
		return;
	}
	bearer = to_cm_bearer(bearer_obj);

	mm_modem_simple_disconnect_sync(self->priv->mm_simple_modem,
			mm_bearer_get_path(bearer->priv->mm_bearer),
					     NULL, &gerr);
	if (gerr) {
		cm_error("Error in dis-connecting the modem %s", gerr->message);
		*err = CM_ERR_MODEM_MM_DISCONNECT;
		g_error_free(gerr);
		goto out_put_bearerobj;
	}
	cm_info("CMModem dis-connected");
out_put_bearerobj:
	cm_object_put(bearer_obj);
}


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

<TITLE>
ErrorHandler (Oracle - Berkeley DB Java API)
</TITLE>

<META NAME="date" CONTENT="2010-04-12">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../style.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

Berkeley DB
 version 4.8.30

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.sleepycat.db

Interface ErrorHandler

public interface ErrorHandler

An interface specifying a callback function to be called when an error
occurs in the Berkeley DB library.

Method Summary

 void
error(Environment environment,
      String errpfx,
      String msg)

          A callback function to be called when an error occurs in the
    Berkeley DB library.

Method Detail

error

void error(Environment environment,
           String errpfx,
           String msg)

A callback function to be called when an error occurs in the
    Berkeley DB library.

    When an error occurs in the Berkeley DB library, an exception is
    thrown.  In some cases, however, the exception may be insufficient
    to completely describe the cause of the error, especially during
    initial application debugging.

    The EnvironmentConfig.setErrorHandler and
    DatabaseConfig.setErrorHandler methods are used to enhance
    the mechanism for reporting error messages to the application.  In
    some cases, when an error occurs, Berkeley DB will invoke the
    ErrorHandler's object error method.  It is up to this method to
    display the error message in an appropriate manner.

Parameters:
environment - The enclosing database environment handle.

errpfx - The prefix string, as previously configured by
    EnvironmentConfig.setErrorPrefix or
    DatabaseConfig.setErrorPrefix.

msg - An error message string.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

Berkeley DB
 version 4.8.30

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright (c) 1996-2009 Oracle.  All rights reserved.


text:
namespace Loki
{

    class ScopeGuardImplBase
    {
        ScopeGuardImplBase& operator =(const ScopeGuardImplBase&);

    protected:

        ~ScopeGuardImplBase()
        {}

        ScopeGuardImplBase(const ScopeGuardImplBase& other) throw()
            : dismissed_(other.dismissed_)
        {
            other.Dismiss();
        }

        template <typename J>
        static void SafeExecute(J& j) throw()
        {
            if (!j.dismissed_)
                try
                {
                    j.Execute();
                }
                catch(...)
                {}
        }

        mutable bool dismissed_;

    public:
        ScopeGuardImplBase() throw() : dismissed_(false)
        {}

        void Dismiss() const throw()
        {
            dismissed_ = true;
        }
    };

    ////////////////////////////////////////////////////////////////
    ///
    /// \typedef typedef const ScopeGuardImplBase& ScopeGuard
    /// \ingroup ExceptionGroup
    ///
    /// See Andrei's and Petru Marginean's CUJ article
    /// http://www.cuj.com/documents/s=8000/cujcexp1812alexandr/alexandr.htm
    ///
    /// Changes to the original code by Joshua Lehrer:
    /// http://www.lehrerfamily.com/scopeguard.html
    ////////////////////////////////////////////////////////////////

    typedef const ScopeGuardImplBase& ScopeGuard;

    template <typename F>
    class ScopeGuardImpl0 : public ScopeGuardImplBase
    {
    public:
        static ScopeGuardImpl0<F> MakeGuard(F fun)
        {
            return ScopeGuardImpl0<F>(fun);
        }

        ~ScopeGuardImpl0() throw()
        {
            SafeExecute(*this);
        }

        void Execute()
        {
            fun_();
        }

    protected:
        ScopeGuardImpl0(F fun) : fun_(fun)
        {}

        F fun_;
    };

    template <typename F>
    inline ScopeGuardImpl0<F> MakeGuard(F fun)
    {
        return ScopeGuardImpl0<F>::MakeGuard(fun);
    }

    template <typename F, typename P1>
    class ScopeGuardImpl1 : public ScopeGuardImplBase
    {
    public:
        static ScopeGuardImpl1<F, P1> MakeGuard(F fun, P1 p1)
        {
            return ScopeGuardImpl1<F, P1>(fun, p1);
        }

        ~ScopeGuardImpl1() throw()
        {
            SafeExecute(*this);
        }

        void Execute()
        {
            fun_(p1_);
        }

    protected:
        ScopeGuardImpl1(F fun, P1 p1) : fun_(fun), p1_(p1)
        {}

        F fun_;
        const P1 p1_;
    };

    template <typename F, typename P1>
    inline ScopeGuardImpl1<F, P1> MakeGuard(F fun, P1 p1)
    {
        return ScopeGuardImpl1<F, P1>::MakeGuard(fun, p1);
    }

    template <typename F, typename P1, typename P2>
    class ScopeGuardImpl2: public ScopeGuardImplBase
    {
    public:
        static ScopeGuardImpl2<F, P1, P2> MakeGuard(F fun, P1 p1, P2 p2)
        {
            return ScopeGuardImpl2<F, P1, P2>(fun, p1, p2);
        }

        ~ScopeGuardImpl2() throw()
        {
            SafeExecute(*this);
        }

        void Execute()
        {
            fun_(p1_, p2_);
        }

    protected:
        ScopeGuardImpl2(F fun, P1 p1, P2 p2) : fun_(fun), p1_(p1), p2_(p2)
        {}

        F fun_;
        const P1 p1_;
        const P2 p2_;
    };

    template <typename F, typename P1, typename P2>
    inline ScopeGuardImpl2<F, P1, P2> MakeGuard(F fun, P1 p1, P2 p2)
    {
        return ScopeGuardImpl2<F, P1, P2>::MakeGuard(fun, p1, p2);
    }

    template <typename F, typename P1, typename P2, typename P3>
    class ScopeGuardImpl3 : public ScopeGuardImplBase
    {
    public:
        static ScopeGuardImpl3<F, P1, P2, P3> MakeGuard(F fun, P1 p1, P2 p2, P3 p3)
        {
            return ScopeGuardImpl3<F, P1, P2, P3>(fun, p1, p2, p3);
        }

        ~ScopeGuardImpl3() throw()
        {
            SafeExecute(*this);
        }

        void Execute()
        {
            fun_(p1_, p2_, p3_);
        }

    protected:
        ScopeGuardImpl3(F fun, P1 p1, P2 p2, P3 p3) : fun_(fun), p1_(p1), p2_(p2), p3_(p3)
        {}

        F fun_;
        const P1 p1_;
        const P2 p2_;
        const P3 p3_;
    };

    template <typename F, typename P1, typename P2, typename P3>
    inline ScopeGuardImpl3<F, P1, P2, P3> MakeGuard(F fun, P1 p1, P2 p2, P3 p3)
    {
        return ScopeGuardImpl3<F, P1, P2, P3>::MakeGuard(fun, p1, p2, p3);
    }

    //************************************************************

    template <class Obj, typename MemFun>
    class ObjScopeGuardImpl0 : public ScopeGuardImplBase
    {
    public:
        static ObjScopeGuardImpl0<Obj, MemFun> MakeObjGuard(Obj& obj, MemFun memFun)
        {
            return ObjScopeGuardImpl0<Obj, MemFun>(obj, memFun);
        }

        ~ObjScopeGuardImpl0() throw()
        {
            SafeExecute(*this);
        }

        void Execute()
        {
            (obj_.*memFun_)();
        }

    protected:
        ObjScopeGuardImpl0(Obj& obj, MemFun memFun) : obj_(obj), memFun_(memFun)
        {}

        Obj& obj_;
        MemFun memFun_;
    };

    template <class Obj, typename MemFun>
    inline ObjScopeGuardImpl0<Obj, MemFun> MakeObjGuard(Obj& obj, MemFun memFun)
    {
        return ObjScopeGuardImpl0<Obj, MemFun>::MakeObjGuard(obj, memFun);
    }

    template <typename Ret, class Obj1, class Obj2>
    inline ObjScopeGuardImpl0<Obj1,Ret(Obj2::*)()> MakeGuard(Ret(Obj2::*memFun)(), Obj1 &obj)
    {
      return ObjScopeGuardImpl0<Obj1,Ret(Obj2::*)()>::MakeObjGuard(obj,memFun);
    }

    template <typename Ret, class Obj1, class Obj2>
    inline ObjScopeGuardImpl0<Obj1,Ret(Obj2::*)()> MakeGuard(Ret(Obj2::*memFun)(), Obj1 *obj)
    {
      return ObjScopeGuardImpl0<Obj1,Ret(Obj2::*)()>::MakeObjGuard(*obj,memFun);
    }

    template <class Obj, typename MemFun, typename P1>
    class ObjScopeGuardImpl1 : public ScopeGuardImplBase
    {
    public:
        static ObjScopeGuardImpl1<Obj, MemFun, P1> MakeObjGuard(Obj& obj, MemFun memFun, P1 p1)
        {
            return ObjScopeGuardImpl1<Obj, MemFun, P1>(obj, memFun, p1);
        }

        ~ObjScopeGuardImpl1() throw()
        {
            SafeExecute(*this);
        }

        void Execute()
        {
            (obj_.*memFun_)(p1_);
        }

    protected:
        ObjScopeGuardImpl1(Obj& obj, MemFun memFun, P1 p1) : obj_(obj), memFun_(memFun), p1_(p1)
        {}

        Obj& obj_;
        MemFun memFun_;
        const P1 p1_;
    };

    template <class Obj, typename MemFun, typename P1>
    inline ObjScopeGuardImpl1<Obj, MemFun, P1> MakeObjGuard(Obj& obj, MemFun memFun, P1 p1)
    {
        return ObjScopeGuardImpl1<Obj, MemFun, P1>::MakeObjGuard(obj, memFun, p1);
    }

    template <typename Ret, class Obj1, class Obj2, typename P1a, typename P1b>
    inline ObjScopeGuardImpl1<Obj1,Ret(Obj2::*)(P1a),P1b> MakeGuard(Ret(Obj2::*memFun)(P1a), Obj1 &obj, P1b p1)
    {
      return ObjScopeGuardImpl1<Obj1,Ret(Obj2::*)(P1a),P1b>::MakeObjGuard(obj,memFun,p1);
    }

    template <typename Ret, class Obj1, class Obj2, typename P1a, typename P1b>
    inline ObjScopeGuardImpl1<Obj1,Ret(Obj2::*)(P1a),P1b> MakeGuard(Ret(Obj2::*memFun)(P1a), Obj1 *obj, P1b p1)
    {
      return ObjScopeGuardImpl1<Obj1,Ret(Obj2::*)(P1a),P1b>::MakeObjGuard(*obj,memFun,p1);
    }

    template <class Obj, typename MemFun, typename P1, typename P2>
    class ObjScopeGuardImpl2 : public ScopeGuardImplBase
    {
    public:
        static ObjScopeGuardImpl2<Obj, MemFun, P1, P2> MakeObjGuard(Obj& obj, MemFun memFun, P1 p1, P2 p2)
        {
            return ObjScopeGuardImpl2<Obj, MemFun, P1, P2>(obj, memFun, p1, p2);
        }

        ~ObjScopeGuardImpl2() throw()
        {
            SafeExecute(*this);
        }

        void Execute()
        {
            (obj_.*memFun_)(p1_, p2_);
        }

    protected:
        ObjScopeGuardImpl2(Obj& obj, MemFun memFun, P1 p1, P2 p2) : obj_(obj), memFun_(memFun), p1_(p1), p2_(p2)
        {}

        Obj& obj_;
        MemFun memFun_;
        const P1 p1_;
        const P2 p2_;
    };

    template <class Obj, typename MemFun, typename P1, typename P2>
    inline ObjScopeGuardImpl2<Obj, MemFun, P1, P2> MakeObjGuard(Obj& obj, MemFun memFun, P1 p1, P2 p2)
    {
        return ObjScopeGuardImpl2<Obj, MemFun, P1, P2>::MakeObjGuard(obj, memFun, p1, p2);
    }

    template <typename Ret, class Obj1, class Obj2, typename P1a, typename P1b, typename P2a, typename P2b>
    inline ObjScopeGuardImpl2<Obj1,Ret(Obj2::*)(P1a,P2a),P1b,P2b> MakeGuard(Ret(Obj2::*memFun)(P1a,P2a), Obj1 &obj, P1b p1, P2b p2)
    {
      return ObjScopeGuardImpl2<Obj1,Ret(Obj2::*)(P1a,P2a),P1b,P2b>::MakeObjGuard(obj,memFun,p1,p2);
    }

    template <typename Ret, class Obj1, class Obj2, typename P1a, typename P1b, typename P2a, typename P2b>
    inline ObjScopeGuardImpl2<Obj1,Ret(Obj2::*)(P1a,P2a),P1b,P2b> MakeGuard(Ret(Obj2::*memFun)(P1a,P2a), Obj1 *obj, P1b p1, P2b p2)
    {
      return ObjScopeGuardImpl2<Obj1,Ret(Obj2::*)(P1a,P2a),P1b,P2b>::MakeObjGuard(*obj,memFun,p1,p2);
    }

} // namespace Loki

#define LOKI_CONCATENATE_DIRECT(s1, s2)  s1##s2
#define LOKI_CONCATENATE(s1, s2)         LOKI_CONCATENATE_DIRECT(s1, s2)
#define LOKI_ANONYMOUS_VARIABLE(str)     LOKI_CONCATENATE(str, __LINE__)

#define LOKI_ON_BLOCK_EXIT      ScopeGuard LOKI_ANONYMOUS_VARIABLE(scopeGuard) = MakeGuard
#define LOKI_ON_BLOCK_EXIT_OBJ  ScopeGuard LOKI_ANONYMOUS_VARIABLE(scopeGuard) = MakeObjGuard

#endif //LOKI_SCOPEGUARD_H_

// $Log: lokiScopeGuard.h,v $
// Revision 1.2  2007/02/01 17:29:00  sharring
// updating to newer version of loki library, with support for multi-threading enabled. manually renamed files to avoid name conflicts, by
// prepending "loki" to the names of header files. also manually edited lokiThreads.h to #define LOKI_OBJECT_LEVEL_THREADING; this could
// also be done with a compile FLAG, perhaps would be better.
//
// Revision 1.1.2.1  2007/02/01 07:36:57  sharring
//
// updating loki to newer version for testing in SFI in the hopes of fixing some
// multi-threading problems seen in acs logging code for which the stack trace
// indicates that loki smart pointers were involved.
//
// Revision 1.6  2006/02/14 12:11:06  syntheticpp
// don't break old ScopeGuard code
//
// Revision 1.5  2006/02/14 11:54:46  syntheticpp
// rename SmartPtr-ByRef and ScopeGuard-ByRefHolder into RefToValue and move it to lokiRefToValue.h
//
// Revision 1.4  2006/01/16 19:05:09  rich_sposato
// Added cvs keywords.
//


text:
ColorReconstruction.SetAlignDepthFloatToReconstructionReferenceFrame Method
===========================================================================

Sets a reference depth frame that is used internally to help with tracking when calling the [AlignDepthFloatFrameToReconstruction](AlignDepthFloatFrameToRe.md) method to calculate a new camera pose.
| ![](../../../../../../resources/note.gif)Note                                                         |
|-------------------------------------------------------------------------------------------------------|
| You should call this method only if you are not using the default tracking behavior of Kinect Fusion. |

Syntax
======

<colgroup>
<col width="100%" />
</colgroup>

C++

public:
void SetAlignDepthFloatToReconstructionReferenceFrame(
         DepthFloatFrame^ referenceFrame
)

<colgroup>
<col width="100%" />
</colgroup>

C#

public void SetAlignDepthFloatToReconstructionReferenceFrame (
         DepthFloatFramereferenceFrame
)

<colgroup>
<col width="100%" />
</colgroup>

JavaScript

colorReconstruction.setAlignDepthFloatToReconstructionReferenceFrame(referenceFrame);

#### Parameters

*referenceFrame*
Type: [DepthFloatFrame](../../DepthFloatFrame_Class.md)
 A previously-created depth float frame that was successfully aligned, or a raycasted model depth.

Exceptions
==========

| Exception type                                                                                | Condition                                                            |
|------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------|
| [ArgumentException](http://msdn.microsoft.com/en-us/library/system.argumentexception.aspx)                 | The *referenceDepthFloatFrame* parameter is an incorrect image size. |
| [ArgumentNullException](http://msdn.microsoft.com/en-us/library/system.argumentnullexception.aspx)         | The *referenceDepthFloatFrame* parameter is **null**.                |
| [InvalidOperationException](http://msdn.microsoft.com/en-us/library/system.invalidoperationexception.aspx) | The call failed for an unknown reason.                               |

Remarks
=======

Internally, the [AlignDepthFloatFrameToReconstruction](AlignDepthFloatFrameToRe.md) method saves the last depth frame that was passed to it and uses this image to help with tracking the next time that is called. For example, this can be used if you are reconstructing and lose track, and then want to restart tracking from a different known location without resetting the volume. To enable the tracking to succeed, you could perform a raycast from the new location to get a depth image (by calling the [CalculatePointCloudAndDepth](CalculatePointCloudAndDe.md) method), and then call **SetAlignDepthFloatToReconstructionReferenceFrame** with the depth image before calling **AlignDepthFloatFrameToReconstruction**.

Requirements
============

**Namespace:**Microsoft.Kinect.Fusion
**Metadata:**microsoft.kinect.fusion.winmd

See also
========

#### Reference

[ColorReconstruction Class](../../ColorReconstruction_Class.md)
 [Microsoft.Kinect.Fusion Namespace](../../../Kinect.Fusion.md)