text:
/*
 * Do not modify this file. This file is generated from the ec2-2015-04-15.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;

using Amazon.EC2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.EC2.Model.Internal.MarshallTransformations
{
    /// <summary>
    /// Response Unmarshaller for Route Object
    /// </summary>
    public class RouteUnmarshaller : IUnmarshaller<Route, XmlUnmarshallerContext>, IUnmarshaller<Route, JsonUnmarshallerContext>
    {
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Route Unmarshall(XmlUnmarshallerContext context)
        {
            Route unmarshalledObject = new Route();
            int originalDepth = context.CurrentDepth;
            int targetDepth = originalDepth + 1;

            if (context.IsStartOfDocument)
               targetDepth += 2;

            while (context.ReadAtDepth(originalDepth))
            {
                if (context.IsStartElement || context.IsAttribute)
                {
                    if (context.TestExpression("destinationCidrBlock", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        unmarshalledObject.DestinationCidrBlock = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("destinationPrefixListId", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        unmarshalledObject.DestinationPrefixListId = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("gatewayId", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        unmarshalledObject.GatewayId = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("instanceId", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        unmarshalledObject.InstanceId = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("instanceOwnerId", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        unmarshalledObject.InstanceOwnerId = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("networkInterfaceId", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        unmarshalledObject.NetworkInterfaceId = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("origin", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        unmarshalledObject.Origin = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("state", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        unmarshalledObject.State = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("vpcPeeringConnectionId", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        unmarshalledObject.VpcPeeringConnectionId = unmarshaller.Unmarshall(context);
                        continue;
                    }
                }
                else if (context.IsEndElement && context.CurrentDepth < originalDepth)
                {
                    return unmarshalledObject;
                }
            }

            return unmarshalledObject;
        }

        /// <summary>
        /// Unmarshaller error response to exception.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Route Unmarshall(JsonUnmarshallerContext context)
        {
            return null;
        }

        private static RouteUnmarshaller _instance = new RouteUnmarshaller();

        /// <summary>
        /// Gets the singleton.
        /// </summary>
        public static RouteUnmarshaller Instance
        {
            get
            {
                return _instance;
            }
        }
    }
}


text:
import uuid, copy

from os import path, fsync, mkdir
from core.igraph_helper import *

from functools import reduce

try:
    import util.misc as misc
    from util.misc import indent_text
except ImportError:
    import util.misc3 as misc
    from util.misc3 import indent_text

import numpy.random as nprnd

from .himesis_utils import standardize_name, is_RAM_attribute, to_non_RAM_attribute

#cross-compatibility
try:
    import cPickle as pickle
except ImportError:
    import pickle as pickle

class HConstants:
    GUID = 'GUID__'
    META_MODEL = 'mm__'
    MT_LABEL = 'MT_label__'
    MT_CONSTRAINT = 'MT_constraint__'
    MT_ACTION = 'MT_action__'
    MT_SUBTYPE_MATCH = 'MT_subtypeMatching__'
    MT_SUBTYPES = 'MT_subtypes__'
    MT_DIRTY = 'MT_dirty__'
    MT_PIVOT_IN = 'MT_pivotIn__'
    MT_PIVOT_OUT = 'MT_pivotOut__'
    MT_PRECOND_PREFIX = 'MT_pre__'
    MT_POSTCOND_PREFIX = 'MT_post__'

class Himesis(igraph.Graph):
    """
        Creates a typed, attributed, directed, multi-graph.
        @param num_nodes: the total number of nodes. If not known, you can add more vertices later
        @param edges: the list of edges where each edge is a tuple representing the ids of the source and target nodes
    """
    Constants = HConstants
    EDGE_LIST_THRESHOLD = 10**3

    def __init__(self, name='', num_nodes=0, edges=[]):
        """
            Creates a typed, attributed, directed, multi-graph.
            @param num_nodes: the total number of nodes. If not known, you can add more vertices later
            @param edges: the list of edges where each edge is a tuple representing the ids of the source and target nodes
        """

        igraph.GraphBase.__init__(self, n=num_nodes, edges=edges, directed=True)
        if not name:
            name = self.__class__.__name__
        self.name = standardize_name(name)

        # # Set universally unique identifiers for the graph and each node
        # if not hasattr(self, 'is_compiled'):
        #     self.is_compiled = False    # this instance is not yet compiled
        #     self['GUID__'] = nprnd.randint(9223372036854775806)
        #     for n in self.node_iter():
        #         self.vs[n]['GUID__'] = nprnd.randint(9223372036854775806)
        # A fast lookup of the node's index by its guid
        # - disable this lookup to save memory
        #self.nodes_id = {}

        # The following attributes are used by the compiler

        #disable these attributes to save memory
        #self.execute_body = None        # holds the content of the execute method
        #self.execute_parameters = []    # holds the arguments of the execute method
        #self.execute_doc = ''           # holds the docstring of the execute method

        #self.init_params = []           # If any further parameters are required for instantiating a sub-class
        #self.import_name = 'Himesis'    # holds the name of the super-class (one of those in this module) of this instance

    def __reduce__(self):
        return (self.name, igraph.Graph.__reduce__(self)[1])

        #remove constructor
        #return (value[1], value[2])
        #dict = [igraph_reduce, self.name, self.is_compiled]

        #return value

    def __reduce__ex(self, protocol):
        return self.__reduce__()

    def copy(self):
        cpy = igraph.Graph.copy(self)
        # cpy.nodes_id = copy.deepcopy(self.nodes_id)

        # only copy these if necessary
        if hasattr(self, "execute_body"):
            cpy.execute_body = copy.deepcopy(self.execute_body)
            cpy.execute_parameters = copy.deepcopy(self.execute_parameters)
            cpy.execute_doc = copy.deepcopy(self.execute_doc)

        if hasattr(self, "NACs"):
            cpy.NACs = copy.deepcopy(self.NACs)

        #cpy["equations"] = copy.deepcopy(self["equations"])
        cpy["equations"] = self["equations"][:]

        # cpy.init_params = copy.deepcopy(self.init_params)
        #cpy.import_name = copy.deepcopy(self.import_name)
        try:
            cpy.is_compiled = self.is_compiled
        except AttributeError:
            pass
        cpy.name = self.name
        return cpy

    def __copy__(self):
        return self.copy()

    def __deepcopy__(self, memo):
        return self.copy()

    def __str__(self):
        return self.name + ' V: ' + str(self.vcount()) + ' E: ' + str(len(self.es)) + ' GUID: ' + str(self[Himesis.Constants.GUID])

    def __repr__(self):
        return "<Himesis:" + self.name + ">"

    def get_id(self):
        """
            Returns the unique identifier of the graph
        """
        return self['GUID__']

    def node_iter(self):
        """
            Iterates over the nodes in the graph, by index
        """
        return range(self.vcount())

    def edge_iter(self):
        """
            Iterates over the edges in the graph, by index
        """
        return range(self.ecount())

    def add_node(self):
        new_node = self.vcount()
        self.add_vertices(1)

        self.vs[new_node]['GUID__'] = nprnd.randint(9223372036854775806)
        #self.vs[new_node][Himesis.Constants.GUID] = random.randint(0, 9223372036854775806)

        #self.nodes_id[id] = new_node
        return new_node

    def delete_nodes(self, nodes):
        self.delete_vertices(nodes)
        # Regenerate the lookup because node indices have changed
        #self.nodes_id = dict([(self.vs[node]["GUID__"], node) for node in range(self.vcount())])

    def get_node(self, id):
        """
            Retrieves the node instance with the specified label.
            @param label: The label of the node.
        """
        # for node in range(self.vcount()):
        #     if id == self.vs[node]['GUID__']:
        #         return node

        try:
            return self.vs["GUID__"].index(id)
        except ValueError:
            #TODO: This should be a TransformationLanguageSpecificException
            raise Exception('No node was found with the given id: ' + str(id))

    def _compile_additional_info(self, file):
        if hasattr(self, "execute_body"):
            s = '''
    def execute(self'''
            if hasattr(self, "execute_parameters"):
                params = ', %s' * len(self.execute_parameters)
                s += params % tuple(self.execute_parameters)
            s += '''):
%s
    '''
            file.write(s % indent_text(self.execute_doc + self.execute_body, 2))

    #for rule graphs, keep the equations the same
    #matchers and rewriters need to change them
    def _validate_equations(self, eqs):
        return str(eqs)

    def __compile_attribute(self, access, value):
        """
        Dump the initialization of the attribute:
        - for string, int, float, and bool types write the value directly;
        - for reference to another Himesis graph, call the constructor;
        - for all other types, dump the pickled value.
        @param access: the access to the attribute
        @param value: the value to set the attribute to
        """

        #only exists in Python2
        try:
            if isinstance(value, unicode):
                return '''
        %s = """%s"""''' % (access, value)
        except Exception:
            pass

        if isinstance(value, str):
            return '''
        %s = """%s"""''' % (access, value)
        elif isinstance(value, int) or isinstance(value, float) or isinstance(value, bool):
            return '''
        %s = %s''' % (access, value)
        elif isinstance(value, uuid.UUID):
            return '''
        %s = UUID('%s')''' % (access, str(value))
        elif isinstance(value, Himesis):
            graphClass = value.name
            return '''
        from .%s import %s
        %s = %s()''' % (graphClass, graphClass, access, graphClass)
        elif isinstance(value, list) or isinstance(value, dict):
            return '''
        %s = %s''' % (access, str(value))
        else:
            raise Exception("Value is not a base type")
            #print("Pickling: " + str(type(value)) + " " + str(value))
            #return '''
        #%s = pickle.loads("""%s""")''' % (access, pickle.dumps(value))

    def compile(self, file_path, init_params = []):
        """
        Compiles the graph into a Python file.
        Compilation is recursive: i.e., all sub-graphs are also compiled.
        @param file_path: The path of the output file.
        """

        # Make sure the directory exists
        # If the path contains the output file name, it will be replaced by the default one
        if path.isfile(file_path):
            file_path = path.dirname(file_path)
        if not path.isdir(file_path):
            mkdir(file_path)

        subgraphs = []      # references to Himesis sub-graphs of this graph

        #with open(file, 'w') as file:

        file = open(path.join(file_path, self.name + '.py'), 'w')
        if True:
            # Save the nodes in increasing order of the occurrence of its meta-model:
            # First build a dictionary {meta-model element: number of nodes of that type}
            meta_models = {}
            if self.vcount() > 0:
                tmp = self.vs[Himesis.Constants.META_MODEL]
                for mm in tmp:
                    if mm not in meta_models:
                        meta_models[mm] = tmp.count(mm)
                del tmp
            # Then, sort the node indices such that the node that has the least frequent type is in the beginning
            # We save the list as an object attribute, because it might be used by a sub-class' compiler
            self.ordered_nodes = sorted(self.node_iter(),
                                   key=lambda v: meta_models[self.vs[v][Himesis.Constants.META_MODEL]])

            himesis_classes = ["Himesis", "HimesisPattern",
                               "HimesisPreConditionPattern", "HimesisPreConditionPatternLHS",
                               "HimesisPreConditionPatternNAC", "HimesisPostConditionPattern"]
            class_name = str(self.__class__.__name__)

            if class_name not in himesis_classes:
                # This class is not a himesis class
                # so we need to get the name of the first base class
                # (probably HimesisPreConditionPatternLHS)
                base_class = self.__class__.__bases__[0]
                class_name = str(base_class.__name__)

            #if class_name != str(self.import_name):
             #   raise Exception("Could not find the same name as self.import_name!")

            file.write('''

from core.himesis import Himesis''')

            if class_name != 'Himesis':
                file.write(''', %s''' % class_name)

            init_params2 = ''
            init_params_values = ''
            if len(init_params) > 0:
                init_params2 = reduce(lambda p1, p2: p1 + p2,
                                    map(lambda p: ', %s' % p,
                                        init_params))
                init_params_values = reduce(lambda p1, p2: p1 + p2,
                                            map(lambda p: ', %s=%s' % (p, p),
                                                init_params))
            file.write('''

class %s(%s):
    def __init__(self%s):
        """
        Creates the himesis graph representing the AToM3 model %s.
        """
        # Flag this instance as compiled now
        self.is_compiled = True

        super(%s, self).__init__(name='%s', num_nodes=%d, edges=[]%s)
''' % (self.name,
       class_name,
       init_params2,
       self.name,
       self.name,
       self.name,
       self.vcount(),
       init_params_values))

            # Add the edges
            file.write('''
        # Add the edges''')
            edge_list = []
            # Determines if it's possible to provide the edges as a single list
            # Because it's faster than adding each edge individually.
            # However, due to Python limitations, the edge list is specified one 1 line
            # So for bigger graphs, we need to add edges in groups.
            if self.ecount() < Himesis.EDGE_LIST_THRESHOLD:
                edge_list = self.get_edgelist()
                # Order the edge list
                for i in range(len(edge_list)):
                    edge_list[i] = [self.ordered_nodes.index(edge_list[i][0]),
                                    self.ordered_nodes.index(edge_list[i][1])]
                file.write('''
        self.add_edges(%s)''' % str(edge_list))
            else:
                pitch = 0
                while pitch < self.ecount():
                    edgeId = pitch
                    edge_list = []
                    while edgeId - pitch < Himesis.EDGE_LIST_THRESHOLD and edgeId < self.ecount():
                        # Using the new order of nodes
                        edge = (self.ordered_nodes.index(self.es[edgeId].source),
                                self.ordered_nodes.index(self.es[edgeId].target))
                        edge_list.append(edge)
                        edgeId += 1
                    file.write('''
        self.add_edges(%s)''' % str(edge_list))
                    pitch += Himesis.EDGE_LIST_THRESHOLD
                file.write('''
        ''')

            # Set the graph attributes
            file.write('''
        # Set the graph attributes''')
            for attr in self.attributes():
                if attr == "equations":
                    file.write('''
        self["equations"] = ''' + self._validate_equations(self[attr]))
                    continue

                value = self[attr]
                access = 'self["%s"]' % attr
                file.write(self.__compile_attribute(access, value))
                if isinstance(value, Himesis):
                    subgraphs.append(value)

            # Set node attributes
            file.write('''

        # Set the node attributes''')
            # Compile the node attributes, always in the reight order
            for new_node_index, old_node_index in enumerate(self.ordered_nodes):
                for attr in self.vs[old_node_index].attribute_names():
                    if self.vs[old_node_index][attr] is not None:
                        value = self.vs[old_node_index][attr]
                        access = 'self.vs[%d]["%s"]' % (new_node_index, attr)
                        file.write(self.__compile_attribute(access, value))
                        if isinstance(value, Himesis):
                            subgraphs.append(value)

            file.write('\n')
            self._compile_additional_info(file)
            file.write('\n')

        file.flush()
        fsync(file.fileno())
        file.close()

        for sg in subgraphs:
            sg.compile(file_path)

        return file.name

    def execute(self, *args):
        raise AttributeError('This method is not implemented in the Himesis class. It should be overridden in a subclass.')

class HimesisPattern(Himesis):
    def __init__(self, name='', num_nodes=0, edges=[]):
        super(HimesisPattern, self).__init__(name, num_nodes, edges)

        #disable these attributes to save memory
        #self.nodes_label = {}
        #self.nodes_pivot_out = {}

    def get_node_with_label(self, label):
        """
            Retrieves the index of the node with the specified label.
            @param label: The label of the node.
        """
        #if not self.nodes_label:
        #    self.nodes_label = dict([(self.vs[i][Himesis.Constants.MT_LABEL], i) for i in self.node_iter()])
        #if label in self.nodes_label:
        #    return self.nodes_label[label]

        try:
            return self.vs['MT_label__'].index(label)
        except ValueError:
            #it's alright for some labels to not be here
            pass

        # for i in range(self.vcount()):
        #     if label == self.vs[i]['MT_label__']:
        #         return i

    def get_pivot_out(self, pivot):
        """
            Retrieves the index of the pivot node
            @param pivot: The label of the pivot.
        """
        # if not self.nodes_pivot_out and Himesis.Constants.MT_PIVOT_OUT in self.vs.attribute_names():
        #     self.nodes_pivot_out = dict([(i, self.vs[i][Himesis.Constants.MT_PIVOT_OUT]) for i in self.node_iter()])
        # if pivot in self.nodes_pivot_out:
        #     return self.nodes_pivot_out[pivot]

        try:
            return self.vs[pivot]['MT_pivotOut__']
        except Exception as e:
            return None

class HimesisPreConditionPattern(HimesisPattern):
    def __init__(self, name='', num_nodes=0, edges=[]):
        super(HimesisPreConditionPattern, self).__init__(name, num_nodes, edges)
        #self.import_name = 'HimesisPreConditionPattern'
        #self.nodes_pivot_in = {}

        self.superclasses_dict = {}

    def _valid_token(self, token):

        if token[0] == "constant":
            return True
        elif token[0] == "concat":
            return self._valid_token(token[1][0]) and self._valid_token(token[1][1])
        node_label = str(token[0])
        return self.get_node_with_label(node_label) is not None

    # for matchers, make sure that the equations refer to valid nodes
    def _validate_equations(self, eqs):
        new_eqs = []
        #print("\nOld eqs: " + str(eqs))
        for eq in eqs:
            if self._valid_token(eq[0]) and self._valid_token(eq[1]):
                new_eqs.append(eq)

        #print("\nNew eqs: " + str(new_eqs))

        return str(new_eqs)

    def get_pivot_in(self, pivot):
        """
            Retrieves the index of the pivot node
            @param pivot: The label of the pivot.
        """
        # if not self.nodes_pivot_in and Himesis.Constants.MT_PIVOT_IN in self.vs.attribute_names():
        #     self.nodes_pivot_in = dict([(self.vs[i][Himesis.Constants.MT_PIVOT_IN], i) for i in self.node_iter()])
        # if pivot in self.nodes_pivot_in:
        #     return self.nodes_pivot_in[pivot]

        if 'MT_pivotIn__' in self.vs.attribute_names():
            for i in range(self.vcount()):
                if pivot == self.vs[i]['MT_pivotIn__']:
                    return i

    def constraint(self, PreMatch, graph):
        """
        If a constraint shall be specified, the corresponding Himesis graph must override this method.
        The condition must be specified in the pattern graph and not the input graph.
        By default, the constraint evaluates to True.
        @param PreMatch: The current match, before the rewriting.
        @param graph: The whole input graph.
        """
        return True

    def get_attr_constraint_name(self, node, attr_name):
        """
            Returns the name of the method to call to evaluate the constraint of the given attribute.
            @param attr_name: The name of the attribute.
        """
        return 'eval_%s%s' % (to_non_RAM_attribute(attr_name), self.vs[node]['MT_label__'])

    def _compile_additional_info(self, file):
        """
        Compiles the constraint code into a callable method.
        @param file: The output file.
        """

        # Attribute constraints code
        for v in self.node_iter():
            for attr in self.vs[v].attribute_names():
                if not self.vs[v][attr]:
                    # There is no action for this attribute
                    continue
                if is_RAM_attribute(attr):
                    file.write('''
    def %s(self, attr_value, this):
%s

''' % (self.get_attr_constraint_name(v, attr), misc.indent_text(self.vs[v][attr], 2)))

        # The constraint code
        code = 'return True'
        if Himesis.Constants.MT_CONSTRAINT in self.attributes() and self[Himesis.Constants.MT_CONSTRAINT]:
            code = self[Himesis.Constants.MT_CONSTRAINT]
        file.write('''
    def constraint(self, PreNode, graph):
        """
            Executable constraint code.
            @param PreNode: Function taking an integer as parameter
                            and returns the node corresponding to that label.
        """
%s
''' %  misc.indent_text(code, 2))

class HimesisPreConditionPatternLHS(HimesisPreConditionPattern):
    def __init__(self, name='', num_nodes=0, edges=[]):
        super(HimesisPreConditionPatternLHS, self).__init__(name, num_nodes, edges)
        #self.import_name = 'HimesisPreConditionPatternLHS'
        self.NACs = []

    def _compile_additional_info(self, file):
        """
        Compiles the constraint code into a callable method and links to NACs.
        @param file: The output file.
        """

        # The NACs
        if len(self.NACs) > 0:
            file.write('''

        # Load the NACs''')
            if self.is_compiled:
                # self.NACs is a list of Himesis graphs
                for NAC in self.NACs:
                    NAC_name = NAC.__class__.__name__
                    file.write("""
        try:
            from .%s import %s
        except Exception:
            from %s import %s
        """ % (NAC_name, NAC_name, NAC_name, NAC_name))
                file.write('''
        self.NACs = %s
''' % str(map(lambda NAC: '%s(LHS=self)' % standardize_name(NAC.__class__.__name__),
                    self.NACs)).replace("'", ""))

            else:
                # self.NACs = ['NAC1', 'NAC2', ..., 'NACn']
                for NAC_name in self.NACs:
                    sname = standardize_name(NAC_name)
                    file.write("""
        try:
            from .%s import %s
        except Exception:
            from %s import %s
        """ % (sname, sname, sname, sname))
                file.write('''
        self.NACs = %s
''' % str(map(lambda NAC: '%s(LHS=self)' % standardize_name(NAC), self.NACs)).replace("'", ""))

        super(HimesisPreConditionPatternLHS, self)._compile_additional_info(file)

class HimesisPreConditionPatternNAC(HimesisPreConditionPattern):
    def __init__(self, LHS, name='', num_nodes=0, edges=[]):
        super(HimesisPreConditionPatternNAC, self).__init__(name, num_nodes, edges)
        self.LHS = LHS
        self.bridge = None
        #self.init_params.append('LHS')
        #self.import_name = 'HimesisPreConditionPatternNAC'

    def compile(self, file_path, init_params=[]):
        return super(HimesisPreConditionPatternNAC, self).compile(file_path, ['LHS'])

    def _compile_additional_info(self, file):
        """
        Compiles the bridge between this NAC and its LHS.
        @param file: The output file.
        """

        # Re-compile the bridge even if the NAC was already compiled, to ensure consistency between the 3 graphs
        self.bridge = self.compute_bridge()
        self.bridge.name = self.name + 'Bridge'
        self.bridge.compile(file.name)

        file.write("""

        # Load the bridge between this NAC and its LHS
        try:
            from .%s import %s
        except Exception:
            from %s import %s""" % (self.bridge.name, self.bridge.name, self.bridge.name, self.bridge.name))
        file.write('''
        self.bridge = %s()
''' % self.bridge.name)

        super(HimesisPreConditionPatternNAC, self)._compile_additional_info(file)

    def compute_bridge(self):
        """
            Creates a HimesisPreConditionPattern defined as the intersection of graph with this instance.
            This is called the 'bridge'.
            From a topological point of view, this method computes the largest common subgraph of these two graphs.
            However, the similarity of nodes of the bridge relies on the meta-model type of the nodes.
            Furthermore, every attribute value is the conjunction of the constraints defined in each graph.
        """
        # G1 is the smallest graph and G2 is the bigger graph
        G1 = self
        G2 = self.LHS
        if G1.vcount() > G2.vcount():
            # Swap
            G1, G2 = G2, G1
        # The bridge
        G = HimesisPreConditionPattern()
        # We don't need to actually solve the largest common subgraph (LCS) problem
        # because we assume that the nodes are labelled uniquely in each graph
        # and that if a label is in G1 and in G2, then it will be in G
        Labels2 = G2.vs[Himesis.Constants.MT_LABEL]
        for label in G1.vs[Himesis.Constants.MT_LABEL]:
            if label in Labels2:
                # Get the corresponding node from G1
                v1 = G1.vs.select(lambda v : v[Himesis.Constants.MT_LABEL] == label)
                if len(v1) == 1:
                    v1 = v1[0]
                elif len(v1) == 0:
                    raise Exception('Label does not exist: ' + str(label))
                else:
                    raise Exception('Label is not unique: ' + str(label))
                # Get the corresponding node from G2
                v2 = G2.vs.select(lambda v : v[Himesis.Constants.MT_LABEL] == label)
                if len(v2) == 1:
                    v2 = v2[0]
                elif len(v2) == 0:
                    raise Exception('Label does not exist: ' + str(label))
                else:
                    raise Exception('Label is not unique: ' + str(label))
                new_node = G.add_node()
                # Now do a conjunction of the attributes
                for attr in v1.attribute_names():
                    if v1[attr] is None:
                        continue
                    G.vs[new_node][attr] = v1[attr]
                for attr in v2.attribute_names():
                    if v2[attr] is None:
                        continue
                    # The attribute is not in v1
                    if attr not in G.vs[new_node].attribute_names():
                        G.vs[new_node][attr] = v2[attr]
                    # Ignore the GUID attribute, it will be automatically set at run-time
                    elif attr == Himesis.Constants.GUID:
                        continue
                    elif is_RAM_attribute(attr):
                        if not v2[attr]:
                            # There is no constraint for this attribute
                            continue
                        # The attribute constraint code is the conjunction of the LHS constraint
                        # with the NAC constraint for this attribute
                        s = '''from .%s import %s
from %s import %s''' % (G1.name, G1.name, G2.name, G2.name)
                        if G1 == self:
                            s += ('''
lhs = %s()''' % G2.name) + '''
return %s(lhs).%s(attr_value, this) and %s().%s(attr_value, this)'''
                        else:
                            s += ('''
lhs = %s()''' % G1.name) + '''
return %s().%s(attr_value, this) and %s(lhs).%s(attr_value, this)'''
                        G.vs[new_node][attr] = s % (G1.name, G1.get_attr_constraint_name(v1.index, attr),
                                                    G2.name, G2.get_attr_constraint_name(v2.index, attr))
                    elif v1[attr] != v2[attr]:
                        #TODO: This should be a TransformationLanguageSpecificException
                        raise Exception('Unable to conjunct \'%s\' while computing the bridge' % attr)
                    #else: v1[attr] == v2[attr], so we don't need to do anything more
        # Now add the edges
        # We only need to go through the edges of the smaller graph
        for e in G1.edge_iter():
            src_label = G1.vs[G1.es[e].source][Himesis.Constants.MT_LABEL]
            trg_label = G1.vs[G1.es[e].target][Himesis.Constants.MT_LABEL]
            src = G.vs.select(lambda v : v[Himesis.Constants.MT_LABEL] == src_label)
            trg = G.vs.select(lambda v : v[Himesis.Constants.MT_LABEL] == trg_label)
            if len(src) == len(trg) == 1:
                src = src[0]
                trg = trg[0]
                G.add_edges([(src.index, trg.index)])
            elif len(src) == 0 :
#                raise Exception('Label does not exist :: '+str(src_label))
                pass
            elif len(trg) == 0 :
#                raise Exception('Label does not exist :: '+str(tgt_label))
                pass
            elif len(src) > 1 :
                raise Exception('Label is not unique: ' + str(src_label))
            elif len(trg) > 1 :
                raise Exception('Label is not unique: ' + str(trg_label))
        return G

class HimesisPostConditionPattern(HimesisPattern):
    def __init__(self, name='', num_nodes=0, edges=[]):
        super(HimesisPostConditionPattern, self).__init__(name, num_nodes, edges)
        self.pre = None
        #self.import_name = 'HimesisPostConditionPattern'

    def action(self, MTpre, MTpost):
        """
        If an action shall be specified, the corresponding Himesis graph must override this method.
        The action must be specified in the pattern graph and not the input graph.
        """
        pass

    def get_attr_action_name(self, node, attr_name):
        """
            Returns the name of the method to call to execute the action of the given attribute.
            @param attr_name: The name of the attribute.
        """
        return 'set_%s%s' % (to_non_RAM_attribute(attr_name), self.vs[node][Himesis.Constants.MT_LABEL])

    # This method must be overridden by every sub-class.
    # There lies the code of the rewriting part of the rule.
    def execute(self, packet):
        raise AttributeError(
            'This method is not implemented in the HimesisPostConditionPattern class. It should be overridden in a subclass.')

    def compile(self, file_path, pre_label_MM_mapping={}):
        """
        Compiles the graph down to a file in an executable format.
        @param file_path: The path of the output file.
        @param pre_label_MM_mapping: If this instance was not yet compiled,
                                     you must specify the mapping from the pre-condition pattern in the form:
                                     {label: meta-model name}.
        """
        assert self.is_compiled or (not self.is_compiled and pre_label_MM_mapping), 'The mapping {label: meta-model name} of the pre-condition pattern must be specified'
        # Augment the graph with the following attribute just for compilation purposes
        self.pre_label_MM_mapping = pre_label_MM_mapping
        return super(HimesisPostConditionPattern, self).compile(file_path)

    def attribute_is_specified(self, code):
        """
            Detects if some action code in the attribute is specified and actually does something
            @param code: The action code.
        """
        for line in code.splitlines():
            if line != '' and not line.startswith('#') and line != 'return attr_value':
                # Returns true also if there is code after return attr_value
                return True
        return False

    def _compile_additional_info(self, file):
        """
        Compiles the execute and action codes into callable methods as well as the pointer to the pre-condition pattern.
        @param file: The output file
        """
        if self.is_compiled:
            # self.pre is a Himesis graph
            file.write('''
        try:
            from .%s import %s
        except Exception:
            from %s import %s
        self.pre = %s()
    ''' % tuple([self.pre.__class__.__name__] * 5))
        else:
            # self.pre = "precondition name"
            file.write('''
        try:
            from .%s import %s
        except Exception:
            from %s import %s
        self.pre = %s()
    ''' % tuple([standardize_name(self.pre)] * 5))

        # Attributes action code
        for v in self.node_iter():
            for attr in self.vs[v].attribute_names():
                if not self.vs[v][attr]:
                    # There is no action for this attribute
                    continue
                if is_RAM_attribute(attr):
                    code = self.vs[v][attr]
                    if self.attribute_is_specified(code):
                        file.write('''
    def %s(self, attr_value, PreNode, graph):
%s

''' % (self.get_attr_action_name(v, attr), misc.indent_text(code, 2)))

        # The action code
        code = 'pass'
        if Himesis.Constants.MT_ACTION in self.attributes() and self[Himesis.Constants.MT_ACTION]:
            code = self[Himesis.Constants.MT_ACTION]
        file.write('''
    def action(self, PostNode, graph):
        """
            Executable constraint code.
            @param PostNode: Function taking an integer as parameter
                             and returns the node corresponding to that label.
        """
%s
''' % misc.indent_text(code, 2))

        # The execute method
        self.set_execute_body()
        assert len(self.execute_body) > 0, 'The execute method has no body'
        self.execute_parameters = ['packet', 'match']
        self.execute_doc = '''"""
    Transforms the current match of the packet according to the rule %s.
    Pivots are also assigned, if any.
    @param packet: The input packet.
    @param match: The match to rewrite.
"""
'''
        super(HimesisPostConditionPattern, self)._compile_additional_info(file)

    def set_attributes(self, node, index, has_old_values):
        transformationCode = []
        for attrName in self.vs.attribute_names():
            if attrName.startswith("MT_pre__") or attrName.startswith("MT_post__"):
                attr = self.vs[node][attrName]
                if not attr:
                    # No action to perform for this attribute
                    continue
                attrName = to_non_RAM_attribute(attrName)
                if self.attribute_is_specified(attr):
                    old_value = 'None'
                    if has_old_values:
                        old_value = "vs[%s]['%s']" % (index, to_non_RAM_attribute(attrName))
                    # TODO: This should be a TransformationLanguageSpecificException
                    transformationCode.append("""vs[%s]['%s'] = self.%s(%s, lambda i: graph.vs[match[i]], graph)
""" \
                                              % (index, to_non_RAM_attribute(attrName),
                                                 self.get_attr_action_name(node, attrName),
                                                 old_value))
        return ''.join(transformationCode)

    #@profile
    def set_execute_body(self):
        """
        Compiles the body of the execute method.
        """

        LHS_labels = {}     # {label: meta-model name}
        if self.is_compiled and Himesis.Constants.MT_LABEL in self.pre.vs.attribute_names():
            LHS_labels = dict([(label, self.pre.vs[self.pre.get_node_with_label(label)][Himesis.Constants.META_MODEL])
                               for label in self.pre.vs[Himesis.Constants.MT_LABEL]])
        else:
            LHS_labels = self.pre_label_MM_mapping  # This was initialized in the overridden compile method
        RHS_labels = []
        if Himesis.Constants.MT_LABEL in self.vs.attribute_names():
            RHS_labels += self.vs[Himesis.Constants.MT_LABEL]

        # Update attributes
        transformationCode = ["""graph = packet.graph

vs = graph.vs

import numpy.random as nprnd

# Build a dictionary {label: node index} mapping each label of the pattern to a node in the graph to rewrite.
# Because of the uniqueness property of labels in a rule, we can store all LHS labels
# and subsequently add the labels corresponding to the nodes to be created.
labels = match.copy()

#===============================================================================
# Update attribute values
#===============================================================================
"""]
        for label in LHS_labels:
            rhsNode = self.get_node_with_label(label)
            if rhsNode is None: continue        # not in the interface graph (LHS n RHS)
            updateCode = self.set_attributes(rhsNode, "labels['%s']" % label, has_old_values=True)
            if len(updateCode) > 0:
                transformationCode.append("""# %s%s
%s""" % (to_non_RAM_attribute(self.vs[rhsNode][Himesis.Constants.META_MODEL]), label, updateCode))
                # Only set the dirty flag if there was a modification in the attributes
                transformationCode.append("""
vs[labels['%s']][Himesis.Constants.MT_DIRTY] = True
""" % label)

        # Create new nodes
        transformationCode.append("""
#===============================================================================
# Create new nodes
#===============================================================================

node_num = graph.vcount()
""")
        num_nodes_to_add = 0
        for label in RHS_labels:
            if label not in LHS_labels:
                num_nodes_to_add += 1

        transformationCode.append("""
graph.add_vertices(%s)

""" % str(num_nodes_to_add))

        new_labels = []
        for label in RHS_labels:
            rhsNode = self.get_node_with_label(label)
            if label not in LHS_labels:
                new_labels += [label]
                className = to_non_RAM_attribute(self.vs[rhsNode]["mm__"])
                transformationCode.append("""# %s%s
labels['%s'] = node_num
vs[node_num]["mm__"] = '%s'
vs[node_num]['GUID__'] = nprnd.randint(9223372036854775806)
""" % (className, label, label, className))

                #HACK: Add rule name to paired_with
                if className == "paired_with":
                    transformationCode.append("""vs[node_num]["attr1"] = self["name"]
""")
                transformationCode += self.set_attributes(rhsNode, 'node_num', has_old_values = False)
                transformationCode.append("""
node_num += 1
""")
#                 transformationCode.append("""# %s%s
# new_node = graph.add_node()
# labels['%s'] = node_num
# vs[node_num]["mm__"] = '%s'
# """ % (className, label, label, className))
#                 transformationCode += set_attributes(rhsNode, 'node_num', has_old_values=False)

        # Link the new nodes
        transformationCode.append("""
#===============================================================================
# Create new edges
#===============================================================================
""")
        transformationCode.append("""graph.add_edges([
""")

        MT_labels = self.vs["MT_label__"]
        mms = self.vs["mm__"]

        ls = sorted(new_labels)
        added_edges = set()
        for edge in self.es:
            src_label = MT_labels[edge.source]
            tar_label = MT_labels[edge.target]

            new_edge = (src_label, tar_label)
            if new_edge in added_edges:
                continue

            for label in ls:
                if new_edge in added_edges:
                    break

                if label == src_label or label == tar_label:

                    added_edges.add(new_edge)

                    transformationCode.append("""# %s%s -> %s%s
    (labels['%s'], labels['%s']),
    """ % (to_non_RAM_attribute(mms[edge.source]),
           src_label,
           to_non_RAM_attribute(mms[edge.target]),
           tar_label,
           src_label,
           tar_label))

                    # visited_edges.append(edge.index)

        transformationCode.append("""])""")

        # Set the output pivots
        transformationCode.append("""
#===============================================================================
# Set the output pivots
#===============================================================================
""")
        if Himesis.Constants.MT_PIVOT_OUT in self.vs.attribute_names():
            for node in self.vs.select(lambda v: v[Himesis.Constants.MT_PIVOT_OUT]):
                node = node.index
                label = self.vs[node][Himesis.Constants.MT_LABEL]
                transformationCode.append(
"""# %s%s
packet.global_pivots['%s'] = graph.vs[labels['%s']][Himesis.Constants.GUID]
""" % (to_non_RAM_attribute(self.vs[node][Himesis.Constants.META_MODEL]), label, self.vs[node][Himesis.Constants.MT_PIVOT_OUT], label))
        #TODO: This should be a TransformationLanguageSpecificException
        transformationCode.append("""
#===============================================================================
# Perform the post-action
#===============================================================================
try:
    self.action(lambda i: graph.vs[labels[i]], graph)
except Exception as e:
    raise Exception('An error has occurred while applying the post-action', e)""")

        # Delete nodes (and edges)
        transformationCode.append("""
#===============================================================================
# Finally, delete nodes (this will automatically delete the adjacent edges)
#===============================================================================
""")
        labels_to_delete = []
        for label in LHS_labels:
            if label not in RHS_labels:
                labels_to_delete.append(label)
        if len(labels_to_delete) > 0:

            for lbl in labels_to_delete:
                transformationCode.append("""# %s%s""" % (LHS_labels[lbl], lbl))
                transformationCode.append("""
graph.delete_nodes(%s)
""" % str('labels["%s"]' % lbl).replace("'", ""))

        # Save the code in the body of the execute method
        self.execute_body = ''.join(transformationCode)

redpajama_set_name: RedPajamaGithub


text:
/*
 * =====================================================================================
 *
 *       Filename:  AgentEntrance.c
 *
 *    Description:  Entry of NuAgent
 *
 *        Version:  0.0.1
 *        Created:  2015/6/26 10:18:05
 *       Revision:  none
 *
 *         Author:  Lin Hui (Link), linhui.568@163.com
 *   Organization:  Nufront
 *
 *--------------------------------------------------------------------------------------
 *       ChangLog:
 *        version    Author      Date          Purpose
 *        0.0.1      Lin Hui    2015/06/26     Create and Initialize
 * =====================================================================================
 */
#include "common.h"

extern const INT8U FwVerNum[3];
const INT8U NuAgentVerNum[3] = {
	0x00,  /* Main version */
	0x02,  /* Sub version */
	0x01   /* Internal version */
};

/* system status */
struct sys_status_t sys_status;

void print_version(void)
{
				/* SDK Version;   	 NuAgent Version;   	Compile Time; */
	log_notice("Sver:<%x.%02x.%02x>; Yeelink:<%x.%02x.%02x>; Time:<%s-%s><%s>;\n",
		FwVerNum[0], FwVerNum[1], FwVerNum[2],
		NuAgentVerNum[0], NuAgentVerNum[1], NuAgentVerNum[2],
        __DATE__, __TIME__,
		#if DEBUG_ON
		"dbg"
		#else
		"rel"
		#endif
	);
	log_notice("=============================================================\n\n");
}

void nl6621_main_entry(void * pParam)
{
	unsigned char prioUser = TCPIP_THREAD_PRIO + 1;

	/* Print NuAgent version */
	print_version();

	/* Create system indicator LED task thread */
	sys_status.status = SYS_STATUS_WIFI_STOP;
	sys_status.onboarding = SYS_STATUS_ONBOARDING_FAILED;
	sys_thread_new("SysIdxLedThread", SysIdxLedThread, NULL, NST_TEST_APP_TASK_STK_SIZE, (prioUser + 7));
	sys_thread_new("SysResetThread", SysResetThread, NULL, NST_TEST_APP_TASK_STK_SIZE, prioUser);

	/* initialize GAgent resource */
    Agent_Init();

	/* Create network task thread. Include UDP server, UDP Broadcast, TCP server, TCP
	 * login cloud. */
	sys_thread_new("UdpServerThread", UdpServerThread, NULL, NST_TEST_APP_TASK_STK_SIZE, (prioUser + 1));
	sys_thread_new("TcpServerThread", TcpServerThread, NULL, NST_TEST_APP_TASK_STK_SIZE, (prioUser + 2));
	sys_thread_new("Yeelink_Run", Yeelink_Run, NULL, NST_TEST_APP_TASK_STK_SIZE, (prioUser+3));
	sys_thread_new("TcpCloudThread", TcpCloudThread, NULL, NST_TEST_APP_TASK_STK_SIZE * 4, (prioUser + 4));

	/* Support user's private task, like NTP, OTA */
	sys_thread_new("OtherTaskThread", OtherTaskThread, NULL, NST_TEST_APP_TASK_STK_SIZE, (prioUser + 5));

#if NUAGENT_UART_SWITCH
	/* Do not open this task, unless you want to use wifi2uart function. */
	sys_thread_new("UartTaskThread", UartTaskThread, NULL, NST_TEST_APP_TASK_STK_SIZE, (prioUser + 6));
#endif

    while (1) {
		/* user can add funcionality here. */

		/* User test case(code in ./sample/ cataloge) */

	    OSTimeDly(400);
    }
}


text:
var defaults = function (target, source) {
  source = source || {};
  for (var key in source) {
    if (source.hasOwnProperty(key) && target[key] === undefined) {
      source[key] = target[key];
    }
  }
  return target;
};

var pw = require('pw');

var readline = require('readline');

module.exports = function(questions, options, callback) {

    if (typeof options === 'function') {
      callback = options;
      options = {};
    }

    options = defaults({
      confirmFailMessage: 'values do not match',
      confirmPostPrefix: 'your answer was:',
      confirmMessage: 'is this correct? [n] >',
      confirmPrefix: 'confirm',
      promptSep: ' > ',
      confirmString: 'y',
      confirmStrToLower: true
    }, options);

    if (options.confirmPrefix.charAt(options.confirmPrefix.length - 1) !== ' ') {
      options.confirmPrefix += ' ';
    }
    var rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    var answers = {};
    var queue = [];

    function write(msg) {
        process.stdout.write(msg);
    }

    function done() {
        if (options.doneMessage) {
          write(options.doneMessage);
        }
        rl.close();
        callback(null, answers);
    };

    function ask(inputs) {

        var input, defaultInput, confirm, prompt;

        var inputItem = inputs.shift();

        if (typeof inputItem === 'string') {
            input = inputItem;
            question = inputItem;
            defaultInput = false;
            confirm = false;
            mask = false;
        }
        else {
            input = Object.keys(inputItem)[0];
            defaultInput = inputItem[input];
            if ({}.toString.call(defaultInput) === '[object Object]') {
                confirm = defaultInput.confirm;
                question = defaultInput.question || input;
                mask = defaultInput.mask || false;
                defaultInput = defaultInput.defaultValue;
            }
            else {
                confirm = false;
                question = input;
                mask = false;
            }
        }

        if (defaultInput) question += ' [' + defaultInput + ']';
        question += options.promptSep;

        if (mask) {
            rl.close();
            var confirmPwd = function (pwd, confirmPwd) {
                if (pwd !== confirmPwd) {
                    console.log(options.confirmFailMessage);
                    inputs.unshift(inputItem);
                }
                else {
                    answers[input] = pwd;
                }
                if (inputs.length > 0) {
                    rl = readline.createInterface({
                        input: process.stdin,
                        output: process.stdout
                    });
                    ask(inputs);
                }
                else done();

            };

            process.stdout.write(question);
            pw(function (password) {

                if (confirm) {
                    write(options.confirmPrefix + question);
                    pw(function (confirmPassword) {
                        confirmPwd(password, confirmPassword);
                    });
                }
                else confirmPwd(password, password);
            });
        }
        else {
            rl.question(question, function (answer) {

                var resolve = function (confirmed, answer) {
                    if (confirmed) answers[input] = answer;
                    else inputs.unshift(inputItem);
                    if (inputs.length > 0) ask(inputs);
                    else done();
                };

                if (answer.length === 0 && defaultInput)
                    answer = defaultInput;

                if (confirm) {
                    console.log(options.confirmPostPrefix, answer);
                    rl.question(options.confirmMessage, function (confirmAnswer) {
                      if (options.confirmStrToLower) {
                        confirmAnswer = confirmAnswer.toLowerCase();
                      }
                      resolve(confirmAnswer === options.confirmString, answer);
                    });
                }
                else {
                    resolve(true, answer);
                }

            });
        }
    }

    ask(questions);
};


text:
.class Landroid/media/AudioTrack$NativeRoutingEventHandlerDelegate;
.super Ljava/lang/Object;
.source "AudioTrack.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/media/AudioTrack;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "NativeRoutingEventHandlerDelegate"
.end annotation

# instance fields
.field private final mHandler:Landroid/os/Handler;

.field final synthetic this$0:Landroid/media/AudioTrack;

# direct methods
.method constructor <init>(Landroid/media/AudioTrack;Landroid/media/AudioTrack;Landroid/media/AudioTrack$OnRoutingChangedListener;Landroid/os/Handler;)V
    .registers 7
    .param p1, "this$0"    # Landroid/media/AudioTrack;
    .param p2, "track"    # Landroid/media/AudioTrack;
    .param p3, "listener"    # Landroid/media/AudioTrack$OnRoutingChangedListener;
    .param p4, "handler"    # Landroid/os/Handler;

    .prologue
    const/4 v1, 0x0

    .line 2436
    iput-object p1, p0, Landroid/media/AudioTrack$NativeRoutingEventHandlerDelegate;->this$0:Landroid/media/AudioTrack;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 2441
    if-eqz p4, :cond_16

    .line 2442
    invoke-virtual {p4}, Landroid/os/Handler;->getLooper()Landroid/os/Looper;

    move-result-object v0

    .line 2449
    .local v0, "looper":Landroid/os/Looper;
    :goto_c
    if-eqz v0, :cond_1b

    .line 2451
    new-instance v1, Landroid/media/AudioTrack$NativeRoutingEventHandlerDelegate$1;

    invoke-direct {v1, p0, v0, p2, p3}, Landroid/media/AudioTrack$NativeRoutingEventHandlerDelegate$1;-><init>(Landroid/media/AudioTrack$NativeRoutingEventHandlerDelegate;Landroid/os/Looper;Landroid/media/AudioTrack;Landroid/media/AudioTrack$OnRoutingChangedListener;)V

    iput-object v1, p0, Landroid/media/AudioTrack$NativeRoutingEventHandlerDelegate;->mHandler:Landroid/os/Handler;

    .line 2438
    :goto_15
    return-void

    .line 2445
    .end local v0    # "looper":Landroid/os/Looper;
    :cond_16
    invoke-static {p1}, Landroid/media/AudioTrack;->-get0(Landroid/media/AudioTrack;)Landroid/os/Looper;

    move-result-object v0

    .restart local v0    # "looper":Landroid/os/Looper;
    goto :goto_c

    .line 2470
    :cond_1b
    iput-object v1, p0, Landroid/media/AudioTrack$NativeRoutingEventHandlerDelegate;->mHandler:Landroid/os/Handler;

    goto :goto_15
.end method

# virtual methods
.method getHandler()Landroid/os/Handler;
    .registers 2

    .prologue
    .line 2475
    iget-object v0, p0, Landroid/media/AudioTrack$NativeRoutingEventHandlerDelegate;->mHandler:Landroid/os/Handler;

    return-object v0
.end method


text:
layout: bare
title: Git and GitHub Foundations Online
description: Git/GitHub Foundations Online Class Notes
tags: [notes, online, class]
path: classnotes/2012-12-05-git-github-foundations-online.md
eventdate: 2012-12-05
---

Held on December 5 & 6, 2012

Teachers:

* Matthew McCullough ([Twitter](http://twitter.com/matthewmccull), [GitHub](https://github.com/matthewmccullough))
* Brent Beer ([Twitter](http://twitter.com/brntbeer), [GitHub](https://github.com/brntbeer))

## Setting Move Detection As Default

    git config diff.renames true #Turn on move detection (-M)
    git config diff.renames copy #Turn on copy detection (-C)

This code was found by:

    git grep -A3 diff.renames

* [Peff commenting on move detection config](http://git.661346.n2.nabble.com/git-show-doesn-t-respect-config-diff-renames-copies-td675625.html)
* [Stack Overflow Move Detection](http://stackoverflow.com/questions/1043388/record-file-copy-operation-with-git)
* [Git config command](http://git-scm.com/docs/git-config)

## Resources

* [Adding SSL Certificates for GitHub.com (Common for Windows XP)](http://stackoverflow.com/questions/3777075/https-github-access/4454754#4454754)
* Disabling SSL Certificate Checks for Git:

        git config --global http.sslVerify false
* [Open Source Git Ignore Templates](https://github.com/github/gitignore)
* [Book Authoring on Git and GitHub](http://teach.github.com/articles/book-authoring-using-git-and-github/)
* [Post Receive Hooks](https://help.github.com/articles/post-receive-hooks)
* [GitHub Training Videos](http://training.github.com/resources/videos/)
* [Using Git with Media Temple](http://carl-topham.com/theblog/post/using-git-media-temple/)
* [GitHub Training Feedback and Follow-up Questions](https://github.com/githubtraining/feedback/issues?state=open)
* [GitHub Commit Status API for Continuous Integration](https://github.com/blog/1227-commit-status-api)
* [Git Credential Cache for HTTP](http://teach.github.com/articles/lesson-git-credential-cache/)
* [GitHub Issues Cheatsheet](http://teach.github.com/articles/github-issues-cheatsheet/)
* [Jenkins Git Plugin](https://wiki.jenkins-ci.org/display/JENKINS/Git+Plugin)
* [Open Source Git Ignores](https://github.com/github/gitignore)
* [Ship of Theseus - Related to Similarity Index](http://en.wikipedia.org/wiki/Ship_of_Theseus)
* [git-p4 Perforce Script](http://answers.perforce.com/articles/KB_Article/Git-P4)
* [Unix watch command](http://en.wikipedia.org/wiki/Watch_(Unix\))
* [SHA-1 Hash Collisions](http://git-scm.com/book/ch6-1.html#A-SHORT-NOTE-ABOUT-SHA-1)
* [NPD Git Cheatsheet](http://ndpsoftware.com/git-cheatsheet.html)
* [More Git Cheatsheets](http://teach.github.com/articles/git-cheatsheets/)

## Installation
* Git Installation
    * [The Git-SCM Web Site (All Platforms)](http://git-scm.com)
    * [The GitHub for Windows Client and Command Line](http://windows.github.com)
* Minimum is 1.7.ANYTHING, but can have issues with HTTPS credential prompting.
* Best is 1.8.0 or higher

## Suggested Books, Articles
* [Free ProGit Book](http://git-scm.com/book)
* [Getting started with Version Control](http://teach.github.com/articles/lesson-new-to-version-control/)
* [The GitHub Flow](http://scottchacon.com/2011/08/31/github-flow.html)
* [DVCS Workflows Book](https://github.com/zkessin/dvcs-workflows)
* [Git Cheat Sheets](http://teach.github.com/articles/git-cheatsheets/)
* [Git Workflow Links](https://pinboard.in/u:matthew.mccullough/t:git+workflow)

## Course Materials, Links
* [Git Teaching Materials](http://teach.github.com)
* [Course Slides](http://teach.github.com/articles/course-slides/)
* [Post-event Git and GitHub questions](https://github.com/githubtraining/feedback/)
* [Free Office Hours Sessions](http://training.github.com/web/free-classes/)

## Q&A Transcript

### Day 1

**Why didn't the first push work when your credential cache was on?**
He had a different set of credentials cached! whoops.

**Will `blame -C` give us weird answers for very common lines such as
`int i;` or `#include "attr.h"`?**
If we tune the `-C` with an integer like `-C9` or `-C80` we can fine
tune to watch for those copies a bit harder or softer.

**How can I see what branches are available?  `git status` shows
current branch, how do I know what other branches there are?**
Great question! A way to see this would be: `git branch`. If you want
to see all branches (even remotes that your repository knows about)
you can use: `git branch -a` to see all of them.

**So it's possible to have multiple remote repo locations per local repo?
Not sure if that's the right terminology.**
Perfect terminology. I have some projects that actually have three remote
repos. Depending on if I have a "fork" of a repository (fork's are something
we'll chat on later for sure), I could have two origins that even live on
GitHub: origin for my fork, and the project my fork came from. Lastly, if
I want to update to heroku.com, I can set a remote to there as well. This
should all become more and more clear as we interact with GitHub more
often! Let me know if you want me to continue to clarify.

**If you accidentally commit a sensitive file is there a way to remove both
file and history to ensure it can't be brought back?**
This can be a tricky situation! **If we haven't pushed to our remote** we can
reset this commit. If in this situation we added the passwords/sensitive
information in our last commit, we can use `git reset`. With git reset,
we can actually say "ok ok, undo those commits and pretend they never
happened" and we actually undo those commits from history. The command to
actually do this (with the previous commit) is: `git reset --hard HEAD^`.
The `HEAD^` part just says "the most recent commit". We can scoot back a
number of commits with the `HEAD~4` where 4 is the number of commits to
jump back. Let me know if I can specify this further, but we'll definitely
be touching on this in this class!

**Is there a CLI for pull requests?**
You can install a gem then "hub pull-request" on a branch.
The one I use is "hub".

**If you cherry pick in a change will Git recognize the history in blame?**
Yep, cherry-pick will result in the same thing.

**Can you please confirm that "origin" means destination on the server?**
Yep! It's essentially just a keyword or bookmark for a specific URL. We can
confirm this with: `git remote -v` and see that it's really a shorthand for
the URL to github.com

**Is forking on the CLI preferred?**
It's all about preferences! I personally use github.com, Matthew uses
a hub gem to do his forking and pull requests. Details about which can
be found here: https://github.com/defunkt/hub

### Day 2

**Why would you want this? I get a "clean" graph, but doesn't it confuse
the 'history'?**
Essentially it can just allow a cleaner history. This can be useful when
we want to undo some commits. As Matthew is showing with that graph, we
can easily undo commits and understand the order at which things have
come into the repo.

**Do you have any recommendation or best practice in terms of when to use
merge and when to use rebase?**
It really depends on what you're looking for: Clean history with the
ability to more easily go back to a safer point... or see where
commits/branches were merged into a branch (like master).
Each has pros and cons and is basically up to you =)

**For those planning to use  Git in a corporate environment (non-public
repos with 24/7  connectivity), how best would one use the combination
of branching _and_ cloning to support parallel development, integration, and
software release?  In other words, is there a better model other than
having a single canonical (archive) repo and individual "sandbox" repos?**
Personally, I've just had my own separate branches depending on what I'm
working on, and send those pull requests into the same repo. Pretend
for just a moment that our "contention" repository is private and we're all
on a software team. As I create some feature, I'd call it
"brentbeer-feature134" and create some changes. I could then send a pull
request from "githubtrainer/master" from "githubtrainer/brentbeer-feature134".
And we have an internal pull request from branch-to-branch within the same
[private] repo. Hope that makes sense!

**Can you show us an example of a merge conflict, and the best practice
for resolving it?**
A reminder that when the pull-request is not automatically mergeable,
there's an (i) that can show you how to merge it locally and update it!

**Can "remote" be seen as the place where "staging" (from yesterday)
happens, in the most recent picture that was shown**
It's more of a local "browser" cache from the upstream.

**Does rebasing mitigate the contention problem or just make for a
simpler graph?**
Hopefully it allows you to save yourself later if a problem were to arrive.
It's easier to reset and fix a problem after a rebase was done.
It also makes for a nice, easy-to-follow graph.

**Is the ability to automatically merge strictly checking if a merge is a
fast forward, or if it's not a fast forward is a test merge performed
somewhere?**
Nope. The reason it doesn't merge is because of the conflict Matthew just
demonstrated. The fast-forward vs non-fast-forward has no effect on if a
pull request can be automatically merged from the interface. Because of
multiple "merge strategies", github.com will act like the command line will.

**Does "cannot be automatically merged" necessarily imply conflict?**
Yep, it does.

**Your previous revert example was a surgical removal of that
point, rather than reverting TO that point**
Revert is simply a reversal of a previous commit. If we noticed an entire
commit was wrong, we could create a new commit to completely reverse it
and record that we reversed it.

**We all make mistakes. Can you show us some ways to undo blunders
(git force notwithstanding!) ... or perhaps suggest some exercises
to avoid future problems?**
`git revert`! It's a super great way to undo some commits while
maintaining that you've actually undone it. Reset removes it from history.

**How would we do the pull request from our command line?**
You can view the https://github.com/defunkt/hub repo if you would like
to read more about it.

**For development / integration / deployment, branches seem to be an
obvious architecture. Could you speak to other possibilities you find
yourself using, such as separate repositories?**
Branches are absolutely great for forming your different changes/features/etc
in a project in a structured way. Separate repositories can actually be
used inside of a current repository, these are often called "submodules"
and are quite a tricky subject!

**Is it true that a rebase never resolves conflicts?**
The idea, to me, is that rebase may save you from some
contention down the line, but it won't solve the conflicts for you.

**How can I remove a remote named 'official' after setting it with a
bad or the wrong URL?**
`git remote remove official`

**What is the tool for merging?**
It's just called "mergetool". You can look at this command with:
`git help mergetool`

**So this provides a cleaner commit history but doesn't reduce
contentions, right? I still get "tip of your current branch is behind"
when trying to push.**
It really adds the ability to mitigate contentions if they happened.
If there had been a bad commit that we merged in instead of rebasing it
may be harder to reset.

**Can we view this on GitHub itself?**
Absolutely! https://github.com/githubtrainer/contention/network
shows these commits from different authors.

**How can we see the graph?**
We can fire up "gitk &" as well to view locally.

**Is there a git hook to refuse these merges on main repo?**
This Stack Overflow link may tie you to more of what you're wanting:
http://stackoverflow.com/questions/5488442/pre-receive-hook-on-server-side-that-refuse-any-push-to-master-which-has-any-non

## Command History

### Day 1

    git --version
    mkdir githubfoundations
    cd githubfoundations
    git init project1
    open .
    mv first.txt project1
    cd project1
    git config user.name
    git config user.email
    git config --global user.name "Matthew McCullough"
    git config --global user.email "matthew@github.com"
    git commit -m "My first commit"
    git remote add origin https://github.com/githubstudent/project1.git
    git cc-off
    git push -u origin master
    mate first.txt
    git reset HEAD first.txt
    git add -p first.txt
    gitx
    git diff
    git diff HEAD
    mate build.log
    mate .gitignore
    git diff --staged
    git commit -m "Part one of changes"
    git add first.txt
    git commit -m "The remainder of the changes"
    git add .gitignore
    git commit -m "Ignoring build log files"
    echo JUNK > build2.log
    echo JUNKCHANGES >> build.log
    echo JUNKCHANGES >> anything.log
    git log
    history
    cp first.txt second.txt
    cp first.txt third.txt
    git commit -m "Copied files"
    git rm second.txt
    git rm third.txt
    git checkout -- second.txt
    git checkout HEAD -- second.txt
    git checkout HEAD -- third.txt
    git commit -m "Renaming the file"
    git log --stat -1
    git log --stat -1 -M
    git log --stat -M
    git log --stat -C
    git log --stat -C -C
    cp uno.txt fourth.txt
    mate fourth.txt
    git commit -m"Copied with slight modifications"
    git log -1 --stat -C
    git log -1 --stat -C -C
    z git_git
    git blame rerere.c
    git blame -C rerere.c
    cd -
    git branch feature
    git commit -a -m "Bug fix"
    git checkout feature
    cat uno.txt
    mate uno.txt
    mv uno.txt redesigned.txt
    git add -A .
    git status
    git commit -m "Feature work"
    git checkout master
    git merge feature
    cat redesigned.txt
    mkdir thousands
    cd thousands
    generaterandomfiles 9001 sample txt
    git commit -m "Over NINE THOUSAND new files"
    git branch
    pwd
    git clone https://github.com/github/gitignore.git
    cd gitignore
    git remote -v
    git fetch
    git fetch -v
    cd ..
    git clone https://github.com/githubstudent/hellogitworld.git
    cd hellogitworld
    ls
    mate matthewmcc.txt
    git add .
    git commit -m"Matthew added some brilliant codez"
    git push

### Day 2

    git help log
    cd -
    git checkout -b feature1
    generaterandomchanges 2 changes txt
    git push -u origin feature1
    hub browse
    vim build.gradle
    git commit -a -m"Broke it"
    git revert HEAD~1
    git reset --hard
    git revert HEAD
    git remote add official https://github.com/githubtrainer/hellogitworld.git
    git ls-remote official
    git help remote
    git fetch official
    git branch -r
    git remote -v
    git merge official/master
    git diff origin/master --stat
    git diff origin/master..HEAD --stat
    git push origin master
    git branch feature3
    git checkout feature3
    git push -u origin feature3
    hub pull-request
    hub
    hub help pull-request
    hub pull-request -b githubtrainer:master -h githubstudent:feature3
    to.scratch
    git clone https://github.com/githubtrainer/hellogitworld.git hgwtrainer
    cd hgwtrainer
    generaterandomchanges 2 sample txt
    git checkout -b githubstudent-feature3 master
    git pull https://github.com/githubstudent/hellogitworld.git feature3
    cat sample1.txt
    git checkout --ours -- sample1.txt
    git mergetool -- sample2.txt
    git commit
    git merge githubstudent-feature3
    git help mergetool
    mate ~/.gitconfig
    git init contention
    echo HI > matthewwashere.txt
    git remote add origin https://github.com/githubtrainer/contention.git
    git push -u origin master
    git commit -m"Contention"
    git push -u origin master:master
    rm -rf contention
    git clone https://github.com/githubtrainer/contention.git
    git add .
    git commit -m"Matthew was here"
    gitx
    gitk &
    mate matthewmcc.txt
    git commit -a -m "Matthews change"
    git revert 205faf
    mate  brntbeer.txt
    git commit -a -m"Matthew changing brents file"
    git pull --rebase
    cat brntbeer.txt
    git mergetool
    git rebase --continue
    git log -2
    git show '5ef6$'
    git show HEAD^
    git show HEAD^^
    git show HEAD^^^
    git show HEAD^^^^
    git show master~5
    git show master~10
    git show HEAD^^^^^^^^^^^^^^^^^^^^^^
    git show HEAD^^^^^^^^^^^^^^^^^^^^^
    cp -r contention brokeit
    cd brokeit
    git rev-parse HEAD
    vim .git/objects/3a/e83e7d7a4a9cba388a5ab192cc213e55c0aea8
    c d..
    cd contention
    cat .git/refs/heads/master
    vim .git/refs/heads/handcrafted
    git branch
    git checkout handcrafted
    touch newfile
    git add newfile
    git commit -m"New file"
    git tag GOODPOINT1 9da2414a068866023cfa867fd399ab50d2b31a96
    git tag -a GOODPOINT2 9da2414a068866023cfa867fd399ab50d2b31a96
    git show GOODPOINT1
    git show GOODPOINT2
    git pull
    git checkout master
    git pull
    git push
    git push --tags
    git push origin GOODPOINT1
    git tag -d GOODPOINT
    git tag -d GOODPOINT1
    git tag -d GOODPOINT2
    git fetch -p
    git fetch
    git remote -p origin
    git fetch -p origin
    git svn clone --stdlayout http://ambientideas.unfuddle.com/svn/ambientideas_sample11-svnscm hgwsub
    cd hgwsub
    git log
    ls
    git commit -a -m"Transaction 1"
    echo STUFF >> newfile2.txt
    git commit -a -m"Transaction 2"
    git svn dcommit
    cd githubfoundations
    svn co https://github.com/githubtrainer/contention.git/trunk consub
    cd consub
    cd ..
    cd hellogitworld
    git reset --hard HEAD^^
    git reset --soft HEAD~5
    git status


text:
#if !defined(SPIRIT_X3_RAW_APRIL_9_2007_0912AM)
#define SPIRIT_X3_RAW_APRIL_9_2007_0912AM

#include <boost/spirit/home/x3/core/skip_over.hpp>
#include <boost/spirit/home/x3/core/parser.hpp>
#include <boost/spirit/home/x3/support/traits/move_to.hpp>
#include <boost/range/iterator_range.hpp>

namespace boost { namespace spirit { namespace x3
{
    // this is a pseudo attribute type indicating that the parser wants the
    // iterator range pointing to the [first, last) matching characters from
    // the input iterators.
    struct raw_attribute_type {};

    template <typename Subject>
    struct raw_directive : unary_parser<Subject, raw_directive<Subject>>
    {
        typedef unary_parser<Subject, raw_directive<Subject> > base_type;
        typedef raw_attribute_type attribute_type;
        static bool const handles_container = Subject::handles_container;
        typedef Subject subject_type;

        raw_directive(Subject const& subject)
          : base_type(subject) {}

        template <typename Iterator, typename Context
            , typename RContext, typename Attribute>
        bool parse(Iterator& first, Iterator const& last
          , Context const& context, RContext& rcontext, Attribute& attr) const
        {
            x3::skip_over(first, last, context);
            Iterator i = first;
            if (this->subject.parse(i, last, context, rcontext, unused))
            {
                traits::move_to(first, i, attr);
                first = i;
                return true;
            }
            return false;
        }

        template <typename Iterator, typename Context, typename RContext>
        bool parse(Iterator& first, Iterator const& last
          , Context const& context, RContext& rcontext, unused_type) const
        {
            return this->subject.parse(first, last, context, rcontext, unused);
        }
    };

    struct raw_gen
    {
        template <typename Subject>
        raw_directive<typename extension::as_parser<Subject>::value_type>
        operator[](Subject const& subject) const
        {
            return { as_parser(subject) };
        }
    };

    auto const raw = raw_gen{};
}}}

#endif


text:
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');

// Delete Options
Option::delete('sandbox');
Option::delete('sandbox_template');


text:
package eu.modernmt.decoder.phrasebased;

import eu.modernmt.decoder.DecoderFeature;
import eu.modernmt.model.Sentence;
import eu.modernmt.model.Translation;
import eu.modernmt.model.Word;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * Created by davide on 02/12/15.
 */
class TranslationXObject {

    static class Hypothesis {
        public String text;
        public float totalScore;
        public String fvals;

        public Hypothesis(String text, float totalScore, String fvals) {
            this.text = text;
            this.totalScore = totalScore;
            this.fvals = fvals;
        }

        public TranslationHypothesis getTranslationHypothesis(Sentence source, HashMap<String, DecoderFeature> features) {
            HashMap<DecoderFeature, float[]> scores = new HashMap<>();

            String[] tokens = fvals.trim().split("\\s+");

            DecoderFeature feature = null;
            float[] weights = new float[tokens.length];
            int index = 0;

            for (int i = 0; i < tokens.length + 1; i++) {
                String token = i < tokens.length ? tokens[i] : null;

                if (token == null || token.endsWith("=")) {
                    if (feature != null)
                        scores.put(feature, Arrays.copyOf(weights, index));

                    if (token != null)
                        feature = features.get(token.substring(0, token.length() - 1));

                    index = 0;
                } else {
                    weights[index++] = Float.parseFloat(token);
                }
            }

            return new TranslationHypothesis(XUtils.explode(this.text), source, null, this.totalScore, scores);
        }
    }

    public String text;
    public Hypothesis[] nbestList;
    public int[] alignment;

    public TranslationXObject(String text, Hypothesis[] nbestList, int[] alignment) {
        this.text = text;
        this.nbestList = nbestList;
        this.alignment = alignment;
    }

    public Translation getTranslation(Sentence source, HashMap<String, DecoderFeature> features) {
        Word[] words = XUtils.explode(text);

        Translation translation = new Translation(words, source, XUtils.decodeAlignment(alignment));

        if (nbestList != null && nbestList.length > 0) {
            List<Translation> nbest = new ArrayList<>(nbestList.length);

            for (Hypothesis hyp : nbestList)
                nbest.add(hyp.getTranslationHypothesis(source, features));

            translation.setNbest(nbest);
        }

        return translation;
    }

}


text:
using System.Linq;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Logging;
using Umbraco.Core.Macros;
using Umbraco.Core.ObjectResolution;
using Umbraco.Core.Profiling;
using Umbraco.Web;
using Umbraco.Web.Macros;
using umbraco;

namespace Umbraco.Tests.Resolvers
{
    [TestFixture]
    public class XsltExtensionsResolverTests : ResolverBaseTest
    {
        [TearDown]
        public void TearDown()
        {
            ActionsResolver.Reset();
        }

        // NOTE
        // ManyResolverTests ensure that we'll get our actions back and ActionsResolver works,
        // so all we're testing here is that plugin manager _does_ find our actions
        // which should be ensured by PlugingManagerTests anyway, so this is useless?
        // maybe not as it seems to handle the "instance" thing... so we test that we respect the singleton?
        [Test]
        public void Find_All_Extensions()
        {
            XsltExtensionsResolver.Current = new XsltExtensionsResolver(
                new ActivatorServiceProvider(),ProfilingLogger.Logger,
                () => PluginManager.ResolveXsltExtensions());

            Resolution.Freeze();

            var extensions = XsltExtensionsResolver.Current.XsltExtensions;
            Assert.AreEqual(3, extensions.Count());

            Assert.IsTrue(extensions.Select(x => x.ExtensionObject.GetType()).Contains(typeof (XsltEx1)));
            Assert.IsTrue(extensions.Select(x => x.ExtensionObject.GetType()).Contains(typeof(XsltEx2)));
            Assert.AreEqual("test1", extensions.Single(x => x.ExtensionObject.GetType() == typeof(XsltEx1)).Namespace);
            Assert.AreEqual("test2", extensions.Single(x => x.ExtensionObject.GetType() == typeof(XsltEx2)).Namespace);
        }

        #region Classes for tests

        [Umbraco.Core.Macros.XsltExtension("test1")]
        public class XsltEx1
        {

        }

        //test with legacy one
        [umbraco.XsltExtension("test2")]
        public class XsltEx2
        {
        }

        #endregion
    }
}


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

<title>Uses of Interface net.jini.discovery.DiscoveryLocatorManagement (River-Internet vtrunk API Documentation (internals))</title>
<meta name="date" content="2016-03-28">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
net.jini.discovery.DiscoveryLocatorManagement

Packages that use DiscoveryLocatorManagement

Package
Description

net.jini.discovery

These are utility classes and interfaces that conform to the discovery and join
protocol defined in the Jini Discovery and Join Specification.

Uses of DiscoveryLocatorManagement in net.jini.discovery

Classes in net.jini.discovery that implement DiscoveryLocatorManagement

Modifier and Type
Class and Description

(package private) class
AbstractLookupDiscoveryManager

This package private superclass of LookupDiscoverManager exists for
 safe construction of LookupDiscoveryManager's state, while retaining
 backward compatibility of the API.

(package private) class
AbstractLookupLocatorDiscovery

This package private superclass of LookupLocatorDiscovery exists for
 safe construction of LookupLocatorDiscovery's state, while retaining
 backward compatibility of the API.

class
LookupDiscoveryManager

This class is a helper utility class that organizes and manages all
 discovery-related activities on behalf of a client or service.

class
LookupLocatorDiscovery

This class encapsulates the functionality required of an entity that
 wishes to employ the unicast discovery protocol to discover a lookup
 service.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright 2007-2013, multiple authors.
Licensed under the Apache License, Version 2.0, see the NOTICE file for attributions.


text:
'use strict';

/**
 * Stringify PostCSS node including its raw "before" string.
 *
 * @param {import('postcss').Node} node
 *
 * @returns {string}
 */
module.exports = function (node) {
	let result = '';

	if (node.raws.before) {
		result += node.raws.before;
	}

	result += node.toString();

	return result;
};


text:
from django.conf.urls import url, include
from django.views.generic.base import RedirectView

from rest_framework import routers
from rest_framework import renderers
from dplace_app import views, api_views

router = routers.DefaultRouter()
router.register(r'variables', api_views.VariableViewSet)
router.register(r'categories', api_views.CategoryViewSet)
router.register(r'codes', api_views.CodeDescriptionViewSet)
router.register(r'values', api_views.ValueViewSet)
router.register(r'societies', api_views.SocietyViewSet)
router.register(r'isocodes', api_views.ISOCodeViewSet)
router.register(r'language_families', api_views.LanguageFamilyViewSet)
router.register(r'languages', api_views.LanguageViewSet)
router.register(r'language_trees', api_views.LanguageTreeViewSet)
router.register(r'geographic_regions', api_views.GeographicRegionViewSet)
router.register(r'sources', api_views.SourceViewSet)
router.register(r'language_tree_labels', api_views.LanguageTreeLabelsViewSet)

urlpatterns = [

    #   !!!!!!  Important  !!!!!!
    #   To reduce traffic caused by bots, spiders, etc
    #   all URL paths with "...?param1=a&param2=b" etc. will return HTTP 404
    #   It's set in:
    #   - "views.py" => def angular(request): [for all pages passed to angular]
    #   - "api_views.py" => def detail(self, request, society_id): [for /society/...?...&]

    url(r'^$', RedirectView.as_view(url='angular/', permanent=True), name='home'),

    # Redirect all static icon images (different sizes) crawled by any sites and bots
    url(r'^favicon\.ico/?$', RedirectView.as_view(url='/static/images/icons/favicon.ico')),
    url(r'^apple\-touch\-icon(\-precomposed)?\.png/?$', RedirectView.as_view(url='/static/images/icons/D-PLACE_Favicon_57x57.png')),
    url(r'^touch\-icon\iphone-\.png/?$', RedirectView.as_view(url='/static/images/icons/D-PLACE_Favicon_57x57.png')),
    url(r'^(apple\-)?touch\-icon\-(?P<size>.+?)(\-precomposed)?\.png/?$', RedirectView.as_view(url='/static/images/icons/D-PLACE_Favicon_%(size)s.png')),
    url(r'^browserconfig\.xml/?$', RedirectView.as_view(url='/static/images/icons/browserconfig.xml')),

    # This is needed in order to auto-generate sitemaps links
    # and to pass only valid paths to angular
    url(r'^home/?$', views.angular),
    url(r'^search/?$', views.angular, name='search'),
    url(r'^societies/?$', views.angular, name='societies'),
    url(r'^about/?$', views.angular, name='about'),
    url(r'^howto/?$', views.angular, name='howto'),
    url(r'^howtocite/?$', views.angular, name='howtocite'),
    url(r'^source/?$', views.angular, name='source'),
    url(r'^technology/?$', views.angular, name='technology'),
    url(r'^legal/?$', views.angular, name='legal'),
    url(r'^team/?$', views.angular, name='team'),
    url(r'^publication/?$', views.angular, name='publication'),

    url(r'^society/(?P<society_id>.*)$',
        api_views.SocietyViewSet.as_view(
            {'get': 'detail'},
            renderer_classes=[renderers.TemplateHTMLRenderer]
        ),
        name='view_society'),
    url(r'^language/(?P<glottocode>.*)$',
        views.view_language,
        name='view_language'),
    url(r'^download$', views.download_file, name='download'),
    url(r'^angular/$', views.angular, name='angular'),
    # API
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^api/v1/', include(router.urls)),
    url(r'^api/v1/find_societies', api_views.find_societies, name='find_societies'),
    url(r'^api/v1/min_and_max', api_views.get_min_and_max, name="min_and_max"),
    url(r'^api/v1/cont_variable', api_views.bin_cont_data, name="cont_variable"),
    url(r'^api/v1/get_categories', api_views.get_categories, name="get_categories"),
    url(r'^api/v1/get_dataset_sources',
        api_views.get_dataset_sources,
        name="get_dataset_sources"),
    url(r'^api/v1/csv_download', api_views.csv_download, name='csv_download'),
    url(r'^api/v1/trees_from_societies', api_views.trees_from_societies, name='trees_from_societies'),

    # catch anything else and let decide angular what to do
    # [is not a good idea for stopping bots]
    # url(r'^.+?/$', views.angular),

]


text:
layout: page
title: Rain Music Conference
date: 2016-05-24
author: Andrew Mayer
tags: weekly links, java
status: published
summary: Suspendisse turpis neque, gravida et dapibus.
banner: images/banner/office-01.jpg
booking:
  startDate: 09/23/2019
  endDate: 09/28/2019
  ctyhocn: FRBSFHX
  groupCode: RMC
published: true
---
Nam ac fringilla lorem. Phasellus fermentum vel orci nec interdum. Proin ornare molestie elit, vel accumsan sapien eleifend ac. Nunc scelerisque gravida neque ut commodo. Ut suscipit lorem eget porta porta. Sed molestie euismod eros, at sagittis sapien aliquet in. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nunc eget lacinia velit. Pellentesque nec dictum sapien. Quisque vel gravida felis, dictum porta purus. Aliquam dapibus et ante ac maximus. Nullam dictum leo tempor, rhoncus ipsum eu, commodo nulla. Integer rutrum faucibus sem, sit amet lobortis mi. Donec tristique metus quis magna malesuada, sit amet condimentum magna blandit.

* Mauris ut massa sed ex commodo fringilla eget et enim
* Curabitur laoreet magna ut erat tincidunt, vitae consectetur enim maximus
* Pellentesque pretium diam vitae magna laoreet, a pharetra lacus porta.

Vivamus tristique hendrerit erat, quis tincidunt enim pharetra sed. Quisque venenatis est quis semper ultrices. Pellentesque vulputate urna nisi, et convallis tortor efficitur non. Donec placerat faucibus enim, quis fringilla mauris. Donec pulvinar lorem ut interdum mollis. Aliquam imperdiet quam magna, dignissim laoreet nisl imperdiet id. Praesent in mollis lorem.


text:
package main

// Prober is satisfied by http.prober and tcp.prober
type Prober interface {
	Probe(address string) error
}