text:
from __future__ import print_function

import os
import subprocess,os.path

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.collections import LineCollection

from shapely import geometry

from . import field

from ..utils import point_in_polygon

def plot_geo(geo):
    def plot_ring(r):
        points = np.array(r.coords)
        plt.plot( points[:,0],points[:,1],'k' )
    plot_ring(geo.exterior)
    for r in geo.interiors:
        plot_ring(r)

def geo2poly(geo_poly,poly_filename):
    """
    given a polygon geometry, write a triangle compatible poly
    file
    """
    print("Writing poly file ", poly_filename)

    # and then only the exterior ring:
    point_list = np.array(geo_poly.exterior.coords)
    # which at least sometimes has a duplicate node at the end that
    # we don't want
    if np.all(point_list[0]==point_list[-1]):
        point_list = point_list[:-1]

    npoints = point_list.shape[0]

    # triangle wants the basic planar-straight-line-graph
    poly_fp = open(poly_filename,'wt')

    # first line is
    # First line: <# of vertices> <dimension (must be 2)>  <# of attributes> <# of boundary markers (0 or 1)>
    poly_fp.write("%i 2 0 0\n"%(npoints))
    # Write out vertices
    for i in range(npoints):
        # <vertex #> <x> <y>  [attributes] [boundary marker]
        poly_fp.write("%i %f %f\n"%(i,point_list[i,0],point_list[i,1]))
    # Write out segments
    # <# of segments> <# of boundary markers (0 or 1)>
    poly_fp.write("%i 0\n"%(npoints))
    for i in range(npoints):
        # <segment #> <endpoint> <endpoint>  [boundary marker]
        poly_fp.write("%i %i %i\n"%(i,i,(i+1)%npoints))
    # number of holes, which for the moment we ignore:
    poly_fp.write("0\n")
    poly_fp.close()

def load_triangle_nodes(node_filename):
    """
    load nodes as output by triangle
    """
    fp = open(node_filename,'rt')
    n_nodes, dim, nattrs, has_boundary_markers = map(int,fp.readline().split())

    nodes = np.zeros( (n_nodes,dim), np.float64)

    for i in range(n_nodes):
        idx,nodes[i,0],nodes[i,1] = map(float,fp.readline().split()[:3])
    fp.close()
    return nodes

def load_triangle_edges(edge_filename):
    """ load finite edges from output from triangle
    """
    fp = open(edge_filename,'rt')
    n_edges,n_markers = map(int,fp.readline().split())
    # indexed into corresponding node file:
    edges = []

    for i in range(n_edges):
        vals=map(int,fp.readline().split()[:3])
        if vals[2] == -1:
            continue # it's a ray
        edges.append( vals[1:3] )
    fp.close()

    return np.array(edges)

def plot_voronoi(poly_filename):
    vor_node = poly_file.replace('.poly','.1.v.node')
    vor_edge = poly_file.replace('.poly','.1.v.edge')

    # load the vor nodes and show them:
    vor_nodes = load_triangle_nodes(vor_node)
    plt.plot(vor_nodes[:,0],vor_nodes[:,1],'r+')

    vor_edges = load_triangle_edges(vor_edge)

    # plot the finite edges:
    # build up the list of lines:
    all_lines = vor_nodes[vor_edges]
    coll = LineCollection(all_lines)
    ax = plt.gca()
    ax.add_collection(coll)

def load_triangle_elements(ele_file):
    fp = open(ele_file,'rt')
    n_elts, nodes_per_elt, n_attrs = map(int,fp.readline().split())

    tris = np.zeros( (n_elts,3), np.int32)

    for i in range(n_elts):
        dummy, tris[i,0],tris[i,1],tris[i,2] = map(int,fp.readline().split()[:4])
    return tris

def plot_elements(tris,nodes):
    edges = set()
    for t in range(tris.shape[0]):
        t_verts = np.sorted(tris[t])
        edges.add( (t_verts[0],t_verts[1]) )
        edges.add( (t_verts[0],t_verts[2]) )
        edges.add( (t_verts[1],t_verts[2]) )

    edges = np.array(list(edges))

    all_lines = nodes[edges]
    coll = LineCollection(all_lines)
    ax = plt.gca()
    ax.add_collection(coll)

# that writes out these files:
# node_file = poly_file.replace('.poly','.1.node')
# element_file = poly_file.replace('.poly','.1.ele')

# tris = load_triangle_elements(element_file)
# nodes = load_triangle_nodes(node_file)
# plot_elements(tris,nodes)

# Look into how to compute the local radius based on the voronoi
# diagram:

# Find the radius at each voronoi center:
#  1. load the voronoi nodes:

# some sort of issue loading the tri information - might be worth
# trying it w/o any islands, but first taking a look...
#  nodes: 2-D, 0 attributes, 1 boundary marker
#  8690 nodes (compare to 8003 nodes in input)

class Graph(object):
    def __init__(self,basename):
        node_file = basename + '.node'
        if os.path.exists(node_file):
            self.nodes = load_triangle_nodes(node_file)
        else:
            self.nodes = None

        edge_file = basename + '.edge'
        if os.path.exists(edge_file):
            self.edges = load_triangle_edges(edge_file)
        else:
            self.edges = None

        element_file = basename + '.ele'
        if os.path.exists(element_file):
            self.elements = load_triangle_elements(element_file)
        else:
            self.elements = None

    def plot(self,colors=None):
        if self.edges is not None:
            self.plot_edges(colors=colors)
        else:
            self.plot_elements(colors=colors)

    def plot_edges(self,colors=None):
        all_lines = self.nodes[self.edges]
        coll = LineCollection(all_lines)
        if colors is not None:
            coll.set_array(colors)
        ax = plt.gca()
        ax.add_collection(coll)
        plt.draw()

    def plot_elements(self,colors=None):
        i = np.array([0,1,2,0])

        all_lines = self.nodes[self.elements[:,i]]
        coll = LineCollection(all_lines)
        if colors is not None:
            coll.set_array(colors)
        ax = plt.gca()
        ax.add_collection(coll)
        plt.draw()

    _vcenters = None
    def vcenters(self):
        if self.elements is None:
            raise Exception("vcenters() called but elements is None")

        if self._vcenters is None:
            # just copied from trigrid
            self._vcenters = np.zeros(( len(self.elements),2 ), np.float64)

            p1x = self.nodes[self.elements[:,0]][:,0]
            p1y = self.nodes[self.elements[:,0]][:,1]
            p2x = self.nodes[self.elements[:,1]][:,0]
            p2y = self.nodes[self.elements[:,1]][:,1]
            p3x = self.nodes[self.elements[:,2]][:,0]
            p3y = self.nodes[self.elements[:,2]][:,1]

            # taken from TRANSFORMER_gang.f90
            dd=2.0*((p1x-p2x)*(p1y-p3y) -(p1x-p3x)*(p1y-p2y))
            b1=p1x**2+p1y**2-p2x**2-p2y**2
            b2=p1x**2+p1y**2-p3x**2-p3y**2
            xc=(b1*(p1y-p3y)-b2*(p1y-p2y))/dd
            yc=(b2*(p1x-p2x)-b1*(p1x-p3x))/dd

            self._vcenters[:,0] = xc
            self._vcenters[:,1] = yc
        return self._vcenters
    _radii = None
    def radii(self):
        if self._radii is None:
            vcenters = self.vcenters()
            vcorners = self.nodes[self.elements[:,0]]
            self._radii = np.sqrt( ((vcenters - vcorners)**2).sum(axis=1) )

        return self._radii

    _nodes2elements = None
    def nodes2elements(self,n1,n2):
        if self._nodes2elements is None:
            e2e = {}
            print("building hash of edges to elements")
            for c in range(len(self.elements)):
                for i in range(3):
                    a = self.elements[c,i]
                    b = self.elements[c,(i+1)%3]
                    if a > b:
                        a,b = b,a

                    k = (a,b)

                    if not e2e.has_key(k):
                        e2e[k] = []

                    e2e[ k ].append(c)

            self._nodes2elements = e2e

            print("done")

        if n1 > n2:
            n1,n2 = n2,n1
        return self._nodes2elements[(n1,n2)]

class Boundary(object):
    n_cleaned = 0 # bean-counter for remove_repeated

    def __init__(self,geo=None,nodes=None,clean_geo=True):
        """
        geo: a Shapely polygon (with holes, ok)
        nodes: an array of points, taken to be the exterior ring of a polygon
        clean_geo: if true, traverse the rings and removed repeated nodes
        """

        if geo:
            all_nodes = []
            all_edges = []
            holes = []
            start_n = 0

            rings = [geo.exterior] + list(geo.interiors)
            for ring in rings:
                orig_nodes = np.array(ring.coords)
                if clean_geo:
                    orig_nodes = self.remove_repeated(orig_nodes)

                # remove repeated last coordinate
                these_nodes = orig_nodes[:-1]

                n_nodes = these_nodes.shape[0]
                n = np.arange(n_nodes)
                these_edges = start_n + np.transpose( np.array([n,(n+1)%n_nodes]) )

                all_nodes.append(these_nodes)
                all_edges.append(these_edges)
                start_n += n_nodes

                ring_poly = geometry.Polygon( these_nodes )
                point_inside = point_in_polygon(ring_poly)
                holes.append(point_inside)

            self.nodes = np.concatenate( all_nodes ) # array(geo.exterior.coords)[:-1,:]
            self.edges = np.concatenate( all_edges )
            self.holes = np.array(holes[1:])
            self.geo = geo

            if clean_geo:
                print("Removed %i repeated nodes"%self.n_cleaned)
        else:
            self.nodes = nodes

            n_nodes = self.nodes.shape[0]
            # construct an edge array that just matches consecutive
            # nodes
            n = np.arange(n_nodes)
            self.edges = np.transpose(np.array([n,(n+1)%n_nodes]))
            self.holes = np.zeros((0,2))

        # automatically find a basic lower-bound length scale
        min_dist_sqr = (((self.nodes[1:] - self.nodes[:-1])**2).sum(axis=1)).min()
        self.min_edge_length = np.sqrt(min_dist_sqr)
        #print("Minimum edge length in boundary inputs is ",self.min_edge_length)

        self._vor = None
        self._tri = None

    _nodes2edge = None
    def nodes2edge(self,a,b):
        # if a,b is boundary edge, return the edge id, otherwise return None
        if self._nodes2edge is None:
            self._nodes2edge = {}

            for e in range(len(self.edges)):
                c,d = self.edges[e]
                if c > d:
                    d,c = c,d

                self._nodes2edge[ (c,d) ] = e
        if a>b:
            b,a = a,b
        k = (a,b)
        if self._nodes2edge.has_key(k):
            return self._nodes2edge[k]
        else:
            return None

    def remove_repeated(self,ring):
        """Remove repeated nodes from an array.
        """
        mask = np.zeros( len(ring),np.bool8 )

        mask[:-1] = np.all(ring[:-1]==ring[1:],axis=1)

        # for i in range(len(ring)-1):
        #     if all(ring[i+1]==ring[i]):
        #         mask[i] = True
        self.n_cleaned += mask.sum()

        return ring[~mask,:]

    def vor(self):
        if self._vor is None:
            self.triangulate()
        return self._vor
    def triangulation(self):
        if self._tri is None:
            self.triangulate()
        return self._tri

    def plot(self,colors=None):
        all_lines = self.nodes[self.edges]
        coll = LineCollection(all_lines)
        if colors is not None:
            coll.set_array(colors)
        ax = plt.gca()
        ax.add_collection(coll)

        # if len(self.holes) > 0:
        #     plot(self.holes[:,0],self.holes[:,1],'ro')

        plt.draw()
    def plot_lines(self):
        plt.plot(self.nodes[:,0], self.nodes[:,1], 'k')

    def split_edges(self,edge_indexes):
        new_nodes = np.nan * np.ones((len(edge_indexes),2), np.float64)
        new_edges = -1 * np.ones((len(edge_indexes),2), np.int32)

        # remember what the next free edge and node are
        next_edge = self.edges.shape[0]
        next_node = self.nodes.shape[0]

        # extend nodes and edges:
        self.nodes = np.concatenate( (self.nodes,new_nodes), axis=0 )
        self.edges = np.concatenate( (self.edges,new_edges), axis=0 )

        ordering = np.arange(self.nodes.shape[0],dtype=np.float64)
        ordering[next_node:] = -1

        for i in range(len(edge_indexes)):
            # node indices to the old endpoints
            pntA,pntC = self.edges[edge_indexes[i]]
            pntB = next_node+i

            self.nodes[pntB] = 0.5*(self.nodes[pntA] + self.nodes[pntC])

            self.edges[edge_indexes[i],1] = pntB
            self.edges[next_edge+i] = [pntB,pntC]
            ordering[pntB] = 0.5*(ordering[pntA]+ordering[pntC])

        new_order = np.argsort(ordering)
        # so j = new_order[i] means that old node j will get mapped
        # to new node i
        self.nodes = self.nodes[new_order]

        # the "inverse" of new_order
        mapping = np.argsort(new_order)

        # not sure about this.  too late to prove it to myself that
        # it works short of just testing it
        self.edges = mapping[self.edges]
        self._nodes2edge = None

    def write_poly(self,poly_filename):
        """ write a triangle compatible poly file
        """
        # and then only the exterior ring:
        point_list = self.nodes

        # probably unnecessary
        if np.all(point_list[0]==point_list[-1]):
            raise Exception("Boundary should have already stripped any repeated endpoints")

        npoints = point_list.shape[0]

        # triangle wants the basic planar-straight-line-graph
        poly_fp = open(poly_filename,'wt')

        # first line is
        # First line: <# of vertices> <dimension (must be 2)>  <# of attributes> <# of boundary markers (0 or 1)>
        poly_fp.write("%i 2 0 0\n"%(npoints))
        # Write out vertices
        for i in range(npoints):
            # <vertex #> <x> <y>  [attributes] [boundary marker]
            poly_fp.write("%i %f %f\n"%(i,point_list[i,0],point_list[i,1]))
        # Write out segments
        # <# of segments> <# of boundary markers (0 or 1)>
        poly_fp.write("%i 0\n"%(npoints))
        for i in range(len(self.edges)):
            # <segment #> <endpoint> <endpoint>  [boundary marker]
            poly_fp.write("%i %i %i\n"%(i,self.edges[i,0],self.edges[i,1]))
        # number of holes
        poly_fp.write( "%d\n"%self.holes.shape[0] )
        for i in range(self.holes.shape[0]):
            poly_fp.write("%d %f %f\n"%(i, self.holes[i,0], self.holes[i,1]) )
        poly_fp.close()

    # def triangulate(self):
    #     ### Run some triangle stuff:
    #     poly_file = "test2.poly"
    #     self.write_poly(poly_file)
    #
    #     cmd = "%s -e -D -p -v %s"%(triangle_path,poly_file)
    #     subprocess.call(cmd,shell=True) # ,stdout=file('/dev/null','w') )
    #
    #     # probably we should get the real geometry that was used, otherwise
    #     # things will get confusing
    #     self.read_poly('test2.1.poly')
    #
    #     self._tri = Graph('test2.1')
    #     self._vor = VoronoiDiagram('test2.1.v')

    def read_poly(self,poly_file):
        """ After triangulating, there may have been Steiner points
        added, and they will exist in the output .poly file.
        This reads that file and replaces self.nodes and self.edges
        with the information in the given polyfile.  Holes will be
        kept the same (although it would be valid to re-read holes, too.

        """
        poly_fp = open(poly_file,'rt')
        new_edges = []
        new_nodes = []

        n_nodes,dim,n_attrs,n_markers = map(int,poly_fp.readline().split())
        if n_nodes == 0:
            # print("Reading nodes from separate file")
            new_nodes = load_triangle_nodes(poly_file.replace('.poly','.node'))
        else:
            raise Exception("Not ready for reading inline nodes")

        n_segments,n_markers = map(int,poly_fp.readline().split())
        new_edges = np.zeros((n_segments,dim), np.int32)

        for i in range(n_segments):
            vals = map(int,poly_fp.readline().split())
            new_edges[i] = vals[1:3]

        # install the new data:
        self.edges = new_edges
        self.nodes = new_nodes
        self.geo = None
        self.src = poly_file

    def subdivide(self):
        """ Find edges that need to be sampled with smaller
        steps and divide them into two edges.
        returns the number of new edges / nodes

        method: calculate voronoi radii
           iterate over edges in boundary
           for each edge, find the voronoi point that they have
             in common.  So this edge should be part of a triangle,
             and we are getting the center of that triangle.

           the voronoi radius with the distance between the voronoi
             point and the edge.  If the edge is too long and needs to
             be subdivided, it will be long (and the voronoi radius large)
             compared to the distance between the edge and the vor. center.

             Can this be done without the vor. radii?
               need
        """

        # the old way calculated voronoi radii and searched for nodes
        # on those circumcircles.  For subdividing, we just need to match
        # each edge with the one voronoi point it belongs to.

        # vor = self.vor()
        # vor.calc_radii(self.nodes)

        # the new way - calculated voronoi points directly from the triangles
        # in the delaunay triangulation, then match with edges with a hash
        # on edge [a,b] node pairs
        triangulation = self.triangulation()
        vcenters = triangulation.vcenters()

        n_edges = self.edges.shape[0]
        to_subdivide = np.zeros(n_edges, np.float64)

        # the only way this works is for the boundary nodes to be exactly
        # the same, so we go boundary edge -> nodes -> delaunay element
        if np.any( self.nodes != triangulation.nodes ):
            raise Exception("Triangulation and boundary use different nodes.")

        print("Choosing edges to subdivide")
        for i in range(n_edges): # over boundary edges
            a,b = self.edges[i]
            elements = triangulation.nodes2elements(a,b)

            if len(elements) != 1:
                print("Edge %d,%d mapped to elements %s"%(a,b,elements))
                raise Exception("Boundary edges should map to exactly one element")

            element = elements[0]

            # compute the point-line distance between
            # this edge and the v center, then compare to
            # the distance from the endpoint to that
            # vcenter
            pntV = vcenters[element]
            pntA = self.nodes[a]
            pntB = self.nodes[b]

            v_radius = np.sqrt( ((pntA-pntV)**2).sum() )
            line_clearance = np.sqrt( (( 0.5*(pntA+pntB) - pntV)**2).sum() )

            if v_radius > 1.2*line_clearance and v_radius > self.min_edge_length:
                # second check - make sure that neither AC nor BC are also on the
                # boundary
                p1,p2,p3 = triangulation.elements[element]
                count = 0
                if self.nodes2edge(p1,p2) is not None:
                    count += 1
                if self.nodes2edge(p2,p3) is not None:
                    count += 1
                if self.nodes2edge(p3,p1) is not None:
                    count += 1

                if count == 1:
                    to_subdivide[i] = 3
                elif count == 0:
                    global bad_boundary
                    bad_boundary = self
                    print("While looking at edge %d=(%d,%d)"%(i,a,b))
                    raise Exception("We should have found at least 1 boundary edge")
                elif count == 3:
                    print("WARNING: Unexpected count of boundary edges in one element: ",count)
                # if 2, then it's a corner and we probably don't want to subdivide

        self.to_subdivide = to_subdivide
        bad_edges = where(to_subdivide)[0]
        self.split_edges( bad_edges )

        # invalidate these:
        self._vor = None
        self._tri = None
        return len(bad_edges)

    def subdivide_iterate(self):
        while 1:
            n_new = self.subdivide()
            print("Subdivide made %d new nodes"%n_new)
            if n_new == 0:
                break

class VoronoiDiagram(Graph):
    radii = None
    dual_nodes = None
    dual_lookup = {}

    def calc_radii(self,del_nodes):
        """  for each of the voronoi points, find it's radius and
        which delaunay points are responsible for it.
        """
        n_nodes = self.nodes.shape[0]

        self.radii = np.zeros( n_nodes, np.float64)
        self.dual_nodes = [None]*n_nodes
        self.dual_lookup = {} # map dual node index to list of vcenters

        # this is where all the time goes!
        # so make a field for the delaunay nodes that will speed up finding them
        I = np.arange(len(del_nodes))

        del_field = field.XYZField(del_nodes, 'nope')
        del_field.build_index()

        for i in range(n_nodes):
            if i % 1000 == 0:
                print(i)

            # find the nearest one...
            nearest = del_field.nearest(self.nodes[i])
            min_radius = np.sqrt( ((del_nodes[nearest] - self.nodes[i])**2).sum() )
            all_near = del_field.within_r(self.nodes[i], 1.00000001*min_radius)

            # dists_sqr = ((del_nodes - self.nodes[i,:])**2).sum(axis=1)
            # rad_sqr = dists_sqr.min()
            # self.dual_nodes[i] = find( dists_sqr <= 1.00001*rad_sqr )
            self.dual_nodes[i] = np.array(all_near)

            for dual_node_idx in self.dual_nodes[i]:
                if not self.dual_lookup.has_key(dual_node_idx):
                    self.dual_lookup[dual_node_idx] = []
                self.dual_lookup[dual_node_idx].append(i)

            self.radii[i] = min_radius # sqrt(rad_sqr)

    def merge_points(self,tol):
        """ After a call to calc_radii(), this can be called to coalesce voronio points
        that are close to each other
        """

        while len(self.nodes) > 1:
            # look for short edges:
            edge_ends = self.nodes[ self.edges ]

            edge_centers = edge_ends.mean(axis=1)
            edge_tols = tol(edge_centers)

            edge_lengths = np.sqrt( ((edge_ends[:,1,:] - edge_ends[:,0,:])**2).sum(axis=1) )
            rel_edge_lengths = edge_lengths / edge_tols

            to_merge = np.argmin(rel_edge_lengths)

            if rel_edge_lengths[ to_merge ] < 1.0:
                # print(" got an edge to merge.")
                self.merge_edge( to_merge )
            else:
                break

    def merge_edge(self,e):
        a,b = self.edges[e]
        # print("merging voronoi edge ",a,b)

        self.edges = np.concatenate( (self.edges[:e], self.edges[e+1:]) )

        # map old node indices to new ones:
        node_mapping = np.arange(len(self.nodes))
        # b has become a
        node_mapping[b] = a
        # and everybody greater than b is shifted down
        node_mapping[ node_mapping > b] -= 1

        if self.radii is not None:
            self.radii = np.concatenate( (self.radii[:b], self.radii[b+1:]) )

            # combine their dual nodes:
            self.dual_nodes[a] = np.unique( np.concatenate( (self.dual_nodes[a],self.dual_nodes[b]) ) )

            # then remove b from the list
            self.dual_nodes = self.dual_nodes[:b] + self.dual_nodes[b+1:]

            for k in self.dual_lookup.keys():
                l = self.dual_lookup[k]
                # k is an index to the boundary points
                # l is a list of indices to voronoi centers

                if b in l:
                    l.remove( b )
                    if not a in l:
                        l.append(a)

                # keep it as a list for now.
                self.dual_lookup[k] = node_mapping[ np.array(l) ].tolist()

        # new node is between the old two nodes:
        self.nodes[a] = 0.5*(self.nodes[a] + self.nodes[b])

        self.edges = node_mapping[ self.edges ]

        self.nodes = np.concatenate( (self.nodes[:b], self.nodes[b+1:] ) )

    def centers_for_dual_node(self,dual_node):
        if self.dual_lookup.has_key(dual_node):
            return self.dual_lookup[dual_node]
        else:
            return []

    def plot_radii(self):
        a = gca()

        for i in range(self.nodes.shape[0]):
            cir = Circle( self.nodes[i], radius=self.radii[i])
            a.add_patch(cir)

    def plot_vor_points(self):
        try:
            colors = self.radii
            print("Got colors from radii")
            plt.scatter(self.nodes[:,0],self.nodes[:,1],50,colors,
                        lw=0,vmin=200,vmax=250)
        except:
            plt.plot(self.nodes[:,0],self.nodes[:,1],'r+')

    def plot(self,show_vor_points=True):
        if show_vor_points:
            self.plot_vor_points()

        # plot the finite edges:
        # build up the list of lines:
        all_lines = self.nodes[self.edges]
        coll = LineCollection(all_lines)
        coll.set_color('m')
        ax = plt.gca()
        ax.add_collection(coll)

        plt.draw()

# since the triangulation didn't add any nodes, just
# use the boundaries nodes instead of tri.nodes

# ### Check radius against edge / voronoi center
# if __name__ == '__main__':
#     ### Load the data
#     # boundary = load_shp.Boundary('/home/rusty/classes/research/meshing/dumbarton.shp')
#
#     # this is full bay, already filtered at 50m
#     boundary = load_shp.Boundary('/home/rusty/classes/research/spatialdata/us/ca/suntans/shoreline/noaa-medres/sfbay-100km-arc/sfbay-100km-arc-50_20.shp')
#
#     geo = boundary.geo
#
#     # points = array( geo.exterior.coords )
#     # points = points[:-1]
#
#     # from paver import upsample_linearring
#     # points = upsample_linearring(points,50)
#
#     bdry_ma = Boundary( geo=geo )
#     print("subdividing...")
#     bdry_ma.subdivide_iterate()
#     print("done")
#
#     vor = bdry_ma.vor()
#     #tri = bdry_ma.tri()
#     #tri.plot()
#
#     print("Calculating radii")
#     vor.calc_radii(bdry_ma.nodes)
#     print("done")
#
#     bdry_ma.plot()
#     bdry_ma.vor().plot_vor_points()
#     plt.axis('equal')
#     plt.draw()


text:
package edu.brown.cs.systems.baggage;

import java.util.ArrayList;
import java.util.Set;

import junit.framework.TestCase;

import org.junit.Test;

import com.google.protobuf.ByteString;

import edu.brown.cs.systems.baggage.BaggageMessages.BaggageMessage;

public class BaggageImplTest extends TestCase {

    @Test
    public void testByteStringEquals() {
        ByteString myval = ByteString.copyFrom("v1".getBytes());
        ByteString myval2 = ByteString.copyFrom("v1".getBytes());
        // ByteString should check the values rather than references for equals
        assertNotSame(myval, myval2);
        assertEquals(myval, ByteString.copyFrom("v1".getBytes()));
        assertEquals(myval, myval2);
        assertTrue(myval.equals(myval2));
        assertEquals(myval.hashCode(), myval2.hashCode());
    }

    @Test
    public void testNamespaceAutoRemoval() {
        BaggageImpl b = new BaggageImpl();
        ByteString myname = ByteString.copyFrom("namespace".getBytes());
        ByteString mykey = ByteString.copyFrom("k1".getBytes());
        ByteString mykey2 = ByteString.copyFrom("k2".getBytes());
        ByteString myval = ByteString.copyFrom("v1".getBytes());
        b.add(myname, mykey, myval);
        b.add(myname, mykey2, myval);
        assertTrue(b.hasNamespace(myname));
        b.remove(myname, mykey);
        assertTrue(b.hasNamespace(myname));
        b.remove(myname, mykey2);
        assertFalse(b.hasNamespace(myname));
    }

    @Test
    public void testAddGetRemove() {
        BaggageImpl b = new BaggageImpl();
        ByteString myname = ByteString.copyFrom("namespace".getBytes());
        ByteString mykey = ByteString.copyFrom("k1".getBytes());
        ByteString mykey2 = ByteString.copyFrom("k2".getBytes());
        ByteString myval = ByteString.copyFrom("v1".getBytes());
        ByteString myval2 = ByteString.copyFrom("v2".getBytes());
        // should return an empty set for non-exist keys
        assertTrue(b.get(myname, mykey).isEmpty());
        // check adding the one value multiple times
        b.add(myname, mykey, myval);
        assertTrue(b.get(myname, mykey).contains(myval));
        b.add(myname, mykey, myval);
        assertTrue(b.get(myname, mykey).contains(myval));
        // check different values for the same key
        b.add(myname, mykey, myval2);
        assertTrue(b.get(myname, mykey).contains(myval));
        assertTrue(b.get(myname, mykey).contains(myval2));
        // check another key
        assertFalse(b.get(myname, mykey2).contains(myval2));
        b.add(myname, mykey2, myval2);
        assertTrue(b.get(myname, mykey).contains(myval));
        assertFalse(b.get(myname, mykey2).contains(myval));
        assertTrue(b.get(myname, mykey2).contains(myval2));
        // remove one key
        b.remove(myname, mykey);
        assertTrue(b.get(myname, mykey).isEmpty());
        assertTrue(b.get(myname, mykey2).contains(myval2));
        // remove all keys
        b.remove(myname, mykey2);
        assertTrue(b.get(myname, mykey).isEmpty());
        assertTrue(b.get(myname, mykey2).isEmpty());
        // re-add
        b.add(myname, mykey, myval);
        assertTrue(b.get(myname, mykey).contains(myval));
    }

    @Test
    public void testAddNull() {
        BaggageImpl b = new BaggageImpl();
        ByteString myname = ByteString.copyFrom("namespace".getBytes());
        ByteString mybytes = ByteString.copyFrom("k1".getBytes());
        b.add(myname, mybytes, null);
        b.add(myname, null, mybytes);
        b.add(myname, null, null);
        assertFalse(b.get(myname, mybytes).contains(null));
        assertFalse(b.get(myname, null).contains(mybytes));
        assertFalse(b.get(myname, null).contains(null));
    }

    @Test
    public void testGetNonexistAndNull() {
        BaggageImpl b = new BaggageImpl();
        ByteString myname = ByteString.copyFrom("namespace".getBytes());
        assertTrue(b.get(myname, ByteString.copyFrom("notexist".getBytes())).isEmpty());
        assertTrue(b.get(myname, null).isEmpty());
    }

    @Test
    public void testRemoveNonexistAndNull() {
        BaggageImpl b = new BaggageImpl();
        ByteString myname = ByteString.copyFrom("namespace".getBytes());
        ByteString myname2 = ByteString.copyFrom("namespace2".getBytes());
        b.remove(myname, ByteString.copyFrom("notexist".getBytes()));
        b.remove(myname, null);
        b.remove(myname2, ByteString.copyFrom("notexist".getBytes()));
    }

    @Test
    public void testReplaceNull() {
        BaggageImpl b = new BaggageImpl();
        ByteString mybytes = ByteString.copyFrom("k1".getBytes());
        ByteString myname = ByteString.copyFrom("namespace".getBytes());
        b.add(myname, mybytes, mybytes);
        assertTrue(b.contains(myname, mybytes));
        b.replace(myname, mybytes, (ByteString) null);
        assertFalse(b.contains(myname, mybytes));
    }

    @Test
    public void testReplaceNullIterable() {
        BaggageImpl b = new BaggageImpl();
        ByteString mybytes = ByteString.copyFrom("k1".getBytes());
        ByteString myname = ByteString.copyFrom("namespace".getBytes());
        b.add(myname, mybytes, mybytes);
        assertTrue(b.contains(myname, mybytes));
        b.replace(myname, mybytes, (ArrayList<ByteString>) null);
        assertFalse(b.contains(myname, mybytes));
    }

    @Test
    public void testReplaceIterableWithNullValue() {
        BaggageImpl b = new BaggageImpl();
        ByteString mybytes = ByteString.copyFrom("k1".getBytes());
        ByteString mybytes2 = ByteString.copyFrom("k2".getBytes());
        ByteString myname = ByteString.copyFrom("namespace".getBytes());
        b.add(myname, mybytes, mybytes);
        assertTrue(b.contains(myname, mybytes));
        // should ignore the null values
        ArrayList<ByteString> l = new ArrayList<ByteString>();
        l.add(mybytes2);
        l.add(null);
        l.add(mybytes2);
        l.add(null);
        b.replace(myname, mybytes, l);
        assertFalse(b.get(myname, mybytes).contains(null));
        assertFalse(b.get(myname, mybytes).contains(mybytes));
        assertTrue(b.get(myname, mybytes).contains(mybytes2));
        // should be equivalent to remove the key if only null in the iterable
        ArrayList<ByteString> l2 = new ArrayList<ByteString>();
        l2.add(null);
        b.replace(myname, mybytes, l2);
        assertFalse(b.contains(myname, mybytes));
    }

    @Test
    public void testReplace() {
        BaggageImpl b = new BaggageImpl();
        ByteString myname = ByteString.copyFrom("namespace".getBytes());
        ByteString myname2 = ByteString.copyFrom("namespace2".getBytes());
        ByteString mybytes = ByteString.copyFrom("k1".getBytes());
        ByteString mybytes2 = ByteString.copyFrom("k2".getBytes());
        // edge cases
        b.replace(myname, mybytes, mybytes);
        assertTrue(b.get(myname, mybytes).contains(mybytes));
        // single replacement
        b.replace(myname, mybytes, mybytes2);
        assertFalse(b.get(myname, mybytes).contains(mybytes));
        assertTrue(b.get(myname, mybytes).contains(mybytes2));
        // replace with an empty list
        b.replace(myname, mybytes, new ArrayList<ByteString>());
        assertTrue(b.get(myname, mybytes).isEmpty());
        // replace with a list with duplicated items
        ArrayList<ByteString> l = new ArrayList<ByteString>();
        l.add(mybytes);
        l.add(mybytes2);
        l.add(mybytes);
        b.replace(myname, mybytes, l);
        assertTrue(b.get(myname, mybytes).contains(mybytes));
        assertTrue(b.get(myname, mybytes).contains(mybytes2));
        assertEquals(2, b.get(myname, mybytes).size());
        // replace with null key
        assertTrue(b.hasNamespace(myname));
        b.replace(myname, null, l);
        assertFalse(b.contains(myname, null));
        b.replace(myname, null, mybytes);
        assertFalse(b.contains(myname, null));
        // replace a non-exist namespace
        b.replace(myname2, mybytes, (ByteString) null);
        assertFalse(b.contains(myname2, mybytes));
        assertFalse(b.hasNamespace(myname2));
    }

    @Test
    public void testSplit() {
        BaggageImpl b = new BaggageImpl();
        ByteString myname = ByteString.copyFrom("namespace".getBytes());
        ByteString myname2 = ByteString.copyFrom("namespace2".getBytes());
        ByteString mybytes = ByteString.copyFrom("k1".getBytes());
        ByteString mybytes2 = ByteString.copyFrom("k2".getBytes());
        b.add(myname, mybytes, mybytes);
        b.add(myname, mybytes, mybytes2);
        b.add(myname2, mybytes2, mybytes);
        BaggageImpl b2 = b.split();
        assertTrue(b.get(myname, mybytes).contains(mybytes));
        assertTrue(b.get(myname, mybytes).contains(mybytes2));
        assertTrue(b.get(myname2, mybytes2).contains(mybytes));
        assertTrue(b2.get(myname, mybytes).contains(mybytes));
        assertTrue(b2.get(myname, mybytes).contains(mybytes2));
        assertTrue(b2.get(myname2, mybytes2).contains(mybytes));
        assertEquals(b.get(myname, mybytes).size(), b2.get(myname, mybytes).size());
        assertEquals(b.get(myname2, mybytes2).size(), b2.get(myname2, mybytes2).size());
    }

    @Test
    public void testJoin() {
        BaggageImpl b = new BaggageImpl();
        BaggageImpl b2 = new BaggageImpl();
        ByteString myname = ByteString.copyFrom("namespace".getBytes());
        ByteString myname2 = ByteString.copyFrom("namespace2".getBytes());
        ByteString v1 = ByteString.copyFrom("k1".getBytes());
        ByteString v2 = ByteString.copyFrom("k2".getBytes());
        ByteString v3 = ByteString.copyFrom("k3".getBytes());
        b.add(myname, v1, v2);
        b.add(myname, v2, v3);
        b2.add(myname, v3, v1);
        b2.add(myname, v2, v1);
        b2.add(myname2, v1, v1);
        b.merge(b2);
        b.merge(null);
        // the original baggage is not affected
        assertTrue(b2.get(myname, v1).isEmpty());
        // new key created
        assertTrue(b.get(myname, v3).contains(v1));
        assertEquals(1, b.get(myname, v3).size());
        // duplicated key merged
        assertTrue(b.get(myname, v2).contains(v1));
        assertTrue(b.get(myname, v2).contains(v3));
        assertEquals(2, b.get(myname, v2).size());
        // new namespace created
        assertTrue(b.get(myname2, v1).contains(v1));
        assertEquals(1, b.get(myname2, v1).size());
    }

    @Test
    public void testCopy() {
        BaggageImpl b = new BaggageImpl();
        ByteString myname = ByteString.copyFrom("namespace".getBytes());
        ByteString v1 = ByteString.copyFrom("k1".getBytes());
        ByteString v2 = ByteString.copyFrom("k2".getBytes());
        ByteString v3 = ByteString.copyFrom("k3".getBytes());
        b.add(myname, v1, v2);
        b.add(myname, v2, v3);
        BaggageImpl b2 = b.split();
        b.add(myname, v3, v1);
        b2.add(myname, v1, v1);
        // the original baggage is not affected
        assertTrue(b2.get(myname, v3).isEmpty());
        assertFalse(b.get(myname, v1).contains(v1));
        // new key created
        assertFalse(b.get(myname, v3).isEmpty());
        assertTrue(b2.get(myname, v1).contains(v1));
        // old values copied
        assertTrue(b.get(myname, v1).contains(v2));
        assertTrue(b.get(myname, v2).contains(v3));
        assertTrue(b2.get(myname, v1).contains(v2));
        assertTrue(b2.get(myname, v2).contains(v3));
    }

    @Test
    public void testSerialization() {
        BaggageImpl b = new BaggageImpl();
        ByteString myname = ByteString.copyFrom("namespace".getBytes());
        ByteString myname2 = ByteString.copyFrom("namespace2".getBytes());
        ByteString v1 = ByteString.copyFrom("k1".getBytes());
        ByteString v2 = ByteString.copyFrom("k2".getBytes());
        ByteString v3 = ByteString.copyFrom("k3".getBytes());
        ByteString v4 = ByteString.copyFrom("k4".getBytes());
        b.add(myname, v1, v2);
        b.add(myname, v2, null);
        b.add(myname, v3, v1);
        b.add(myname, v2, v1);
        b.add(myname2, v1, v4);
        byte[] s = b.toByteArray();
        b.add(myname, v4, v4);
        BaggageImpl b2 = BaggageImpl.deserialize(s);
        // recovery of serialization
        assertTrue(b2.get(myname, v2).contains(v1));
        assertFalse(b2.get(myname, v2).contains(null));
        assertTrue(b2.get(myname, v3).contains(v1));
        assertTrue(b2.get(myname, v1).contains(v2));
        assertTrue(b2.get(myname2, v1).contains(v4));
        // deserialize creates a new copy
        assertTrue(b2.get(myname, v4).isEmpty());
        // edge cases
        assertNull(BaggageImpl.deserialize((byte[]) null));
        assertNull(BaggageImpl.deserialize(new byte[0]));
        assertNull(BaggageImpl.deserialize(new byte[1]));
        assertNull(BaggageImpl.deserialize("not valid".getBytes()));
        assertNull(BaggageImpl.deserialize(BaggageMessage.newBuilder().build().toByteArray()));
        // null for empty baggage
        assertEquals(0, new BaggageImpl().toByteArray().length);
    }

    @Test
    public void testNamespace() {
        BaggageImpl b = new BaggageImpl();
        ByteString myoldname = ByteString.copyFrom("not-a-namespace".getBytes());
        ByteString myname = ByteString.copyFrom("namespace".getBytes());
        ByteString myname2 = ByteString.copyFrom("namespace2".getBytes());
        // should be able to run correctly even the namespace does not exist
        assertFalse(b.contains(myoldname, myname));
        assertEquals(0, b.get(myoldname, myname).size());
        b.remove(myoldname, myname);
        // namespaces should be isolated
        b.add(myname, myname, myname);
        assertFalse(b.contains(myname2, myname));
        assertTrue(b.get(myname, myname).contains(myname));
        b.add(myname2, myname, myname2);
        assertTrue(b.contains(myname2, myname));
        assertEquals(1, b.get(myname2, myname).size());
        assertTrue(b.get(myname2, myname).contains(myname2));
        assertEquals(1, b.get(myname, myname).size());
        // should be able to return all namespaces
        Set<ByteString> names = b.namespaces();
        assertTrue(names.contains(myname));
        assertTrue(names.contains(myname2));
        assertEquals(2, names.size());
        // should be able to remove a namespace
        b.removeAll(myname);
        assertFalse(b.hasNamespace(myname));
        assertTrue(b.hasNamespace(myname2));
    }
}

redpajama_set_name: RedPajamaGithub


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

namespace NBitcoin.Protocol
{
	/// <summary>
	/// Ask block headers that happened since BlockLocators
	/// </summary>
	[Payload("getheaders")]
	public class GetHeadersPayload : Payload
	{
		public GetHeadersPayload()
		{

		}
		public GetHeadersPayload(BlockLocator locator)
		{
			BlockLocators = locator;
		}
		uint version = (uint)ProtocolVersion.PROTOCOL_VERSION;
		public ProtocolVersion Version
		{
			get
			{
				return (ProtocolVersion)version;
			}
			set
			{
				version = (uint)value;
			}
		}

		BlockLocator blockLocators;

		public BlockLocator BlockLocators
		{
			get
			{
				return blockLocators;
			}
			set
			{
				blockLocators = value;
			}
		}

		uint256 hashStop = uint256.Zero;
		public uint256 HashStop
		{
			get
			{
				return hashStop;
			}
			set
			{
				hashStop = value;
			}
		}

		public override void ReadWriteCore(BitcoinStream stream)
		{
			stream.ReadWrite(ref version);
			stream.ReadWrite(ref blockLocators);
			stream.ReadWrite(ref hashStop);
		}
	}
}


text:
package io.sundr.example;

public class Other {
  public static final String FOO_NAME = "foo";
  public static final String SOMETHING_NAME = "myName";

  @TestAnnotation(name = FOO_NAME)
  private String foo;

  @TestAnnotation(name = SOMETHING_NAME, values = { 1, 2, 3, 5, 7 })
  private void something() {
  }
}


text:
package org.apache.karaf.webconsole.osgi.core.pkg.column;

import org.apache.felix.utils.manifest.Clause;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.osgi.framework.Constants;

public class ResolutionPanel extends Panel {

    private static final long serialVersionUID = 1L;

    public ResolutionPanel(String id, IModel<Clause> model) {
        super(id);

        Clause clause = model.getObject();

        String resolution = clause.getDirective(Constants.RESOLUTION_DIRECTIVE);
        if (resolution == null) {
            resolution = Constants.RESOLUTION_MANDATORY;
        }

        String css = "icon-question-sign"; // unknown resolution
        if (Constants.RESOLUTION_MANDATORY.equals(resolution)) {
            css = "icon-lock";
        } else if (Constants.RESOLUTION_OPTIONAL.equals(resolution)) {
            css = "icon-adjust";
        }

        add(new Label("resolution", resolution).setRenderBodyOnly(true));
        Label icon = new Label("icon", "");
        icon.add(new AttributeModifier("class", css));
        add(icon);

        add(new AttributeModifier("title", "Resolution is " + resolution));
    }

}


text:
declare -A params=$6       # Create an associative array
declare -A headers=${9}    # Create an associative array
declare -A rewrites=${10}  # Create an associative array
paramsTXT=""
if [ -n "$6" ]; then
    for element in "${!params[@]}"
    do
        paramsTXT="${paramsTXT}
        fastcgi_param ${element} ${params[$element]};"
    done
fi
headersTXT=""
if [ -n "${9}" ]; then
   for element in "${!headers[@]}"
   do
      headersTXT="${headersTXT}
      add_header ${element} ${headers[$element]};"
   done
fi
rewritesTXT=""
if [ -n "${10}" ]; then
   for element in "${!rewrites[@]}"
   do
      rewritesTXT="${rewritesTXT}
      location ~ ${element} { if (!-f \$request_filename) { return 301 ${rewrites[$element]}; } }"
   done
fi

if [ "$7" = "true" ]
then configureXhgui="
location /xhgui {
        try_files \$uri \$uri/ /xhgui/index.php?\$args;
}
"
else configureXhgui=""
fi

block="server {
    listen ${3:-80};
    listen ${4:-443} ssl http2;
    server_name $1;
    root \"$2\";

    index index.html index.htm index.php app_dev.php;

    charset utf-8;

    $rewritesTXT

    location / {
        try_files \$uri \$uri/ /app_dev.php?\$query_string;
        $headersTXT
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log off;
    error_log  /var/log/nginx/$1-ssl-error.log error;

    sendfile off;

    client_max_body_size 100m;

    # DEV
    location ~ ^/(app_dev|app_test|config)\.php(/|\$) {
        fastcgi_split_path_info ^(.+\.php)(/.*)\$;
        fastcgi_pass unix:/var/run/php/php$5-fpm.sock;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        $paramsTXT

        fastcgi_intercept_errors off;
        fastcgi_buffer_size 16k;
        fastcgi_buffers 4 16k;
    }

    # PROD
    location ~ ^/app\.php(/|$) {
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        fastcgi_pass unix:/var/run/php/php$5-fpm.sock;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        $paramsTXT

        fastcgi_intercept_errors off;
        fastcgi_buffer_size 16k;
        fastcgi_buffers 4 16k;
        internal;
    }

    location ~ /\.ht {
        deny all;
    }

    $configureXhgui

    ssl_certificate     /etc/nginx/ssl/$1.crt;
    ssl_certificate_key /etc/nginx/ssl/$1.key;
}
"

echo "$block" > "/etc/nginx/sites-available/$1"
ln -fs "/etc/nginx/sites-available/$1" "/etc/nginx/sites-enabled/$1"


text:
package org.springframework.cloud.loadbalancer.core;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.DefaultRequest;
import org.springframework.cloud.client.loadbalancer.DefaultRequestContext;
import org.springframework.cloud.client.loadbalancer.DefaultResponse;
import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.Response;
import org.springframework.cloud.client.loadbalancer.reactive.ReactiveLoadBalancer;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClients;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.cloud.loadbalancer.support.ServiceInstanceListSuppliers;
import org.springframework.cloud.loadbalancer.support.SimpleObjectProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.Environment;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

/**
 * @author Spencer Gibb
 */
@SpringBootTest
class LoadBalancerTests {

	@Autowired
	private LoadBalancerClientFactory clientFactory;

	@Test
	void roundRobbinLoadbalancerWorks() {
		ReactiveLoadBalancer<ServiceInstance> reactiveLoadBalancer = this.clientFactory.getInstance("myservice",
				ReactiveLoadBalancer.class, ServiceInstance.class);

		then(reactiveLoadBalancer).isInstanceOf(RoundRobinLoadBalancer.class);
		then(reactiveLoadBalancer).isInstanceOf(ReactorLoadBalancer.class);
		ReactorLoadBalancer<ServiceInstance> loadBalancer = (ReactorLoadBalancer<ServiceInstance>) reactiveLoadBalancer;

		// order dependent on seedPosition -1 of RoundRobinLoadBalancer
		List<String> hosts = Arrays.asList("ahost", "chost", "bhostsecure", "ahost");

		assertLoadBalancer(loadBalancer, hosts);
	}

	private void assertLoadBalancer(ReactorLoadBalancer<ServiceInstance> loadBalancer, List<String> hosts) {
		for (String host : hosts) {
			Mono<Response<ServiceInstance>> source = loadBalancer.choose();
			StepVerifier.create(source).consumeNextWith(response -> {
				then(response).isNotNull();
				then(response.hasServer()).isTrue();

				ServiceInstance instance = response.getServer();
				then(instance).isNotNull();
				then(instance.getHost()).as("instance host is incorrent %s", host).isEqualTo(host);

				if (host.contains("secure")) {
					then(instance.isSecure()).isTrue();
				}
				else {
					then(instance.isSecure()).isFalse();
				}
			}).verifyComplete();
		}
	}

	@Test
	void emptyHosts() {
		ResolvableType type = ResolvableType.forClassWithGenerics(ReactorLoadBalancer.class, ServiceInstance.class);
		ReactorLoadBalancer<ServiceInstance> loadBalancer = this.clientFactory.getInstance("unknownservice", type);

		then(loadBalancer).isInstanceOf(RoundRobinLoadBalancer.class);

		Mono<Response<ServiceInstance>> source = loadBalancer.choose();
		StepVerifier.create(source).consumeNextWith(response -> {
			then(response).isNotNull();
			then(response.hasServer()).isFalse();
		}).verifyComplete();
	}

	@Test
	void staticConfigurationWorks() {
		String serviceId = "test1";
		RoundRobinLoadBalancer loadBalancer = new RoundRobinLoadBalancer(ServiceInstanceListSuppliers
				.toProvider(serviceId, instance(serviceId, "1host", false), instance(serviceId, "2host-secure", true)),
				serviceId, -1);
		assertLoadBalancer(loadBalancer, Arrays.asList("1host", "2host-secure"));
	}

	private static DefaultServiceInstance instance(String serviceId, String host, boolean secure) {
		return new DefaultServiceInstance(serviceId, serviceId, host, 80, secure);
	}

	@SuppressWarnings("ConstantConditions")
	@Test
	void canPassHintViaRequest() {
		String serviceId = "test1";
		RoundRobinLoadBalancer loadBalancer = new TestHintLoadBalancer(ServiceInstanceListSuppliers.toProvider(
				serviceId, instance(serviceId, "1host", false), instance(serviceId, "2host-secure", true)), serviceId);
		Request<DefaultRequestContext> request = new DefaultRequest<>(new DefaultRequestContext("test2", "test2"));

		ServiceInstance serviceInstance = loadBalancer.choose(request).block().getServer();

		assertThat(serviceInstance.getServiceId()).isEqualTo("test2");
	}

	@Test
	void selectedInstanceCallback() {
		String serviceId = "test1";
		ServiceInstance serviceInstance = instance(serviceId, "1host", false);
		SameInstancePreferenceServiceInstanceListSupplier supplier = mock(
				SameInstancePreferenceServiceInstanceListSupplier.class);
		when(supplier.get(any())).thenReturn(Flux.just(Collections.singletonList(serviceInstance)));
		RoundRobinLoadBalancer loadBalancer = new RoundRobinLoadBalancer(new SimpleObjectProvider<>(supplier),
				serviceId);

		loadBalancer.choose().block();

		verify(supplier).selectedServiceInstance(serviceInstance);
	}

	private static class TestHintLoadBalancer extends RoundRobinLoadBalancer {

		TestHintLoadBalancer(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider,
				String serviceId) {
			super(serviceInstanceListSupplierProvider, serviceId);
		}

		@SuppressWarnings("rawtypes")
		@Override
		public Mono<Response<ServiceInstance>> choose(Request request) {
			if (request.getContext() instanceof DefaultRequestContext requestContext) {
				return Mono.just(new DefaultResponse(instance(requestContext.getHint(), "host", false)));
			}
			return Mono.empty();
		}

	}

	@EnableAutoConfiguration
	@SpringBootConfiguration(proxyBeanMethods = false)
	@LoadBalancerClients({ @LoadBalancerClient(name = "myservice", configuration = MyServiceConfig.class),
			@LoadBalancerClient(name = "unknownservice", configuration = MyServiceConfig.class) })
	@EnableCaching
	protected static class Config {

	}

	protected static class MyServiceConfig {

		@Bean
		public RoundRobinLoadBalancer roundRobinContextLoadBalancer(LoadBalancerClientFactory clientFactory,
				Environment env) {
			String serviceId = LoadBalancerClientFactory.getName(env);
			return new RoundRobinLoadBalancer(
					clientFactory.getLazyProvider(serviceId, ServiceInstanceListSupplier.class), serviceId, -1);
		}

	}

}


text:
@interface NegativeStackedBarChartViewController : DemoBaseViewController

@end


text:
var LindaCrowdsale = artifacts.require('../contracts/LindaCrowdsale.sol')
var LindaPresale = artifacts.require('../contracts/LindaPresale.sol')

const duration = {
  seconds: function (val) { return val},
  minutes: function (val) { return val * this.seconds(60) },
  hours: function (val) { return val * this.minutes(60) },
  days: function (val) { return val * this.hours(24) },
  weeks: function (val) { return val * this.days(7) },
  years: function (val) { return val * this.days(365)}
}

module.exports = function (deployer, network, accounts) {

  // WARNING: these parameters are for testing purposes.
  // The real values of the ICO should be set at deployment time.

  // common parameters
  const startTime = web3.eth.getBlock('latest').timestamp + duration.minutes(5) // in time units
  const endTime = startTime + duration.minutes(10)
  const rate = new web3.BigNumber(2346) //rate at the moment of deployment
  const goal = new web3.BigNumber(web3.toWei(5, 'ether')) // minimum ether to raise
  //replace wallet addresses by real ones
  const wallet = '0x5a1779bf0764623ad070b6d53571b293f1c06469' // wallet to get all the ether
  const tokenOwner = '0xB8CBAe47F750889E31E9d243F49E424DD0DAA99C' // address of the token owner once the presale and the ico end

  // presale
  const presaleCap = new web3.BigNumber(web3.toWei(3581.17, 'ether')) // maximum for the presale

  // ico
  const cap = new web3.BigNumber(web3.toWei(43862.77, 'ether')) // maximum for the ico
  //replace wallet addresses by real ones
  const teamWallet = '0x5bdf1446a54142c0fa62c782b24bdcef6e901dae' // wallet that will hold the team tokens once the ico is finished
  const tokenAddress ='0x07245299493b43bf455f3d9357bfc02b4aafc876' // wallet address of the presale-created token
  const teamLockTime = duration.minutes(5) // freezing time for the team tokens (9 months)
  const unsoldLockTime = duration.minutes(8) // freezing time for the unsold tokens (10 years)

  //deployer.deploy(LindaCrowdsale, startTime, endTime, rate, goal, cap, wallet, teamWallet, tokenAddress, tokenOwner, teamLockTime, unsoldLockTime)

  deployer.deploy(LindaPresale, startTime, endTime, rate, goal, presaleCap, tokenOwner, wallet)
}


text:
package com.vmware.q3training.service.notification;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class NotificationService {

	public EmailReceipt sendEmail(String toAddress, String subject, String message) {
		EmailReceipt emailReceipt = new EmailReceipt();

		String from = "q3training@vmware.com";
        String host = "localhost";

        // Get system properties
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        Session session = Session.getDefaultInstance(properties);

        try {
            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(from));
            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
            mimeMessage.setSubject(subject);
            mimeMessage.setText(message);

            // Send message
            Transport.send(mimeMessage);
            System.out.println("Sent message successfully....");
            emailReceipt.setSuccess(true);
            emailReceipt.setError("No error, email was sent successfully!");
         }catch (MessagingException mex) {
        	emailReceipt.setSuccess(false);
        	emailReceipt.setError(mex.getMessage());
            mex.printStackTrace();
         }
  		return emailReceipt;
	}

}


text:
namespace Microsoft.Azure.CognitiveServices.ContentModerator.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// The category2 score details of the text. <a
    /// href="https://aka.ms/textClassifyCategories">Click here</a>
    /// for more details on category classification.
    /// </summary>
    public partial class ClassificationCategory2
    {
        /// <summary>
        /// Initializes a new instance of the ClassificationCategory2 class.
        /// </summary>
        public ClassificationCategory2()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the ClassificationCategory2 class.
        /// </summary>
        /// <param name="score">The category2 score.</param>
        public ClassificationCategory2(double? score = default(double?))
        {
            Score = score;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the category2 score.
        /// </summary>
        [JsonProperty(PropertyName = "Score")]
        public double? Score { get; set; }

    }
}


text:
"""The base classes for RDFValue tests."""

from typing import Text

from grr_response_core.lib import serialization
from grr_response_core.lib.rdfvalues import structs as rdf_structs

# pylint:mode=test

class RDFValueTestMixin(object):
  """The base class for testing RDFValue implementations."""

  # This should be overridden by the RDFValue class we want to test.
  rdfvalue_class = lambda *args, **kw: None

  __abstract = True  # Do not register this class so pylint: disable=g-bad-name

  def GenerateSample(self, number=0):
    """Create a pre-populated instance of the RDFValue.

    Args:
      number: A sample number. Derived classes should return a different sample
        for each number.
    """
    _ = number
    return self.rdfvalue_class()

  def CheckRDFValue(self, value, sample):
    """Check that the rdfproto is the same as the sample."""
    self.assertIsInstance(sample, self.rdfvalue_class)
    self.assertIsInstance(value, self.rdfvalue_class)

    self.assertEqual(value, sample)

  def testComparisons(self):
    """Checks that object comparisons work."""
    sample1 = self.GenerateSample(1)

    # pylint: disable=g-generic-assert
    self.assertTrue(sample1 == self.GenerateSample(1))
    self.assertFalse(sample1 == self.GenerateSample(2))
    self.assertTrue(sample1 != self.GenerateSample(2))
    self.assertFalse(sample1 != self.GenerateSample(1))
    # pylint: enable=g-generic-assert

  def testHashability(self):
    """RDFValue instances need to act as keys in a dict."""
    sample1 = self.GenerateSample(1)

    if isinstance(sample1, rdf_structs.RDFStruct):
      self.skipTest("Hashing is unsupported.")

    # Different instances with the same value need to hash to the same.
    self.assertEqual(hash(sample1), hash(self.GenerateSample(1)))
    self.assertNotEqual(hash(sample1), hash(self.GenerateSample(2)))

  def testInitialization(self):
    """Check that we can use an empty initializer.

    RDFValues are created in many different ways, sometimes in stages by
    gradually populating fields. The only time you can be sure the user has
    finished creating a proto is when it is serialized. This means strong
    validation that requires all fields populated can't be done in init, but
    should be done in SerializeToBytes.
    """
    self.rdfvalue_class()

    # Initialize from another instance.
    sample = self.GenerateSample()

    self.CheckRDFValue(self.rdfvalue_class(sample), sample)

  def testSerialization(self, sample=None):
    """Make sure the RDFValue instance can be serialized."""
    if sample is None:
      sample = self.GenerateSample()

    # Serializing to a string must produce a string.
    serialized = serialization.ToBytes(sample)
    self.assertIsInstance(serialized, bytes)

    # Ensure we can parse it again.

    rdfvalue_object = serialization.FromBytes(self.rdfvalue_class, serialized)
    self.CheckRDFValue(rdfvalue_object, sample)

    # Serializing to data store must produce something the data store can
    # handle.
    serialized = serialization.ToWireFormat(sample)
    protobuf_type = serialization.GetProtobufType(type(sample))

    if protobuf_type == "bytes":
      self.assertIsInstance(serialized, bytes)
    elif protobuf_type == "string":
      self.assertIsInstance(serialized, Text)
    elif protobuf_type in ["unsigned_integer", "integer"]:
      self.assertIsInstance(serialized, int)
    else:
      self.fail("%s has no valid protobuf_type" % self.rdfvalue_class)

    # Ensure we can parse it again.
    rdfvalue_object = serialization.FromWireFormat(self.rdfvalue_class,
                                                   serialized)
    self.CheckRDFValue(rdfvalue_object, sample)

class RDFProtoTestMixin(RDFValueTestMixin):
  """A harness for testing RDFProto implementations."""

  __abstract = True  # Do not register this class so pylint: disable=g-bad-name

  def testInitializationEx(self):
    """Check we can initialize from additional parts."""
    sample = self.GenerateSample()

    # RDFProto can be initialized from a serialized protobuf.
    serialized = sample.SerializeToBytes()
    rdfvalue_sample = self.rdfvalue_class.FromSerializedBytes(serialized)
    self.CheckRDFValue(rdfvalue_sample, sample)

    # RDFProto can be initialized from another RDFProto.
    new_rdfvalue_sample = self.rdfvalue_class(rdfvalue_sample)
    self.CheckRDFValue(new_rdfvalue_sample, rdfvalue_sample)


text:
id: style-props-value-px
title: Shorthand for Specifying Pixel Values in style props
layout: tips
permalink: style-props-value-px.html
prev: maximum-number-of-jsx-root-nodes.html
next: children-props-type.html
---

When specifying a pixel value for your inline `style` prop, React automatically appends the string "px" for you after your number value, so this works:

```js
var divStyle = {height: 10}; // rendered as "height:10px"
ReactDOM.render(<div style={divStyle}>Hello World!</div>, mountNode);
```

See [Inline Styles](/react/tips/inline-styles.html) for more info.

Sometimes you _do_ want to keep the CSS properties unitless. Here's a list of properties that won't get the automatic "px" suffix:

- `animationIterationCount`
- `boxFlex`
- `boxFlexGroup`
- `boxOrdinalGroup`
- `columnCount`
- `fillOpacity`
- `flex`
- `flexGrow`
- `flexPositive`
- `flexShrink`
- `flexNegative`
- `flexOrder`
- `fontWeight`
- `lineClamp`
- `lineHeight`
- `opacity`
- `order`
- `orphans`
- `stopOpacity`
- `strokeDashoffset`
- `strokeOpacity`
- `strokeWidth`
- `tabSize`
- `widows`
- `zIndex`
- `zoom`


text:
using UnityEditor;
using System;
using System.Reflection;

namespace NaughtyAttributes.Editor
{
    public static class PropertyUtility
    {
        public static T GetAttribute<T>(SerializedProperty property) where T : Attribute
        {
            T[] attributes = GetAttributes<T>(property);
            return attributes.Length > 0 ? attributes[0] : null;
        }

        public static T[] GetAttributes<T>(SerializedProperty property) where T : Attribute
        {
            FieldInfo fieldInfo = ReflectionUtility.GetField(GetTargetObject(property), property.name);

            return (T[])fieldInfo.GetCustomAttributes(typeof(T), true);
        }

        public static UnityEngine.Object GetTargetObject(SerializedProperty property)
        {
            return property.serializedObject.targetObject;
        }
    }
}


text:
struct Fibonacci {
    curr: u32,
    next: u32,
}

// Implement 'Iterator' for 'Fibonacci'
impl Iterator for Fibonacci {
    type Item = u32;
    // The 'Iterator' trait only requires the 'next' method to be defined. The
    // return type is 'Option<T>', 'None' is returned when the 'Iterator' is
    // over, otherwise the next value is returned wrapped in 'Some'
    fn next(&mut self) -> Option<u32> {
        let new_next = self.curr + self.next;

        self.curr = self.next;
        self.next = new_next;

        // 'Some' is always returned, this is an infinite value generator
        Some(self.curr)
    }
}

// Returns a fibonacci sequence generator
fn fibonacci() -> Fibonacci {
    Fibonacci { curr: 1, next: 1 }
}

fn main() {
    // Iterator that generates: 0, 1 and 2
    let mut sequence = 0..3;

    println!("Four consecutive `next` calls on range(0, 3)");
    println!("> {:?}", sequence.next());
    println!("> {:?}", sequence.next());
    println!("> {:?}", sequence.next());
    println!("> {:?}", sequence.next());

    // The for construct will iterate an 'Iterator' until it returns 'None'.
    // Every 'Some' value is unwrapped and bound to a variable.
    println!("Iterate over range(0, 3) using for");
    for i in 0..3 {
        println!("> {}", i);
    }

    // The 'take(n)' method will reduce an iterator to its first 'n' terms,
    // which is pretty useful for infinite value generators
    println!("The first four terms of the Fibonacci sequence are: ");
    for i in fibonacci().take(4) {
        println!("> {}", i);
    }

    // The 'skip(n)' method will shorten an iterator by dropping its first 'n'
    // terms
    println!("The next four terms of the Fibonacci sequence are: ");
    for i in fibonacci().skip(4).take(4) {
        println!("> {}", i);
    }

    let array = [1u32, 3, 3, 7];

    // The 'iter' method produces an 'Iterator' over an array/slice
    println!("Iterate the following array {:?}", array.as_slice());
    for i in array.iter() {
        println!("> {}", i);
    }
}


text:
// Generated by xsd compiler for android/java
// DO NOT CHANGE!
package com.ebay.trading.api;

import java.io.Serializable;
import com.leansoft.nano.annotation.*;
import java.util.List;

/**
 *
 * eBay Store Cross Promotions are no longer supported in the Trading API, so the
 * <b>CrossPromotion</b> container will either not be returned, or, if it is
 * returned, the data in the container may not be accurate. Contains one or
 * more items cross-promoted with the display or purchase of a referring item.
 *
 */
public class CrossPromotionsType implements Serializable {

    private static final long serialVersionUID = -1L;

	@Element(name = "ItemID")
	@Order(value=0)
	public String itemID;

	@Element(name = "PrimaryScheme")
	@Order(value=1)
	public PromotionSchemeCodeType primaryScheme;

	@Element(name = "PromotionMethod")
	@Order(value=2)
	public PromotionMethodCodeType promotionMethod;

	@Element(name = "SellerID")
	@Order(value=3)
	public String sellerID;

	@Element(name = "ShippingDiscount")
	@Order(value=4)
	public boolean shippingDiscount;

	@Element(name = "StoreName")
	@Order(value=5)
	public String storeName;

	@Element(name = "PromotedItem")
	@Order(value=6)
	public List<PromotedItemType> promotedItem;

	@AnyElement
	@Order(value=7)
	public List<Object> any;

}


text:
namespace fplbase {

AsyncLoader::AsyncLoader() : loading_(nullptr), num_pending_requests_(0) {
}

AsyncLoader::~AsyncLoader() {
  {
    std::lock_guard<std::mutex> lock(mutex_);
    queue_.clear();
  }
  Stop();
}

void AsyncLoader::Stop() {
  if (worker_thread_.joinable()) {
    StopLoadingWhenComplete();
    worker_thread_.join();
  }
}

void AsyncLoader::QueueJob(AsyncAsset *res) {
  {
    std::lock_guard<std::mutex> lock(mutex_);
    queue_.push_back(res);
    ++num_pending_requests_;
  }
  job_cv_.notify_one();
}

void AsyncLoader::AbortJob(AsyncAsset *res) {
  bool was_loading = false;
  {
    std::lock_guard<std::mutex> lock(mutex_);
    was_loading = loading_ == res;
  }

  if (was_loading) {
    PauseLoading();
  }

  {
    std::lock_guard<std::mutex> lock(mutex_);
    auto iter = std::find(queue_.begin(), queue_.end(), res);
    if (iter != queue_.end()) {
      queue_.erase(iter);
      --num_pending_requests_;
    }

    iter = std::find(done_.begin(), done_.end(), res);
    if (iter != done_.end()) {
      done_.erase(iter);
      --num_pending_requests_;
    }
  }

  if (was_loading) {
    StartLoading();
  }
}

void AsyncLoader::StartLoading() {
  if (!worker_thread_.joinable()) {
    worker_thread_ = std::thread(AsyncLoader::LoaderThread, this);
  }
}

void AsyncLoader::PauseLoading() {
  {
    std::lock_guard<std::mutex> lock(mutex_);
    queue_.push_front(nullptr);
  }
  job_cv_.notify_one();
  worker_thread_.join();
}

void AsyncLoader::StopLoadingWhenComplete() { QueueJob(nullptr); }

bool AsyncLoader::TryFinalize() {
  for (;;) {
    AsyncAsset *resource = nullptr;
    {
      std::lock_guard<std::mutex> lock(mutex_);
      if (done_.size() > 0) resource = done_[0];
    }

    if (!resource) break;
    bool ok = resource->Finalize();
    if (!ok) {
      // Can't do much here, since res is already constructed. Caller has to
      // check IsValid() to know if resource can be used.
    }

    {
      std::lock_guard<std::mutex> lock(mutex_);
      // It's possible that the resource was destroyed during its finalize
      // callbacks, so ensure that it's still the first item in done_.
      if (done_.size() > 0 && done_.front() == resource) {
        done_.pop_front();
      }
      --num_pending_requests_;
    }
  }
  bool finished;
  {
    std::unique_lock<std::mutex> lock(mutex_);
    finished = num_pending_requests_ == 0;
  }
  return finished;
}

void AsyncLoader::LoaderWorker() {
  for (;;) {
    {
      std::unique_lock<std::mutex> lock(mutex_);
      job_cv_.wait(lock, [this]() { return queue_.size() > 0; });
      loading_ = queue_.front();
      queue_.pop_front();
    }

    if (!loading_) {
      break;
    }

    loading_->Load();
    std::lock_guard<std::mutex> lock(mutex_);
    done_.push_back(loading_);
    loading_ = nullptr;
  }
}

// static
int AsyncLoader::LoaderThread(void *user_data) {
  reinterpret_cast<AsyncLoader *>(user_data)->LoaderWorker();
  return 0;
}
}  // namespace fplbase


text:
#include "../cli/cli.hpp"

using AVM::Cli;

/**
 * Compile a Aml module or Aml script for AVM.
 */

int
main(const int argc, const char **argv) {
	return (new Cli("amlc", argc, argv))->run();
}


text:
This is an automatic setup script for setting up a Virtual Machine with [MediaWiki](https://www.mediawiki.org) (the software behind Wikipedia), [Semantic MediaWiki](https://www.semantic-mediawiki.org) (which adds structured data editing features to MediaWiki) and the [RDFIO](https://github.com/rdfio/RDFIO) extension, which adds data import, export and querying support to Semantic MediaWiki.

It is very simple to use: Clone this git repository into a folder on you computer, install Vagrant, Ansible and Virtualbox (which are super easy to install on most systems), and then run `vagrant up` in the folder, and just wait for the script to do its job. See the [installation section](#Installation) for more details.

In technical terms, this setup uses [Vagrant](https://www.vagrantup.com/) as a wrapper, to allow starting the script with one simple command (`vagrant up`) and [Ansible](https://www.ansible.com/) for doing the installation and configurations (often called "provisioning") in the background.

The fact that Ansible is used for provisioning, means that the installation
instructions are easy to understand and change, and that they can be equally
well installed elsewhere too, like in the cloud, or a local computer.

![RDFIO screenshot showing the in-built SPARQL endpoint](http://i.imgur.com/PMMIHZ4.png)

# Updates

**Sep 4, 2017:** Our paper on RDFIO was just published:

Lampa S, Willighagen E, Kohonen P, King A, Vrandečić D, Grafström R, Spjuth O

[RDFIO: extending Semantic MediaWiki for interoperable biomedical data management](https://jbiomedsem.biomedcentral.com/articles/10.1186/s13326-017-0136-y)

*Journal of Biomedical Semantics*. **8**:35 (2017). DOI: [10.1186/s13326-017-0136-y](https://dx.doi.org/10.1186/s13326-017-0136-y).

# Installation

## Prerequisites

The vagrant box requires the following softwares in order to set it up:

- [Virtualbox](https://www.virtualbox.org/)
- [Vagrant](https://www.vagrantup.com/)
- [Ansible](https://www.ansible.com/)
- An SSH Client (Already included in Linux and OS/X)

For Ubuntu 16.04, we provide brief installation instructions for them below:

### Virtualbox

Install on Ubuntu 16.04 with:

```bash
sudo apt-get install virtualbox
```

### Vagrant

Install on Ubuntu 16.04 by [downloading the debian installer](https://www.vagrantup.com/downloads.html) and installing it:

```bash
wget https://releases.hashicorp.com/vagrant/1.8.1/vagrant_1.8.1_x86_64.deb
sudo dpkg -i vagrant_1.8.1_x86_64.deb
```

### Ansible

**N.B:** Probably needs Ansible 2.x or higher! (Works well with 2.0.2, but **not** 1.7.2)

Install on Ubuntu 16.04 with:

```bash
sudo apt-get install ansible
```

## Bring up the Vagrant box

Clone this repo:

```bash
git clone https://github.com/rdfio/rdfio-vagrantbox
```
Enter the cloned folder:

```bash
cd rdfio-vagrantbox
```

... and let vagrant take care of the rest:

```bash
vagrant up
```

Surf in to your new MediaWiki installation on:

* [localhost:8080/w](http://localhost:8080/w)

Log in with "Admin" and "changethis".

Done!

To see the MediaWiki installation via the commandline, you can SSH in to your machine and enter the wiki installation folder like so:

```bash
vagrant ssh
cd /var/www/html/w
```

## Known issues

After bringing up the vagrant box, you might see an error like this:

```bash
==> virtualbox: mesg: ttyname failed: Inappropriate ioctl for device
```

This is a minor glitch with vagrant, and nothing to worry about.


text:
Acceptance tests are used to test<br>user interaction and application flow.

They emulate user interaction and confirm expected results.

---

Some acceptance tests you might write are:

- A user is able to log in via the login form.
- A user is able to create a blog post.
- A visitor does not have access to the admin panel.

### Sample acceptance test

ember-cli comes with acceptance test support out of the box. For creating your first test, you just need to run:

ember generate acceptance-test <name>

```
$ ember generate acceptance-test user-can-login-via-form
version: 1.13.8
installing acceptance-test
  create tests/acceptance/user-can-login-via-form-test.js

```

### Show Me The Code!

tests/acceptance/user-can-login-via-form-test.js

```javascript
import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from 'testing-ember/tests/helpers/start-app';

module('Acceptance | user can login via form', {
  beforeEach: function() {
    this.application = startApp();
  },

  afterEach: function() {
    Ember.run(this.application, 'destroy');
  }
});
```

```javascript
test('visiting /user-can-login-via-form', function(assert) {
  visit('/user-can-login-via-form');

  andThen(function() {
    assert.equal(currentURL(), '/user-can-login-via-form');
  });
});
```

Note:
This will only display in the notes window.


text:
enum AutoSizer_Follower
{
  AutoSizer_Follow_Left,
  AutoSizer_Follow_Right,
  AutoSizer_Follow_LeftRight,
  AutoSizer_Follow_HCenter,
  AutoSizer_Follow_Top,
  AutoSizer_Follow_Bottom,
  AutoSizer_Follow_TopBottom,
  AutoSizer_Follow_VCenter,
};

enum AutoSizer_Leader
{
  AutoSizer_Lead_Left,
  AutoSizer_Lead_Right,
  AutoSizer_Lead_HCenter,
  AutoSizer_Lead_Top,
  AutoSizer_Lead_Bottom,
  AutoSizer_Lead_VCenter,
};

enum AutoSizer_Refresh
{
  AutoSizer_Refresh_NoRefresh,
  AutoSizer_Refresh_Refresh,
  AutoSizer_Refresh_BkRefresh,
};

/////////////////////////////////////////////////////////////////////////////
// AutoSizerRule

struct AutoSizerRule
{
// Data Members
public:
  #pragma pack(push, 4)
    UINT               m_idFollower;
    UINT               m_idLeader;
    AutoSizer_Follower m_eFollower :12;
    AutoSizer_Leader   m_eLeader   :12;
    AutoSizer_Refresh  m_eRefresh  : 8;
  #pragma pack(pop)

// Attributes
public:
  bool IsEnd() const
  {
    return !m_idFollower;
  }
};

/////////////////////////////////////////////////////////////////////////////
// Rule Map Macros

#define BEGIN_AUTO_SIZER_MAP(name)                                          \
  static AutoSizerRule name [] =                                            \
  {

#define AUTO_SIZER_ENTRY(idFollow, edgeFollow, idLead, edgeLead, refresh)   \
    {                                                                       \
      (UINT)idFollow,                                                       \
      (UINT)idLead,                                                         \
      AutoSizer_Follow_##edgeFollow,                                        \
      AutoSizer_Lead_##edgeLead,                                            \
      AutoSizer_Refresh_##refresh                                           \
    },

#define END_AUTO_SIZER_MAP()                                                \
    AUTO_SIZER_ENTRY(0, Left, 0, Left, NoRefresh)                           \
  };

/////////////////////////////////////////////////////////////////////////////
// CAutoSizer

class CAutoSizer
{
// Construction / Destruction
public:
  CAutoSizer();

// Attributes
public:
  bool SetWindowAndRules(HWND hwnd, const AutoSizerRule* pRules);
  bool SetMinSize(int cx, int cy, bool bDlgUnits = true);
  bool SetMinSize(SIZE size, bool bDlgUnits = true);
  SIZE GetMinSize() const;
  HWND GetWindow() const;
  const RECT* GetClientRect() const;
  const RECT* GetOriginalClientRect() const;

// Operations
public:
  bool ProcessMessage(MSG* pMsg);
  bool ProcessMessage(UINT uMsg, WPARAM wp, LPARAM lp, LRESULT* plr);
  bool AddRule(HWND hwndFollower, AutoSizer_Follower edgeFollower,
    HWND hwndLeader, AutoSizer_Leader edgeLeader, AutoSizer_Refresh refresh);
  bool RemoveRules(HWND hwndFollower);

// Implementation
protected:
  void ComputeMinRects();
  void UpdatePositions();

// Message Handlers
protected:
  void OnDestroy();
  void OnGetMinMaxInfo(MINMAXINFO* pMMI);
  void OnSize(UINT nType, int cx, int cy);
  void OnStyleChanged();

// Types
protected:
  struct XRule
  {
    XRule();
    XRule(const AutoSizerRule* pRule);
    XRule(const XRule& that);
    const XRule& operator=(const AutoSizerRule* pRule);
    const XRule& operator=(const XRule& that);
    bool operator==(const AutoSizerRule* pRule);
    HWND GetFollower() const;
    HWND GetLeader() const;
    void ResolveIDs(CAutoSizer* pSizer);
    bool SaveInitialOffsets(CAutoSizer* pSizer);
    bool UpdateRectangle(CAutoSizer* pSizer, RECT& rcNew) const;
  private:
    AutoSizerRule m_Rule;
    int           m_Offsets[2];
  };
  typedef std::vector<XRule> XRules;
  typedef XRules::iterator   XRuleIt;

// Data Members
protected:
  XRules m_Rules;
  HWND   m_hwnd;
  RECT   m_rcMinClient;
  RECT   m_rcMinWindow;
  RECT   m_rcClient;
  RECT   m_rcClientOriginal;
  bool   m_bRecomputeMinWindow : 1;
};

/////////////////////////////////////////////////////////////////////////////
// Inline Attributes

inline bool CAutoSizer::SetMinSize(SIZE size, bool bDlgUnits)
{
  return SetMinSize(size.cx, size.cy, bDlgUnits);
}

inline SIZE CAutoSizer::GetMinSize() const
{
  SIZE size = {m_rcMinClient.right, m_rcMinClient.bottom};
  return size;
}

inline HWND CAutoSizer::GetWindow() const
{
  return m_hwnd;
}

inline const RECT* CAutoSizer::GetClientRect() const
{
  return &m_rcClient;
}

inline const RECT* CAutoSizer::GetOriginalClientRect() const
{
  return &m_rcClientOriginal;
}

/////////////////////////////////////////////////////////////////////////////

inline CAutoSizer::XRule::XRule()
{
  ZeroMemory(&m_Rule, sizeof(m_Rule));
  ZeroMemory(m_Offsets, sizeof(m_Offsets));
}

inline CAutoSizer::XRule::XRule(const AutoSizerRule* pRule)
{
  CopyMemory(&m_Rule, pRule, sizeof(m_Rule));
}

inline CAutoSizer::XRule::XRule(const XRule& that)
{
  CopyMemory(&m_Rule, &that.m_Rule, sizeof(m_Rule));
  CopyMemory(m_Offsets, that.m_Offsets, sizeof(m_Offsets));
}

inline const CAutoSizer::XRule& CAutoSizer::XRule::operator=(const AutoSizerRule* pRule)
{
  CopyMemory(&m_Rule, pRule, sizeof(m_Rule));
  ZeroMemory(m_Offsets, sizeof(m_Offsets));
  return *this;
}

inline const CAutoSizer::XRule& CAutoSizer::XRule::operator=(const XRule& that)
{
  CopyMemory(&m_Rule, &that.m_Rule, sizeof(m_Rule));
  CopyMemory(m_Offsets, that.m_Offsets, sizeof(m_Offsets));
  return *this;
}

inline bool CAutoSizer::XRule::operator==(const AutoSizerRule* pRule)
{
  return 0 == memcmp(pRule, &m_Rule, sizeof(m_Rule));
}

inline HWND CAutoSizer::XRule::GetFollower() const
{
  HWND hwnd = reinterpret_cast<HWND>(m_Rule.m_idFollower);
  _ASSERTE(::IsWindow(hwnd));
  return hwnd;
}

inline HWND CAutoSizer::XRule::GetLeader() const
{
  HWND hwnd = reinterpret_cast<HWND>(m_Rule.m_idLeader);
  _ASSERTE(::IsWindow(hwnd));
  return hwnd;
}

inline void CAutoSizer::XRule::ResolveIDs(CAutoSizer* pSizer)
{
  HWND hwndParent = pSizer->GetWindow();
  _ASSERTE(::IsWindow(hwndParent));

  HWND hwndFollower = m_Rule.m_idFollower ?
    ::GetDlgItem(hwndParent, m_Rule.m_idFollower) : hwndParent;
  _ASSERTE(::IsWindow(hwndFollower));
  m_Rule.m_idFollower = reinterpret_cast<UINT>(hwndFollower);

  HWND hwndLeader = m_Rule.m_idLeader ?
    ::GetDlgItem(hwndParent, m_Rule.m_idLeader) : hwndParent;
  _ASSERTE(::IsWindow(hwndLeader));
  m_Rule.m_idLeader = reinterpret_cast<UINT>(hwndLeader);
}

/////////////////////////////////////////////////////////////////////////////
// Message Macros for ATL usage

#ifdef _ATL
  #define AUTO_SIZER_MESSAGE_HANDLER(autoSizer)                             \
    if (autoSizer.ProcessMessage(uMsg, wParam, lParam, &lResult))           \
      return TRUE;
#endif // _ATL

/////////////////////////////////////////////////////////////////////////////

#endif // !__AutoSizer_h__


text:
Oro Doctrine Extensions
=======================

[![Build Status](https://travis-ci.org/orocrm/doctrine-extensions.svg?branch=master)](https://travis-ci.org/orocrm/doctrine-extensions)

Table of Contents
-----------------

- [DQL Functions](#dql-functions-list)
    - [Installation](#installation)
    - [Functions Registration](#functions-registration)
        - [Doctrine2](#doctrine2)
        - [Symfony2](#symfony2)
        - [Silex](#silex)
        - [Zend Framework 2](#zend-framework-2)
    - [Extendability and Database Support](#extendability-and-database-support)
        - [Architecture](#architecture)
        - [Adding new platform](#adding-new-platform)
        - [Adding new function](#adding-new-function)
- [Field Types](#field-types)

DQL Functions
=============

This library provide set of cross database doctrine DQL functions. Supported databases are MySQL and PostgreSQL.
Available functions:

* `DATE(expr)` - Extract the date part of a date or datetime expression
* `TIME(expr)` - Extract the time portion of the expression passed
* `TIMESTAMP(expr)` - Convert expression to TIMESTAMP
* `TIMESTAMPDIFF(unit, datetime_expr1, datetime_expr2)` - Returns *datetime_expr2* – *datetime_expr1*, where *datetime_expr1* and *datetime_expr2* are date or datetime expressions. The *unit* should be one of the following values: *MICROSECOND* (microseconds), *SECOND*, *MINUTE*, *HOUR*, *DAY*, *WEEK*, *MONTH*, *QUARTER*, or *YEAR*.
* `CONVERT_TZ(expr, from_tz, to_tz)` - Converts a datetime value expr from the time zone given by from_tz to the time zone given by to_tz and returns the resulting datetime value
* `DAY(expr)` - Return the day of the month (0-31)
* `DAYOFWEEK(expr)` - Returns the weekday index for date (1 = Sunday, 2 = Monday, …, 7 = Saturday). These index values correspond to the ODBC standard.
* `DAYOFMONTH(expr)` - Returns the day of the month for date, in the range 1 to 31, or 0 for dates such as '0000-00-00' or '2008-00-00' that have a zero day part.
* `DAYOFYEAR(expr)` - Return the day of the year (1-366)
* `HOUR(expr)` - Return the hour from the date passed
* `MINUTE(expr)` - Return the minute from the date passed
* `MONTH(expr)` - Return the month from the date passed
* `QUARTER(expr)` - Return the quarter from the date passed
* `SECOND(expr)` - Return the second from the date passed
* `WEEK(expr)` - The number of the week of the year that the day is in. By definition (ISO 8601), weeks start on Mondays and the first week of a year contains January 4 of that year. In other words, the first Thursday of a year is in week 1 of that year.
* `YEAR(expr)` - Return the year from the date passed
* `POW(expr, power)` - Return the argument raised to the specified power
* `SIGN(expr)` - Return the sign of the argument
* `CAST(expr as type)` - Takes an expression of any type and produces a result value of a specified type. Supported types are: "char, string, text, date, datetime, time, int, integer, decimal"
* `GROUP_CONCAT` - Return a concatenated string

GROUP_CONCAT full syntax:
```
GROUP_CONCAT([DISTINCT] expr [,expr ...]
            [ORDER BY {unsigned_integer | col_name | expr}
                [ASC | DESC] [,col_name ...]]
            [SEPARATOR str_val])
```

Installation
------------

Add the following dependency to your composer.json
```json
{
    "require": {
        "oro/doctrine-extensions": "dev-master"
    }
}
```
Functions Registration
----------------------

### Doctrine2

[Doctrine2 Documentation: "DQL User Defined Functions"](http://docs.doctrine-project.org/en/latest/cookbook/dql-user-defined-functions.html)

```php
<?php
$config = new \Doctrine\ORM\Configuration();
$config->addCustomStringFunction('group_concat', 'Oro\ORM\Query\AST\Functions\String\GroupConcat');
$config->addCustomNumericFunction('hour', 'Oro\ORM\Query\AST\Functions\SimpleFunction');
$config->addCustomDatetimeFunction('date', 'Oro\ORM\Query\AST\Functions\SimpleFunction');

$em = EntityManager::create($dbParams, $config);
```

### Symfony2

In Symfony2 you can register functions in `config.yml`

```yaml
doctrine:
    orm:
        dql:
            datetime_functions:
                date:           Oro\ORM\Query\AST\Functions\SimpleFunction
                time:           Oro\ORM\Query\AST\Functions\SimpleFunction
                timestamp:      Oro\ORM\Query\AST\Functions\SimpleFunction
                convert_tz:     Oro\ORM\Query\AST\Functions\DateTime\ConvertTz
            numeric_functions:
                timestampdiff:  Oro\ORM\Query\AST\Functions\Numeric\TimestampDiff
                dayofyear:      Oro\ORM\Query\AST\Functions\SimpleFunction
                dayofmonth:     Oro\ORM\Query\AST\Functions\SimpleFunction
                dayofweek:      Oro\ORM\Query\AST\Functions\SimpleFunction
                week:           Oro\ORM\Query\AST\Functions\SimpleFunction
                day:            Oro\ORM\Query\AST\Functions\SimpleFunction
                hour:           Oro\ORM\Query\AST\Functions\SimpleFunction
                minute:         Oro\ORM\Query\AST\Functions\SimpleFunction
                month:          Oro\ORM\Query\AST\Functions\SimpleFunction
                quarter:        Oro\ORM\Query\AST\Functions\SimpleFunction
                second:         Oro\ORM\Query\AST\Functions\SimpleFunction
                year:           Oro\ORM\Query\AST\Functions\SimpleFunction
                sign:           Oro\ORM\Query\AST\Functions\Numeric\Sign
                pow:            Oro\ORM\Query\AST\Functions\Numeric\Pow
            string_functions:
                group_concat:   Oro\ORM\Query\AST\Functions\String\GroupConcat
                cast:           Oro\ORM\Query\AST\Functions\Cast
```

### Silex

If you are using an ORM service provider make sure that you are adding the custom function to the configuration

for [palmasev/DoctrineORMServiceProvider](https://github.com/palmasev/DoctrineORMServiceProvider)

``` php

    $config = $app['doctrine_orm.configuration'];

    $config->addCustomDateTimeFunction( 'year', 'Oro\ORM\Query\AST\Functions\SimpleFunction' );
    $config->addCustomDateTimeFunction( 'month', 'Oro\ORM\Query\AST\Functions\SimpleFunction' );
```

for [dflydev/dflydev-doctrine-orm-service-provider](https://github.com/dflydev/dflydev-doctrine-orm-service-provider)

``` php

    $app->register( new Dflydev\Silex\Provider\DoctrineOrm\DoctrineOrmServiceProvider, [
        ...
        'orm.custom.functions.string' => [
            'cast'          => 'Oro\ORM\Query\AST\Functions\Cast',
            'group_concat'  => 'Oro\ORM\Query\AST\Functions\String\GroupConcat'
        ],
        'orm.custom.functions.datetime' => [
            'date'          => 'Oro\ORM\Query\AST\Functions\SimpleFunction',
            'time'          => 'Oro\ORM\Query\AST\Functions\SimpleFunction',
            'timestamp'     => 'Oro\ORM\Query\AST\Functions\SimpleFunction',
            'convert_tz'    => 'Oro\ORM\Query\AST\Functions\DateTime\ConvertTz'
        ],
        'orm.custom.functions.numeric' => [
            'timestampdiff' => 'Oro\ORM\Query\AST\Functions\Numeric\TimestampDiff',
            'dayofyear'     => 'Oro\ORM\Query\AST\Functions\SimpleFunction',
            'dayofweek'     => 'Oro\ORM\Query\AST\Functions\SimpleFunction',
            'week'          => 'Oro\ORM\Query\AST\Functions\SimpleFunction',
            'day'           => 'Oro\ORM\Query\AST\Functions\SimpleFunction',
            'hour'          => 'Oro\ORM\Query\AST\Functions\SimpleFunction',
            'minute'        => 'Oro\ORM\Query\AST\Functions\SimpleFunction',
            'month'         => 'Oro\ORM\Query\AST\Functions\SimpleFunction',
            'quarter'       => 'Oro\ORM\Query\AST\Functions\SimpleFunction',
            'second'        => 'Oro\ORM\Query\AST\Functions\SimpleFunction',
            'year'          => 'Oro\ORM\Query\AST\Functions\SimpleFunction',
            'sign'          => 'Oro\ORM\Query\AST\Functions\Numeric\Sign',
            'pow'           => 'Oro\ORM\Query\AST\Functions\Numeric\Pow',
        ]
    ]);
```
### Zend Framework 2

In Zend Framework 2 you can register functions in `config/autoload/doctrine.global.php`

``` php
return [
        'doctrine' => [
        'configuration' => [
            'orm_default' => [
                'datetime_functions' => [
                    'date' =>            'Oro\ORM\Query\AST\Functions\SimpleFunction',
                    'time' =>            'Oro\ORM\Query\AST\Functions\SimpleFunction',
                    'timestamp' =>      'Oro\ORM\Query\AST\Functions\SimpleFunction',
                    'convert_tz' =>      'Oro\ORM\Query\AST\Functions\DateTime\ConvertTz',
                ],
                'numeric_functions' => [
                    'timestampdiff'  =>  'Oro\ORM\Query\AST\Functions\Numeric\TimestampDiff',
                    'dayofyear'  =>      'Oro\ORM\Query\AST\Functions\SimpleFunction',
                    'dayofmonth'  =>     'Oro\ORM\Query\AST\Functions\SimpleFunction',
                    'dayofweek'  =>      'Oro\ORM\Query\AST\Functions\SimpleFunction',
                    'week'  =>           'Oro\ORM\Query\AST\Functions\SimpleFunction',
                    'day'  =>            'Oro\ORM\Query\AST\Functions\SimpleFunction',
                    'hour'  =>           'Oro\ORM\Query\AST\Functions\SimpleFunction',
                    'minute'  =>         'Oro\ORM\Query\AST\Functions\SimpleFunction',
                    'month'  =>          'Oro\ORM\Query\AST\Functions\SimpleFunction',
                    'quarter'  =>        'Oro\ORM\Query\AST\Functions\SimpleFunction',
                    'second'  =>         'Oro\ORM\Query\AST\Functions\SimpleFunction',
                    'year'  =>           'Oro\ORM\Query\AST\Functions\SimpleFunction',
                    'sign'  =>           'Oro\ORM\Query\AST\Functions\Numeric\Sign',
                    'pow'  =>            'Oro\ORM\Query\AST\Functions\Numeric\Pow',
                ],
                'string_functions' => [
                    'group_concat' =>   'Oro\ORM\Query\AST\Functions\String\GroupConcat',
                    'cast' =>           'Oro\ORM\Query\AST\Functions\Cast'
                ]
            ]
        ]
    ]
];
```
Extendability and Database Support
----------------------------------

### Architecture

Most of functions, that require only one ArithmeticPrimary argument may be parsed with `Oro\ORM\Query\AST\Functions\SimpleFunction`.
This class is responsible for parsing function definition and saving parsed data to parameters. It is extended from
`Oro\ORM\Query\AST\Functions\AbstractPlatformAwareFunctionNode`. This layer work with DQL function parsing.
SQL generation is responsibility of platform specific functions, that extends `PlatformFunctionNode`.
`AbstractPlatformAwareFunctionNode` creates appropriate instance of platform function based on current connection Database Platform instance name and DQL function name.

Platform function classes naming rule is:

```
Oro\ORM\Query\AST\Platform\Functions\$platformName\$functionName
```

### Adding new platform
To add support of new platform you just need to create new folder `Oro\ORM\Query\AST\Platform\Functions\$platformName`
and implement required function there according to naming rules

### Adding new function

In case when your function is function with only one ArithmeticPrimary argument you may not create DQL function parser
and use `Oro\ORM\Query\AST\Functions\SimpleFunction` for this.
Then only platform specific SQL implementation of your function is required.

In case when your are implementing more complex function, like GROUP_CONCAT both DQL parser and SQL implementations are required.

If you want to add new function to this library feel free to fork it and create pull request with your implementation.
Please, remember to update documentation with your new functions. All new functions MUST be implemented for all platforms.

Field Types
===========

This library also consist additional field types:

* `MoneyType`
* `PercentType`
* `ObjectType`
* `ArrayType`

`ObjectType` and `ArrayType` use base64 encoded string to store values in Db instead of storing serialized strings.
For backward compatibility values that are already stored in Db will be unserialized without base64 encoding. New values
will be base64 encoded before storing in Db and base64 decoded before unserialization.


text:
namespace swri_console_util
{
  class ProgressBar
  {
  public:
    ProgressBar();
    ~ProgressBar();

    void SetStartTime(const ros::WallTime& start_time);
    void SetProgress(double percent_complete);
    void PrintTime();
    void CheckForPause();
    char ReadCharFromStdin();

    static std::string GetTimeString(double seconds);
    static std::string IntToString(int64_t i, int width = 0);

  private:
    void SetupTerminal();
    void RestoreTerminal();

    bool paused_;

    double percent_complete_;

    ros::WallTime start_time_;
    ros::WallDuration paused_time_;

    termios orig_flags_;
    fd_set  stdin_fdset_;
    int     maxfd_;
  };
}

#endif  // CONSOLE_UTIL_PROGRESS_BAR_H_