text:
#include "config.h"
#include "ICOImageDecoder.h"

#include <algorithm>

#include "BMPImageReader.h"
#include "PNGImageDecoder.h"
#include "PlatformInstrumentation.h"
#include <wtf/PassOwnPtr.h>

namespace WebCore {

// Number of bits in .ICO/.CUR used to store the directory and its entries,
// respectively (doesn't match sizeof values for member structs since we omit
// some fields).
static const size_t sizeOfDirectory = 6;
static const size_t sizeOfDirEntry = 16;

ICOImageDecoder::ICOImageDecoder(ImageSource::AlphaOption alphaOption,
                                 ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption)
    : ImageDecoder(alphaOption, gammaAndColorProfileOption)
    , m_decodedOffset(0)
{
}

ICOImageDecoder::~ICOImageDecoder()
{
}

void ICOImageDecoder::setData(SharedBuffer* data, bool allDataReceived)
{
    if (failed())
        return;

    ImageDecoder::setData(data, allDataReceived);

    for (BMPReaders::iterator i(m_bmpReaders.begin()); i != m_bmpReaders.end(); ++i) {
        if (*i)
            (*i)->setData(data);
    }
    for (size_t i = 0; i < m_pngDecoders.size(); ++i)
        setDataForPNGDecoderAtIndex(i);
}

bool ICOImageDecoder::isSizeAvailable()
{
    if (!ImageDecoder::isSizeAvailable())
        decode(0, true);

    return ImageDecoder::isSizeAvailable();
}

IntSize ICOImageDecoder::size() const
{
    return m_frameSize.isEmpty() ? ImageDecoder::size() : m_frameSize;
}

IntSize ICOImageDecoder::frameSizeAtIndex(size_t index) const
{
    return (index && (index < m_dirEntries.size())) ? m_dirEntries[index].m_size : size();
}

bool ICOImageDecoder::setSize(unsigned width, unsigned height)
{
    // The size calculated inside the BMPImageReader had better match the one in
    // the icon directory.
    return m_frameSize.isEmpty() ? ImageDecoder::setSize(width, height) : ((IntSize(width, height) == m_frameSize) || setFailed());
}

size_t ICOImageDecoder::frameCount()
{
    decode(0, true);
    if (m_frameBufferCache.isEmpty()) {
        m_frameBufferCache.resize(m_dirEntries.size());
        for (size_t i = 0; i < m_dirEntries.size(); ++i)
            m_frameBufferCache[i].setPremultiplyAlpha(m_premultiplyAlpha);
    }
    // CAUTION: We must not resize m_frameBufferCache again after this, as
    // decodeAtIndex() may give a BMPImageReader a pointer to one of the
    // entries.
    return m_frameBufferCache.size();
}

ImageFrame* ICOImageDecoder::frameBufferAtIndex(size_t index)
{
    // Ensure |index| is valid.
    if (index >= frameCount())
        return 0;

    ImageFrame* buffer = &m_frameBufferCache[index];
    if (buffer->status() != ImageFrame::FrameComplete) {
        PlatformInstrumentation::willDecodeImage("ICO");
        decode(index, false);
        PlatformInstrumentation::didDecodeImage();
    }
    return buffer;
}

bool ICOImageDecoder::setFailed()
{
    m_bmpReaders.clear();
    m_pngDecoders.clear();
    return ImageDecoder::setFailed();
}

bool ICOImageDecoder::hotSpot(IntPoint& hotSpot) const
{
    // When unspecified, the default frame is always frame 0. This is consistent with
    // BitmapImage where currentFrame() starts at 0 and only increases when animation is
    // requested.
    return hotSpotAtIndex(0, hotSpot);
}

bool ICOImageDecoder::hotSpotAtIndex(size_t index, IntPoint& hotSpot) const
{
    if (index >= m_dirEntries.size() || m_fileType != CURSOR)
        return false;

    hotSpot = m_dirEntries[index].m_hotSpot;
    return true;
}

// static
bool ICOImageDecoder::compareEntries(const IconDirectoryEntry& a, const IconDirectoryEntry& b)
{
    // Larger icons are better.  After that, higher bit-depth icons are better.
    const int aEntryArea = a.m_size.width() * a.m_size.height();
    const int bEntryArea = b.m_size.width() * b.m_size.height();
    return (aEntryArea == bEntryArea) ? (a.m_bitCount > b.m_bitCount) : (aEntryArea > bEntryArea);
}

void ICOImageDecoder::setDataForPNGDecoderAtIndex(size_t index)
{
    if (!m_pngDecoders[index])
        return;

    const IconDirectoryEntry& dirEntry = m_dirEntries[index];
    // Copy out PNG data to a separate vector and send to the PNG decoder.
    // FIXME: Save this copy by making the PNG decoder able to take an
    // optional offset.
    RefPtr<SharedBuffer> pngData(SharedBuffer::create(&m_data->data()[dirEntry.m_imageOffset], m_data->size() - dirEntry.m_imageOffset));
    m_pngDecoders[index]->setData(pngData.get(), isAllDataReceived());
}

void ICOImageDecoder::decode(size_t index, bool onlySize)
{
    if (failed())
        return;

    // If we couldn't decode the image but we've received all the data, decoding
    // has failed.
    if ((!decodeDirectory() || (!onlySize && !decodeAtIndex(index))) && isAllDataReceived())
        setFailed();
    // If we're done decoding this frame, we don't need the BMPImageReader or
    // PNGImageDecoder anymore.  (If we failed, these have already been
    // cleared.)
    else if ((m_frameBufferCache.size() > index) && (m_frameBufferCache[index].status() == ImageFrame::FrameComplete)) {
        m_bmpReaders[index].clear();
        m_pngDecoders[index].clear();
    }
}

bool ICOImageDecoder::decodeDirectory()
{
    // Read and process directory.
    if ((m_decodedOffset < sizeOfDirectory) && !processDirectory())
        return false;

    // Read and process directory entries.
    return (m_decodedOffset >= (sizeOfDirectory + (m_dirEntries.size() * sizeOfDirEntry))) || processDirectoryEntries();
}

bool ICOImageDecoder::decodeAtIndex(size_t index)
{
    ASSERT_WITH_SECURITY_IMPLICATION(index < m_dirEntries.size());
    const IconDirectoryEntry& dirEntry = m_dirEntries[index];
    const ImageType imageType = imageTypeAtIndex(index);
    if (imageType == Unknown)
        return false; // Not enough data to determine image type yet.

    if (imageType == BMP) {
        if (!m_bmpReaders[index]) {
            // We need to have already sized m_frameBufferCache before this, and
            // we must not resize it again later (see caution in frameCount()).
            ASSERT(m_frameBufferCache.size() == m_dirEntries.size());
            m_bmpReaders[index] = adoptPtr(new BMPImageReader(this, dirEntry.m_imageOffset, 0, true));
            m_bmpReaders[index]->setData(m_data.get());
            m_bmpReaders[index]->setBuffer(&m_frameBufferCache[index]);
        }
        m_frameSize = dirEntry.m_size;
        bool result = m_bmpReaders[index]->decodeBMP(false);
        m_frameSize = IntSize();
        return result;
    }

    if (!m_pngDecoders[index]) {
        m_pngDecoders[index] = adoptPtr(
            new PNGImageDecoder(m_premultiplyAlpha ? ImageSource::AlphaPremultiplied : ImageSource::AlphaNotPremultiplied,
                                m_ignoreGammaAndColorProfile ? ImageSource::GammaAndColorProfileIgnored : ImageSource::GammaAndColorProfileApplied));
        setDataForPNGDecoderAtIndex(index);
    }
    // Fail if the size the PNGImageDecoder calculated does not match the size
    // in the directory.
    if (m_pngDecoders[index]->isSizeAvailable() && (m_pngDecoders[index]->size() != dirEntry.m_size))
        return setFailed();
    m_frameBufferCache[index] = *m_pngDecoders[index]->frameBufferAtIndex(0);
    return !m_pngDecoders[index]->failed() || setFailed();
}

bool ICOImageDecoder::processDirectory()
{
    // Read directory.
    ASSERT(!m_decodedOffset);
    if (m_data->size() < sizeOfDirectory)
        return false;
    const uint16_t fileType = readUint16(2);
    const uint16_t idCount = readUint16(4);
    m_decodedOffset = sizeOfDirectory;

    // See if this is an icon filetype we understand, and make sure we have at
    // least one entry in the directory.
    if (((fileType != ICON) && (fileType != CURSOR)) || (!idCount))
        return setFailed();

    m_fileType = static_cast<FileType>(fileType);

    // Enlarge member vectors to hold all the entries.
    m_dirEntries.resize(idCount);
    m_bmpReaders.resize(idCount);
    m_pngDecoders.resize(idCount);
    return true;
}

bool ICOImageDecoder::processDirectoryEntries()
{
    // Read directory entries.
    ASSERT(m_decodedOffset == sizeOfDirectory);
    if ((m_decodedOffset > m_data->size()) || ((m_data->size() - m_decodedOffset) < (m_dirEntries.size() * sizeOfDirEntry)))
        return false;
    for (IconDirectoryEntries::iterator i(m_dirEntries.begin()); i != m_dirEntries.end(); ++i)
        *i = readDirectoryEntry();  // Updates m_decodedOffset.

    // Make sure the specified image offsets are past the end of the directory
    // entries.
    for (IconDirectoryEntries::iterator i(m_dirEntries.begin()); i != m_dirEntries.end(); ++i) {
        if (i->m_imageOffset < m_decodedOffset)
            return setFailed();
    }

    // Arrange frames in decreasing quality order.
    std::sort(m_dirEntries.begin(), m_dirEntries.end(), compareEntries);

    // The image size is the size of the largest entry.
    const IconDirectoryEntry& dirEntry = m_dirEntries.first();
    // Technically, this next call shouldn't be able to fail, since the width
    // and height here are each <= 256, and |m_frameSize| is empty.
    return setSize(dirEntry.m_size.width(), dirEntry.m_size.height());
}

ICOImageDecoder::IconDirectoryEntry ICOImageDecoder::readDirectoryEntry()
{
    // Read icon data.
    // The casts to uint8_t in the next few lines are because that's the on-disk
    // type of the width and height values.  Storing them in ints (instead of
    // matching uint8_ts) is so we can record dimensions of size 256 (which is
    // what a zero byte really means).
    int width = static_cast<uint8_t>(m_data->data()[m_decodedOffset]);
    if (!width)
        width = 256;
    int height = static_cast<uint8_t>(m_data->data()[m_decodedOffset + 1]);
    if (!height)
        height = 256;
    IconDirectoryEntry entry;
    entry.m_size = IntSize(width, height);
    if (m_fileType == CURSOR) {
        entry.m_bitCount = 0;
        entry.m_hotSpot = IntPoint(readUint16(4), readUint16(6));
    } else {
        entry.m_bitCount = readUint16(6);
        entry.m_hotSpot = IntPoint();
    }
    entry.m_imageOffset = readUint32(12);

    // Some icons don't have a bit depth, only a color count.  Convert the
    // color count to the minimum necessary bit depth.  It doesn't matter if
    // this isn't quite what the bitmap info header says later, as we only use
    // this value to determine which icon entry is best.
    if (!entry.m_bitCount) {
        int colorCount = static_cast<uint8_t>(m_data->data()[m_decodedOffset + 2]);
        if (!colorCount)
            colorCount = 256;  // Vague in the spec, needed by real-world icons.
        for (--colorCount; colorCount; colorCount >>= 1)
            ++entry.m_bitCount;
    }

    m_decodedOffset += sizeOfDirEntry;
    return entry;
}

ICOImageDecoder::ImageType ICOImageDecoder::imageTypeAtIndex(size_t index)
{
    // Check if this entry is a BMP or a PNG; we need 4 bytes to check the magic
    // number.
    ASSERT_WITH_SECURITY_IMPLICATION(index < m_dirEntries.size());
    const uint32_t imageOffset = m_dirEntries[index].m_imageOffset;
    if ((imageOffset > m_data->size()) || ((m_data->size() - imageOffset) < 4))
        return Unknown;
    return strncmp(&m_data->data()[imageOffset], "\x89PNG", 4) ? BMP : PNG;
}

}


text:
package es.tid.pce.computingEngine.algorithms.multiLayer;

import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.jgrapht.graph.DirectedMultigraph;
import org.jgrapht.graph.SimpleDirectedWeightedGraph;

import es.tid.ospf.ospfv2.lsa.tlv.subtlv.complexFields.BitmapLabelSet;
import es.tid.pce.computingEngine.algorithms.ComputingAlgorithmPreComputation;
import es.tid.tedb.DomainTEDB;
import es.tid.tedb.IntraDomainEdge;
import es.tid.tedb.MultiLayerTEDB;
import es.tid.tedb.TEDB;
import es.tid.tedb.TE_Information;
import es.tid.tedb.WSONInformation;

public class Multilayer_Algorithm_auxGraphPreComputation implements ComputingAlgorithmPreComputation{

	private SimpleDirectedWeightedGraph<Object, IntraDomainEdge> baseSimplegraph;

	private SimpleDirectedWeightedGraph<Object, IntraDomainEdge> Opticalgraph;

	private SimpleDirectedWeightedGraph<Object, IntraDomainEdge> IPGraph;

	public SimpleDirectedWeightedGraph<Object, IntraDomainEdge> getIPGraph() {
		return IPGraph;
	}

	public void setIPGraph(
			SimpleDirectedWeightedGraph<Object, IntraDomainEdge> iPGraph) {
		IPGraph = iPGraph;
	}

	public SimpleDirectedWeightedGraph<Object, IntraDomainEdge> getOpticalgraph() {
		return Opticalgraph;
	}

	public void setOpticalgraph(SimpleDirectedWeightedGraph<Object, IntraDomainEdge> opticalgraph) {
		Opticalgraph = opticalgraph;
	}

	private SimpleDirectedWeightedGraph<Object, IntraDomainEdge> Interlayer;

	public SimpleDirectedWeightedGraph<Object, IntraDomainEdge> getInterlayer() {
		return Interlayer;
	}

	public void setInterlayer(SimpleDirectedWeightedGraph<Object, IntraDomainEdge> interlayer) {
		Interlayer = interlayer;
	}

	private SimpleDirectedWeightedGraph<Object, IntraDomainEdge> aux_graph;

	private int numLambdas;

	private double peso_WLE=0;

	private Logger log;

	private Lock graphLock;

	private DomainTEDB ted;

	private WSONInformation WSONInfo;

	private double peso_LPE = 1;

	public Multilayer_Algorithm_auxGraphPreComputation(){
		log=LoggerFactory.getLogger("PCEServer");
	}

	private int grooming_policie=2;   // 0 --> MinTH: Minimizing the Number of Traffic Hops
									// 1 --> MinLP: Minimizing the number of LigthPaths
	 								// 2 --> MinWL: Minimizing the number of Wavelength-Links (WLE)
	private Integer MaxNodesOptical;

	public Integer getMaxNodesOptical() {
		return MaxNodesOptical;
	}

	public int getGrooming_policie() {
		return grooming_policie;
	}

	public class InfoNodo{ //Nodes --> (layer, I/0, nodeIP)
		private int numLayer;
		private int I_O;   // 1 -->
		private Object IPnode;

		public int getnumLayer(){
			return this.numLayer;
		}
		public void setnumLayer(int numLayer){
			this.numLayer = numLayer;
		}
		public int getI_O(){
			return this.I_O;
		}
		public void setI_O(int I_O){
			this.I_O = I_O;
		}
		public Object getIPnode(){
			return this.IPnode;
		}
		public void setIPnode(Object IPnode){
			this.IPnode = IPnode;
		}
	}

	//table of relation of nodes and info in the AuxGraph
	public Hashtable<Integer, InfoNodo> infoTable;

	public Hashtable<Integer, InfoNodo> getInfoTable() {
		return infoTable;
	}

	public void setInfoTable(Hashtable<Integer, InfoNodo> infoTable) {
		this.infoTable = infoTable;
	}

	public Hashtable<Integer, Object> info_IntNodes_IPv4;

	public Hashtable<Object, Object> Interlayer_relation_IP;
	public Hashtable<Object, Object> Interlayer_relation_OPTICAL;

	public Hashtable<Object, Object> getInterlayer_relation_OPTICAL() {
		return Interlayer_relation_OPTICAL;
	}

	public void setInterlayer_relation_OPTICAL(
			Hashtable<Object, Object> interlayerRelationOPTICAL) {
		Interlayer_relation_OPTICAL = interlayerRelationOPTICAL;
	}

	public Hashtable<Object, Object> getInterlayer_relation() {
		return Interlayer_relation_IP;
	}

	public void setInterlayer_relation(Hashtable<Object, Object> interlayerRelation) {
		Interlayer_relation_IP = interlayerRelation;
	}

	public Hashtable<Object, Integer> info_IPv4_IntNodes;
	//relación Nodos reales --> Nodos de acceso en el Auxiliar Graph
	public Hashtable<Object, Object> relation_access_nodes;

	public Hashtable<Object, Object> getRelation_access_nodes() {
		return relation_access_nodes;
	}

	public void setRelation_access_nodes(Hashtable<Object, Object> relationAccessNodes) {
		relation_access_nodes = relationAccessNodes;
	}

	public Hashtable<Object, Integer> getInfo_IPv4_IntNodes() {
		return info_IPv4_IntNodes;
	}

	public void setInfo_IPv4_IntNodes(Hashtable<Object, Integer> infoIPv4IntNodes) {
		info_IPv4_IntNodes = infoIPv4IntNodes;
	}

	public Hashtable<Integer, Object> getinfo_IntNodes_IPv4() {
		return info_IntNodes_IPv4;
	}

	public void setinfo_IntNodes_IPv4(Hashtable<Integer, Object> infoNodes) {
		this.info_IntNodes_IPv4 = infoNodes;
	}

	public void initialize(){
		graphLock=new ReentrantLock();
		double peso_GrmE=0, peso_TxE=0, peso_RxE=0, peso_MuxE = 0,
				peso_DmxE = 0, peso_WBE = 0;

		if(grooming_policie == 0){
			log.info("Grooming polocy: Minimizing the Number of Traffic Hops");
			peso_WLE = 10;
			peso_GrmE = 1000;
			peso_TxE = 20;
			peso_RxE = 20;
		}
		else if(grooming_policie == 1){
			log.info("Grooming polocy: Minimizing the number of Lightpaths");
			peso_WLE = 10;
			peso_GrmE = 20;
			peso_TxE = 200;
			peso_RxE = 200;
		}
		else if(grooming_policie == 2){
			log.info("Grooming polocy: Minimizing the number of Wavelength_links");
			peso_WLE = 1000;
			peso_GrmE = 0;
			peso_TxE = 20;
			peso_RxE = 20;
		}
		int num_nodes;

		Set<Object> nodes= baseSimplegraph.vertexSet();
		num_nodes = nodes.size(); // number of nodes

		//Create the  Optical_networkGraph
		//number of layer, input / output, number of node
		int layer=1;
		int numNode = 0;
		Object Nodeaux = null;
		String baseIP = "172.20.1.";
		String cadena_sumar = "0.0.1.0";
		aux_graph=new SimpleDirectedWeightedGraph<Object,IntraDomainEdge>(IntraDomainEdge.class);
		infoTable = new Hashtable<Integer, InfoNodo>();
		info_IntNodes_IPv4 = new Hashtable<Integer, Object>();
		Interlayer_relation_IP = new Hashtable<Object, Object>();
		Interlayer_relation_OPTICAL = new Hashtable<Object, Object>();
		info_IPv4_IntNodes = new Hashtable<Object, Integer>();
		relation_access_nodes = new Hashtable<Object, Object>();
		numLambdas = ((MultiLayerTEDB)ted).getWSONinfo().getNumLambdas();
		int I_O = 0;
		Object Node;
		int numNode_ip = 0;

		//relación interlayer

		Iterator<Object> iter_op = Opticalgraph.vertexSet().iterator();
		Iterator<Object> iter_ip = baseSimplegraph.vertexSet().iterator();

		while ((iter_ip.hasNext()) && (iter_op.hasNext())){
			Object node_IP = iter_ip.next();
			Object node_OP = iter_op.next();
			Interlayer_relation_IP.put(node_OP, node_IP);
			Interlayer_relation_OPTICAL.put(node_IP, node_OP);
			log.info("node_IP : "+node_IP+" node_OP :"+node_OP);
		}

		//asociar a cada Object de cada nodo, una string con la info Nodes --> (l, I/0, N_node), para saber
		//a qué pertenece cada nodo --> un mapeo

		//////////////////////////////////////////////////////////////////////////////////////
		//				 CREAMOS EL AUXILIARY GRAPH --> number Lambdas + 2 layers
		//////////////////////////////////////////////////////////////////////////////////////

		Iterator<Object> iternodes = nodes.iterator(); // iterator for the node source

		for (layer=1; layer<=numLambdas+2; layer++) //iteration with wavelengths
		{
			numNode_ip = 0;
			baseIP = "172.20."+layer+".";
			while (iternodes.hasNext())
			{
				Node = iternodes.next();  //IP of the current node
				String source =new String();

				if (I_O == 1){
					I_O = 0;
				}
				source = baseIP+ String.valueOf(numNode_ip);
				try {
					Nodeaux = (Inet4Address)Inet4Address.getByName(source);
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (layer == numLambdas+2)
					relation_access_nodes.put(Node, Nodeaux);

				info_IntNodes_IPv4.put(numNode, Nodeaux);
				info_IPv4_IntNodes.put(Nodeaux, numNode);

				log.info("Nodo :"+Nodeaux+" "+info_IPv4_IntNodes.get(Nodeaux));
				InfoNodo info1=new InfoNodo();
				//input --> 0
				aux_graph.addVertex(Nodeaux);
				info1.setI_O(I_O);		//input / output
				if ((layer>=1) && (layer<=numLambdas)){
					info1.setIPnode(Interlayer_relation_OPTICAL.get(Node));
				}
				else
					info1.setIPnode(Node);

				info1.setnumLayer(layer);
				infoTable.put(numNode, info1);
				numNode_ip++;
				numNode++;

				String source2 =new String();
				source2 = baseIP+ String.valueOf(numNode_ip);

				try {
					Nodeaux = (Inet4Address) Inet4Address.getByName(source2);
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				InfoNodo info2=new InfoNodo();
				//output --> 1
				I_O = 1;
				aux_graph.addVertex(Nodeaux);
				info2.setI_O(I_O);     //input / output

				if ((layer>=1) && (layer<=numLambdas)){
					info2.setIPnode(Interlayer_relation_OPTICAL.get(Node));
				}
				else
					info2.setIPnode(Node);

				info2.setnumLayer(layer);
				infoTable.put(numNode, info2);
				info_IntNodes_IPv4.put(numNode, Nodeaux);
				info_IPv4_IntNodes.put(Nodeaux, numNode);

				numNode++;
				numNode_ip++;
			}
			iternodes = nodes.iterator();

		}

		///////////////////////////////////////////////////////////////////////////////
		//		 	ya tenemos creado el grafo con todos los nodos
		// 		 	hay que añadir todas las conexiones entre nodos
		/////////////////////////////////////////////////////////////////////////////

							// ADD  the RxE and TxE Links //
		int numNodes = numNode;
		MaxNodesOptical = numNode; //max number of nodes in the aux graph
		int max;

		//primer nodo de la capa de acceso (input)
		Integer NodeAccesLayer_input = ((MaxNodesOptical/(numLambdas + 2))*(numLambdas + 1));
		Object IP_NodeAccesLayer_input;
		IP_NodeAccesLayer_input = info_IntNodes_IPv4.get(NodeAccesLayer_input);

		//primer nodo de la capa de acceso (output)
		Integer NodeAccesLayer_output = NodeAccesLayer_input + 1;
		Object IP_NodeAccesLayer_output;
		IP_NodeAccesLayer_output = info_IntNodes_IPv4.get(NodeAccesLayer_output);

		max = NodeAccesLayer_input;  // numero del primer nodo de capa de acceso IP
		int node_actual_OP = 0;  // empezamos por el nodo 1 del grafo auxiliar
		Object IP_node_actual_OP = info_IntNodes_IPv4.get(node_actual_OP);

		int ligthPath_layer = ((MaxNodesOptical/(numLambdas + 2))*(numLambdas));

		while (node_actual_OP < ligthPath_layer) //hasta que lleguemos a la capa de LSPs
		{
			if (NodeAccesLayer_input > (MaxNodesOptical-1)) // llegamos al ultimo nodo capa de acceso
			{
				NodeAccesLayer_input = ((MaxNodesOptical/(numLambdas + 2))*(numLambdas + 1));
				IP_NodeAccesLayer_input = info_IntNodes_IPv4.get(NodeAccesLayer_input);

				NodeAccesLayer_output = NodeAccesLayer_input + 1;
				IP_NodeAccesLayer_output = info_IntNodes_IPv4.get(NodeAccesLayer_output);
			}
			IntraDomainEdge link1=new IntraDomainEdge();
			try{
				//add the RxE
				aux_graph.addEdge(IP_node_actual_OP, IP_NodeAccesLayer_input);
				link1 = aux_graph.getEdge(IP_node_actual_OP, IP_NodeAccesLayer_input);
				aux_graph.setEdgeWeight(link1, peso_RxE);
			}catch(Exception e){
				e.printStackTrace();
			}

			//TE_Information tE_info=link.getTE_info().set;
			//link.setTE_info(tE_info)

			node_actual_OP++;
			IP_node_actual_OP = info_IntNodes_IPv4.get(node_actual_OP);

			//add the TxE
			IntraDomainEdge link2=new IntraDomainEdge();
			aux_graph.addEdge(IP_NodeAccesLayer_output, IP_node_actual_OP);
			link2 = aux_graph.getEdge(IP_NodeAccesLayer_output, IP_node_actual_OP);
			aux_graph.setEdgeWeight(link2, peso_TxE);

			node_actual_OP = node_actual_OP + 1;
			IP_node_actual_OP = info_IntNodes_IPv4.get(node_actual_OP);
			NodeAccesLayer_input=NodeAccesLayer_input+2;
			IP_NodeAccesLayer_input = info_IntNodes_IPv4.get(NodeAccesLayer_input);
			NodeAccesLayer_output= NodeAccesLayer_output + 2;
			IP_NodeAccesLayer_output = info_IntNodes_IPv4.get(NodeAccesLayer_output);
		} 						// RxE and TxE Links CREATED
		///////////////////////////////////////////////////////////////////////////////

							   //add the WBE and GrmE Links //
		int node_actual_input = 0, node_actual_output = 1;
		Object IP_node_actual_input = info_IntNodes_IPv4.get(node_actual_input);
		Object IP_node_actual_output = info_IntNodes_IPv4.get(node_actual_output);

		int number_nodes_layer = MaxNodesOptical/(numLambdas + 2);

		while ((node_actual_input<=(MaxNodesOptical - 1)) && (node_actual_output<=MaxNodesOptical))
		{
			if ((node_actual_input / number_nodes_layer) == (numLambdas)){ // LigthPath Layer
				node_actual_input = node_actual_input + number_nodes_layer;
				node_actual_output = node_actual_output + number_nodes_layer;
				IP_node_actual_input = info_IntNodes_IPv4.get(node_actual_input);
				IP_node_actual_output = info_IntNodes_IPv4.get(node_actual_output);
				continue;
			}

			if 	(node_actual_input<max){
				IntraDomainEdge link3=new IntraDomainEdge();
				aux_graph.addEdge(IP_node_actual_input, IP_node_actual_output); //add the WBE
				link3 = aux_graph.getEdge(IP_node_actual_input, IP_node_actual_output);
				aux_graph.setEdgeWeight(link3, peso_WBE);
			}

			else if (node_actual_input >= max)  // max =>> First node input access layer
			{
				aux_graph.addEdge(IP_node_actual_input, IP_node_actual_output); //add the GrmE
				IntraDomainEdge link4=new IntraDomainEdge();
				link4 = aux_graph.getEdge(IP_node_actual_input, IP_node_actual_output);
				aux_graph.setEdgeWeight(link4, peso_GrmE);
			}
			node_actual_input = node_actual_input + 2;
			node_actual_output = node_actual_output + 2;
			IP_node_actual_input = info_IntNodes_IPv4.get(node_actual_input);
			IP_node_actual_output = info_IntNodes_IPv4.get(node_actual_output);
		} 							// WBE and GrmE links CREATED //
		///////////////////////////////////////////////////////////////////

										// ADD the WLE Links //
		InfoNodo info3=new InfoNodo();
		int node_src= 0;
		int node_dst= 0;
		Set<IntraDomainEdge> edges = baseSimplegraph.edgeSet();

		Object Src_IP = null;
		Object Dst_IP = null;

		Iterator<IntraDomainEdge> iterEdges = edges.iterator();

		while (iterEdges.hasNext())
		{
			IntraDomainEdge Edge = iterEdges.next();

			Object Src = Edge.getSource();   // Nodo Real origen del lINK
			Object Dst = Edge.getTarget();   // Nodo Real destino del LINK

			node_src = info_IPv4_IntNodes.get(relation_access_nodes.get(Src));
			node_dst = info_IPv4_IntNodes.get(relation_access_nodes.get(Dst));

			node_src = node_src - (number_nodes_layer*(numLambdas + 1)) + 1;
			node_dst = node_dst - (number_nodes_layer*(numLambdas + 1));

			for (layer = 1; layer<=numLambdas ; layer++)
			{
				Src_IP = info_IntNodes_IPv4.get(node_src);
				Dst_IP = info_IntNodes_IPv4.get(node_dst);

				IntraDomainEdge link5=new IntraDomainEdge();

				aux_graph.addEdge(Src_IP, Dst_IP); //add the WLE link
				link5 = aux_graph.getEdge(Src_IP, Dst_IP);
				aux_graph.setEdgeWeight(link5, peso_WLE);

				node_src = node_src + number_nodes_layer;
				node_dst = node_dst + number_nodes_layer;
			}
		}							// WLE Links CREATED //
		///////////////////////////////////////////////////////////////////
							   // ADD the DmxE and MuxE Links //

		// layer --> num_lambdas + 1

		int actual_LP_input = ((MaxNodesOptical/(numLambdas+2))*(numLambdas));
		Object IP_actual_LP_input;
		IP_actual_LP_input = info_IntNodes_IPv4.get(actual_LP_input);

		int actual_LP_output = actual_LP_input + 1;
		Object IP_actual_LP_output;
		IP_actual_LP_output = info_IntNodes_IPv4.get(actual_LP_output);

		//primer nodo de la capa de acceso (output)
		int Node_AccesLayer_input = ((MaxNodesOptical/(numLambdas + 2))*(numLambdas + 1));
		Object IP_Node_AccesLayer_input = info_IntNodes_IPv4.get(Node_AccesLayer_input);
		int Node_AccesLayer_output = Node_AccesLayer_input + 1;
		Object IP_Node_AccesLayer_output;
		IP_Node_AccesLayer_output = info_IntNodes_IPv4.get(Node_AccesLayer_output);

		while (Node_AccesLayer_output <= MaxNodesOptical)
		{
			IntraDomainEdge link6=new IntraDomainEdge();
			aux_graph.addEdge(IP_actual_LP_input, IP_Node_AccesLayer_input);
			link6 = aux_graph.getEdge(IP_actual_LP_input, IP_Node_AccesLayer_input);
			aux_graph.setEdgeWeight(link6, peso_DmxE);

			IntraDomainEdge link7=new IntraDomainEdge();
			aux_graph.addEdge(IP_Node_AccesLayer_output, IP_actual_LP_output);
			link7 = aux_graph.getEdge(IP_Node_AccesLayer_output, IP_actual_LP_output);
			aux_graph.setEdgeWeight(link7, peso_MuxE);

			actual_LP_input = actual_LP_input + 2;
			actual_LP_output = actual_LP_output + 2;
			Node_AccesLayer_input = Node_AccesLayer_input + 2;
			Node_AccesLayer_output = Node_AccesLayer_output + 2;

			IP_actual_LP_input = info_IntNodes_IPv4.get(actual_LP_input);
			IP_actual_LP_output = info_IntNodes_IPv4.get(actual_LP_output);
			IP_Node_AccesLayer_input = info_IntNodes_IPv4.get(Node_AccesLayer_input);
			IP_Node_AccesLayer_output = info_IntNodes_IPv4.get(Node_AccesLayer_output);
		}

		((MultiLayerTEDB)ted).setUpperLayerGraph(aux_graph);
		baseSimplegraph=((MultiLayerTEDB)ted).getUpperLayerGraph();
		aux_graph = ((MultiLayerTEDB)ted).getUpperLayerGraph();

		// DmuxE and MuxE Links CREATED //

		/////////////////////////////////////////////////////////////////////
		// AUXILIARY GRAPH --> CREATED !!
		/////////////////////////////////////////////////////////////////////
	}

	@Override
	public void setTEDB(TEDB ted) {
		try {
			baseSimplegraph=((MultiLayerTEDB)ted).getUpperLayerGraph();
			Opticalgraph=((MultiLayerTEDB)ted).getDuplicatedLowerLayerkGraph();
			Interlayer = ((MultiLayerTEDB)ted).getDuplicatedInterLayerGraph();
			log.info("Using SimpleTEDB");
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(0);
		}
		WSONInfo=((DomainTEDB)ted).getWSONinfo();
		this.ted=(DomainTEDB)ted;
		this.numLambdas=WSONInfo.getNumLambdas();
	}
	@Override
	public void setGrooming_policie(int groomingPolicie) {
		grooming_policie = groomingPolicie;
	}

	public SimpleDirectedWeightedGraph<Object, IntraDomainEdge> getbaseSimplegraph() {
		return baseSimplegraph;
	}

	public Lock getGraphLock() {
		return graphLock;
	}

	public void setGraphLock(Lock graphLock) {
		this.graphLock = graphLock;
	}

	public WSONInformation getWSONInfo() {
		return WSONInfo;
	}

	public void setWSONInfo(WSONInformation wSONInfo) {
		WSONInfo = wSONInfo;
	}

	@Override
	public void notifyNewEdge(Object source, Object destination) {
	}

	@Override
	public void notifyNewVertex(Object vertex) {
	}

	@Override
	public void notifyTEDBFullUpdate() {
	}

	@Override
	public void notifyWavelengthEndReservation(
			LinkedList<Object> sourceVertexList,
			LinkedList<Object> targetVertexList, int wavelength) {
	}

	@Override
	public void notifyWavelengthReservation(
			LinkedList<Object> sourceVertexList,
			LinkedList<Object> targetVertexList, int wavelength) {
	}

	@Override
	public void notifyWavelengthStatusChange(Object source,
			Object destination, BitmapLabelSet previousBitmapLabelSet,
			BitmapLabelSet newBitmapLabelSet) {
	}

	@Override
	public void notifyNewEdgeIP(Object source, Object destination, TE_Information informationTEDB) {
	}

	@Override
	public void notificationEdgeIP_AuxGraph(Object src, Object dst, TE_Information informationTEDB) {
		int number_nodes_layer = MaxNodesOptical/(numLambdas + 2);
		Object src_aux = null;
		Object dst_aux = null;

		src_aux = relation_access_nodes.get(src);
		dst_aux = relation_access_nodes.get(dst);

		Integer src_aux_id, dst_aux_id;
		src_aux_id = info_IPv4_IntNodes.get(src_aux);
		dst_aux_id = info_IPv4_IntNodes.get(dst_aux);

		src_aux_id = src_aux_id - number_nodes_layer + 1;
		dst_aux_id = dst_aux_id - number_nodes_layer;

		src_aux = info_IntNodes_IPv4.get(src_aux_id);
		dst_aux = info_IntNodes_IPv4.get(dst_aux_id);

		graphLock.lock();
		try{

			IntraDomainEdge edge = null;
			edge = baseSimplegraph.getEdge(src_aux, dst_aux);
			if (edge==null){
				edge = new IntraDomainEdge();
				//add the new link (Light Path Edge)

				edge.setTE_info(informationTEDB);
				baseSimplegraph.addEdge(src_aux, dst_aux, edge);
				edge = baseSimplegraph.getEdge(src_aux, dst_aux);
				baseSimplegraph.setEdgeWeight(edge, peso_LPE);
			}
			else{
				//the LPE already exist
				log.info("El light Path ya existe --> actualizamos su BW");
				edge.setTE_info(informationTEDB);
			}
		}finally{
			graphLock.unlock();
		}
	}

	@Override
	public void notificationEdgeOPTICAL_AuxGraph(Object src, Object dst, int lambda) {
		//Para verlo en el puerto de mantenimiento
		Opticalgraph.getEdge(src, dst).getTE_info().setWavelengthOccupied(lambda);

		//tengo que saber la correspondencia de nodos!
		int number_nodes_layer = MaxNodesOptical/(numLambdas + 2);

		Object src_IP = Interlayer_relation_IP.get(src);
		Object dst_IP = Interlayer_relation_IP.get(dst);

		Object src_aux_relation = relation_access_nodes.get(src_IP);
		Object dst_aux_relation = relation_access_nodes.get(dst_IP);

		Integer src_aux_id = info_IPv4_IntNodes.get(src_aux_relation);
		Integer dst_aux_id = info_IPv4_IntNodes.get(dst_aux_relation);

		src_aux_id = (src_aux_id - number_nodes_layer*((numLambdas + 1)-(lambda))) + 1;
		dst_aux_id = dst_aux_id - number_nodes_layer*((numLambdas + 1)-(lambda));

		Object src_aux = info_IntNodes_IPv4.get(src_aux_id);
		Object dst_aux = info_IntNodes_IPv4.get(dst_aux_id);

		graphLock.lock();
		try{
			IntraDomainEdge edge = null;
			edge = baseSimplegraph.getEdge(src_aux, dst_aux);
			if (edge==null){
				//add the WLE
				baseSimplegraph.addEdge(src_aux, dst_aux);
				edge = baseSimplegraph.getEdge(src_aux, dst_aux);
				baseSimplegraph.setEdgeWeight(edge, peso_WLE);
			}
			else{
				//delete the WLE
				baseSimplegraph.removeEdge(edge);
			}
		}finally{
			graphLock.unlock();
		}
	}

	@Override
	public ArrayList<SimpleDirectedWeightedGraph<Object, IntraDomainEdge>> getNetworkGraphs() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ArrayList<DirectedMultigraph<Object, IntraDomainEdge>> getNetworkMultiGraphs() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean isMultifiber() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public String printBaseTopology() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String printTopology(int lambda) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setMultifiber(boolean multifiber) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setNetworkMultiGraphs(
			ArrayList<DirectedMultigraph<Object, IntraDomainEdge>> networkMultiGraphs) {
		// TODO Auto-generated method stub

	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.datastax.dse.driver.api.core.graph;

import com.datastax.oss.driver.api.core.type.reflect.GenericType;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.tinkerpop.gremlin.process.traversal.Path;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;

/**
 * A node in a tree-like structure representing a Graph or a Graph component.
 *
 *
It can be:
 *
 *

 *
a scalar value of a primitive type (boolean, string, int, long, double);
 *
a graph element (vertex, edge, path or property);
 *
a list of nodes;
 *
a set of nodes;
 *
a map of nodes.
 *

 *
 * This interface provides test methods to find out what a node represents, and conversion methods
 * to cast it to a particular Java type. Two generic methods {@link #as(Class)} and {@link
 * #as(GenericType)} can produce any arbitrary Java type, provided that the underlying serialization
 * runtime has been correctly configured to support the requested conversion.
 */
public interface GraphNode {

  /** Whether this node represents a {@code null} value. */
  boolean isNull();

  /**
   * Returns {@code true} if this node is a {@link Map}, and {@code false} otherwise.
   *
   *
If this method returns {@code true}, you can convert this node with {@link #asMap()}, or use
   * {@link #keys()} and {@link #getByKey(Object)} to access the individual fields (note that
   * entries are not ordered, so {@link #getByIndex(int)} does not work).
   */
  boolean isMap();

  /** The keys of this map node, or an empty iterator if it is not a map. */
  Iterable<?> keys();

  /**
   * Returns the value for the given key as a node.
   *
   *
If this node is not a map, or does not contain the specified key, {@code null} is returned.
   *
   *
If the property value has been explicitly set to {@code null}, implementors may return a
   * special "null node" instead of {@code null}.
   */
  GraphNode getByKey(Object key);

  /** Deserializes and returns this node as a {@link Map}. */
  <K, V> Map<K, V> asMap();

  /**
   * Returns {@code true} if this node is a {@link List}, and {@code false} otherwise.
   *
   *
If this method returns {@code true}, you can convert this node with {@link #asList()}, or
   * use {@link #size()} and {@link #getByIndex(int)} to access the individual fields.
   */
  boolean isList();

  /** The size of the current node, if it is a list or map, or {@code 0} otherwise. */
  int size();

  /**
   * Returns the element at the given index as a node.
   *
   *
If this node is not a list, or {@code index} is out of bounds (i.e. less than zero or {@code
   * >= size()}, {@code null} is returned; no exception will be thrown.
   *
   *
If the requested element has been explicitly set to {@code null}, implementors may return a
   * special "null node" instead of {@code null}.
   */
  GraphNode getByIndex(int index);

  /** Deserializes and returns this node as a {@link List}. */
  <T> List<T> asList();

  /**
   * Returns {@code true} if this node is a simple scalar value, (i.e., string, boolean or number),
   * and {@code false} otherwise.
   *
   *
If this method returns {@code true}, you can convert this node with {@link #asString()},
   * {@link #asBoolean()}, {@link #asInt()}, {@link #asLong()} or {@link #asDouble()}.
   */
  boolean isValue();

  /**
   * Returns this node as an integer.
   *
   *
If the underlying object is not convertible to integer, implementors may choose to either
   * throw {@link ClassCastException} or return [null | empty | some default value], whichever is
   * deemed more appropriate.
   */
  int asInt();

  /**
   * Returns this node as a boolean.
   *
   *
If the underlying object is not convertible to boolean, implementors may choose to either
   * throw {@link ClassCastException} or return [null | empty | some default value], whichever is
   * deemed more appropriate.
   */
  boolean asBoolean();

  /**
   * Returns this node as a long integer.
   *
   *
If the underlying object is not convertible to long, implementors may choose to either throw
   * {@link ClassCastException} or return [null | empty | some default value], whichever is deemed
   * more appropriate.
   */
  long asLong();

  /**
   * Returns this node as a long integer.
   *
   *
If the underlying object is not convertible to double, implementors may choose to either
   * throw {@link ClassCastException} or return [null | empty | some default value], whichever is
   * deemed more appropriate.
   */
  double asDouble();

  /**
   * A valid string representation of this node.
   *
   *
If the underlying object is not convertible to a string, implementors may choose to either
   * throw {@link ClassCastException} or return an empty string, whichever is deemed more
   * appropriate.
   */
  String asString();

  /**
   * Deserializes and returns this node as an instance of {@code clazz}.
   *
   *
Before attempting such a conversion, there must be an appropriate converter configured on
   * the underlying serialization runtime.
   */
  <ResultT> ResultT as(Class<ResultT> clazz);

  /**
   * Deserializes and returns this node as an instance of the given {@link GenericType type}.
   *
   *
Before attempting such a conversion, there must be an appropriate converter configured on
   * the underlying serialization runtime.
   */
  <ResultT> ResultT as(GenericType<ResultT> type);

  /**
   * Returns {@code true} if this node is a {@link Vertex}, and {@code false} otherwise.
   *
   *
If this method returns {@code true}, then {@link #asVertex()} can be safely called.
   */
  boolean isVertex();

  /** Returns this node as a Tinkerpop {@link Vertex}. */
  Vertex asVertex();

  /**
   * Returns {@code true} if this node is a {@link Edge}, and {@code false} otherwise.
   *
   *
If this method returns {@code true}, then {@link #asEdge()} can be safely called.
   */
  boolean isEdge();

  /** Returns this node as a Tinkerpop {@link Edge}. */
  Edge asEdge();

  /**
   * Returns {@code true} if this node is a {@link Path}, and {@code false} otherwise.
   *
   *
If this method returns {@code true}, then {@link #asPath()} can be safely called.
   */
  boolean isPath();

  /** Returns this node as a Tinkerpop {@link Path}. */
  Path asPath();

  /**
   * Returns {@code true} if this node is a {@link Property}, and {@code false} otherwise.
   *
   *
If this method returns {@code true}, then {@link #asProperty()} can be safely called.
   */
  boolean isProperty();

  /** Returns this node as a Tinkerpop {@link Property}. */
  <T> Property<T> asProperty();

  /**
   * Returns {@code true} if this node is a {@link VertexProperty}, and {@code false} otherwise.
   *
   *
If this method returns {@code true}, then {@link #asVertexProperty()} ()} can be safely
   * called.
   */
  boolean isVertexProperty();

  /** Returns this node as a Tinkerpop {@link VertexProperty}. */
  <T> VertexProperty<T> asVertexProperty();

  /**
   * Returns {@code true} if this node is a {@link Set}, and {@code false} otherwise.
   *
   *
If this method returns {@code true}, you can convert this node with {@link #asSet()}, or use
   * {@link #size()}.
   */
  boolean isSet();

  /** Deserializes and returns this node as a {@link Set}. */
  <T> Set<T> asSet();
}


text:
#define BOOST_TEST_MODULE "test_license_locator"
#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>

#include <iostream>
#include <iterator>
#include <cstdio>
#include <fstream>
#include <vector>
#include <boost/filesystem.hpp>
#include <boost/optional.hpp>
#include <boost/test/unit_test.hpp>
#include <stdlib.h>

#include <licensecc_properties.h>
#include <licensecc_properties_test.h>

#include "../../src/library/os/os.h"
#include "../../src/library/base/EventRegistry.h"
#include "../../src/library/locate/ApplicationFolder.hpp"
#include "../../src/library/locate/EnvironmentVarLocation.hpp"
#include "../../src/library/locate/ExternalDefinition.hpp"

#define MOCK_LICENSE PROJECT_TEST_SRC_DIR "/library/test_reader.ini"

namespace test {
using namespace license::locate;
using namespace std;
using namespace boost::filesystem;

static boost::optional<path> find_file(const path &dir_path, const path &file_name) {
	const recursive_directory_iterator end;
	const auto it = find_if(recursive_directory_iterator(dir_path), end,
							[&file_name](const directory_entry &e) { return e.path().filename() == file_name; });
	return it == end ? boost::optional<path>() : it->path();
}

/*****************************************************************************
 * Application Folder tests
 *****************************************************************************/
BOOST_AUTO_TEST_CASE(read_license_near_module) {
	const string testExeFolder = PROJECT_BINARY_DIR "/test/library";
	bool exeFileFound = false;
	string referenceExeFileName;
	string referenceLicenseFileName;
	// Verify we're pointing the correct executable, in windows isn't clear where it's built
#ifdef _WIN32
	boost::optional<path> exeLocation(find_file(path(testExeFolder), path(BOOST_TEST_MODULE ".exe")));
	exeFileFound = exeLocation.has_value();
	if (exeFileFound) {
		referenceExeFileName = exeLocation.get().string();
		referenceLicenseFileName =
			referenceExeFileName.replace(referenceExeFileName.find(BOOST_TEST_MODULE ".exe"),
										 string(BOOST_TEST_MODULE ".exe").size(), BOOST_TEST_MODULE ".lic");
	}
#else
	referenceExeFileName = testExeFolder + "/" + BOOST_TEST_MODULE;
	std::ifstream f(referenceExeFileName.c_str());
	exeFileFound = f.good();
	referenceLicenseFileName = testExeFolder + "/" + BOOST_TEST_MODULE ".lic";
#endif
	BOOST_WARN_MESSAGE(!exeFileFound, "File [" + referenceExeFileName + "] NOT found");
	if (exeFileFound) {
		// copy test license near module
		std::ifstream src(MOCK_LICENSE, std::ios::binary);
		std::ofstream dst(referenceLicenseFileName, std::ios::binary);
		dst << src.rdbuf();
		dst.close();

		license::EventRegistry registry;
		ApplicationFolder applicationFolder;
		vector<string> licenseInfos = applicationFolder.license_locations(registry);
		BOOST_CHECK(registry.isGood());
		BOOST_REQUIRE_EQUAL(1, licenseInfos.size());
		string currentLocation = licenseInfos[0];
		BOOST_CHECK_MESSAGE(equivalent(path(referenceLicenseFileName), path(currentLocation)),
							"file " + currentLocation + "found at expected location");
		string licenseRealContent = applicationFolder.retrieve_license_content(currentLocation);
		src.seekg(0, ios::beg);
		std::string referenceContent((std::istreambuf_iterator<char>(src)), std::istreambuf_iterator<char>());
		BOOST_CHECK_MESSAGE(referenceContent.compare(licenseRealContent) == 0, "File content is same");
		remove(referenceLicenseFileName.c_str());
	}
}

/*****************************************************************************
 * External_Definition tests
 *****************************************************************************/

BOOST_AUTO_TEST_CASE(external_definition) {
	// an application can define multiple license locations separated by ';'
	string applicationDefinedString = MOCK_LICENSE ";/this/one/doesnt/exist";

	// read test license
	std::ifstream src(MOCK_LICENSE, std::ios::binary);
	std::string referenceContent((std::istreambuf_iterator<char>(src)), std::istreambuf_iterator<char>());
	license::EventRegistry registry;
	LicenseLocation licLocation = {LICENSE_PATH};
	std::copy(applicationDefinedString.begin(), applicationDefinedString.end(), licLocation.licenseData);
	ExternalDefinition externalDefinition(&licLocation);
	vector<string> licenseInfos = externalDefinition.license_locations(registry);
	BOOST_CHECK(registry.isGood());
	BOOST_CHECK_EQUAL(1, licenseInfos.size());
	string currentLocation = licenseInfos[0];
	BOOST_CHECK_MESSAGE(string(MOCK_LICENSE).compare(currentLocation) == 0, "file found at expected location");
	string licenseRealContent = externalDefinition.retrieve_license_content(currentLocation);
	BOOST_CHECK_MESSAGE(referenceContent.compare(licenseRealContent) == 0, "File content is same");
}

/**
 * The license file doesn't exist. Check that the locator reports the right error
 */
BOOST_AUTO_TEST_CASE(external_definition_not_found) {
	string applicationDefinedString = PROJECT_TEST_SRC_DIR "/this/file/doesnt/exist";
	license::EventRegistry registry;
	LicenseLocation licLocation = {LICENSE_PATH};
	std::copy(applicationDefinedString.begin(), applicationDefinedString.end(), licLocation.licenseData);
	ExternalDefinition externalDefinition(&licLocation);
	vector<string> licenseInfos = externalDefinition.license_locations(registry);

	BOOST_CHECK_MESSAGE(registry.isGood(), "No fatal error for now, only warnings");
	registry.turnWarningsIntoErrors();
	BOOST_REQUIRE_MESSAGE(!registry.isGood(), "Error detected");
	BOOST_CHECK_EQUAL(0, licenseInfos.size());
	BOOST_CHECK_MESSAGE(registry.getLastFailure()->event_type == LICENSE_FILE_NOT_FOUND, "Error detected");
}

/*****************************************************************************
 * EnvironmentVarLocation tests
 *****************************************************************************/
BOOST_AUTO_TEST_CASE(environment_var_location) {
	// an application can define multiple license locations separated by ';'
	const char *environment_variable_value = MOCK_LICENSE ";/this/one/doesnt/exist";
#ifdef _WIN32
	_putenv_s(LCC_LICENSE_LOCATION_ENV_VAR, environment_variable_value);
#else
	setenv(LCC_LICENSE_LOCATION_ENV_VAR, environment_variable_value, 1);
#endif
	// read test license
	std::ifstream src(MOCK_LICENSE, std::ios::binary);
	std::string referenceContent((std::istreambuf_iterator<char>(src)), std::istreambuf_iterator<char>());
	license::EventRegistry registry;

	EnvironmentVarLocation envVarLocationStrategy;
	vector<string> licenseInfos = envVarLocationStrategy.license_locations(registry);
	BOOST_CHECK(registry.isGood());
	BOOST_CHECK_EQUAL(1, licenseInfos.size());
	string currentLocation = licenseInfos[0];
	BOOST_CHECK_MESSAGE(string(MOCK_LICENSE).compare(currentLocation) == 0, "file found at expected location");
	string licenseRealContent = envVarLocationStrategy.retrieve_license_content(currentLocation);
	BOOST_CHECK_MESSAGE(referenceContent.compare(licenseRealContent) == 0, "File content is same");
	UNSETENV(LCC_LICENSE_LOCATION_ENV_VAR);
}

/**
 * The license file doesn't exist. Check that the locator reports the right error
 */
BOOST_AUTO_TEST_CASE(environment_var_location_not_found) {
	const char *environment_variable_value = PROJECT_TEST_SRC_DIR "/this/file/doesnt/exist";
	SETENV(LCC_LICENSE_LOCATION_ENV_VAR, environment_variable_value);

	license::EventRegistry registry;
	EnvironmentVarLocation envVarLocationStrategy;
	vector<string> licenseInfos = envVarLocationStrategy.license_locations(registry);
	BOOST_CHECK_MESSAGE(registry.isGood(), "No fatal error for now, only warnings");
	registry.turnWarningsIntoErrors();
	BOOST_REQUIRE_MESSAGE(!registry.isGood(), "Error detected");
	BOOST_CHECK_EQUAL(0, licenseInfos.size());
	BOOST_CHECK_MESSAGE(registry.getLastFailure()->event_type == LICENSE_FILE_NOT_FOUND, "Error detected");
	UNSETENV(LCC_LICENSE_LOCATION_ENV_VAR);
}

/**
 * The license file doesn't exist. Check that the locator reports the right error
 */
BOOST_AUTO_TEST_CASE(environment_var_location_not_defined) {
	UNSETENV(LCC_LICENSE_LOCATION_ENV_VAR);
	license::EventRegistry registry;
	EnvironmentVarLocation environmentVarLocation;
	vector<string> licenseInfos = environmentVarLocation.license_locations(registry);

	BOOST_CHECK_MESSAGE(registry.isGood(), "No fatal error for now, only warnings");
	registry.turnWarningsIntoErrors();
	BOOST_REQUIRE_MESSAGE(!registry.isGood(), "Error detected");
	BOOST_CHECK_EQUAL(0, licenseInfos.size());
	BOOST_CHECK_MESSAGE(registry.getLastFailure()->event_type == ENVIRONMENT_VARIABLE_NOT_DEFINED, "Error detected");
}

}  // namespace test


text:
using namespace Torque;

static bool sReadGIF(Stream &stream, GBitmap *bitmap);
static bool sWriteGIF(GBitmap *bitmap, Stream &stream, U32 compressionLevel);

static struct _privateRegisterGIF
{
   _privateRegisterGIF()
   {
      GBitmap::Registration reg;

      reg.extensions.push_back( "gif" );

      reg.readFunc = sReadGIF;
      reg.writeFunc = sWriteGIF;

      GBitmap::sRegisterFormat( reg );
   }
} sStaticRegisterGIF;

//-------------------------------------- Replacement I/O for standard LIBjpeg
//                                        functions.  we don't wanna use
//                                        FILE*'s...
static S32 gifReadDataFn(GifFileType *gifinfo, GifByteType *data, S32 length)
{
   Stream *stream = (Stream*)gifinfo->UserData;
   AssertFatal(stream != NULL, "gifReadDataFn::No stream.");
   int pos = stream->getPosition();
   if (stream->read(length, data))
      return length;

   if (stream->getStatus() == Stream::EOS)
      return (stream->getPosition()-pos);
   else
      return 0;
}

//--------------------------------------
#if 0
// CodeReview - until we can write these, get rid of warning by disabling method.
static S32 gifWriteDataFn(GifFileType *gifinfo, GifByteType *data, S32 length)
{
   Stream *stream = (Stream*)gifinfo->UserData;
   AssertFatal(stream != NULL, "gifWriteDataFn::No stream.");
   if (stream->write(length, data))
      return length;
   else
      return 0;
}
#endif

//--------------------------------------
static bool sReadGIF( Stream &stream, GBitmap *bitmap )
{
   GifFileType *gifinfo = DGifOpen( (void*)&stream, gifReadDataFn);
   if (!gifinfo)
      return false;

   GifRecordType recordType;
   do
   {
      if (DGifGetRecordType(gifinfo, &recordType) == GIF_ERROR)
         break;

      if (recordType == IMAGE_DESC_RECORD_TYPE)
      {
         if (DGifGetImageDesc(gifinfo) == GIF_ERROR)
            break;

         GFXFormat format = (gifinfo->SBackGroundColor == 0 ) ? GFXFormatR8G8B8 : GFXFormatR8G8B8A8;
         bitmap->allocateBitmap(gifinfo->SWidth, gifinfo->SHeight, false, format);

         // Assume no transparency until proven otherwise
         bitmap->setHasTransparency(false);

         U32 gwidth = gifinfo->Image.Width ? gifinfo->Image.Width : bitmap->getWidth();
         U32 gheight= gifinfo->Image.Height ? gifinfo->Image.Height : bitmap->getHeight();
         U32 gifSize = gwidth * gheight;
         U8  *data   = new U8[gifSize];

         if (DGifGetLine(gifinfo, data, gifSize) != GIF_ERROR)
         {
            // use the global or local color table ?
            GifColorType *color = NULL;
            if (gifinfo->Image.ColorMap)
               color = gifinfo->Image.ColorMap->Colors;
            else if (gifinfo->SColorMap)
               color = gifinfo->SColorMap->Colors;

            if (color)
            {
               U8 *dst = bitmap->getAddress(gifinfo->Image.Left, gifinfo->Image.Top);
               U8 *src = data;
               U32 right  = gifinfo->Image.Left + gwidth;
               U32 bottom = gifinfo->Image.Top + gheight;
               U32 next   = (bitmap->getWidth() - gwidth) * bitmap->getBytesPerPixel();

               if (format == GFXFormatR8G8B8A8)
               {
                  for (U32 y=gifinfo->Image.Top; y<bottom; y++)
                  {
                     for (U32 x=gifinfo->Image.Left; x<right; x++, src++)
                     {
                        if (*src == gifinfo->SBackGroundColor)
                        {
                           // this is a transparent pixel
                           dst[0] = 0;    // red
                           dst[1] = 0;    // green
                           dst[2] = 0;    // blue
                           dst[3] = 0;    // alpha

                           bitmap->setHasTransparency(true);
                        }
                        else
                        {
                           dst[0] = color[*src].Red;
                           dst[1] = color[*src].Green;
                           dst[2] = color[*src].Blue;
                           dst[3] = 0;    // alpha
                        }
                        dst += bitmap->getBytesPerPixel();
                     }
                     dst += next;
                  }
               }
               else
               {
                  for (U32 y=gifinfo->Image.Top; y<bottom; y++)
                  {
                     for (U32 x=gifinfo->Image.Left; x<right; x++, src++)
                     {
                        dst[0] = color[*src].Red;
                        dst[1] = color[*src].Green;
                        dst[2] = color[*src].Blue;
                        dst += bitmap->getBytesPerPixel();
                     }
                     dst += next;
                  }
               }
               delete [] data;
               DGifCloseFile(gifinfo);
               return true;
            }
         }
         // failure
         delete [] data;
         break;
      }
      else if (recordType == EXTENSION_RECORD_TYPE)
      {
         GifByteType *extension;
         S32 extCode;

         // Skip any extension blocks in file
         if (DGifGetExtension(gifinfo, &extCode, &extension) != GIF_ERROR)
         {
            while (extension != NULL)
            {
               if (DGifGetExtensionNext(gifinfo, &extension) == GIF_ERROR)
               {
                  return false;
               }
            }
         }
         else
         {
            return false;
         }
      }

      // There used to be a break right here. This caused the while condition to
      // never get processed, and so it never looped through all the records in
      // the GIF. I took a quick peek back at TGB and TGE histories and I am not
      // sure where this change got made, but I can't figure out why the loading
      // worked at all, ever, with that break in there. The only case I can think
      // of is if the first record in the GIF was the bitmap data.
      // [6/6/2007 Pat]

   }while (recordType != TERMINATE_RECORD_TYPE);

   DGifCloseFile(gifinfo);
   return true;
}

//--------------------------------------------------------------------------
static bool sWriteGIF(GBitmap *bitmap, Stream &stream, U32 compressionLevel)
{
   TORQUE_UNUSED( bitmap );
   TORQUE_UNUSED( stream );
   TORQUE_UNUSED( compressionLevel );

   return false;
}


text:
using System.Collections.Generic;

namespace Emzi0767.Ada.Config
{
    public class AdaGuildConfig
    {
        public ulong? ModLogChannel { get; internal set; }
        public bool? DeleteCommands { get; internal set; }
        public string CommandPrefix { get; internal set; }
        public ulong? MuteRole { get; internal set; }
        internal List<AdaModAction> ModActions { get; set; }

        public AdaGuildConfig()
        {
            this.ModActions = new List<AdaModAction>();
        }
    }
}


text:
layout: post
status: publish
published: true
title: !binary |-
  T3dlbiB0aWVudCAodG91am91cnMpIMOgIGxhIHPDqWxlY3Rpb24=
author: mick
author_login: mick
author_email: mickael@flochlay.com
wordpress_id: 816
wordpress_url: http://morningcoffee.mickaelflochlay.com/?p=816
date: 2011-09-28 19:13:47.000000000 +02:00
categories:
- Sport
tags:
- Manchester United
- Michael Owen
- !binary |-
  U8OpbGVjdGlvbiBhbmdsYWlzZQ==
- foot
comments: []
---
Michael Owen :

La fois suivante, je n'étais pas dans l'équipe, et c'était fini.

Les joueurs de foot tiennent vraiment des propos étonnants parfois. Avant de penser à la sélection, il devrait penser à jouer un peu plus avec Manchester United.

via Owen tient (toujours) à la sélection - Foot - ANG - L'EQUIPE.FR.


text:
namespace WorldSalt.UnitTests.Network.Streams.Frames {
    using NUnit.Framework;
    using Rhino.Mocks;
    using WorldSalt.Network.Direction;
    using WorldSalt.Network.Frames;
    using WorldSalt.Network.Streams.Bytes;
    using WorldSalt.Network.Streams.Frames;

    [TestFixture]
	public class FrameSinkFactoryUnitTest {
		private IByteSink<FromServer> byteSink;
		private ITypedFrame<FromServer> frame;

		private FrameSinkFactory<FromServer> target;

		[SetUp]
		public void Setup() {
			byteSink = MockRepository.GenerateMock<IByteSink<FromServer>>();
			frame = MockRepository.GenerateMock<ITypedFrame<FromServer>>();

			target = new FrameSinkFactory<FromServer>();
		}

		[Test]
		public void ShouldRenderToByteSinkOnPut() {
			var expectedBytes = new byte[] {
				0x12, 0x34
			};
			byteSink.Expect(x => x.Put(expectedBytes));
			frame.Stub(x => x.GetBytes()).Return(expectedBytes);

			var sink = target.Create(byteSink);
			sink.Put(frame);

			byteSink.VerifyAllExpectations();
		}
	}
}


text:
<?php
namespace Core\Acl\Model;

use Zend\Permissions\Acl\Resource\ResourceInterface;

class Resource implements ResourceInterface
{

    const RESOURCE_SEPARATOR = '::';

    /**
     *
     * @var int
     */
    protected $_id;

    /**
     *
     * @var string
     */
    protected $_controller;

    /**
     *
     * @var string
     */
    protected $_action;

    /**
     * Array of resource code parents
     *
     * @var null|Resource[]
     */
    protected $_parents;

    /**
     * Number of level that current resource is downgrade.
     * Sample:
     * Level 0: resourceId is [controller]::[action]
     * Level 1: resourceId is [controller]
     *
     * @var int
     */
    protected $_downgradeLevels = 0;

    /**
     * Used by ResultSet to pass each database row to the entity
     */
    public function exchangeArray($data)
    {
        $this->setId((isset($data['id'])) ? $data['id'] : null);
        $this->setController((isset($data['controller'])) ? $data['controller'] : null);
        $this->setAction((isset($data['action'])) ? $data['action'] : null);

        if (isset($data['parents'])) {
            foreach ($data['parents'] as $item) {
                $resource = new Resource();
                $resource->exchangeArray($item);
                $this->_parents[] = $resource->getResourceCode();
            }
        } else {
            $this->_parents = null;
        }
    }

    /**
     * Returns the string identifier of the Resource
     *
     * @return string|null
     */
    public function getResourceId()
    {
        // null resource
        if (is_null($this->getController())) {
            return null;
        }

        // Add Controller to resourceId
        $resourceId = mb_strtolower($this->getController(), 'UTF-8');

        // Add Action if exists and if not is downgraded
        if ($this->getDowngradeLevels() === 0 && $this->getAction()) {
            $resourceId .= self::RESOURCE_SEPARATOR . mb_strtolower($this->getAction(), 'UTF-8');
        }

        return $resourceId;
    }

    /**
     * Increase level of resourceId
     */
    public function downgrade()
    {
        $this->_downgradeLevels ++;
    }

    /**
     *
     * @param \Zend\ $action
     */
    public function setAction($action)
    {
        $this->_action = $action;
    }

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

    /**
     *
     * @param unknown $controller
     */
    public function setController($controller)
    {
        $this->_controller = $controller;
    }

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

    /**
     *
     * @param int $id
     */
    public function setId($id)
    {
        $this->_id = $id;
    }

    /**
     *
     * @return int
     */
    public function getId()
    {
        return $this->_id;
    }

    /**
     *
     * @param array $parents
     */
    public function setParents($parents)
    {
        $this->_parents = $parents;
    }

    /**
     *
     * @return array
     */
    public function getParents()
    {
        return $this->_parents;
    }

    /**
     *
     * @return int
     */
    public function getDowngradeLevels()
    {
        return $this->_downgradeLevels;
    }
}


text:
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals

from datetime import datetime
from datetime import timedelta

from google.appengine.ext import ndb
from google.appengine.ext.db import NeedIndexError
from pytz import utc

from yelp_beans.models import MeetingSpec
from yelp_beans.models import MeetingSubscription

def filter_subscriptions_by_user_data(subscriptions, user):
    approved_subscriptions = []
    for subscription in subscriptions:
        subscription_rules = ndb.Key(urlsafe=subscription['id']).get().rules
        for rule in subscription_rules:
            rule = rule.get()
            metadata = user.metadata
            if metadata.get(rule.name) == rule.value:
                approved_subscriptions.append(subscription)
    return approved_subscriptions

def merge_subscriptions_with_preferences(user):
    user_preferences = [
        {
            'subscription_id': user_subscription.get().subscription.urlsafe(),
            'datetime_id': user_subscription.get().preference.urlsafe()
        } for user_subscription in user.subscription_preferences
    ]
    subscriptions = [
        {
            'id': subscription.key.urlsafe(),
            'title': subscription.title,
            'office': subscription.office,
            'location': subscription.location,
            'size': subscription.size,
            'timezone': subscription.timezone,
            'datetime': get_subscription_dates(subscription),
        } for subscription in MeetingSubscription.query().fetch()
    ]
    for subscription in subscriptions:
        for user_preference in user_preferences:
            if subscription['id'] == user_preference['subscription_id']:
                for date in subscription['datetime']:
                    if date['id'] == user_preference['datetime_id']:
                        date['active'] = True

    return subscriptions

def get_subscription_dates(subscription):
    return [
        {
            'id': date.urlsafe(),
            'date': date.get().datetime.replace(tzinfo=utc).isoformat(),
            'active': False
        }
        for date in subscription.datetime
    ]

def get_specs_from_subscription(subscription):
    specs = []
    for subscription_datetime in subscription.datetime:

        week_start = datetime.now() - timedelta(days=datetime.now().weekday())
        week_start = week_start.replace(
            hour=0, minute=0, second=0, microsecond=0)

        subscription_dt = subscription_datetime.get().datetime
        week_iter = week_start
        while week_iter.weekday() != subscription_dt.weekday():
            week_iter += timedelta(days=1)

        specs.append(
            MeetingSpec(
                meeting_subscription=subscription.key,
                datetime=week_iter.replace(
                    hour=subscription_dt.hour, minute=subscription_dt.minute)
            )
        )
    return week_start, specs

def store_specs_from_subscription(subscription_key, week_start, specs):
    """
    Idempotent function to store meeting specs for this week.
    """
    try:
        current_specs = MeetingSpec.query(
            MeetingSpec.meeting_subscription == subscription_key,
            MeetingSpec.datetime > week_start
        ).fetch()
    except NeedIndexError:
        current_specs = []

    if current_specs:
        return

    ndb.put_multi(specs)
    return specs


text:
layout: post
status: publish
published: true
title: WSE 2.0
author:
  display_name: Tomas Restrepo
  login: tomasr
  email: tomas@winterdom.com
  url: http://winterdom.com/
author_login: tomasr
author_email: tomas@winterdom.com
author_url: http://winterdom.com/
wordpress_id: 711
wordpress_url: http://winterdom.com/2004/03/wse20
date: '2004-03-22 07:33:55 +0000'
date_gmt: '2004-03-22 07:33:55 +0000'
categories:
- Web Services
tags: []
comments: []
---

I know I'm going to be asking a question I'm not gonna get answered, but here it goes anyway:

Any idea when we might see the at least a more recent preview of WSE 2.0? I'd be happy with a preview (even a buggy one)..

The reason I ask is that I've been lately playing with WSE a little bit and seeing how we could take advantage of it in our system, and of the things I've been experimenting with has been writing custom SoapTransports.

So, now, I see the entire Transport/Channel stack seems to have changed, so I'd love to be able to get some bits to play with and see if I can rewrite my code to fit the new model....


text:
> Cloud Datastore Client Library for Node.js

*Looking for more Google APIs than just Datastore? You might want to check out [`google-cloud`][google-cloud].*

- [API Documentation][gcloud-datastore-docs]
- [Official Documentation][cloud-datastore-docs]

*Follow the [activation instructions][cloud-datastore-activation] to use the Cloud Datastore API with your project.*

```sh
$ npm install --save @google-cloud/datastore
```
```js
var datastore = require('@google-cloud/datastore')({
  projectId: 'grape-spaceship-123',
  keyFilename: '/path/to/keyfile.json'
});

var key = datastore.key(['Product', 'Computer']);

datastore.get(key, function(err, entity) {
  console.log(err || entity);
});

// Save data to Datastore.
var blogPostData = {
  title: 'How to make the perfect homemade pasta',
  author: 'Andrew Chilton',
  isDraft: true
};

var blogPostKey = datastore.key('BlogPost');

datastore.save({
  key: blogPostKey,
  data: blogPostData
}, function(err) {
  // `blogPostKey` has been updated with an ID so you can do more operations
  // with it, such as an update.
  blogPostData.isDraft = false;

  datastore.save({
    key: blogPostKey,
    data: blogPostData
  }, function(err) {
    if (!err) {
      // The blog post is now published!
    }
  });
});

// Promises are also supported by omitting callbacks.
datastore.save({
  key: blogPostKey,
  data: blogPostData
}).then(function() {
  // The blog post is now published!
});

// It's also possible to integrate with third-party Promise libraries.
var datastore = require('@google-cloud/datastore')({
  promise: require('bluebird')
});
```

## Authentication

It's incredibly easy to get authenticated and start using Google's APIs. You can set your credentials on a global basis as well as on a per-API basis. See each individual API section below to see how you can auth on a per-API-basis. This is useful if you want to use different accounts for different Cloud services.

### On Google Cloud Platform

If you are running this client on Google Cloud Platform, we handle authentication for you with no configuration. You just need to make sure that when you [set up the GCE instance][gce-how-to], you add the correct scopes for the APIs you want to access.

``` js
var datastore = require('@google-cloud/datastore')();
// ...you're good to go!
```

### Elsewhere

If you are not running this client on Google Cloud Platform, you need a Google Developers service account. To create a service account:

1. Visit the [Google Developers Console][dev-console].
2. Create a new project or click on an existing project.
3. Navigate to  **APIs & auth** > **APIs section** and turn on the following APIs (you may need to enable billing in order to use these services):
  * Cloud Datastore API
4. Navigate to **APIs & auth** >  **Credentials** and then:
  * If you want to use a new service account key, click on **Create credentials** and select **Service account key**. After the account key is created, you will be prompted to download the JSON key file that the library uses to authenticate your requests.
  * If you want to generate a new service account key for an existing service account, click on **Generate new JSON key** and download the JSON key file.

``` js
var projectId = process.env.GCLOUD_PROJECT; // E.g. 'grape-spaceship-123'

var datastore = require('@google-cloud/datastore')({
  projectId: projectId,

  // The path to your key file:
  keyFilename: '/path/to/keyfile.json'

  // Or the contents of the key file:
  credentials: require('./path/to/keyfile.json')
});

// ...you're good to go!
```

[versioning]: https://github.com/GoogleCloudPlatform/google-cloud-node#versioning
[google-cloud]: https://github.com/GoogleCloudPlatform/google-cloud-node
[gce-how-to]: https://cloud.google.com/compute/docs/authentication#using
[dev-console]: https://console.developers.google.com/project
[gcloud-datastore-docs]: https://googlecloudplatform.github.io/google-cloud-node/#/docs/datastore
[cloud-datastore-docs]: https://cloud.google.com/datastore/docs
[cloud-datastore-activation]: https://cloud.google.com/datastore/docs/activate


text:
namespace base {

// Win32UnwindFunctions -------------------------------------------------------

const HMODULE ModuleHandleTraits::kNonNullModuleForTesting =
    reinterpret_cast<HMODULE>(static_cast<uintptr_t>(-1));

// static
bool ModuleHandleTraits::CloseHandle(HMODULE handle) {
  if (handle == kNonNullModuleForTesting)
    return true;

  return ::FreeLibrary(handle) != 0;
}

// static
bool ModuleHandleTraits::IsHandleValid(HMODULE handle) {
  return handle != nullptr;
}

// static
HMODULE ModuleHandleTraits::NullHandle() {
  return nullptr;
}

namespace {

// Implements the UnwindFunctions interface for the corresponding Win32
// functions.
class Win32UnwindFunctions : public Win32StackFrameUnwinder::UnwindFunctions {
public:
  Win32UnwindFunctions();
  ~Win32UnwindFunctions() override;

  PRUNTIME_FUNCTION LookupFunctionEntry(DWORD64 program_counter,
                                        PDWORD64 image_base) override;

  void VirtualUnwind(DWORD64 image_base,
                     DWORD64 program_counter,
                     PRUNTIME_FUNCTION runtime_function,
                     CONTEXT* context) override;

  ScopedModuleHandle GetModuleForProgramCounter(
      DWORD64 program_counter) override;

private:
  DISALLOW_COPY_AND_ASSIGN(Win32UnwindFunctions);
};

Win32UnwindFunctions::Win32UnwindFunctions() {}
Win32UnwindFunctions::~Win32UnwindFunctions() {}

PRUNTIME_FUNCTION Win32UnwindFunctions::LookupFunctionEntry(
    DWORD64 program_counter,
    PDWORD64 image_base) {
#ifdef _WIN64
  return RtlLookupFunctionEntry(program_counter, image_base, nullptr);
#else
  NOTREACHED();
  return nullptr;
#endif
}

void Win32UnwindFunctions::VirtualUnwind(DWORD64 image_base,
                                         DWORD64 program_counter,
                                         PRUNTIME_FUNCTION runtime_function,
                                         CONTEXT* context) {
#ifdef _WIN64
  void* handler_data;
  ULONG64 establisher_frame;
  KNONVOLATILE_CONTEXT_POINTERS nvcontext = {};
  RtlVirtualUnwind(UNW_FLAG_NHANDLER, image_base, program_counter,
                   runtime_function, context, &handler_data,
                   &establisher_frame, &nvcontext);
#else
  NOTREACHED();
#endif
}

ScopedModuleHandle Win32UnwindFunctions::GetModuleForProgramCounter(
    DWORD64 program_counter) {
  HMODULE module_handle = nullptr;
  // GetModuleHandleEx() increments the module reference count, which is then
  // managed and ultimately decremented by ScopedModuleHandle.
  if (!::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
                           reinterpret_cast<LPCTSTR>(program_counter),
                           &module_handle)) {
    const DWORD error = ::GetLastError();
    DCHECK_EQ(ERROR_MOD_NOT_FOUND, static_cast<int>(error));
  }
  return ScopedModuleHandle(module_handle);
}

// LeafUnwindBlacklist --------------------------------------------------------

// Records modules that are known to have functions that violate the Microsoft
// x64 calling convention and would be dangerous to manually unwind if
// encountered as the last frame on the call stack. Functions like these have
// been observed in injected third party modules that either do not provide
// function unwind information, or do not provide the required function prologue
// and epilogue. The former case was observed in several AV products and the
// latter in a WndProc function associated with Actual Window
// Manager/aimemb64.dll. See https://crbug.com/476422.
class LeafUnwindBlacklist {
 public:
  static LeafUnwindBlacklist* GetInstance();

  // Returns true if |module| has been blacklisted.
  bool IsBlacklisted(const void* module) const;

  // Records |module| for blacklisting.
  void BlacklistModule(const void* module);

 private:
  friend struct DefaultSingletonTraits<LeafUnwindBlacklist>;

  LeafUnwindBlacklist();
  ~LeafUnwindBlacklist();

  // The set of modules known to have functions that violate the Microsoft x64
  // calling convention.
  base::hash_set<const void*> blacklisted_modules_;

  DISALLOW_COPY_AND_ASSIGN(LeafUnwindBlacklist);
};

// static
LeafUnwindBlacklist* LeafUnwindBlacklist::GetInstance() {
  // Leaky for performance reasons.
  return Singleton<LeafUnwindBlacklist,
                   LeakySingletonTraits<LeafUnwindBlacklist>>::get();
}

bool LeafUnwindBlacklist::IsBlacklisted(const void* module) const {
  return ContainsKey(blacklisted_modules_, module);
}

void LeafUnwindBlacklist::BlacklistModule(const void* module) {
  CHECK(module);
  blacklisted_modules_.insert(module);
}

LeafUnwindBlacklist::LeafUnwindBlacklist() {}
LeafUnwindBlacklist::~LeafUnwindBlacklist() {}

}  // namespace

// Win32StackFrameUnwinder ----------------------------------------------------

// hipis0e011b8.dll from McAfee Host Intrusion Prevention has been observed to
// provide a pointer to a bogus RUNTIME_FUNCTION structure. This function checks
// that the values in the structure look plausible.
bool SanityCheckRuntimeFunction(PRUNTIME_FUNCTION runtime_function,
                                ULONG64 image_base,
                                DWORD64 program_counter) {
  const DWORD64 program_counter_offset = program_counter - image_base;
  return (runtime_function->BeginAddress <= runtime_function->EndAddress &&
          program_counter_offset >= runtime_function->BeginAddress &&
          program_counter_offset <= runtime_function->EndAddress);
}

Win32StackFrameUnwinder::UnwindFunctions::~UnwindFunctions() {}
Win32StackFrameUnwinder::UnwindFunctions::UnwindFunctions() {}

Win32StackFrameUnwinder::Win32StackFrameUnwinder()
    : Win32StackFrameUnwinder(make_scoped_ptr(new Win32UnwindFunctions)) {
}

Win32StackFrameUnwinder::~Win32StackFrameUnwinder() {}

bool Win32StackFrameUnwinder::TryUnwind(CONTEXT* context,
                                        ScopedModuleHandle* module) {
#ifdef _WIN64
  CHECK(!at_top_frame_ || unwind_info_present_for_all_frames_);

  ScopedModuleHandle frame_module =
      unwind_functions_->GetModuleForProgramCounter(context->Rip);
  // The module may have been unloaded since we recorded the stack. Note that if
  // this check detects module as valid, it still could be a different module at
  // the same instruction pointer address (i.e. if the module was unloaded and a
  // different module loaded in overlapping memory). This should occur extremely
  // rarely.
  if (!frame_module.IsValid())
    return false;

  ULONG64 image_base;
  // Try to look up unwind metadata for the current function.
  PRUNTIME_FUNCTION runtime_function =
      unwind_functions_->LookupFunctionEntry(context->Rip, &image_base);

  if (runtime_function) {
    if (!SanityCheckRuntimeFunction(runtime_function, image_base, context->Rip))
      return false;

    unwind_functions_->VirtualUnwind(image_base, context->Rip, runtime_function,
                                     context);
    at_top_frame_ = false;
  } else {
    // RtlLookupFunctionEntry didn't find unwind information. This could mean
    // the code at the instruction pointer is in:
    //
    // 1. a true leaf function (i.e. a function that neither calls a function,
    //    nor allocates any stack space itself) in which case the return
    //    address is at RSP, or
    //
    // 2. a function that doesn't adhere to the Microsoft x64 calling
    //    convention, either by not providing the required unwind information,
    //    or by not having the prologue or epilogue required for unwinding;
    //    this case has been observed in crash data in injected third party
    //    DLLs.
    //
    // In valid code, case 1 can only occur (by definition) as the last frame
    // on the stack. This happens in about 5% of observed stacks and can
    // easily be unwound by popping RSP and using it as the next frame's
    // instruction pointer.
    //
    // Case 2 can occur anywhere on the stack, and attempting to unwind the
    // stack will result in treating whatever value happens to be on the stack
    // at RSP as the next frame's instruction pointer. This is certainly wrong
    // and very likely to lead to crashing by deferencing invalid pointers in
    // the next RtlVirtualUnwind call.
    //
    // If we see case 2 at a location not the last frame, and all the previous
    // frame had valid unwind information, then this is definitely bad code.
    // We blacklist the module as untrustable for unwinding if we encounter a
    // function in it that doesn't have unwind information.

    if (at_top_frame_) {
      at_top_frame_ = false;

      // We are at the end of the stack. It's very likely that we're in case 1
      // since the vast majority of code adheres to the Microsoft x64 calling
      // convention. But there's a small chance we might be unlucky and be in
      // case 2. If this module is known to have bad code according to the
      // leaf unwind blacklist, stop here, otherwise manually unwind.
      if (LeafUnwindBlacklist::GetInstance()->IsBlacklisted(
              reinterpret_cast<const void*>(image_base))) {
        return false;
      }

      context->Rip = context->Rsp;
      context->Rsp += 8;
      unwind_info_present_for_all_frames_ = false;
    } else {
      // We're not at the end of the stack. This frame is untrustworthy and we
      // can't safely unwind from here.
      if (!image_base) {
        // A null image_base means that the the last unwind produced an invalid
        // instruction pointer. This has been observed where unwind information
        // was present for a function but was inconsistent with the actual
        // function code, in particular in BoringSSL. See
        // https://crbug.com/542919.
      } else if (unwind_info_present_for_all_frames_) {
        // Unwind information was present for all previous frames, so we can
        // be confident this is case 2. Record the module to be blacklisted.
        LeafUnwindBlacklist::GetInstance()->BlacklistModule(
            reinterpret_cast<const void *>(image_base));
      } else {
        // We started off on a function without unwind information. It's very
        // likely that all frames up to this point have been good, and this
        // frame is case 2. But it's possible that the initial frame was case
        // 2 but hadn't been blacklisted yet, and we've started to go off into
        // the weeds. Since we can't be sure, just bail out without
        // blacklisting the module; chances are we'll later encounter the same
        // function on a stack with full unwind information.
      }
      return false;
    }
  }

  module->Set(frame_module.Take());
  return true;
#else
  NOTREACHED();
  return false;
#endif
}

Win32StackFrameUnwinder::Win32StackFrameUnwinder(
    scoped_ptr<UnwindFunctions> unwind_functions)
    : at_top_frame_(true),
      unwind_info_present_for_all_frames_(true),
      unwind_functions_(unwind_functions.Pass()) {
}

}  // namespace base


text:
package com.facebook.buck.features.apple.project;

import static org.junit.Assert.assertEquals;

import com.facebook.buck.core.model.BuildTargetFactory;
import com.facebook.buck.core.rules.SourcePathRuleFinder;
import com.facebook.buck.core.rules.resolver.impl.TestActionGraphBuilder;
import com.facebook.buck.core.sourcepath.FakeSourcePath;
import com.facebook.buck.core.sourcepath.resolver.impl.DefaultSourcePathResolver;
import java.nio.file.Paths;
import org.junit.Before;
import org.junit.Test;

public class PathRelativizerTest {
  private PathRelativizer pathRelativizer;

  @Before
  public void setUp() {
    pathRelativizer =
        new PathRelativizer(
            Paths.get("output0/output1"),
            DefaultSourcePathResolver.from(new SourcePathRuleFinder(new TestActionGraphBuilder()))
                ::getRelativePath);
  }

  @Test
  public void testOutputPathToBuildTargetPath() {
    assertEquals(
        Paths.get("../../foo/bar"), pathRelativizer.outputDirToRootRelative(Paths.get("foo/bar")));
  }

  @Test
  public void testOutputPathToSourcePath() {
    assertEquals(
        Paths.get("../../source/path/foo.h"),
        pathRelativizer.outputPathToSourcePath(FakeSourcePath.of("source/path/foo.h")));
  }

  @Test
  public void testOutputDirToRootRelative() {
    assertEquals(
        Paths.get("../../foo/bar"),
        pathRelativizer.outputPathToBuildTargetPath(
            BuildTargetFactory.newInstance("//foo/bar:baz")));
  }

  @Test
  public void testOutputDirToRootRelativeDoesNotAddExtraDotDots() {
    assertEquals(
        Paths.get("something"),
        pathRelativizer.outputDirToRootRelative(Paths.get("output0/output1/something")));
  }

  @Test
  public void testOutputDirToRootRelativeWorksForCurrentDir() {
    assertEquals(
        Paths.get("."), pathRelativizer.outputDirToRootRelative(Paths.get("output0/output1")));
  }

  @Test
  public void testOutputDirToRootRelativeWorksForParentDir() {
    assertEquals(Paths.get(".."), pathRelativizer.outputDirToRootRelative(Paths.get("output0")));
  }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <parent>
    <artifactId>powermock-modules-test</artifactId>
    <groupId>org.powermock</groupId>
    <version>1.5.5-SNAPSHOT</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.powermock</groupId>
  <artifactId>powermock-modules-test-mockito</artifactId>
  <name>powermock-modules-test-mockito</name>
  <version>1.5.5-SNAPSHOT</version>
  <packaging>pom</packaging>

  <description>
    Tests for Mockito module.
  </description>

  <dependencies>
    <dependency>
       <groupId>org.powermock</groupId>
       <artifactId>powermock-api-mockito</artifactId>
       <version>${project.version}</version>
    </dependency>
    <dependency>
         <groupId>org.powermock.tests</groupId>
         <artifactId>powermock-tests-utils</artifactId>
         <version>${project.version}</version>
         <scope>test</scope>
    </dependency>
  </dependencies>
  <modules>
    <module>junit4</module>
    <module>junit49</module>
    <module>junit4-rule-objenesis</module>
    <module>junit4-rule-xstream</module>
    <module>junit4-agent</module>
  </modules>
</project>