text:
package org.openprovenance.prov.dot;
import java.util.List;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedList;
import java.io.File;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.xml.namespace.QName;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.JAXBException;
import javax.xml.bind.JAXBElement;
//import org.w3c.dom.Element;

import org.openprovenance.prov.xml.Entity;
import org.openprovenance.prov.xml.Activity;
import org.openprovenance.prov.xml.Relation0;
import org.openprovenance.prov.xml.Relation;
import org.openprovenance.prov.xml.Agent;
import org.openprovenance.prov.xml.Used;
import org.openprovenance.prov.xml.HasType;
import org.openprovenance.prov.xml.WasGeneratedBy;
import org.openprovenance.prov.xml.WasDerivedFrom;
import org.openprovenance.prov.xml.WasAttributedTo;
import org.openprovenance.prov.xml.WasAssociatedWith;
import org.openprovenance.prov.xml.DerivedByInsertionFrom;
import org.openprovenance.prov.xml.ProvFactory;
import org.openprovenance.prov.xml.ProvUtilities;
import org.openprovenance.prov.xml.Identifiable;
import org.openprovenance.prov.xml.ProvDeserialiser;
import org.openprovenance.prov.xml.HasAnnotation;
import org.openprovenance.prov.xml.Note;
import org.openprovenance.prov.xml.Bundle;
import org.openprovenance.prov.xml.HasExtensibility;

import org.openprovenance.prov.dot.ProvPrinterConfiguration;
import org.openprovenance.prov.dot.AgentMapEntry;
import org.openprovenance.prov.dot.AccountColorMapEntry;
import org.openprovenance.prov.dot.EntityMapEntry;
import org.openprovenance.prov.dot.ActivityMapEntry;
import org.openprovenance.prov.dot.RelationStyleMapEntry;
import org.openprovenance.prov.dot.ProvPrinterConfigDeserialiser;

/** Serialisation of  Prov representation to DOT format. */
public class ProvToDot {
    public final static String DEFAULT_CONFIGURATION_FILE="defaultConfig.xml";
    public final static String DEFAULT_CONFIGURATION_FILE_WITH_ROLE="defaultConfigWithRole.xml";
    public final static String USAGE="prov2dot provFile.xml out.dot out.pdf [configuration.xml]";

    ProvUtilities u=new ProvUtilities();
    ProvFactory of=new ProvFactory();

    public String qnameToString(QName qName) {
        return qName.getLocalPart();
    }

    public static void main(String [] args) throws Exception {
        if ((args==null) || (args.length==0) || (args.length>4)) {
            System.out.println(USAGE);
            return;
        }

        String opmFile=args[0];
        String outDot=args[1];
        String outPdf=args[2];
        String configFile=((args.length==4) ? args[3] : null);

        ProvToDot converter=((configFile==null) ? new ProvToDot() : new ProvToDot(configFile));

        converter.convert(opmFile,outDot,outPdf);
    }

    public ProvToDot() {
        InputStream is=this.getClass().getClassLoader().getResourceAsStream(DEFAULT_CONFIGURATION_FILE);
        init(is);
    }
    public ProvToDot(boolean withRoleFlag) {
        InputStream is;
        if (withRoleFlag) {
            is=this.getClass().getClassLoader().getResourceAsStream(DEFAULT_CONFIGURATION_FILE_WITH_ROLE);
        } else {
            is=this.getClass().getClassLoader().getResourceAsStream(DEFAULT_CONFIGURATION_FILE);
        }
        init(is);
    }

    public ProvToDot(String configurationFile) {
        this();
        init(configurationFile);
    }

    public ProvPrinterConfigDeserialiser getDeserialiser() {
        return ProvPrinterConfigDeserialiser.getThreadProvPrinterConfigDeserialiser();
    }

    public void init(String configurationFile) {
        ProvPrinterConfigDeserialiser printerDeserial=getDeserialiser();
        try {
            ProvPrinterConfiguration opc=printerDeserial.deserialiseProvPrinterConfiguration(new File(configurationFile));
            init(opc);
        } catch (JAXBException je) {
            je.printStackTrace();
        }
    }

    public void init(InputStream is) {
        ProvPrinterConfigDeserialiser printerDeserial=getDeserialiser();
        try {
            ProvPrinterConfiguration opc=printerDeserial.deserialiseProvPrinterConfiguration(is);
            init(opc);
        } catch (JAXBException je) {
            je.printStackTrace();
        }
    }

    public void init(ProvPrinterConfiguration configuration) {
        if (configuration==null) return;

        if (configuration.getRelations()!=null) {
            if (configuration.getRelations().getDefault()!=null) {
                defaultRelationStyle=configuration.getRelations().getDefault();
            }

            for (RelationStyleMapEntry edge: configuration.getRelations().getRelation()) {
                edgeStyleMap.put(edge.getType(),edge);
            }
        }

        if (configuration.getActivities()!=null) {
            if (configuration.getActivities().isDisplayValue()!=null) {
                this.displayActivityValue=configuration.getActivities().isDisplayValue();
            }
            if (configuration.getActivities().isColoredAsAccount()!=null) {
                this.displayActivityColor=configuration.getActivities().isColoredAsAccount();
            }
            for (ActivityMapEntry process: configuration.getActivities().getActivity()) {
                processNameMap.put(process.getValue(),process.getDisplay());
            }
        }

        if (configuration.getEntities()!=null) {
            if (configuration.getEntities().isDisplayValue()!=null) {
                this.displayEntityValue=configuration.getEntities().isDisplayValue();
            }
            if (configuration.getEntities().isColoredAsAccount()!=null) {
                this.displayEntityColor=configuration.getEntities().isColoredAsAccount();
            }
            for (EntityMapEntry artifact: configuration.getEntities().getEntity()) {
                artifactNameMap.put(artifact.getValue(),artifact.getDisplay());
            }
        }

        if (configuration.getAgents()!=null) {
            if (configuration.getAgents().isDisplayValue()!=null) {
                this.displayAgentValue=configuration.getAgents().isDisplayValue();
            }
            if (configuration.getAgents().isColoredAsAccount()!=null) {
                this.displayAgentColor=configuration.getAgents().isColoredAsAccount();
            }
            for (AgentMapEntry agent: configuration.getAgents().getAgent()) {
                agentNameMap.put(agent.getValue(),agent.getDisplay());
            }
        }

        if (configuration.getAccounts()!=null) {
            if (configuration.getAccounts().getDefaultAccount()!=null) {
                this.defaultAccountLabel=configuration.getAccounts().getDefaultAccount();
            }
            if (configuration.getAccounts().getDefaultColor()!=null) {
                this.defaultAccountColor=configuration.getAccounts().getDefaultColor();
            }
            for (AccountColorMapEntry account: configuration.getAccounts().getAccount()) {
                accountColourMap.put(account.getName(),account.getColor());
            }
        }

        if (configuration.getGraphName()!=null) {
            this.name=configuration.getGraphName();
        }

    }

    public void convert(String opmFile, String dotFile, String pdfFile)
        throws java.io.FileNotFoundException, java.io.IOException, JAXBException {
        convert (ProvDeserialiser.getThreadProvDeserialiser().deserialiseBundle(new File(opmFile)),dotFile,pdfFile);
    }

    public void convert(Bundle graph, String dotFile, String pdfFile)
        throws java.io.FileNotFoundException, java.io.IOException {
        convert(graph,new File(dotFile));
        Runtime runtime = Runtime.getRuntime();
        java.lang.Process proc = runtime.exec("dot -o " + pdfFile + " -Tpdf " + dotFile);
    }

    public void convert(Bundle graph, File file) throws java.io.FileNotFoundException{
        OutputStream os=new FileOutputStream(file);
        convert(graph, new PrintStream(os));
    }

    public void convert(Bundle graph, PrintStream out) {
        List<Relation0> edges=u.getRelations(graph);

        prelude(out);

        if (graph.getRecords().getActivity()!=null) {
            for (Activity p: graph.getRecords().getActivity()) {
                emitActivity(p,out);
            }
        }

        if (graph.getRecords().getEntity()!=null) {
            for (Entity p: graph.getRecords().getEntity()) {
                emitEntity(p,out);
            }
        }

        if (graph.getRecords().getAgent()!=null) {
            for (Agent p: graph.getRecords().getAgent()) {
                emitAgent(p,out);
            }
        }

        for (Relation0 e: edges) {
            if (!(e instanceof HasAnnotation))
            emitDependency(e,out);
        }

        postlude(out);

    }

    boolean collapseAnnotations=true;

    static int embeddedAnnotationCounter=0;
    public void emitAnnotations(HasExtensibility node, PrintStream out) {

    }

    //////////////////////////////////////////////////////////////////////
    ///
    ///                              ELEMENTS
    ///
    //////////////////////////////////////////////////////////////////////

    public void emitActivity(Activity p, PrintStream out) {
        HashMap<String,String> properties=new HashMap();

        emitElement(p.getId(),
                 addActivityShape(p,addActivityLabel(p, addActivityColor(p,properties))),
                 out);

                emitAnnotations("", p,out);
    }

    public void emitEntity(Entity a, PrintStream out) {
        HashMap<String,String> properties=new HashMap();

        emitElement(a.getId(),
                 addEntityShape(a,addEntityLabel(a, addEntityColor(a,properties))),
                 out);

        emitAnnotations("", a,out);
    }

    public void emitAgent(Agent ag, PrintStream out) {
        HashMap<String,String> properties=new HashMap();

        emitElement(ag.getId(),
                 addAgentShape(ag,addAgentLabel(ag, addAgentColor(ag,properties))),
                 out);

        emitAnnotations("", ag,out);

    }

    public void emitAnnotations(String id, HasExtensibility ann, PrintStream out) {

        if ((ann.getAny()==null) || (ann.getAny().isEmpty())
            &&
            (((HasType)ann).getType().isEmpty())) return;

        HashMap<String,String> properties=new HashMap();
        QName newId=annotationId(((Identifiable)ann).getId(),id);
        emitElement(newId,
                    addAnnotationShape(ann,addAnnotationColor(ann,addAnnotationLabel(ann,properties))),
                    out);
        HashMap<String,String> linkProperties=new HashMap();
        emitRelation(qnameToString(newId),
                     qnameToString(((Identifiable)ann).getId()),
                     addAnnotationLinkProperties(ann,linkProperties),out,true);
    }

    int annotationCount=0;
    public QName annotationId(QName id,String node) {
        if (true || id==null) {
            return new QName("http://foo/ignore","ann" + node + (annotationCount++));
        } else {
            return id;
        }
    }

    public HashMap<String,String> addAnnotationLinkProperties(HasExtensibility ann, HashMap<String,String> properties) {
        properties.put("arrowhead","none");
        properties.put("style","dashed");
        properties.put("color","gray");
        return properties;
    }

    public HashMap<String,String> addActivityShape(Activity p, HashMap<String,String> properties) {
        properties.put("shape","polygon");
        properties.put("sides","4");
        return properties;
    }

    public HashMap<String,String> addBlankNodeShape(HashMap<String,String> properties) {
        properties.put("shape","point");
        properties.put("label","");
        return properties;
    }

    public HashMap<String,String> addActivityLabel(Activity p, HashMap<String,String> properties) {
        properties.put("label",processLabel(p));
        return properties;
    }

    public HashMap<String,String> addActivityColor(Activity p, HashMap<String,String> properties) {
        if (displayActivityColor) {
            properties.put("color",processColor(p));
            properties.put("fontcolor",processColor(p));
        }
        addColors(p,properties);
        return properties;
    }

    public  HashMap<String,String> addColors(HasExtensibility e, HashMap<String,String> properties) {
        Hashtable<String,List<Object>> table=e.attributesWithNamespace("http://openprovenance.org/Toolbox/dot#");

        List<Object> o=table.get("fillcolor");
        if (o!=null && !o.isEmpty()) {
            properties.put("fillcolor", o.get(0).toString());
            properties.put("style", "filled");
        }
        o=table.get("color");
        if (o!=null && !o.isEmpty()) {
            properties.put("color", o.get(0).toString());
        }
        o=table.get("url");
        if (o!=null && !o.isEmpty()) {
            properties.put("URL", o.get(0).toString());
        }
        return properties;
    }

    public HashMap<String,String> addEntityShape(Entity p, HashMap<String,String> properties) {
        // default is good for entity
        List<Object> types=p.getType();
        for (Object type: types) {
            if (type instanceof QName) {
                QName name=(QName) type;
                if (("Dictionary".equals(name.getLocalPart()))
                    ||
                    ("EmptyDictionary".equals(name.getLocalPart()))) {
                    properties.put("shape","folder");
                }
            }
        }
        return properties;
    }

    public HashMap<String,String> addEntityColor(Entity a, HashMap<String,String> properties) {
        if (displayEntityColor) {
            properties.put("color",entityColor(a));
            properties.put("fontcolor",entityColor(a));
        }
        addColors(a,properties);
        return properties;
    }

    public HashMap<String,String> addEntityLabel(Entity p, HashMap<String,String> properties) {
        properties.put("label",entityLabel(p));
        return properties;
    }

    public HashMap<String,String> addAgentShape(Agent p, HashMap<String,String> properties) {
        properties.put("shape","house");
        //properties.put("sides","8");
        return properties;
    }

    public HashMap<String,String> addAgentLabel(Agent p, HashMap<String,String> properties) {
        properties.put("label",agentLabel(p));
        return properties;
    }

    public HashMap<String,String> addAgentColor(Agent a, HashMap<String,String> properties) {
        if (displayAgentColor) {
            properties.put("color",agentColor(a));
            properties.put("fontcolor",agentColor(a));
        }
        addColors(a,properties);
        return properties;
    }

    public HashMap<String,String> addAnnotationShape(HasExtensibility ann, HashMap<String,String> properties) {
        properties.put("shape","note");
        return properties;
    }
    public HashMap<String,String> addAnnotationLabel(HasExtensibility ann, HashMap<String,String> properties) {
        String label="";
        label=label+"<
\n";
        for (Object type: ((HasType)ann).getType()) {
            label=label+"
\n";
            label=label+"	    " + "type" + ":	\n";
            label=label+"	    " + convertValue(type) + "	\n";
            label=label+"
\n";
        }
        for (Object prop: ann.getAny()) {

            if (prop instanceof JAXBElement) {
                JAXBElement je=(JAXBElement) prop;
                QName attribute=je.getName();
                if ("fillcolor".equals(attribute.getLocalPart())) {
                    // no need to display this attribute
                    break;
                }
            }

            label=label+"
\n";
            label=label+"	    " + convertProperty(prop) + ":	\n";
            label=label+"	    " + convertValue(prop) + "	\n";
            label=label+"
\n";
        }
        label=label+"
>\n";
        properties.put("label",label);
        properties.put("fontsize","10");
        return properties;
    }

   public String convertValue(Object v) {
       if (v instanceof QName) {
           QName name=(QName) v;
           return name.getLocalPart();
       }
       String label=getPropertyValueFromAny(v);
       System.out.println("Foudn value " + label);
       int i=label.lastIndexOf("#");
       int j=label.lastIndexOf("/");
       return label.substring(Math.max(i,j)+1, label.length());
   }

    public String qnameToUri(QName qname) {
        return qname.getNamespaceURI() + qname.getLocalPart();
    }

    public String convertProperty(Object oLabel) {
        String label=getPropertyFromAny(oLabel);
        int i=label.lastIndexOf("#");
        int j=label.lastIndexOf("/");
        return label.substring(Math.max(i,j)+1, label.length());
    }

    public String getPropertyFromAny (Object o) {
        if (o instanceof JAXBElement) {
            return qnameToUri(((JAXBElement)o).getName());
        } else if (o instanceof org.w3c.dom.Element) {
            return ((org.w3c.dom.Element)o).getTagName();
        } else {
            return o.toString();
        }
    }

    public String getPropertyValueFromAny (Object o) {
        if (o instanceof JAXBElement) {
            Object val=((JAXBElement)o).getValue();
            if (val instanceof QName) {
                QName q=(QName)val;
                return q.getNamespaceURI() + q.getLocalPart();
            } else {
                return "" +  val;
            }
        } else if (o instanceof org.w3c.dom.Element) {
            return ((org.w3c.dom.Element)o).getFirstChild().getNodeValue();
        } else {
            return o.toString();
        }
    }

    public HashMap<String,String> addAnnotationColor(HasExtensibility ann, HashMap<String,String> properties) {
        if (displayAnnotationColor) {
            properties.put("color",annotationColor(ann));
            properties.put("fontcolor","black");
            //properties.put("style","filled");
        }
        return properties;
    }

    boolean displayActivityValue=false;
    boolean displayActivityColor=false;
    boolean displayEntityValue=false;
    boolean displayEntityColor=false;
    boolean displayAgentColor=false;
    boolean displayAgentValue=false;
    boolean displayAnnotationColor=true;

    public String processLabel(Activity p) {
        if (displayActivityValue) {
            return convertActivityName(""+of.getLabel(p));
        } else {
            return qnameToString(p.getId());
        }
    }
    public String processColor(Activity p) {
        // Note, I should compute effective account membership
        List<String> colors=new LinkedList();
        // for (AccountRef acc: p.getAccount()) {
        //     String accountLabel=((Account)acc.getRef()).getId();
        //     String colour=convertAccount(accountLabel);
        //     colors.add(colour);
        // }

        return selectColor(colors);
    }

    // returns the first non transparent color
    public String selectColor(List<String> colors) {
        String tr="transparent";
        for (String c: colors) {
            if (!(c.equals(tr))) return c;
        }
        return tr;
    }

    public String entityLabel(Entity p) {
        if (displayEntityValue) {
            return convertEntityName(""+of.getLabel(p));
        } else {
            System.out.println(" ----> " + qnameToString(p.getId()) + "    " + of.getLabel(p));
            return qnameToString(p.getId());
        }
    }
    public String entityColor(Entity p) {
        // Note, I should compute effective account membership
        List<String> colors=new LinkedList();
        // for (AccountRef acc: p.getAccount()) {
        //     String accountLabel=((Account)acc.getRef()).getId();
        //     String colour=convertAccount(accountLabel);
        //     colors.add(colour);
        // }
        return selectColor(colors);
    }
    public String agentColor(Agent p) {
        // Note, I should compute effective account membership
        List<String> colors=new LinkedList();
        // for (AccountRef acc: p.getAccount()) {
        //     String accountLabel=((Account)acc.getRef()).getId();
        //     String colour=convertAccount(accountLabel);
        //     colors.add(colour);
        // }
        return selectColor(colors);
    }

    public String annotationColor(HasExtensibility ann) {
        List<String> colors=new LinkedList();
        colors.add("gray");
        return selectColor(colors);
    }

    public String agentLabel(Agent p) {
        if (displayAgentValue) {
            return convertAgentName(""+of.getLabel(p));
        } else {
            return qnameToString(p.getId());
        }
    }

    HashMap<String,String> processNameMap=new HashMap<String,String>();
    public String convertActivityName(String process) {
        String name=processNameMap.get(process);
        if (name!=null) return name;
        return process;
    }
    HashMap<String,String> artifactNameMap=new HashMap<String,String>();
    public String convertEntityName(String artifact) {
        String name=artifactNameMap.get(artifact);
        if (name!=null) return name;
        return artifact;
    }
    HashMap<String,String> agentNameMap=new HashMap<String,String>();
    public String convertAgentName(String agent) {
        String name=agentNameMap.get(agent);
        if (name!=null) return name;
        return agent;
    }

    int bncounter=0;

    //////////////////////////////////////////////////////////////////////
    ///
    ///                              EDGES
    ///
    //////////////////////////////////////////////////////////////////////

    public void emitDependency(Relation0 e, PrintStream out) {
        HashMap<String,String> properties=new HashMap();

        // List<AccountRef> accounts=e.getAccount();
        // if (accounts.isEmpty()) {
        //     accounts=new LinkedList();
        //     accounts.add(of.newAccountRef(of.newAccount(defaultAccountLabel)));
        // }

        // for (AccountRef acc: accounts) {
        //     String accountLabel=((Account)acc.getRef()).getId();
        //     addRelationAttributes(accountLabel,e,properties);
        //        }
        List<QName> others=u.getOtherCauses(e);
        if (others !=null) { // n-ary case
            String bnid="bn" + (bncounter++);

            emitBlankNode(dotify(bnid), addBlankNodeShape(properties), out);

            HashMap<String,String> properties2=new HashMap();
            properties2.put("arrowhead","none");

            HashMap<String,String> properties3=new HashMap();

            emitRelation( qnameToString(u.getEffect(e)),
                          bnid,
                          properties2,
                          out,
                          true);

            relationName(e, properties3);

            if (e instanceof DerivedByInsertionFrom) {
                properties3.put("arrowhead","onormal");
            }

            emitRelation( bnid,
                          qnameToString(u.getCause(e)),
                          properties3,
                          out,
                          true);

            HashMap<String,String> properties4=new HashMap();

            for (QName other: others) {
                emitRelation( bnid,
                              qnameToString(other),
                              properties4,
                              out,
                              true);
            }

        } else { // binary case
            relationName(e, properties);
            if (e instanceof Relation) {
                addColors((Relation)e,properties);
            }

            emitRelation( qnameToString(u.getEffect(e)),
                          qnameToString(u.getCause(e)),
                          properties,
                          out,
                          true);

        }
    }

    void relationName(Relation0 e, HashMap<String,String> properties) {
	String l=getShortLabelForRelation(e);
	if (l!=null) {
	    properties.put("taillabel",l);
	    properties.put("labelangle", "60.0");
	    properties.put("labeldistance", "1.5");
	    properties.put("rotation", "20");
	    properties.put("labelfontsize", "8");
	}
    }

    String getLabelForRelation(Relation0 e) {
	if (e instanceof Used) return "used";
	if (e instanceof WasGeneratedBy) return "wasGeneratedBy";
	if (e instanceof WasDerivedFrom) return "wasDerivedFrom";
	if (e instanceof WasAssociatedWith) return "wasAssociatedWith";
	if (e instanceof WasAttributedTo) return "wasAttributedTo";
	return null;
    }
    String getShortLabelForRelation(Relation0 e) {
	if (e instanceof Used) return "used";
	if (e instanceof WasGeneratedBy) return "wgb";
	if (e instanceof WasDerivedFrom) return "wdf";
	if (e instanceof WasAssociatedWith) return "waw";
	if (e instanceof WasAttributedTo) return "wat";
	return null;
    }

    public HashMap<String,String> addRelationAttributes(String accountLabel,
                                                        Relation0 e,
                                                        HashMap<String,String> properties) {
        String colour=convertAccount(accountLabel);
        properties.put("color",colour);
        properties.put("fontcolor",colour);
        properties.put("style",getRelationStyle(e));
        addRelationLabel(e,properties);
        return properties;
    }

    /* Displays type if any, role otherwise. */
    public void addRelationLabel(Relation0 e0, HashMap<String,String> properties) {
        String label=null;
        if (!(e0 instanceof Relation)) return;
        Relation e=(Relation)e0;
        List<Object> type=of.getType(e);
        if ((type!=null) || (!type.isEmpty())) {
            label=type.get(0).toString();
        } else if (getRelationPrintRole(e)) {
            String role=of.getRole(e);
            if (role!=null) {
                label=displayRole(role);
                properties.put("fontsize","8");
            }
        }
        if (label!=null) {
            properties.put("label",convertRelationLabel(label));
            if (properties.get("fontsize")==null) {
                properties.put("fontsize","10");
            }
        }
    }

    public String displayRole(String role) {
        return "(" + role + ")";
    }

    public String convertRelationLabel(String label) {
        return label.substring(label.indexOf("#")+1, label.length());
    }

    HashMap<String,String> accountColourMap=new HashMap<String,String>();
    public String convertAccount(String account) {
        String colour=accountColourMap.get(account);
        if (colour!=null) return colour;
        return defaultAccountColor;
    }

    String defaultRelationStyle;
    HashMap<String,RelationStyleMapEntry> edgeStyleMap=new HashMap<String,RelationStyleMapEntry>();

    public String getRelationStyle(Relation0 edge) {
        String name=edge.getClass().getName();
        RelationStyleMapEntry style=edgeStyleMap.get(name);
        if (style!=null) return style.getStyle();
        return defaultRelationStyle;
    }

    public boolean getRelationPrintRole(Relation0 edge) {
        String name=edge.getClass().getName();
        RelationStyleMapEntry style=edgeStyleMap.get(name);
        if (style!=null) {
            Boolean flag=style.isPrintRole();
            if (flag==null) return false;
            return flag;
        } else {
            return false;
        }
    }

    //////////////////////////////////////////////////////////////////////
    ///
    ///                              DOT FORMAT GENERATION
    ///
    //////////////////////////////////////////////////////////////////////

    String name;
    String defaultAccountLabel;
    String defaultAccountColor;

    /* make name compatible with dot notation*/

    public String dotify(String name) {
        return "n" + name.replace('-','_').replace('.','_').replace('/','_');
    }

    public void emitElement(QName name, HashMap<String,String> properties, PrintStream out) {
        StringBuffer sb=new StringBuffer();
        sb.append(""+dotify(qnameToString(name)));
        emitProperties(sb,properties);
        out.println(sb.toString());
    }

    public void emitBlankNode(String bnid, HashMap<String,String> properties, PrintStream out) {
        StringBuffer sb=new StringBuffer();
	sb.append(bnid);
        emitProperties(sb,properties);
        out.println(sb.toString());
    }

    public void emitRelation(String src, String dest, HashMap<String,String> properties, PrintStream out, boolean directional) {
        StringBuffer sb=new StringBuffer();
        sb.append(dotify(src));
        if (directional) {
            sb.append(" -> ");
        } else {
            sb.append(" -- ");
        }
        sb.append(dotify(dest));
        emitProperties(sb,properties);
        out.println(sb.toString());
    }

    public void emitProperties(StringBuffer sb,HashMap<String,String> properties) {
        sb.append(" [");
        boolean first=true;
        for (String key: properties.keySet()) {
            if (first) {
                first=false;
            } else {
                sb.append(",");
            }
            String value=properties.get(key);
            sb.append(key);
            if (value.startsWith("<")) {
                sb.append("=");
                sb.append(value);
            } else {
                sb.append("=\"");
                sb.append(value);
                sb.append("\"");
            }

        }
        sb.append("]");
    }

    void prelude(PrintStream out) {
        out.println("digraph " + name + " { rankdir=\"BT\"; ");
    }

    void postlude(PrintStream out) {
        out.println("}");
        out.close();
    }

}


text:
package fr.openwide.core.test.jpa.more.business.audit.service;

import fr.openwide.core.jpa.more.business.audit.service.IAbstractAuditService;
import fr.openwide.core.test.jpa.more.business.audit.model.MockAudit;
import fr.openwide.core.test.jpa.more.business.audit.model.MockAuditAction;
import fr.openwide.core.test.jpa.more.business.audit.model.MockAuditActionEnum;
import fr.openwide.core.test.jpa.more.business.audit.model.MockAuditFeature;
import fr.openwide.core.test.jpa.more.business.audit.model.MockAuditFeatureEnum;

public interface IMockAuditService extends IAbstractAuditService<MockAudit> {

	MockAuditAction getAuditActionByEnum(MockAuditActionEnum auditActionEnum);

	MockAuditFeature getAuditFeatureByEnum(MockAuditFeatureEnum auditFeatureEnum);
}

redpajama_set_name: RedPajamaGithub


text:
import ConfigParser
from os import path
from subprocess import call

class BuildConfig:
    def __init__(self, base_dir, name, project_config):
        self.base_dir = base_dir
        self.name = name
        self.project_config = project_config
        default_build_config = {
            'external': '',
            'internal': '',
            'description': ''
        }
        self.build_parser = ConfigParser.SafeConfigParser(default_build_config)
        self.build_parser.read(path.join(base_dir, name, 'build.cfg'))

    def name_version(self):
        return '%s-%s' % (self.name, self.project_config.api_version())

    def gir_name(self):
        return self.build_parser.get('default', 'gir_name')

    def gir_name_version(self):
        return '%s-%s' % (self.gir_name(), self.project_config.api_version())

    def description(self):
        return self.build_parser.get('default', 'description')

    def external_packages(self):
        return self.build_parser.get('packages', 'external')

    def internal_packages(self):
        return self.build_parser.get('packages', 'internal')

    def packages(self):
        return '%s %s' % (self.internal_packages(), self.external_packages())

    def pkg_configs(self):
        pkgs = [pkg for pkg in self.packages().split()
                if call(['pkg-config', pkg]) == 0]
        return ' '.join(pkgs)

    def source_pattern(self):
        return path.join(self.base_dir, self.name, '**', '*.vala')


text:
class customMSM:

    seed = 1234567890
    digits = 10

    ##Reading seed value from file if exists.
    def get_seed(self):
        try:
            seed_file = open('seed', 'r')
            data = seed_file.readline()
            seed_file.close
            if len(data) > customMSM.digits:
                data = strip(data[:customMSM.digits])
            customMSM.seed = int(data)
        except:
            pass

    ##Modification of seed value
    def generate_new_seed(self):
        customMSM.seed = str(customMSM.seed * customMSM.seed)
        while len(customMSM.seed) < customMSM.digits * 2:
            customMSM.seed = '1' + customMSM.seed
        start = int(customMSM.digits / 2)
        end = start + customMSM.digits
        customMSM.seed = int(customMSM.seed[start:end])

    ##This function returns a random number between 0 and limit, with 0 inclusive and limit exclusive.
    def random(self, limit):
        self.get_seed()
        for i in range(0,25000):
            self.generate_new_seed()
        selection = customMSM.seed % limit      ##I chose % as it maintains equal biasnes towards all the possible output numbers.
        customMSM.seed += selection             ##To try reduce repeatitive patterns.
        file = open('seed', 'w')                ##Saving seed value to file for more randomized value and to reduce chance of producing same number at each execution with same input condition.
        file.write(str(customMSM.seed))
        file.close
        return selection


text:
..
 This work is licensed under a Creative Commons Attribution 3.0 Unported
 License.

 http://creativecommons.org/licenses/by/3.0/legalcode

==========================
Resource Meta-data Caching
==========================

This was discussed at the YVR summit as follow up to issues raised during the
Operators feedback session.

Problem description
===================

Ceilometer polls regularly via the compute-agent to get resource meta-data'
for all instances. This polling adds load to Nova, Neutron, and Keystone
APIs, which at scale causes a significant performance impact. This meta-data
does not change very often, and the load is likewise often unnecessary.

Proposed change
===============

Lets take advantage of the changes-since parameter in the nova api call.
We'll start by creating an in-memory cache to store the resource meta-data
on the initial polling and the time of that polling. Then the compute agent
will use the changes-since parameter in all subsequent pollings. This will
reduce the amount of data queried and returned by the Nova API. The results
of this call will update the cache, and the cache will be used to return
the data. Also, we should populate the instance flavor and image data in
the cache as well.

Alternatives
------------

Do nothing

Data model impact
-----------------

None

REST API impact
---------------

None

Security impact
---------------

None

Pipeline impact
---------------

None

Other end user impact
---------------------

None

Performance/Scalability Impacts
-------------------------------

Should provide greater overall scalability due to the reduction in API load
and reduced traffic flows.

Other deployer impact
---------------------

None

Developer impact
----------------

None

Implementation
==============

Assignee(s)
-----------

Primary assignee:
  jasonamyers

Other contributors:
  None

Ongoing maintainer:
  jasonamyers

Work Items
----------

 - Implement an in-memory cache in the compute agent.
 - Change compute-agent to populate an in-memory cache.
 - Change compute-agent to use the changes-since parameter in the Nova API call .
 - Change compute-agent to record the polling timestamp in the cache.
 - Change compute-agent to cache the flavor and image metadata as well.

Future lifecycle
================

None

Dependencies
============

None

Testing
=======

We will need to add tests for meta-data cache flag, API changed-since
queries, compute-agent cache control, and image/flavor caching.

Documentation Impact
====================

We will need to document the changes to the polling process, the new meta-data
cache config option, and create new documentation that describes the caching
work-flow.

References
==========

https://etherpad.openstack.org/p/YVR-ops-ceilometer


text:
#ifndef _RU_UNAUDIT_REFRESH_TASK_EXECUTOR_H_
#define _RU_UNAUDIT_REFRESH_TASK_EXECUTOR_H_

/* -
*-C++-*-
******************************************************************************
*
* File:         RuUnAuditRefreshTaskExecutor.h
* Description:  Definition of class CRUUnAuditRefreshTaskExecutor.
*
*
* Created:      08/14/2000
* Language:     C++
*
*
******************************************************************************
*/

//--------------------------------------------------------------------------//
//
//	CRUUnAuditRefreshTaskExecutor
//
//	This class handle the refresh of a NO AUDIT/NO AUDITONREFRESH MV,
//	and the initialization (through recompute) of an AUDITED MV whose
//	status is NON_INITIALIZED/UNAVAILABLE.
//
//	The class implements a finite state machine where some states
//	may be executed in a different process. The task executor supports
//	the refresh of either a single MV, or a list of pipelined MVs.
//
//	The process of refresh is performed outside the transaction boundaries,
//	to avoid the problems of autoabort and lock escalation.
//	NOTE. CURRENTLY, THE REFRESH IS DONE IN A TRANSACTION BECAUSE OF AN
//	EXTERNAL DEPENDENCY ON DP2: THE TRANSACTION IS OPENED AUTOMATICALLY
//	BECAUSE OF THE READ-COMMITTED SELECT FROM THE AUDITED TABLES.
//
//	The MV(s) remain(s) non-available throughout the process of refresh,
//	because the algorithm sometimes performs non-recoverable actions.
//	The MV (and its indexes) are returned to the available state at the
//	end of the execution.
//
//	The process of recompute can be optimized in two ways:
//	(1) The use of purgedata from MV (instead of the DELETE part of
//		INTERNAL REFRESH), if there was previously some data in the MV,
//		and the user has a DELETE privilege.
//	(2) The indexes are disabled during recompute (to avoid IM), and
//		populated separately (without transaction) when the recompute is over.
//
//	When initializing an ON STATEMENT MV, the task executor employs
//	sophisticated lock handling to ensure that at the end of refresh
//	the MV is consistent with the tables, and incremental maintenance
//	can start immediately.
//
//--------------------------------------------------------------------------//

#include "RuSimpleRefreshTaskExecutor.h"

class REFRESH_LIB_CLASS CRUUnAuditRefreshTaskExecutor :
		public CRUSimpleRefreshTaskExecutor
{
private:
	typedef CRUSimpleRefreshTaskExecutor inherited;

public:
	CRUUnAuditRefreshTaskExecutor(CRURefreshTask *pParentTask = NULL);
	virtual ~CRUUnAuditRefreshTaskExecutor();

public:
	//-- Implementation of pure virtuals
	virtual void Work();
	virtual void Init();

public:
	// These functions serialize/de-serialize the executor's context
	// for the message communication with the remote server process

	// Used at the main process side
	virtual void StoreRequest(CUOFsIpcMessageTranslator &translator);
	virtual void LoadReply(CUOFsIpcMessageTranslator &translator)
	{
		inherited::LoadReply(translator);
	}

	// Used at the remote process side
	virtual void LoadRequest(CUOFsIpcMessageTranslator &translator);
	virtual void StoreReply(CUOFsIpcMessageTranslator &translator)
	{
		inherited::StoreReply(translator);
	}

	//----------------------------------//
	//	Private Members
	//----------------------------------//
private:
	enum STATES {
		// Local states
		EX_PROLOGUE = MAIN_STATES_START,
		EX_EPILOGUE,
		EX_PURGE_DATA,
		// Remote states
		EX_REFRESH = REMOTE_STATES_START,
		EX_RECOMPUTE,
		EX_POPINDEX
	};

	// Work() callees
	void Start();
	void Prologue();
	void Refresh();
	void PurgeData();
	void Recompute();
	void PopulateIndexes();
	void Epilogue();

	void ComposeMySql();
	void ComposeIndexesSql();

	// First txn: set the MV (+ optionally its indexes) non-available
	void SetObjectsUnavailable();
	// Last txn: set the MV (+ optionally its indexes) back available
	void ResetObjectsAvailable();

	void UnLockMV();

	// Special handling of the ON STATEMENT MV's initialization
	void PrologueHandleOnStatementMV();
	void EpilogueHandleOnStatementMV();

	void ExecuteIndexStatmenents(CRUSQLDynamicStatementContainer &container,
								 Lng32 errorCode);
private:
	enum SQL_STATEMENT {

		RU_UNLOCK_TABLE = 0,
		NUM_OF_SQL_STMT // should always be last
	};

	// Statements specific for this task executor
	CRUSQLDynamicStatementContainer unAuditRefreshTEDynamicContainer_;
	CRUSQLDynamicStatementContainer *pUnAuditPopIndexdynamicContainer_;
	CRUSQLDynamicStatementContainer *pUnAuditAvailableIndeXdynamicContainer_;
	CRUSQLDynamicStatementContainer *pUnAuditUnavailableIndeXdynamicContainer_;
	TInt32 numOfIndexes_;

	// The container of LOCK TABLE statements
	CRUSQLDynamicStatementContainer *pLockTablesTEDynamicContainer_;

	BOOL isPurgedata_;
	BOOL isPopindex_;
};

#endif


text:
package com.mountain.domain;

import java.io.Serializable;
import java.math.BigDecimal;

import javax.persistence.Cacheable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

@Entity
@Cacheable
@Cache(region = "books", usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Book implements Serializable {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;

	private String title;
	private String description;
	private BigDecimal price;
	private Integer year;
	private String author;
	private String Isbn;

	@ManyToOne(optional = false)
	private Category category;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public BigDecimal getPrice() {
		return price;
	}

	public void setPrice(BigDecimal price) {
		this.price = price;
	}

	public Integer getYear() {
		return year;
	}

	public void setYear(Integer year) {
		this.year = year;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getIsbn() {
		return Isbn;
	}

	public void setIsbn(String isbn) {
		Isbn = isbn;
	}

	public Category getCategory() {
		return category;
	}

	public void setCategory(Category category) {
		this.category = category;
	}

	@Override
	public boolean equals(Object object) {
		if (this == object) {
			return true;
		}
		if (object == null || getClass() != object.getClass()) {
			return false;
		}
		Book other = (Book) object;

		return new EqualsBuilder().append(this.getTitle(), other.getTitle())
				.append(this.getAuthor(), other.getAuthor()).isEquals();
	}

	@Override
	public int hashCode() {
		return new HashCodeBuilder().append(getAuthor()).append(getTitle())
				.toHashCode();
	}

	@Override
	public String toString() {
		ToStringBuilder builder = new ToStringBuilder(this,
				ToStringStyle.MULTI_LINE_STYLE);
		builder.append("title", this.title);
		builder.append("author", this.author);
		builder.append("isbn", this.Isbn);
		return builder.build();
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace School
{
    public class Person
    {
        private string name;

        public Person(string name)
        {
            this.Name = name;
        }
        public string Name
        {
            get { return this.name; }
            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    throw new ArgumentNullException("Name cannot be empty or null.");
                }
                this.name = value;
            }
        }
    }
}


text:
#include <Inventor/annex/Profiler/nodes/SoProfilerStats.h>

#include <map>

#include <Inventor/annex/Profiler/elements/SoProfilerElement.h>
#include <Inventor/annex/Profiler/SbProfilingData.h>
#include <Inventor/actions/SoAudioRenderAction.h>
#include <Inventor/actions/SoCallbackAction.h>
#include <Inventor/actions/SoGetBoundingBoxAction.h>
#include <Inventor/actions/SoGetMatrixAction.h>
#include <Inventor/actions/SoGetPrimitiveCountAction.h>
#include <Inventor/actions/SoGLRenderAction.h>
#include <Inventor/actions/SoHandleEventAction.h>
#include <Inventor/actions/SoRayPickAction.h>
#include <Inventor/actions/SoSearchAction.h>
#include <Inventor/actions/SoWriteAction.h>
#include <Inventor/errors/SoDebugError.h>
#include <Inventor/lists/SbList.h>
#include <Inventor/misc/SoState.h>
#include <Inventor/nodes/SoSeparator.h>
#include <Inventor/elements/SoCacheElement.h>

#include "nodes/SoSubNodeP.h"
#include "misc/SbHash.h"

// decide whether to expose profiling stats by node type or by
// user-specified node names
#define BY_TYPE 1

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

/*!
  \class SoProfilerStats SoProfilerStats.h Inventor/annex/Profiler/nodes/SoProfilerStats.h
  \brief The SoProfilerStats class is a node for exposing profiling results gathered by \a SoProfilerElement.

  TODO: Describe functionality and provide usage example.

  \sa SoProfilerElement
  \ingroup profiler
*/

/*!
  \var SoMFName SoProfilerStats::nodeType

  Name of type types traversed during the current render traversal.

  This field is tightly connected to the \a timePerNodeType field as
  they will contain the same number of elements, and each value
  in \a timePerNodeType matches the node type with the same index in
  this field.

  \sa SoProfilerStats::timePerNodeType
*/

/*!
  \var SoMFTime SoProfilerStats::timePerNodeType

  Time spent, during the current render traversal, per node type.

  This field is tightly connected to the \a nodeType field as
  they will contain the same number of elements, and each value
  in this field matches the node type with the same index in
  \a nodeType.

  \sa SoProfilerStats::nodeType
*/

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

#define PUBLIC(obj) ((obj)->master)

class SoProfilerStatsP {
private:
  struct TypeTimings {
    SbTime max, total;
    int32_t count;
  };

public:
  SoProfilerStatsP(void) : master(NULL) {
  }
  ~SoProfilerStatsP(void) { }

  void doAction(SoAction * action);
  void clearProfilingData(void);
  void updateActionTimingMaps(SoProfilerElement * e, SoAction * action);
  void updateActionTimingFields(SoProfilerElement * e);
  void updateNodeTypeTimingMap(SoProfilerElement * e);
  void updateNodeTypeTimingFields();

  std::map<int16_t, SbProfilingData *> action_map;
  std::map<int16_t, TypeTimings> type_timings;
  std::map<const char *, TypeTimings> name_timings;

  SoProfilerStats * master;

  SbHash<int16_t, SbTime> action_timings;
}; // SoProfilerStatsP

void
SoProfilerStatsP::doAction(SoAction * action)
{
  // every SoGLRenderAction traversal will set a flag that causes
  // the profiling data to be cleared at the next traversal, regardless of
  // type
  static SbBool clear_state = FALSE;
  if (clear_state) {
    this->clearProfilingData();
    clear_state = FALSE;
  }

  this->action_timings.put(SoGLRenderAction::getClassTypeId().getKey(),
                           SbTime::zero());

  SoState * state = action->getState();
  if (state->isElementEnabled(SoCacheElement::getClassStackIndex())) {
    SoCacheElement::invalidate(state);
  }

  SoProfilerElement * e = SoProfilerElement::get(state);
  if (!e) { return; }

  std::map<int16_t, SbProfilingData *>::iterator it =
    this->action_map.find(action->getTypeId().getKey());
  if (it != this->action_map.end()) {
    (*((*it).second)) += e->getProfilingData();
  } else {
    SbProfilingData * data = new SbProfilingData(e->getProfilingData());
    std::pair<int16_t, SbProfilingData *> entry(action->getTypeId().getKey(), data);
    this->action_map.insert(entry);
  }

  this->updateNodeTypeTimingMap(e);
  this->updateActionTimingMaps(e, action);

  if (action->isOfType(SoGLRenderAction::getClassTypeId())) {
    this->updateNodeTypeTimingFields();
    updateActionTimingFields(e);
    PUBLIC(this)->profilingUpdate.touch();

    clear_state = TRUE;
  }
} // doAction

void
SoProfilerStatsP::clearProfilingData(void)
{
  std::map<int16_t, SbProfilingData *>::iterator it, end;
  for (it = this->action_map.begin(), end = this->action_map.end();
       it != end; ++it) {
    delete (*it).second;
  }
  this->action_map.clear();
  this->action_timings.clear();
#if BY_TYPE
  this->type_timings.clear();
#else
  this->name_timings.clear();
#endif
} // clearActionMap

void
SoProfilerStatsP::updateActionTimingMaps(SoProfilerElement * e,
                                         SoAction * action)
{
  int16_t type = action->getTypeId().getKey();
  SbTime time = SbTime::zero();
  SbBool found = this->action_timings.get(type, time);
  if (found)
    time += e->getProfilingData().getActionDuration();
  else
    time = e->getProfilingData().getActionDuration();

  this->action_timings.put(type, time);
} // updateActionTimingMaps

void
SoProfilerStatsP::updateNodeTypeTimingMap(SoProfilerElement * e)
{
  const SbProfilingData & data = e->getProfilingData();
#if BY_TYPE
  SbList<SbProfilingNodeTypeKey> keys;
  data.getStatsForTypesKeyList(keys);
  int keyCount = keys.getLength();
  for (int i = 0; i < keyCount; ++i) {
    SbProfilingNodeTypeKey k = keys[i];
    std::map<int16_t, TypeTimings>::iterator it = this->type_timings.find(k);
    if (it != this->type_timings.end()) {
      /*TypeTimings & timings = */it->second;
      SbTime totaltime, maxtime;
      uint32_t count;
      data.getStatsForType(k, totaltime, maxtime, count);
      it->second.total += totaltime;
      it->second.max += maxtime;
      it->second.count += count;

    } else {
      TypeTimings timings;
      SbTime totaltime, maxtime;
      uint32_t count;
      data.getStatsForType(k, totaltime, maxtime, count);
      timings.total = totaltime;
      timings.max = maxtime;
      timings.count = count;
      std::pair<int16_t, TypeTimings> entry(k, timings);
      this->type_timings.insert(entry);
    }
  }
#else
  SbList<SbProfilingNodeNameKey> keys;
  data.getStatsForNamesKeyList(keys);
  int keyCount = keys.getLength();
  for (int i = 0; i < keyCount; ++i) {
    SbProfilingNodeNameKey k = keys[i];
    std::map<const char *, TypeTimings>::iterator it = this->name_timings.find(k);
    if (it != this->name_timings.end()) {
      TypeTimings & timings = it->second;
      SbTime totaltime, maxtime;
      uint32_t count;
      data.getStatsForName(k, totaltime, maxtime, count);
      it->second.total += totaltime;
      it->second.max += maxtime;
      it->second.count += count;
    } else {
      TypeTimings timings;
      SbTime totaltime, maxtime;
      uint32_t count;
      data.getStatsForName(k, totaltime, maxtime, count);
      timings.total = totaltime;
      timings.max = maxtime;
      timings.count = count;
      std::pair<SbProfilingNodeNameKey, TypeTimings> entry(k, timings);
      this->name_timings.insert(entry);
    }
  }
#endif
} // updateNodeTypeTimingMaps

void
SoProfilerStatsP::updateNodeTypeTimingFields()
{
#if BY_TYPE
  int keyCount = (int) this->type_timings.size();
#else
  int keyCount = (int) this->name_timings.size();
#endif

  PUBLIC(this)->renderedNodeType.setNum(keyCount);
  SbName * typeNameArr = PUBLIC(this)->renderedNodeType.startEditing();

  PUBLIC(this)->renderingTimePerNodeType.setNum(keyCount);
  SbTime * renderingTimePerNodeTypeArr = PUBLIC(this)->renderingTimePerNodeType.startEditing();

  PUBLIC(this)->renderingTimeMaxPerNodeType.setNum(keyCount);
  SbTime * renderingTimeMaxPerNodeTypeArr = PUBLIC(this)->renderingTimeMaxPerNodeType.startEditing();

  PUBLIC(this)->renderedNodeTypeCount.setNum(keyCount);
  uint32_t * nodeTypeCountArr = PUBLIC(this)->renderedNodeTypeCount.startEditing();

  int index = 0;
#if BY_TYPE
  std::map<int16_t, TypeTimings>::iterator it, end;
  for (it = this->type_timings.begin(), end = this->type_timings.end();
       it != end; ++it, ++index) {
    typeNameArr[index] = SoType::fromKey(it->first).getName();
#else
  std::map<const char *, TypeTimings>::iterator it, end;
  for (it = this->name_timings.begin(), end = this->name_timings.end();
       it != end; ++it, ++index) {
    typeNameArr[index] = SbName(it->first);
#endif
    renderingTimePerNodeTypeArr[index] = it->second.total;
    renderingTimeMaxPerNodeTypeArr[index] = it->second.max;
    nodeTypeCountArr[index] = it->second.count;
  }

  PUBLIC(this)->renderedNodeType.finishEditing();
  PUBLIC(this)->renderingTimePerNodeType.finishEditing();
  PUBLIC(this)->renderingTimeMaxPerNodeType.finishEditing();
  PUBLIC(this)->renderedNodeTypeCount.finishEditing();
} // updateNodeTypeTimingFields

void
SoProfilerStatsP::updateActionTimingFields(SoProfilerElement * COIN_UNUSED_ARG(e))
{
  SbList<int16_t> actions;
  this->action_timings.makeKeyList(actions);
  int actionCount = actions.getLength();

  PUBLIC(this)->profiledAction.setNum(actionCount);
  SbName * profiledActionArr = PUBLIC(this)->profiledAction.startEditing();

  PUBLIC(this)->profiledActionTime.setNum(actionCount);
  SbTime * profiledActionTimeArr = PUBLIC(this)->profiledActionTime.startEditing();

  for (int i = 0; i < actionCount; ++i) {
    int16_t type = actions[i];
    profiledActionArr[i] = SoType::fromKey(type).getName();

    SbTime time = SbTime::zero();
    this->action_timings.get(type, time);
    profiledActionTimeArr[i] = time;
  }

  PUBLIC(this)->profiledAction.finishEditing();
  PUBLIC(this)->profiledActionTime.finishEditing();
} // updateActionTimingFields

#undef PUBLIC

#define PRIVATE(obj) ((obj)->pimpl)

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

SO_NODE_SOURCE(SoProfilerStats);

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

// Doc from superclass.
void
SoProfilerStats::initClass(void)
{
  SO_NODE_INTERNAL_INIT_CLASS(SoProfilerStats, SO_FROM_COIN_3_0);

  SO_ENABLE(SoGLRenderAction, SoProfilerElement);
  SO_ENABLE(SoHandleEventAction, SoProfilerElement);
}

/*!
  Constructor
 */
SoProfilerStats::SoProfilerStats(void)
{
  PRIVATE(this)->master = this;

  SO_NODE_INTERNAL_CONSTRUCTOR(SoProfilerStats);

  SO_NODE_ADD_FIELD(renderedNodeType, (""));
  SO_NODE_ADD_FIELD(renderingTimePerNodeType, (0.0f));
  SO_NODE_ADD_FIELD(renderingTimeMaxPerNodeType, (0.0f));
  SO_NODE_ADD_FIELD(renderedNodeTypeCount, (0));
  SO_NODE_ADD_FIELD(profiledAction, (""));
  SO_NODE_ADD_FIELD(profiledActionTime, (0.0f));
  SO_NODE_ADD_FIELD(profilingUpdate, ());

  this->renderedNodeType.setNum(0);
  this->renderedNodeType.setDefault(TRUE);
  this->renderingTimePerNodeType.setNum(0);
  this->renderingTimePerNodeType.setDefault(TRUE);
  this->renderingTimeMaxPerNodeType.setNum(0);
  this->renderingTimeMaxPerNodeType.setDefault(TRUE);
  this->renderedNodeTypeCount.setNum(0);
  this->renderedNodeTypeCount.setDefault(TRUE);
  this->profiledAction.setNum(0);
  this->profiledAction.setDefault(TRUE);
  this->profiledActionTime.setNum(0);
  this->profiledActionTime.setDefault(TRUE);

}

/*!
  Destructor
 */
SoProfilerStats::~SoProfilerStats()
{
}

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

// Doc from superclass.
void
SoProfilerStats::GLRender(SoGLRenderAction * action)
{
  PRIVATE(this)->doAction(action);
}

// Doc from superclass.
void
SoProfilerStats::handleEvent(SoHandleEventAction * action)
{
  PRIVATE(this)->doAction(action);
}

// Doc from superclass.
void
SoProfilerStats::rayPick(SoRayPickAction * action)
{
  PRIVATE(this)->doAction(action);
}

// Doc from superclass.
void
SoProfilerStats::getBoundingBox(SoGetBoundingBoxAction * action)
{
  PRIVATE(this)->doAction(action);
}

// Doc from superclass.
void
SoProfilerStats::audioRender(SoAudioRenderAction * action)
{
  PRIVATE(this)->doAction(action);
}

// Doc from superclass.
void
SoProfilerStats::callback(SoCallbackAction * action)
{
  PRIVATE(this)->doAction(action);
}

// Doc from superclass.
void
SoProfilerStats::getMatrix(SoGetMatrixAction * action)
{
  PRIVATE(this)->doAction(action);
}

// Doc from superclass.
void
SoProfilerStats::pick(SoPickAction * action)
{
  PRIVATE(this)->doAction(action);
}

// Doc from superclass.
void
SoProfilerStats::search(SoSearchAction * action)
{
  PRIVATE(this)->doAction(action);
}

// Doc from superclass.
void
SoProfilerStats::write(SoWriteAction * action)
{
  PRIVATE(this)->doAction(action);
}

// Doc from superclass.
void
SoProfilerStats::getPrimitiveCount(SoGetPrimitiveCountAction * action)
{
  PRIVATE(this)->doAction(action);
}

// Doc from superclass.
void
SoProfilerStats::notify(SoNotList * COIN_UNUSED_ARG(l))
{
  // we disable notifications from this node, to avoid constant
  // redraws of the scene graph.
  //
  // and it doesn't expose any state relevant for any other nodes that
  // do "real work" in the scenegraph anyway, so this is the correct
  // thing to do.
}

const SbProfilingData &
SoProfilerStats::getProfilingData(SoType actiontype) const
{
  std::map<int16_t, SbProfilingData *>::const_iterator it =
    PRIVATE(this)->action_map.find(actiontype.getKey());
  if (it != PRIVATE(this)->action_map.end()) {
    return (*((*it).second));
  }

  static SbProfilingData nodata;
  return nodata;
}

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

#undef PRIVATE
#undef BY_TYPE


text:
package net.bytebuddy.implementation.bytecode.assign.primitive;

import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.test.utility.ObjectPropertyAssertion;
import org.junit.Test;

public class PrimitiveUnboxingDelegateOtherTest {

    @Test(expected = IllegalArgumentException.class)
    public void testIllegalSourceTypeThrowsException() throws Exception {
        PrimitiveUnboxingDelegate.forReferenceType(new TypeDescription.Generic.OfNonGenericType.ForLoadedType(int.class));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testVoidIllegal() throws Exception {
        PrimitiveUnboxingDelegate.forPrimitive(TypeDescription.Generic.VOID);
    }

    @Test
    public void testObjectProperties() throws Exception {
        ObjectPropertyAssertion.of(PrimitiveUnboxingDelegate.class).apply();
        ObjectPropertyAssertion.of(PrimitiveUnboxingDelegate.ImplicitlyTypedUnboxingResponsible.class).apply();
        ObjectPropertyAssertion.of(PrimitiveUnboxingDelegate.ExplicitlyTypedUnboxingResponsible.class).apply();
    }
}


text:
from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5 import QtWidgets

import constants

class ControlLayout(QtWidgets.QBoxLayout):
    """
    Layout class containing user controls.
    """

    WIDTH = 200

    def __init__(self):
        super().__init__(self.TopToBottom)

        label = QtWidgets.QLabel()
        label.setText('Select picture type')

        self.type_dropdown = QtWidgets.QComboBox()
        self.type_dropdown.addItem(None)
        self.type_dropdown.addItems(constants.IMAGE_TYPES)

        self.solar_button = QtWidgets.QPushButton('Set solar perimeter')
        self.lunar_button = QtWidgets.QPushButton('Set lunar perimeter')

        self.save_button = QtWidgets.QPushButton('Save')
        self.save_button.setEnabled(False)

        self.reset_button = QtWidgets.QPushButton('Reset')

        self.skip_button = QtWidgets.QPushButton('Skip this image')

        widgets = [label, self.type_dropdown, self.solar_button,
                   self.lunar_button, self.save_button, self.reset_button,
                   self.skip_button]

        fixed = QtWidgets.QSizePolicy.Fixed
        for w in widgets:
            w.setSizePolicy(QtWidgets.QSizePolicy(fixed, fixed))
            w.setMinimumWidth(self.WIDTH)
            self.addWidget(w)

    def reset(self):
        """
        Reset controls to their original state.
        """
        self.type_dropdown.setCurrentIndex(0)
        self.solar_button.setEnabled(True)
        self.lunar_button.setEnabled(True)
        self.save_button.setEnabled(False)

    def width(self):
        return self.WIDTH

class ImageLabel(QtWidgets.QLabel):
    """
    QLabel subclass that will display images. Adds event handling for mouse
    clicks.
    """

    def __init__(self, parent_layout, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.parent_layout = parent_layout

    def mousePressEvent(self, event):
        pos = event.pos().x(), event.pos().y()
        self.parent_layout.mouse_pressed.emit(pos)

class ImageLayout(QtWidgets.QBoxLayout):
    """
    Layout class responsible for displaying images.
    """

    # We make this signal part of ImageLayout, instead of part of the
    # ImageLabel instance, because the ImageLayout instace lives for the
    # life of the application, where the ImageLabel instances do not
    # Signal should be emitted with a tuple of two ints
    mouse_pressed = QtCore.pyqtSignal(tuple, name='mouse_pressed')

    def __init__(self):
        super().__init__(self.TopToBottom)
        self.widget = None

    def show_image(self, image):
        """
        Sets current image to image, where image is a numpy array - OpenCV's
        image format.
        """
        if self.widget is not None:
            # Effectively removes the widget from the layout
            self.widget.setParent(None)

        height, width, channel = image.shape
        bytes_per_line = width * channel

        if channel == 1:
            fmt = QtGui.QImage.Format_Mono
        elif channel == 3:
            # Unfortunatly, this results in blues and reds being swapped
            # as OpenCV uses BGR, not RGB and this is not supported by Qt.
            # We could do a conversion, but this would be slow and it is not
            # worth it
            fmt = QtGui.QImage.Format_RGB888
        else:
            raise ValueError('Invalid number of channels')

        qimage = QtGui.QImage(image.data, width, height, bytes_per_line, fmt)

        self.widget = QtWidgets.QWidget()
        pixmap = QtGui.QPixmap(qimage)
        label = ImageLabel(self, self.widget)
        label.setPixmap(pixmap)

        self.addWidget(self.widget)
        self.widget.setFixedSize(qimage.width(), qimage.height())
        self.widget.show()

    def height(self):
        return self.spacing() + self._get_widget_dim(width=False)

    def width(self):
        return self.spacing() + self._get_widget_dim(width=True)

    def _get_widget_dim(self, width):
        """
        Returns dimension of layout's main widget. Simply calling
        self.widget.[width|height]() is not effective here.
        """
        item = self.itemAt(0)
        if item is None:
            return 0
        if width:
            return item.widget().width()
        return item.widget().height()

class MainWindow(QtWidgets.QMainWindow):
    """
    Main application window.
    """

    def __init__(self):
        super().__init__()
        self.ctrl_layout = None
        self.image_layout = None
        self._create_main_layout()

    def _create_main_layout(self):
        """
        Constructs main window layout.
        """
        self.ctrl_layout = ControlLayout()
        self.image_layout = ImageLayout()

        layout = QtWidgets.QBoxLayout(QtWidgets.QBoxLayout.LeftToRight)
        layout.addLayout(self.ctrl_layout)
        layout.addLayout(self.image_layout)

        widget = QtWidgets.QWidget()
        widget.setLayout(layout)

        self.setCentralWidget(widget)
        self._resize()

    def _resize(self):
        """
        Resizes main window to fit image and control layouts.
        """
        self.resize(self.ctrl_layout.width() + self.image_layout.width(),
                    self.image_layout.height())


text:
declare const global: any;
declare const Symbol: any;

import * as Rx from '../../dist/cjs/Rx';
import {ObservableInput} from '../../dist/cjs/Observable';
import {root} from '../../dist/cjs/util/root';
import {$$iterator} from '../../dist/cjs/symbol/iterator';
import $$symbolObservable from 'symbol-observable';

export function lowerCaseO<T>(...args): Rx.Observable<T> {
  const values = [].slice.apply(arguments);

  const o = {
    subscribe: function (observer) {
      values.forEach(function (v) {
        observer.next(v);
      });
      observer.complete();
    }
  };

  o[Symbol.observable] = function () {
    return this;
  };

  return <any>o;
};

export const createObservableInputs = <T>(value: T) => Rx.Observable.of<ObservableInput<T>>(
  Rx.Observable.of<T>(value),
  Rx.Observable.of<T>(value, Rx.Scheduler.async),
  [value],
  Promise.resolve(value),
  <any>({ [$$iterator]: () => {
      const iteratorResults = [
        {value, done: false},
        {done: true}
      ];
      return {
        next: () => {
          return iteratorResults.shift();
        }
      };
    }}),
  <any>({ [$$symbolObservable]: () => Rx.Observable.of(value) })
);

global.__root__ = root;


text:
import { ISmartenitConfig } from './smartenit-config.interface';
import { InjectionToken } from '@angular/core';

export let INITIAL_CONFIG = new InjectionToken<ISmartenitConfig>('app.config');


text:
package org.apache.metron.maas.util;

import org.apache.curator.framework.CuratorFramework;
import org.apache.metron.maas.config.MaaSConfig;
import org.apache.zookeeper.KeeperException;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;

public enum ConfigUtil {
  INSTANCE;
  private static ThreadLocal<ObjectMapper> _mapper = new ThreadLocal<ObjectMapper>() {

    @Override
    protected ObjectMapper initialValue() {
      return new ObjectMapper();
    }
  };
  public <T> T read(CuratorFramework client, String root, T def, Class<T> clazz) throws Exception {
    try {
      byte[] data = client.getData().forPath(root);
      return read(data, clazz);
    }
    catch(KeeperException.NoNodeException nne) {
      return def;
    }
  }
  public <T> T read(byte[] data, Class<T> clazz) throws Exception {
      return _mapper.get().readValue(data, clazz);
  }
  public byte[] toBytes(Object o) throws IOException {
    return _mapper.get().writeValueAsBytes(o);
  }
}


text:
package com.khoubyari.example.exception;

/**
 * For HTTP 404 errros
 */
public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException() {
        super();
    }

    public ResourceNotFoundException(String message, Throwable cause) {
        super(message, cause);
    }

    public ResourceNotFoundException(String message) {
        super(message);
    }

    public ResourceNotFoundException(Throwable cause) {
        super(cause);
    }

}


text:
package bookshop2.supplier;

import javax.jms.Message;
import javax.jms.MessageListener;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.aries.Assert;
import org.aries.common.AbstractEvent;
import org.aries.event.multicaster.EventMulticasterProxy;
import org.aries.jms.client.JmsClient;
import org.aries.tx.AbstractArquillianTest;
import org.aries.tx.AbstractJMSListenerArquillionTest;
import org.aries.tx.TransactionTestControl;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;

import bookshop2.Invoice;
import bookshop2.Shipment;
import bookshop2.ShipmentCompleteEvent;
import bookshop2.ShipmentCompleteMessage;
import bookshop2.ShipmentConfirmedEvent;
import bookshop2.ShipmentFailedMessage;
import bookshop2.ShipmentRequestMessage;
import bookshop2.ShipmentScheduledEvent;
import bookshop2.ShipmentScheduledMessage;
import bookshop2.shipper.ShipperTestEARBuilder;
import bookshop2.shipper.event.ShipperEventReceiverMBean;
import bookshop2.shipper.outgoing.shipmentComplete.ShipmentCompleteReply;
import bookshop2.shipper.outgoing.shipmentFailed.ShipmentFailedReply;
import bookshop2.shipper.outgoing.shipmentScheduled.ShipmentScheduledReply;
import bookshop2.supplier.client.shipBooks.ShipBooks;
import bookshop2.supplier.client.shipBooks.ShipBooksProxyForJMS;
import bookshop2.util.Bookshop2Fixture;

@RunAsClient
@RunWith(Arquillian.class)
public class ShipBooksJMSListenerCIT extends AbstractJMSListenerArquillionTest {

	private TransactionTestControl transactionTestControl;

	private EventMulticasterProxy eventMulticasterProxy;

	private JmsClient shipBooksClient;

	private JmsClient shipmentScheduledHandler;

	private JmsClient shipmentCompleteHandler;

	private JmsClient shipmentFailedHandler;

	private ShipmentRequestMessage shipmentRequestMessage;

	private ShipmentScheduledMessage shipmentScheduledMessage;

	private ShipmentCompleteMessage shipmentCompleteMessage;

	private ShipmentFailedMessage shipmentFailedMessage;

	private ShipmentScheduledEvent shipmentScheduledEvent;

	private ShipmentConfirmedEvent shipmentConfirmedEvent;

	private ShipmentCompleteEvent shipmentCompleteEvent;

	protected boolean shipmentScheduledReceived;

	protected boolean shipmentCompleteReceived;

	protected boolean shipmentFailedReceived;

	private Object shipmentFailedReason;

	@Override
	public String getServerName() {
		return "hornetQ01_local";
	}

	@Override
	public String getDomainId() {
		return "bookshop2.supplier";
	}

	@Override
	public String getServiceId() {
		return "bookshop2.supplier.shipBooks";
	}

	@Override
	public String getTargetArchive() {
		return SupplierTestEARBuilder.NAME;
	}

	@Override
	public String getTargetDestination() {
		return getJNDINameForQueue("inventory_bookshop2_supplier_ship_books_queue");
	}

	public String getLocalShipmentScheduledDestination() {
		return "test_message_domain_test_destination_queue_a";
	}

	public String getLocalShipmentCompleteDestination() {
		return "test_message_domain_test_destination_queue_b";
	}

	public String getLocalShipmentFailedDestination() {
		return "test_message_domain_test_destination_queue_c";
	}

	@Override
	public Class<?> getTestClass() {
		return ShipBooksJMSListenerCIT.class;
	}

	@BeforeClass
	public static void beforeClass() throws Exception {
		AbstractArquillianTest.beforeClass();
	}

	@AfterClass
	public static void afterClass() throws Exception {
		AbstractArquillianTest.afterClass();
	}

	@Before
	public void setUp() throws Exception {
		super.setUp();
		startServer();
		createTransactionControl();
		createEventMulticasterProxy();
		createShipmentRequestMessage();
	}

	protected void createTransactionControl() throws Exception {
		transactionTestControl = new TransactionTestControl();
		transactionTestControl.setupTransactionManager();
	}

	public EventMulticasterProxy createEventMulticasterProxy() throws Exception {
		eventMulticasterProxy = new EventMulticasterProxy();
		eventMulticasterProxy.setJmxManager(jmxManager);
		eventMulticasterProxy.setMBeanName(ShipperEventReceiverMBean.MBEAN_NAME);
		return eventMulticasterProxy;
	}

	@After
	public void tearDown() throws Exception {
		shipBooksClient.reset();
		shipBooksClient = null;
		shipmentScheduledHandler.reset();
		shipmentScheduledHandler = null;
		shipmentCompleteHandler.reset();
		shipmentCompleteHandler = null;
		shipmentFailedHandler.reset();
		shipmentFailedHandler = null;
		shipmentRequestMessage = null;
		shipmentScheduledMessage = null;
		shipmentCompleteMessage = null;
		shipmentFailedMessage = null;
		shipmentScheduledEvent = null;
		shipmentConfirmedEvent = null;
		shipmentCompleteEvent = null;
		shipmentScheduledReceived = false;
		shipmentCompleteReceived = false;
		shipmentFailedReceived = false;
		super.tearDown();
	}

//	@Deployment(name = "txManagerEAR", order = 1)
//	@TargetsContainer("hornetQ01_local")
//	public static EnterpriseArchive createTXManagerEAR() {
//		TXManagerTestEARBuilder builder = new TXManagerTestEARBuilder();
//		return builder.createEAR();
//	}

	@TargetsContainer("hornetQ01_local")
	@Deployment(name = "supplierEAR", order = 2)
	public static EnterpriseArchive createSupplierEAR() {
		SupplierTestEARBuilder builder = new SupplierTestEARBuilder();
		builder.setIncludeWar(true);
		return builder.createEAR();
	}

	@TargetsContainer("hornetQ01_local")
	@Deployment(name = "shipperEAR", order = 3)
	public static EnterpriseArchive createShipperEAR() {
		ShipperTestEARBuilder builder = new ShipperTestEARBuilder();
		builder.setIncludeWar(true);
		builder.setDeployJms(false);
		return builder.createEAR();
	}

	public void createShipmentRequestMessage() {
		createShipmentRequestMessage(false, false);
	}

	public void createShipmentRequestCancelMessage() {
		createShipmentRequestMessage(true, false);
	}

	public void createShipmentRequestUndoMessage() {
		createShipmentRequestMessage(false, true);
	}

	public void createShipmentRequestMessage(boolean cancel, boolean undo) {
		shipmentRequestMessage = Bookshop2Fixture.create_ShipmentRequestMessage(cancel, undo);
		shipmentRequestMessage.addToReplyToDestinations("ShipmentScheduled", getLocalShipmentScheduledDestination());
		shipmentRequestMessage.addToReplyToDestinations("ShipmentComplete", getLocalShipmentCompleteDestination());
		shipmentRequestMessage.addToReplyToDestinations("ShipmentFailed", getLocalShipmentFailedDestination());
		initializeMessage(shipmentRequestMessage);
	}

	public void createShipmentScheduledEvent() {
		shipmentScheduledEvent = Bookshop2Fixture.create_ShipmentScheduledEvent();
		initializeEvent(shipmentScheduledEvent);
	}

	public void createShipmentConfirmedEvent() {
		shipmentConfirmedEvent = Bookshop2Fixture.create_ShipmentConfirmedEvent();
		initializeEvent(shipmentConfirmedEvent);
	}

	public void createShipmentCompleteEvent() {
		shipmentCompleteEvent = Bookshop2Fixture.create_ShipmentCompleteEvent();
		initializeEvent(shipmentCompleteEvent);
	}

	@Test
	@InSequence(value = 1)
	public void testShipBooks_ShipmentScheduled() throws Exception {
		String testName = "testShipBooks_ShipmentScheduled";
		log.info(testName+": started");
		registerNotificationListeners();
		createShipmentScheduledEvent();
		expectedMessage = "bookshop2.supplier.ShipmentScheduled";
		expectedEvent = "bookshop2.supplier.ShipmentScheduled_Response_Sent";
		//execution started
		runTest_shipBooks();
		//execution finished
		Assert.isTrue(shipmentScheduledReceived);
		Assert.isFalse(shipmentCompleteReceived);
		Assert.isFalse(shipmentFailedReceived);
		Assert.isFalse(isFiredRequestDone("ShipBooks"));
		Assert.isTrue(isFiredResponseSent("ShipmentScheduled"));
		Assert.isFalse(isFiredResponseSent("ShipmentComplete"));
		Assert.isFalse(isFiredResponseSent("ShipmentFailed"));
		log.info(testName+": done");
		if (errorMessage != null)
			fail(errorMessage);
	}

	@Test
	@InSequence(value = 2)
	public void testShipBooks_ShipmentComplete() throws Exception {
		String testName = "testShipBooks_ShipmentComplete";
		log.info(testName+": started");
		registerNotificationListeners();
		createShipmentConfirmedEvent();
		expectedMessage = "bookshop2.supplier.ShipmentComplete";
		expectedEvent = "bookshop2.supplier.ShipBooks_Request_Done";
		//execution started
		runTest_shipBooks();
		//execution finished
		Assert.isFalse(shipmentScheduledReceived);
		Assert.isTrue(shipmentCompleteReceived);
		Assert.isFalse(shipmentFailedReceived);
		Assert.isTrue(isFiredRequestDone("ShipBooks"));
		Assert.isFalse(isFiredResponseSent("ShipmentScheduled"));
		Assert.isTrue(isFiredResponseSent("ShipmentComplete"));
		Assert.isFalse(isFiredResponseSent("ShipmentFailed"));
		log.info(testName+": done");
		if (errorMessage != null)
			fail(errorMessage);
	}

	@Test
	@InSequence(value = 3)
	public void testShipBooks_Success() throws Exception {
		String testName = "testShipBooks_Success";
		log.info(testName+": started");
		registerNotificationListeners();
		createShipmentScheduledEvent();
		createShipmentConfirmedEvent();
		expectedMessage = "bookshop2.supplier.ShipmentComplete";
		expectedEvent = "bookshop2.supplier.ShipBooks_Request_Done";
		//execution started
		runTest_shipBooks();
		//execution finished
		Assert.isTrue(shipmentScheduledReceived);
		Assert.isTrue(shipmentCompleteReceived);
		Assert.isFalse(shipmentFailedReceived);
		Assert.isTrue(isFiredRequestDone("ShipBooks"));
		Assert.isTrue(isFiredResponseSent("ShipmentScheduled"));
		Assert.isTrue(isFiredResponseSent("ShipmentComplete"));
		Assert.isFalse(isFiredResponseSent("ShipmentFailed"));
		log.info(testName+": done");
		if (errorMessage != null)
			fail(errorMessage);
	}

	public void runTest_shipBooks() throws Exception {
		// prepare the environment
		removeMessagesFromDestinations();

		// prepare context
		//beginTransaction();

		// prepare mocks
		registerForResult();

		// prepare endpoints
		shipBooksClient = startShipBooksClient();
		shipmentScheduledHandler = startShipmentScheduledHandler();
		shipmentCompleteHandler = startShipmentCompleteHandler();
		shipmentFailedHandler = startShipmentFailedHandler();
		sendRequest_ShipBooks();

		if (eventsExist())
			fireEvents();

		// wait for result
		Object result = waitForCompletion();
		validateResult(result);

		// close context
		//commitTransaction();

		// validate the environment
		assertEmptyTargetDestination();
		removeMessagesFromDestinations();
	}

	protected void sendRequest_ShipBooks() throws Exception {
		shipBooksClient.send(shipmentRequestMessage, correlationId, null);
	}

	protected void sendRequest_ShipBooks_Cancel() throws Exception {
		createShipmentRequestCancelMessage();
		sendRequest_ShipBooks();
	}

	protected void sendRequest_ShipBooks_Undo() throws Exception {
		createShipmentRequestUndoMessage();
		sendRequest_ShipBooks();
	}

	protected boolean eventsExist() {
		return shipmentScheduledEvent != null ||
			shipmentConfirmedEvent != null ||
			shipmentCompleteEvent != null;
	}

	protected void fireEvents() throws Exception {
		Thread.sleep(2000);
		if (shipmentScheduledEvent != null)
			fireEvent(shipmentScheduledEvent);
		if (shipmentConfirmedEvent != null)
			fireEvent(shipmentConfirmedEvent);
		if (shipmentCompleteEvent != null)
			fireEvent(shipmentCompleteEvent);
	}

	protected void fireEvent(AbstractEvent event) throws Exception {
		eventMulticasterProxy.dispatchEvent(event);
	}

	protected void registerNotificationListeners() throws Exception {
		addRequestNotificationListeners("ShipBooks");
		addResponseNotificationListeners("ShipmentScheduled");
		addResponseNotificationListeners("ShipmentComplete");
		addResponseNotificationListeners("ShipmentFailed");
		addProcessNotificationListeners("ShipmentScheduled");
		addProcessNotificationListeners("ShipmentConfirmed");
	}

	protected void removeMessagesFromDestinations() throws Exception {
		removeMessagesFromQueue(getTargetArchive(), getTargetDestination());
		removeMessagesFromQueue(getTargetArchive(), getLocalShipmentCompleteDestination());
		removeMessagesFromQueue(getTargetArchive(), getLocalShipmentScheduledDestination());
		removeMessagesFromQueue(getTargetArchive(), getLocalShipmentFailedDestination());
	}

	protected JmsClient startShipBooksClient() throws Exception {
		JmsClient client = new ShipBooksProxyForJMS(ShipBooks.ID);
		configureClient(client, getTargetDestination());
		client.setCreateTemporaryQueue(true);
		client.initialize();
		return client;
	}

	protected JmsClient startShipmentScheduledHandler() throws Exception {
		JmsClient client = createClient(getJNDINameForQueue(getLocalShipmentScheduledDestination()));
		client.setMessageListener(createShipmentScheduledResponseListener());
		client.initialize();
		return client;
	}

	protected JmsClient startShipmentCompleteHandler() throws Exception {
		JmsClient client = createClient(getJNDINameForQueue(getLocalShipmentCompleteDestination()));
		client.setMessageListener(createShipmentCompleteResponseListener());
		client.initialize();
		return client;
	}

	protected JmsClient startShipmentFailedHandler() throws Exception {
		JmsClient client = createClient(getJNDINameForQueue(getLocalShipmentFailedDestination()));
		client.setMessageListener(createShipmentFailedResponseListener());
		client.initialize();
		return client;
	}

//	protected MessageListener createResponseListener() {
//		return new MessageListener() {
//			public void onMessage(Message message) {
//				try {
//					Object object = getObjectFromMessage(message);
//					Assert.notNull(object, "Payload not found");
//					validateResult(object);
//				} catch (Throwable e) {
//					errorMessage = ExceptionUtils.getRootCauseMessage(e);
//				}
//			}
//		};
//	}

	protected MessageListener createShipmentScheduledResponseListener() {
		return new MessageListener() {
			public void onMessage(Message message) {
				try {
					log.info("#### [test]: ShipmentScheduled received");
					Object object = getObjectFromMessage(message);
					Assert.notNull(object, "Payload not found");
					Assert.isTrue(object instanceof ShipmentScheduledMessage, "Payload type not correct");
					shipmentScheduledMessage = (ShipmentScheduledMessage) object;
					validate(shipmentScheduledMessage);
				} catch (Throwable e) {
					errorMessage = ExceptionUtils.getRootCauseMessage(e);
				} finally {
					if (expectedMessage != null && expectedMessage.equalsIgnoreCase("bookshop2.supplier.ShipmentScheduled"))
						expectedMessageResult.set(true);
					shipmentScheduledReceived = true;
				}
			}
		};
	}

	protected MessageListener createShipmentCompleteResponseListener() {
		return new MessageListener() {
			public void onMessage(Message message) {
				try {
					log.info("#### [test]: ShipmentComplete received");
					Object object = getObjectFromMessage(message);
					Assert.notNull(object, "Payload not found");
					Assert.isTrue(object instanceof ShipmentCompleteMessage, "Payload type not correct");
					shipmentCompleteMessage = (ShipmentCompleteMessage) object;
					validate(shipmentCompleteMessage);
				} catch (Throwable e) {
					errorMessage = ExceptionUtils.getRootCauseMessage(e);
				} finally {
					if (expectedMessage != null && expectedMessage.equalsIgnoreCase("bookshop2.supplier.ShipmentComplete"))
						expectedMessageResult.set(true);
					shipmentCompleteReceived = true;
				}
			}
		};
	}

	protected MessageListener createShipmentFailedResponseListener() {
		return new MessageListener() {
			public void onMessage(Message message) {
				try {
					log.info("#### [test]: ShipmentFailed received");
					Object object = getObjectFromMessage(message);
					Assert.notNull(object, "Payload not found");
					Assert.isTrue(object instanceof ShipmentFailedMessage, "Payload type not correct");
					shipmentFailedMessage = (ShipmentFailedMessage) object;
					validate(shipmentFailedMessage);
				} catch (Throwable e) {
					errorMessage = ExceptionUtils.getRootCauseMessage(e);
				} finally {
					if (expectedMessage != null && expectedMessage.equalsIgnoreCase("bookshop2.supplier.ShipmentFailed"))
						expectedMessageResult.set(true);
					shipmentFailedReceived = true;
				}
			}
		};
	}

	protected void validateResult(Object result) {
		if (result instanceof ShipmentScheduledMessage) {
			validate((ShipmentScheduledMessage) result);
		} else if (result instanceof ShipmentCompleteMessage) {
			validate((ShipmentCompleteMessage) result);
		} else if (result instanceof ShipmentFailedMessage) {
			validate((ShipmentFailedMessage) result);
		} else if (result instanceof String) {
			String resultString = result.toString();
			if ((expectedError != null && !expectedError.equalsIgnoreCase(resultString)) &&
				(expectedEvent != null && !expectedEvent.equalsIgnoreCase(resultString)))
					errorMessage = "Unexpected message: "+result;
		} else {
			errorMessage = "Unrecognized result: "+result;
		}
	}

	protected void validate(ShipmentScheduledMessage shipmentScheduledMessage) {
		Assert.notNull(shipmentScheduledMessage, "Message must be specified");
		Shipment expectedShipment = shipmentRequestMessage.getShipment();
		Shipment actualShipment = shipmentScheduledMessage.getShipment();
		Bookshop2Fixture.assertShipmentCorrect(actualShipment);
		Bookshop2Fixture.assertSameShipment(expectedShipment, actualShipment);
	}

	protected void validate(ShipmentCompleteMessage shipmentCompleteMessage) {
		Assert.notNull(shipmentCompleteMessage, "Message must be specified");
		Shipment expectedShipment = shipmentRequestMessage.getShipment();
		//TODO Invoice expectedInvoice = shipmentRequestMessage.getInvoice();
		Shipment actualShipment = shipmentCompleteMessage.getShipment();
		Invoice actualInvoice = shipmentCompleteMessage.getInvoice();
		Bookshop2Fixture.assertShipmentCorrect(actualShipment);
		Bookshop2Fixture.assertInvoiceCorrect(actualInvoice);
		Bookshop2Fixture.assertSameShipment(expectedShipment, actualShipment);
		//TODO Bookshop2Fixture.assertInvoiceEquals(expectedInvoice, actualInvoice);
	}

	protected void validate(ShipmentFailedMessage shipmentFailedMessage) {
		Assert.notNull(shipmentFailedMessage, "Message must be specified");
		Bookshop2Fixture.assertShipmentCorrect(shipmentFailedMessage.getShipment());
		Assert.equals(shipmentFailedMessage.getReason(), shipmentFailedReason);
	}

}


text:
#region Using directives

using System;

#endregion

namespace Nettiers.AdventureWorks.Entities
{
	///
	/// Individual products associated with a specific purchase order. See PurchaseOrderHeader.
	///
	/// <remarks>
	/// This file is generated once and will never be overwritten.
	/// </remarks>
	[Serializable]
	[CLSCompliant(true)]
	public partial class PurchaseOrderDetail : PurchaseOrderDetailBase
	{
		#region Constructors

		///
		/// Creates a new <see cref="PurchaseOrderDetail"/> instance.
		///
		public PurchaseOrderDetail():base(){}

		#endregion
	}
}


text:
Basic example of MauxIotConnector usage with some Postman collections.

You will find a complete description of it in the Tutorial section of www.mauxilium.it site.


text:
//
//  ExploreContainerViewController.h
//  Explore Prototype
//
//  Created by Alex Shepard on 9/12/14.
//  Copyright (c) 2014 iNaturalist. All rights reserved.
//

#import <UIKit/UIKit.h>

/**
 An object that adopts the ExploreViewControllerControlIcon protocol
 is responsible for providing a UIImage icon. A container view controller
 will present some control (ie a segmented control) for switching between
 child view controllers. Each child presents a different control icon,
 allowing the user to choose which child to view.

 @see ExploreContainerViewController
 */
@protocol ExploreViewControllerControlIcon <NSObject>
@property (readonly) UIImage *controlIcon;
@end

/**
 The ExploreContainerViewController class presents a container view
 controller that can be filled with child view controllers. It also
 presents a UISegmentedControl that allows the user to pick between
 the children. Children implement the ExploreViewControllerControlIcon
 protocol to provide icons/images for the UISegmentedControl.

 @see ExploreViewControllerControlIcon
 */
@interface ExploreContainerViewController : UIViewController

/**
 The segmented control that is presented in the Navigation bar of
 this container UIViewController. Manipulating the segmented control
 allows the user to display the different child view controllers.
 */
@property UISegmentedControl *segmentedControl;

/**
 The children of this container view controller.
 */
@property NSArray *viewControllers;

/**
 The currently selected view controller of this container.
 */
@property UIViewController *selectedViewController;

/**
 Subclasses can implement an overlay view to provide a view that
 is always above child of this container, regardless of which child
 is active.
 */
@property UIView *overlayView;

/**
 Callback when the user changes the segmented control. Switch this container
 to show a new child view controller.
 */
- (void)segmentedControlChanged:(UISegmentedControl *)control;

/**
 Show a child view controller.
 */
- (void)displayContentController:(UIViewController*)content;

/**
 Hide a child view controller.
 */
- (void)hideContentController:(UIViewController*)content;

/**
 Frame for a child view controller.
 */
- (CGRect)frameForContentController;

@end


text:
import { EventEmitter } from '@angular/core';
import { Hours } from './../../../users/hours.model';
import { NgForm } from '@angular/forms';
import { AppBodyComponent } from './../../app-body.component';
import { User } from './../../../users/user.model';
import { Component, OnInit, Input } from '@angular/core';
import * as firebase from 'firebase';
@Component({
  selector: 'app-work-table',
  templateUrl: './work-table.component.html',
  styleUrls: ['./work-table.component.css']
})
export class WorkTableComponent implements OnInit {
  private hoursChanged = new EventEmitter<Hours[]>();
  private types = [1,2,3];
 private edit: {
    date: String,
    day: string,
    employer: String,
    startHour: String,
    endHour: String,
    totalHours: String,
    key: string
  };

days = [];

  constructor(private appBody: AppBodyComponent) { }

  ngOnInit() {
    this.days = this.appBody.user.hours;
    this.days.sort((a, b)=>{
    if(a.date < b.date) return -1;
    if(a.date > b.date) return 1;
    return 0;
})
  this.hoursChanged.subscribe(
    (hour: Hours[]) => {
      this.days = this.days.sort((a, b)=>{
    if(a.date < b.date) return -1;
    if(a.date > b.date) return 1;
    return 0;
})
    }
  )

  }

  onEdit(day: any) {
    this.edit = day;
  }

  onDelete(day: any){
    var warning = confirm("אתה בטוח?");
    if(warning){
    firebase.database().ref('users/' + String(this.appBody.user.key) + '/hours/' + String(day.key)).remove();
    this.days[this.days.indexOf(day)]
    this.days.splice(this.days.indexOf(day), 1);}
  }

  onSubmit(form: NgForm) {
    let dateLen = form.value.date.length;
    let newDate =form.value.date;

    if(String(form.value.date[2])!=='/') {
      newDate = form.value.date.slice(dateLen-2, dateLen) + '/'
                  + form.value.date.slice(dateLen-5, dateLen-3) + '/'
                  + form.value.date.slice(0, dateLen-6);
    }

    this.edit.date = newDate;
    this.edit.day = form.value.day;
    this.edit.employer = form.value.employer;
    this.edit.endHour = form.value.endHour;
    this.edit.startHour = form.value.startHour;
    this.edit.totalHours = form.value.totalHours;
    firebase.database().ref('users/' + String(this.appBody.user.key) + '/hours/' + String(this.edit.key) + '/date').set(newDate);
    firebase.database().ref('users/' + String(this.appBody.user.key) + '/hours/' + String(this.edit.key) + '/day').set(form.value.day);
    firebase.database().ref('users/' + String(this.appBody.user.key) + '/hours/' + String(this.edit.key) + '/employer').set(form.value.employer);
    firebase.database().ref('users/' + String(this.appBody.user.key) + '/hours/' + String(this.edit.key) + '/endHour').set(form.value.endHour);
    firebase.database().ref('users/' + String(this.appBody.user.key) + '/hours/' + String(this.edit.key) + '/startHour').set(form.value.startHour);
    firebase.database().ref('users/' + String(this.appBody.user.key) + '/hours/' + String(this.edit.key) + '/totalHours').set(form.value.totalHours);
    this.edit = null;
  }

}


text:
#include "stdafx.h"
#pragma warning(disable:4251)

#include "SResProviderZip.h"
#include <pugixml/pugixml.hpp>

extern HICON CURSORICON_LoadFromBuf(const BYTE * bits,DWORD filesize,INT width, INT height,BOOL fCursor, UINT loadflags);
extern HICON CURSORICON_LoadFromFile( LPCWSTR filename,
                              INT width, INT height,
                              BOOL fCursor, UINT loadflags);

namespace SOUI{

    SResProviderZip::SResProviderZip():m_renderFactory(NULL)
	{
	}

	SResProviderZip::~SResProviderZip(void)
	{
	}

	HBITMAP SResProviderZip::LoadBitmap(LPCTSTR pszResName )
	{
		SStringT strPath=_GetFilePath(pszResName,_T("BITMAP"));
		if(strPath.IsEmpty()) return NULL;
		CZipFile zf;
		if(!m_zipFile.GetFile(strPath,zf)) return NULL;

		HDC hDC = GetDC(NULL);
		//¶Áȡλͼͷ
		BITMAPFILEHEADER *pBmpFileHeader=(BITMAPFILEHEADER *)zf.GetData();
		//¼ì²âλͼͷ
		if (pBmpFileHeader->bfType != ((WORD) ('M'<<8)|'B'))
		{
			return NULL;
		}
		//ÅжÏλͼ³¤¶È
		if (pBmpFileHeader->bfSize > (UINT)zf.GetSize())
		{
			return NULL;
		}
		LPBITMAPINFO lpBitmap=(LPBITMAPINFO)(pBmpFileHeader+1);
		LPVOID lpBits=(LPBYTE)zf.GetData()+pBmpFileHeader->bfOffBits;
		HBITMAP hBitmap= CreateDIBitmap(hDC,&lpBitmap->bmiHeader,CBM_INIT,lpBits,lpBitmap,DIB_RGB_COLORS);
		ReleaseDC(NULL,hDC);

		return hBitmap;
	}

	HICON SResProviderZip::LoadIcon(LPCTSTR pszResName ,int cx/*=0*/,int cy/*=0*/)
	{
		SStringT strPath=_GetFilePath(pszResName,_T("ICON"));
		if(strPath.IsEmpty()) return NULL;
		CZipFile zf;
		if(!m_zipFile.GetFile(strPath,zf)) return NULL;

        return CURSORICON_LoadFromBuf(zf.GetData(),zf.GetSize(),cx,cy,FALSE,LR_DEFAULTSIZE|LR_DEFAULTCOLOR);
	}

    HCURSOR SResProviderZip::LoadCursor( LPCTSTR pszResName )
    {
        SStringT strPath=_GetFilePath(pszResName,_T("CURSOR"));
        if(strPath.IsEmpty()) return NULL;
        CZipFile zf;
        if(!m_zipFile.GetFile(strPath,zf)) return NULL;
        return (HCURSOR)CURSORICON_LoadFromBuf(zf.GetData(),zf.GetSize(),0,0,TRUE,LR_DEFAULTSIZE|LR_DEFAULTCOLOR);
    }

	IBitmap * SResProviderZip::LoadImage( LPCTSTR strType,LPCTSTR pszResName)
	{
		SStringT strPath=_GetFilePath(pszResName,strType);
		if(strPath.IsEmpty()) return NULL;
		CZipFile zf;
		if(!m_zipFile.GetFile(strPath,zf)) return NULL;
        IBitmap * pBmp=NULL;
        m_renderFactory->CreateBitmap(&pBmp);
        if(!pBmp) return NULL;
        pBmp->LoadFromMemory(zf.GetData(),zf.GetSize());
        return pBmp;
	}

    IImgX   * SResProviderZip::LoadImgX( LPCTSTR strType,LPCTSTR pszResName )
    {
        SStringT strPath=_GetFilePath(pszResName,strType);
        if(strPath.IsEmpty()) return NULL;
        CZipFile zf;
        if(!m_zipFile.GetFile(strPath,zf)) return NULL;

        IImgX *pImgX=NULL;
        m_renderFactory->GetImgDecoderFactory()->CreateImgX(&pImgX);
        if(!pImgX) return NULL;

        if(0==pImgX->LoadFromMemory(zf.GetData(),zf.GetSize()))
        {
            pImgX->Release();
            pImgX=NULL;
        }
        return pImgX;
    }

	BOOL SResProviderZip::_Init( LPCTSTR pszZipFile ,LPCSTR pszPsw)
	{
		if(!m_zipFile.Open(pszZipFile)) return FALSE;
        m_zipFile.SetPassword(pszPsw);
		return _LoadSkin();
	}

	BOOL SResProviderZip::_Init( HINSTANCE hInst,LPCTSTR pszResName,LPCTSTR pszType  ,LPCSTR pszPsw)
	{
		if(!m_zipFile.Open(hInst,pszResName,pszType)) return FALSE;
        m_zipFile.SetPassword(pszPsw);
		return _LoadSkin();
	}

    BOOL SResProviderZip::Init( WPARAM wParam,LPARAM lParam )
    {
        ZIPRES_PARAM *zipParam=(ZIPRES_PARAM*)wParam;
        m_renderFactory = zipParam->pRenderFac;

        if(zipParam->type == ZIPRES_PARAM::ZIPFILE)
            return _Init(zipParam->pszZipFile,zipParam->pszPsw);
        else
            return _Init(zipParam->peInfo.hInst,zipParam->peInfo.pszResName,zipParam->peInfo.pszResType,zipParam->pszPsw);
    }

	SStringT SResProviderZip::_GetFilePath( LPCTSTR pszResName,LPCTSTR pszType )
	{
		SResID resID(pszType,pszResName);
		SMap<SResID,SStringT>::CPair *p = m_mapFiles.Lookup(resID);
		if(!p) return _T("");
		return p->m_value;
	}

	size_t SResProviderZip::GetRawBufferSize( LPCTSTR strType,LPCTSTR pszResName )
	{
		SStringT strPath=_GetFilePath(pszResName,strType);
		if(strPath.IsEmpty()) return FALSE;
		ZIP_FIND_DATA zfd;
		HANDLE hf=m_zipFile.FindFirstFile(strPath,&zfd);
		if(INVALID_HANDLE_VALUE==hf) return 0;
		m_zipFile.FindClose(hf);
		return zfd.nFileSizeUncompressed;
	}

	BOOL SResProviderZip::GetRawBuffer( LPCTSTR strType,LPCTSTR pszResName,LPVOID pBuf,size_t size )
	{
		SStringT strPath=_GetFilePath(pszResName,strType);
		if(strPath.IsEmpty()) return FALSE;
		CZipFile zf;
		if(!m_zipFile.GetFile(strPath,zf)) return NULL;
		if(size<zf.GetSize())
		{
			SetLastError(ERROR_INSUFFICIENT_BUFFER);
			return FALSE;
		}
		memcpy(pBuf,zf.GetData(),zf.GetSize());
		return TRUE;
	}

	BOOL SResProviderZip::HasResource( LPCTSTR strType,LPCTSTR pszResName )
	{
		SResID resID(strType,pszResName);
		SMap<SResID,SStringT>::CPair *p = m_mapFiles.Lookup(resID);
		return p!=NULL;
	}

	BOOL SResProviderZip::_LoadSkin()
	{
		CZipFile zf;
		BOOL bIdx=m_zipFile.GetFile(UIRES_INDEX,zf);
		if(!bIdx) return FALSE;

		pugi::xml_document xmlDoc;
		SStringA strFileName;
		if(!xmlDoc.load_buffer_inplace(zf.GetData(),zf.GetSize(),pugi::parse_default,pugi::encoding_utf8)) return FALSE;
		pugi::xml_node xmlElem=xmlDoc.child(L"resource");
        if(!xmlElem) return FALSE;
        pugi::xml_node resType=xmlElem.first_child();
		while(resType)
		{
            pugi::xml_node resFile=resType.first_child();
            while(resFile)
            {
                SResID id(S_CW2T(resType.name()),S_CW2T(resFile.attribute(L"name").value()));
                m_mapFiles[id] = S_CW2T(resFile.attribute(L"path").value());
                resFile=resFile.next_sibling();
            }
            resType = resType.next_sibling();
		}
		return TRUE;
	}

    namespace RESPROVIDER_ZIP
    {
        BOOL SCreateInstance( IObjRef ** ppObj )
        {
            *ppObj = new SResProviderZip;
            return TRUE;
        }
    }

}//namespace SOUI


text:
<?php

# Copyright 2015 Wayne D Grant (www.waynedgrant.com)
# Licensed under the MIT License

require_once('LayerMap.php');

abstract class ObservationMap extends LayerMap {

    protected function __construct($apiKey, $workingFolder) {
        parent::__construct($apiKey, $workingFolder);
    }

    protected function getCapabilitiesUrl() {
        return MessageFormatter::formatMessage('en_GB',
            'http://datapoint.metoffice.gov.uk/public/data/layer/wxobs/all/json/capabilities?key={0}',
            array($this->apiKey));
    }

    protected function readLatestTimestamp($mapCapabilities) {
        $layer = $this->findLayer($mapCapabilities, $this->getLayerName());

        return $layer->Service->Times->Time[0];
    }

    protected function readAvailableTimesteps($mapCapabilities) {
        $layer = $this->findLayer($mapCapabilities, $this->getLayerName());

        $timesteps = $layer->Service->Times->Time;

        rsort($timesteps, SORT_STRING);

        return $timesteps;
    }

    protected function generateMapImageUrl($timestep, $timestamp) {
        return MessageFormatter::formatMessage('en_GB',
            'http://datapoint.metoffice.gov.uk/public/data/layer/wxobs/{0}/png?TIME={1}Z&key={2}',
            array($this->getLayerName(), $timestep, $this->apiKey));
    }

    abstract protected function getLayerName();
}

?>