text:
#include <stdexcept>
#include "sweep.h"
#include "sweep_context.h"
#include "advancing_front.h"
#include "../common/utils.h"

namespace p2t {

// Triangulate simple polygon with holes
void Sweep::Triangulate(SweepContext& tcx)
{
  tcx.InitTriangulation();
  tcx.CreateAdvancingFront(nodes_);
  // Sweep points; build mesh
  SweepPoints(tcx);
  // Clean up
  FinalizationPolygon(tcx);
}

void Sweep::SweepPoints(SweepContext& tcx)
{
  for (int i = 1; i < tcx.point_count(); i++) {
    Point& point = *tcx.GetPoint(i);
    Node* node = &PointEvent(tcx, point);
    for (unsigned int i = 0; i < point.edge_list.size(); i++) {
      EdgeEvent(tcx, point.edge_list[i], node);
    }
  }
}

void Sweep::FinalizationPolygon(SweepContext& tcx)
{
  // Get an Internal triangle to start with
  Triangle* t = tcx.front()->head()->next->triangle;
  Point* p = tcx.front()->head()->next->point;
  while (!t->GetConstrainedEdgeCW(*p)) {
    t = t->NeighborCCW(*p);
  }

  // Collect interior triangles constrained by edges
  tcx.MeshClean(*t);
}

Node& Sweep::PointEvent(SweepContext& tcx, Point& point)
{
  Node& node = tcx.LocateNode(point);
  Node& new_node = NewFrontTriangle(tcx, point, node);

  // Only need to check +epsilon since point never have smaller
  // x value than node due to how we fetch nodes from the front
  if (point.x <= node.point->x + EPSILON) {
    Fill(tcx, node);
  }

  //tcx.AddNode(new_node);

  FillAdvancingFront(tcx, new_node);
  return new_node;
}

void Sweep::EdgeEvent(SweepContext& tcx, Edge* edge, Node* node)
{
  tcx.edge_event.constrained_edge = edge;
  tcx.edge_event.right = (edge->p->x > edge->q->x);

  if (IsEdgeSideOfTriangle(*node->triangle, *edge->p, *edge->q)) {
    return;
  }

  // For now we will do all needed filling
  // TODO: integrate with flip process might give some better performance
  //       but for now this avoid the issue with cases that needs both flips and fills
  FillEdgeEvent(tcx, edge, node);
  EdgeEvent(tcx, *edge->p, *edge->q, node->triangle, *edge->q);
}

void Sweep::EdgeEvent(SweepContext& tcx, Point& ep, Point& eq, Triangle* triangle, Point& point)
{
  if (IsEdgeSideOfTriangle(*triangle, ep, eq)) {
    return;
  }

  Point* p1 = triangle->PointCCW(point);
  Orientation o1 = Orient2d(eq, *p1, ep);
  if (o1 == COLLINEAR) {
    if( triangle->Contains(&eq, p1)) {
      triangle->MarkConstrainedEdge(&eq, p1 );
      // We are modifying the constraint maybe it would be better to
      // not change the given constraint and just keep a variable for the new constraint
      tcx.edge_event.constrained_edge->q = p1;
      triangle = &triangle->NeighborAcross(point);
      EdgeEvent( tcx, ep, *p1, triangle, *p1 );
    } else {
      std::runtime_error("EdgeEvent - collinear points not supported");
      assert(0);
    }
    return;
  }

  Point* p2 = triangle->PointCW(point);
  Orientation o2 = Orient2d(eq, *p2, ep);
  if (o2 == COLLINEAR) {
    if( triangle->Contains(&eq, p2)) {
      triangle->MarkConstrainedEdge(&eq, p2 );
      // We are modifying the constraint maybe it would be better to
      // not change the given constraint and just keep a variable for the new constraint
      tcx.edge_event.constrained_edge->q = p2;
      triangle = &triangle->NeighborAcross(point);
      EdgeEvent( tcx, ep, *p2, triangle, *p2 );
    } else {
      std::runtime_error("EdgeEvent - collinear points not supported");
      assert(0);
    }
    return;
  }

  if (o1 == o2) {
    // Need to decide if we are rotating CW or CCW to get to a triangle
    // that will cross edge
    if (o1 == CW) {
      triangle = triangle->NeighborCCW(point);
    }       else{
      triangle = triangle->NeighborCW(point);
    }
    EdgeEvent(tcx, ep, eq, triangle, point);
  } else {
    // This triangle crosses constraint so lets flippin start!
    FlipEdgeEvent(tcx, ep, eq, triangle, point);
  }
}

bool Sweep::IsEdgeSideOfTriangle(Triangle& triangle, Point& ep, Point& eq)
{
  int index = triangle.EdgeIndex(&ep, &eq);

  if (index != -1) {
    triangle.MarkConstrainedEdge(index);
    Triangle* t = triangle.GetNeighbor(index);
    if (t) {
      t->MarkConstrainedEdge(&ep, &eq);
    }
    return true;
  }
  return false;
}

Node& Sweep::NewFrontTriangle(SweepContext& tcx, Point& point, Node& node)
{
  Triangle* triangle = new Triangle(point, *node.point, *node.next->point);

  triangle->MarkNeighbor(*node.triangle);
  tcx.AddToMap(triangle);

  Node* new_node = new Node(point);
  nodes_.push_back(new_node);

  new_node->next = node.next;
  new_node->prev = &node;
  node.next->prev = new_node;
  node.next = new_node;

  if (!Legalize(tcx, *triangle)) {
    tcx.MapTriangleToNodes(*triangle);
  }

  return *new_node;
}

void Sweep::Fill(SweepContext& tcx, Node& node)
{
  Triangle* triangle = new Triangle(*node.prev->point, *node.point, *node.next->point);

  // TODO: should copy the constrained_edge value from neighbor triangles
  //       for now constrained_edge values are copied during the legalize
  triangle->MarkNeighbor(*node.prev->triangle);
  triangle->MarkNeighbor(*node.triangle);

  tcx.AddToMap(triangle);

  // Update the advancing front
  node.prev->next = node.next;
  node.next->prev = node.prev;

  // If it was legalized the triangle has already been mapped
  if (!Legalize(tcx, *triangle)) {
    tcx.MapTriangleToNodes(*triangle);
  }

}

void Sweep::FillAdvancingFront(SweepContext& tcx, Node& n)
{

  // Fill right holes
  Node* node = n.next;

  while (node->next) {
    // if HoleAngle exceeds 90 degrees then break.
    if (LargeHole_DontFill(node)) break;
    Fill(tcx, *node);
    node = node->next;
  }

  // Fill left holes
  node = n.prev;

  while (node->prev) {
    // if HoleAngle exceeds 90 degrees then break.
    if (LargeHole_DontFill(node)) break;
    Fill(tcx, *node);
    node = node->prev;
  }

  // Fill right basins
  if (n.next && n.next->next) {
    double angle = BasinAngle(n);
    if (angle < PI_3div4) {
      FillBasin(tcx, n);
    }
  }
}

// True if HoleAngle exceeds 90 degrees.
bool Sweep::LargeHole_DontFill(Node* node) {

  Node* nextNode = node->next;
  Node* prevNode = node->prev;
  if (!AngleExceeds90Degrees(node->point, nextNode->point, prevNode->point))
          return false;

  // Check additional points on front.
  Node* next2Node = nextNode->next;
  // "..Plus.." because only want angles on same side as point being added.
  if ((next2Node != NULL) && !AngleExceedsPlus90DegreesOrIsNegative(node->point, next2Node->point, prevNode->point))
          return false;

  Node* prev2Node = prevNode->prev;
  // "..Plus.." because only want angles on same side as point being added.
  if ((prev2Node != NULL) && !AngleExceedsPlus90DegreesOrIsNegative(node->point, nextNode->point, prev2Node->point))
          return false;

  return true;
}

bool Sweep::AngleExceeds90Degrees(Point* origin, Point* pa, Point* pb) {
  double angle = Angle(*origin, *pa, *pb);
  bool exceeds90Degrees = ((angle > PI_div2) || (angle < -PI_div2));
  return exceeds90Degrees;
}

bool Sweep::AngleExceedsPlus90DegreesOrIsNegative(Point* origin, Point* pa, Point* pb) {
  double angle = Angle(*origin, *pa, *pb);
  bool exceedsPlus90DegreesOrIsNegative = (angle > PI_div2) || (angle < 0);
  return exceedsPlus90DegreesOrIsNegative;
}

double Sweep::Angle(Point& origin, Point& pa, Point& pb) {
  /* Complex plane
   * ab = cosA +i*sinA
   * ab = (ax + ay*i)(bx + by*i) = (ax*bx + ay*by) + i(ax*by-ay*bx)
   * atan2(y,x) computes the principal value of the argument function
   * applied to the complex number x+iy
   * Where x = ax*bx + ay*by
   *       y = ax*by - ay*bx
   */
  double px = origin.x;
  double py = origin.y;
  double ax = pa.x- px;
  double ay = pa.y - py;
  double bx = pb.x - px;
  double by = pb.y - py;
  double x = ax * by - ay * bx;
  double y = ax * bx + ay * by;
  double angle = atan2(x, y);
  return angle;
}

double Sweep::BasinAngle(Node& node)
{
  double ax = node.point->x - node.next->next->point->x;
  double ay = node.point->y - node.next->next->point->y;
  return atan2(ay, ax);
}

double Sweep::HoleAngle(Node& node)
{
  /* Complex plane
   * ab = cosA +i*sinA
   * ab = (ax + ay*i)(bx + by*i) = (ax*bx + ay*by) + i(ax*by-ay*bx)
   * atan2(y,x) computes the principal value of the argument function
   * applied to the complex number x+iy
   * Where x = ax*bx + ay*by
   *       y = ax*by - ay*bx
   */
  double ax = node.next->point->x - node.point->x;
  double ay = node.next->point->y - node.point->y;
  double bx = node.prev->point->x - node.point->x;
  double by = node.prev->point->y - node.point->y;
  return atan2(ax * by - ay * bx, ax * bx + ay * by);
}

bool Sweep::Legalize(SweepContext& tcx, Triangle& t)
{
  // To legalize a triangle we start by finding if any of the three edges
  // violate the Delaunay condition
  for (int i = 0; i < 3; i++) {
    if (t.delaunay_edge[i])
      continue;

    Triangle* ot = t.GetNeighbor(i);

    if (ot) {
      Point* p = t.GetPoint(i);
      Point* op = ot->OppositePoint(t, *p);
      int oi = ot->Index(op);

      // If this is a Constrained Edge or a Delaunay Edge(only during recursive legalization)
      // then we should not try to legalize
      if (ot->constrained_edge[oi] || ot->delaunay_edge[oi]) {
        t.constrained_edge[i] = ot->constrained_edge[oi];
        continue;
      }

      bool inside = Incircle(*p, *t.PointCCW(*p), *t.PointCW(*p), *op);

      if (inside) {
        // Lets mark this shared edge as Delaunay
        t.delaunay_edge[i] = true;
        ot->delaunay_edge[oi] = true;

        // Lets rotate shared edge one vertex CW to legalize it
        RotateTrianglePair(t, *p, *ot, *op);

        // We now got one valid Delaunay Edge shared by two triangles
        // This gives us 4 new edges to check for Delaunay

        // Make sure that triangle to node mapping is done only one time for a specific triangle
        bool not_legalized = !Legalize(tcx, t);
        if (not_legalized) {
          tcx.MapTriangleToNodes(t);
        }

        not_legalized = !Legalize(tcx, *ot);
        if (not_legalized)
          tcx.MapTriangleToNodes(*ot);

        // Reset the Delaunay edges, since they only are valid Delaunay edges
        // until we add a new triangle or point.
        // XXX: need to think about this. Can these edges be tried after we
        //      return to previous recursive level?
        t.delaunay_edge[i] = false;
        ot->delaunay_edge[oi] = false;

        // If triangle have been legalized no need to check the other edges since
        // the recursive legalization will handles those so we can end here.
        return true;
      }
    }
  }
  return false;
}

bool Sweep::Incircle(Point& pa, Point& pb, Point& pc, Point& pd)
{
  double adx = pa.x - pd.x;
  double ady = pa.y - pd.y;
  double bdx = pb.x - pd.x;
  double bdy = pb.y - pd.y;

  double adxbdy = adx * bdy;
  double bdxady = bdx * ady;
  double oabd = adxbdy - bdxady;

  if (oabd <= 0)
    return false;

  double cdx = pc.x - pd.x;
  double cdy = pc.y - pd.y;

  double cdxady = cdx * ady;
  double adxcdy = adx * cdy;
  double ocad = cdxady - adxcdy;

  if (ocad <= 0)
    return false;

  double bdxcdy = bdx * cdy;
  double cdxbdy = cdx * bdy;

  double alift = adx * adx + ady * ady;
  double blift = bdx * bdx + bdy * bdy;
  double clift = cdx * cdx + cdy * cdy;

  double det = alift * (bdxcdy - cdxbdy) + blift * ocad + clift * oabd;

  return det > 0;
}

void Sweep::RotateTrianglePair(Triangle& t, Point& p, Triangle& ot, Point& op)
{
  Triangle* n1, *n2, *n3, *n4;
  n1 = t.NeighborCCW(p);
  n2 = t.NeighborCW(p);
  n3 = ot.NeighborCCW(op);
  n4 = ot.NeighborCW(op);

  bool ce1, ce2, ce3, ce4;
  ce1 = t.GetConstrainedEdgeCCW(p);
  ce2 = t.GetConstrainedEdgeCW(p);
  ce3 = ot.GetConstrainedEdgeCCW(op);
  ce4 = ot.GetConstrainedEdgeCW(op);

  bool de1, de2, de3, de4;
  de1 = t.GetDelunayEdgeCCW(p);
  de2 = t.GetDelunayEdgeCW(p);
  de3 = ot.GetDelunayEdgeCCW(op);
  de4 = ot.GetDelunayEdgeCW(op);

  t.Legalize(p, op);
  ot.Legalize(op, p);

  // Remap delaunay_edge
  ot.SetDelunayEdgeCCW(p, de1);
  t.SetDelunayEdgeCW(p, de2);
  t.SetDelunayEdgeCCW(op, de3);
  ot.SetDelunayEdgeCW(op, de4);

  // Remap constrained_edge
  ot.SetConstrainedEdgeCCW(p, ce1);
  t.SetConstrainedEdgeCW(p, ce2);
  t.SetConstrainedEdgeCCW(op, ce3);
  ot.SetConstrainedEdgeCW(op, ce4);

  // Remap neighbors
  // XXX: might optimize the markNeighbor by keeping track of
  //      what side should be assigned to what neighbor after the
  //      rotation. Now mark neighbor does lots of testing to find
  //      the right side.
  t.ClearNeighbors();
  ot.ClearNeighbors();
  if (n1) ot.MarkNeighbor(*n1);
  if (n2) t.MarkNeighbor(*n2);
  if (n3) t.MarkNeighbor(*n3);
  if (n4) ot.MarkNeighbor(*n4);
  t.MarkNeighbor(ot);
}

void Sweep::FillBasin(SweepContext& tcx, Node& node)
{
  if (Orient2d(*node.point, *node.next->point, *node.next->next->point) == CCW) {
    tcx.basin.left_node = node.next->next;
  } else {
    tcx.basin.left_node = node.next;
  }

  // Find the bottom and right node
  tcx.basin.bottom_node = tcx.basin.left_node;
  while (tcx.basin.bottom_node->next
         && tcx.basin.bottom_node->point->y >= tcx.basin.bottom_node->next->point->y) {
    tcx.basin.bottom_node = tcx.basin.bottom_node->next;
  }
  if (tcx.basin.bottom_node == tcx.basin.left_node) {
    // No valid basin
    return;
  }

  tcx.basin.right_node = tcx.basin.bottom_node;
  while (tcx.basin.right_node->next
         && tcx.basin.right_node->point->y < tcx.basin.right_node->next->point->y) {
    tcx.basin.right_node = tcx.basin.right_node->next;
  }
  if (tcx.basin.right_node == tcx.basin.bottom_node) {
    // No valid basins
    return;
  }

  tcx.basin.width = tcx.basin.right_node->point->x - tcx.basin.left_node->point->x;
  tcx.basin.left_highest = tcx.basin.left_node->point->y > tcx.basin.right_node->point->y;

  FillBasinReq(tcx, tcx.basin.bottom_node);
}

void Sweep::FillBasinReq(SweepContext& tcx, Node* node)
{
  // if shallow stop filling
  if (IsShallow(tcx, *node)) {
    return;
  }

  Fill(tcx, *node);

  if (node->prev == tcx.basin.left_node && node->next == tcx.basin.right_node) {
    return;
  } else if (node->prev == tcx.basin.left_node) {
    Orientation o = Orient2d(*node->point, *node->next->point, *node->next->next->point);
    if (o == CW) {
      return;
    }
    node = node->next;
  } else if (node->next == tcx.basin.right_node) {
    Orientation o = Orient2d(*node->point, *node->prev->point, *node->prev->prev->point);
    if (o == CCW) {
      return;
    }
    node = node->prev;
  } else {
    // Continue with the neighbor node with lowest Y value
    if (node->prev->point->y < node->next->point->y) {
      node = node->prev;
    } else {
      node = node->next;
    }
  }

  FillBasinReq(tcx, node);
}

bool Sweep::IsShallow(SweepContext& tcx, Node& node)
{
  double height;

  if (tcx.basin.left_highest) {
    height = tcx.basin.left_node->point->y - node.point->y;
  } else {
    height = tcx.basin.right_node->point->y - node.point->y;
  }

  // if shallow stop filling
  if (tcx.basin.width > height) {
    return true;
  }
  return false;
}

void Sweep::FillEdgeEvent(SweepContext& tcx, Edge* edge, Node* node)
{
  if (tcx.edge_event.right) {
    FillRightAboveEdgeEvent(tcx, edge, node);
  } else {
    FillLeftAboveEdgeEvent(tcx, edge, node);
  }
}

void Sweep::FillRightAboveEdgeEvent(SweepContext& tcx, Edge* edge, Node* node)
{
  while (node->next->point->x < edge->p->x) {
    // Check if next node is below the edge
    if (Orient2d(*edge->q, *node->next->point, *edge->p) == CCW) {
      FillRightBelowEdgeEvent(tcx, edge, *node);
    } else {
      node = node->next;
    }
  }
}

void Sweep::FillRightBelowEdgeEvent(SweepContext& tcx, Edge* edge, Node& node)
{
  if (node.point->x < edge->p->x) {
    if (Orient2d(*node.point, *node.next->point, *node.next->next->point) == CCW) {
      // Concave
      FillRightConcaveEdgeEvent(tcx, edge, node);
    } else{
      // Convex
      FillRightConvexEdgeEvent(tcx, edge, node);
      // Retry this one
      FillRightBelowEdgeEvent(tcx, edge, node);
    }
  }
}

void Sweep::FillRightConcaveEdgeEvent(SweepContext& tcx, Edge* edge, Node& node)
{
  Fill(tcx, *node.next);
  if (node.next->point != edge->p) {
    // Next above or below edge?
    if (Orient2d(*edge->q, *node.next->point, *edge->p) == CCW) {
      // Below
      if (Orient2d(*node.point, *node.next->point, *node.next->next->point) == CCW) {
        // Next is concave
        FillRightConcaveEdgeEvent(tcx, edge, node);
      } else {
        // Next is convex
      }
    }
  }

}

void Sweep::FillRightConvexEdgeEvent(SweepContext& tcx, Edge* edge, Node& node)
{
  // Next concave or convex?
  if (Orient2d(*node.next->point, *node.next->next->point, *node.next->next->next->point) == CCW) {
    // Concave
    FillRightConcaveEdgeEvent(tcx, edge, *node.next);
  } else{
    // Convex
    // Next above or below edge?
    if (Orient2d(*edge->q, *node.next->next->point, *edge->p) == CCW) {
      // Below
      FillRightConvexEdgeEvent(tcx, edge, *node.next);
    } else{
      // Above
    }
  }
}

void Sweep::FillLeftAboveEdgeEvent(SweepContext& tcx, Edge* edge, Node* node)
{
  while (node->prev->point->x > edge->p->x) {
    // Check if next node is below the edge
    if (Orient2d(*edge->q, *node->prev->point, *edge->p) == CW) {
      FillLeftBelowEdgeEvent(tcx, edge, *node);
    } else {
      node = node->prev;
    }
  }
}

void Sweep::FillLeftBelowEdgeEvent(SweepContext& tcx, Edge* edge, Node& node)
{
  if (node.point->x > edge->p->x) {
    if (Orient2d(*node.point, *node.prev->point, *node.prev->prev->point) == CW) {
      // Concave
      FillLeftConcaveEdgeEvent(tcx, edge, node);
    } else {
      // Convex
      FillLeftConvexEdgeEvent(tcx, edge, node);
      // Retry this one
      FillLeftBelowEdgeEvent(tcx, edge, node);
    }
  }
}

void Sweep::FillLeftConvexEdgeEvent(SweepContext& tcx, Edge* edge, Node& node)
{
  // Next concave or convex?
  if (Orient2d(*node.prev->point, *node.prev->prev->point, *node.prev->prev->prev->point) == CW) {
    // Concave
    FillLeftConcaveEdgeEvent(tcx, edge, *node.prev);
  } else{
    // Convex
    // Next above or below edge?
    if (Orient2d(*edge->q, *node.prev->prev->point, *edge->p) == CW) {
      // Below
      FillLeftConvexEdgeEvent(tcx, edge, *node.prev);
    } else{
      // Above
    }
  }
}

void Sweep::FillLeftConcaveEdgeEvent(SweepContext& tcx, Edge* edge, Node& node)
{
  Fill(tcx, *node.prev);
  if (node.prev->point != edge->p) {
    // Next above or below edge?
    if (Orient2d(*edge->q, *node.prev->point, *edge->p) == CW) {
      // Below
      if (Orient2d(*node.point, *node.prev->point, *node.prev->prev->point) == CW) {
        // Next is concave
        FillLeftConcaveEdgeEvent(tcx, edge, node);
      } else{
        // Next is convex
      }
    }
  }

}

void Sweep::FlipEdgeEvent(SweepContext& tcx, Point& ep, Point& eq, Triangle* t, Point& p)
{
  Triangle& ot = t->NeighborAcross(p);
  Point& op = *ot.OppositePoint(*t, p);

  if (&ot == NULL) {
    // If we want to integrate the fillEdgeEvent do it here
    // With current implementation we should never get here
    //throw new RuntimeException( "[BUG:FIXME] FLIP failed due to missing triangle");
    assert(0);
  }

  if (InScanArea(p, *t->PointCCW(p), *t->PointCW(p), op)) {
    // Lets rotate shared edge one vertex CW
    RotateTrianglePair(*t, p, ot, op);
    tcx.MapTriangleToNodes(*t);
    tcx.MapTriangleToNodes(ot);

    if (p == eq && op == ep) {
      if (eq == *tcx.edge_event.constrained_edge->q && ep == *tcx.edge_event.constrained_edge->p) {
        t->MarkConstrainedEdge(&ep, &eq);
        ot.MarkConstrainedEdge(&ep, &eq);
        Legalize(tcx, *t);
        Legalize(tcx, ot);
      } else {
        // XXX: I think one of the triangles should be legalized here?
      }
    } else {
      Orientation o = Orient2d(eq, op, ep);
      t = &NextFlipTriangle(tcx, (int)o, *t, ot, p, op);
      FlipEdgeEvent(tcx, ep, eq, t, p);
    }
  } else {
    Point& newP = NextFlipPoint(ep, eq, ot, op);
    FlipScanEdgeEvent(tcx, ep, eq, *t, ot, newP);
    EdgeEvent(tcx, ep, eq, t, p);
  }
}

Triangle& Sweep::NextFlipTriangle(SweepContext& tcx, int o, Triangle& t, Triangle& ot, Point& p, Point& op)
{
  if (o == CCW) {
    // ot is not crossing edge after flip
    int edge_index = ot.EdgeIndex(&p, &op);
    ot.delaunay_edge[edge_index] = true;
    Legalize(tcx, ot);
    ot.ClearDelunayEdges();
    return t;
  }

  // t is not crossing edge after flip
  int edge_index = t.EdgeIndex(&p, &op);

  t.delaunay_edge[edge_index] = true;
  Legalize(tcx, t);
  t.ClearDelunayEdges();
  return ot;
}

Point& Sweep::NextFlipPoint(Point& ep, Point& eq, Triangle& ot, Point& op)
{
  Orientation o2d = Orient2d(eq, op, ep);
  if (o2d == CW) {
    // Right
    return *ot.PointCCW(op);
  } else if (o2d == CCW) {
    // Left
    return *ot.PointCW(op);
  } else {
    //throw new RuntimeException("[Unsupported] Opposing point on constrained edge");
    assert(0);
    return *ot.PointCCW(op);
  }
}

void Sweep::FlipScanEdgeEvent(SweepContext& tcx, Point& ep, Point& eq, Triangle& flip_triangle,
                              Triangle& t, Point& p)
{
  Triangle& ot = t.NeighborAcross(p);
  Point& op = *ot.OppositePoint(t, p);

  if (&t.NeighborAcross(p) == NULL) {
    // If we want to integrate the fillEdgeEvent do it here
    // With current implementation we should never get here
    //throw new RuntimeException( "[BUG:FIXME] FLIP failed due to missing triangle");
    assert(0);
  }

  if (InScanArea(eq, *flip_triangle.PointCCW(eq), *flip_triangle.PointCW(eq), op)) {
    // flip with new edge op->eq
    FlipEdgeEvent(tcx, eq, op, &ot, op);
    // TODO: Actually I just figured out that it should be possible to
    //       improve this by getting the next ot and op before the the above
    //       flip and continue the flipScanEdgeEvent here
    // set new ot and op here and loop back to inScanArea test
    // also need to set a new flip_triangle first
    // Turns out at first glance that this is somewhat complicated
    // so it will have to wait.
  } else{
    Point& newP = NextFlipPoint(ep, eq, ot, op);
    FlipScanEdgeEvent(tcx, ep, eq, flip_triangle, ot, newP);
  }
}

Sweep::~Sweep() {

    // Clean up memory
    for(size_t i = 0; i < nodes_.size(); i++) {
        delete nodes_[i];
    }

}

}


text:
package test.app.sample.bo;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.ibatis.session.*;
import test.app.sample.dao.*;
import test.app.sample.domain.Fda3;
import test.app.sample.util.BoException;

public class Fda3Bo {

    private static Fda3Bo instance = new Fda3Bo();

    public static Fda3Bo getInstance() {
        return instance;
    }

    private Fda3Bo() {
    }

    public int create( Fda3 value ) throws BoException {
        SqlSession session = null;
        int result = 0;

        try {
            session = SessionFactory.getSession();
            Fda3Dao mapper = session.getMapper( Fda3Dao.class );
            result = mapper.create( value );
            session.commit();

        } catch ( Exception e ) {
            session.rollback();
            throw new BoException( e );

        } finally {
            if ( session != null )
                session.close();
        }

        return result;
    }

    public int update( Fda3 value ) throws BoException {
        SqlSession session = null;
        int result = 0;

        try {
            session = SessionFactory.getSession();
            Fda3Dao mapper = session.getMapper( Fda3Dao.class );
            result = mapper.update( value );
            session.commit();

        } catch ( Exception e ) {
            session.rollback();
            throw new BoException( e );

        } finally {
            if ( session != null )
                session.close();
        }

        return result;
    }

    public int delete( Long key ) throws BoException {
        SqlSession session = null;
        int result = 0;
        String where = "KEY='" + key + "' ";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put( "where", where );

        try {
            session = SessionFactory.getSession();
            Fda3Dao mapper = session.getMapper( Fda3Dao.class );
            result = mapper.delete( map );
            session.commit();

        } catch ( Exception e ) {
            session.rollback();
            throw new BoException( e );

        } finally {
            if ( session != null )
                session.close();
        }

        return result;
    }

    public Fda3 read( Long key ) throws BoException {
        SqlSession session = null;
        Fda3 result;
        String where = "KEY='" + key + "' ";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put( "where", where );

        try {
            session = SessionFactory.getSession();
            Fda3Dao mapper = session.getMapper( Fda3Dao.class );
            result = mapper.read( map );
            session.commit();

        } catch ( Exception e ) {
            session.rollback();
            throw new BoException( e );

        } finally {
            if ( session != null )
                session.close();
        }

        return result;
    }

    // PROTECTED CODE -->

}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hadoop.hive.ql.parse;

import org.apache.calcite.rel.RelNode;

/**
 * Wrapper of Calcite plan.
 */
public class CBOPlan {
  private final RelNode plan;
  private final String invalidAutomaticRewritingMaterializationReason;

  public CBOPlan(RelNode plan, String invalidAutomaticRewritingMaterializationReason) {
    this.plan = plan;
    this.invalidAutomaticRewritingMaterializationReason = invalidAutomaticRewritingMaterializationReason;
  }

  /**
   * Root node of plan.
   * @return Root {@link RelNode}
   */
  public RelNode getPlan() {
    return plan;
  }

  /**
   * Returns an error message if this plan can not be a definition of a Materialized view which is an input of
   * Calcite based materialized view query rewrite.
   * Null or empty string otherwise.
   * @return String contains error message or null.
   */
  public String getInvalidAutomaticRewritingMaterializationReason() {
    return invalidAutomaticRewritingMaterializationReason;
  }
}


text:
package org.apache.cxf.buslifecycle;

/**
 * The manager interface for registering BusLifeCycleListeners.
 *
 * A class that implements the BusLifeCycleListener interface can be
 * registered or unregistered to receive notification of Bus
 * lifecycle events.
 */
public interface BusLifeCycleManager extends BusLifeCycleListener {

    /**
     * Register a listener to receive Bus lifecycle notification.
     *
     * @param listener The BusLifeCycleListener that will
     * receive the events.
     */
    void registerLifeCycleListener(BusLifeCycleListener listener);

    /**
     * Unregister a listener so that it will no longer receive Bus
     * lifecycle events.
     *
     * @param listener The BusLifeCycleListener to unregister.
     */
    void unregisterLifeCycleListener(BusLifeCycleListener listener);
}


text:
<?php
/**
 * Class is adding routing for plugin
 *
 * @package    sfDoctrineGuardConfirmPlugin
 * @subpackage lib.routing
 * @author     Daniel Ancuta <whisller@gmail.com>
 */
class sfGuardConfirmRouting
{
    /**
     * Listens to the routing.load_configuration event.
     *
     * @param sfEvent An sfEvent instance
     */
    static public function listenToRoutingLoadConfigurationEvent(sfEvent $event)
    {
        $r = $event->getSubject();

        // preprend our routes

        // add route for action to confirm by user
        $r->prependRoute('sf_doctrine_guard_confirm_plugin', new sfRoute('/sf_guard_confirm/:hash/:kind', array('module' => 'sfGuardConfirm',
                                                                                'action' => 'Confirm')));
    }
}


text:
// Generated by dts-bundle-generator v6.5.0

import { BindingExpression, EventManager, Expression, ListenerExpression, LookupFunctions, ObserverLocator, Parser, SVGAnalyzer, bindingMode } from 'aurelia-binding';
import { BehaviorInstruction, BindingLanguage, HtmlBehaviorResource, ViewResources } from 'aurelia-templating';

export declare class AttributeMap {
	elements: any;
	allElements: any;
	constructor(svg: SVGAnalyzer);
	/**
	 * Maps a specific HTML element attribute to a javascript property.
	 */
	register(elementName: string, attributeName: string, propertyName: string): void;
	/**
	 * Maps an HTML attribute to a javascript property.
	 */
	registerUniversal(attributeName: string, propertyName: string): void;
	/**
	 * Returns the javascript property name for a particlar HTML attribute.
	 */
	map(elementName: string, attributeName: string): any;
}
export declare class InterpolationBindingExpression {
	constructor(observerLocator: ObserverLocator, targetProperty: string, parts: (string | Expression)[], mode: bindingMode, lookupFunctions: LookupFunctions, attribute: string);
	createBinding(target: any): ChildInterpolationBinding | InterpolationBinding;
}
export declare class InterpolationBinding {
	constructor(observerLocator: ObserverLocator, parts: (string | Expression)[], target: any, targetProperty: string, mode: bindingMode, lookupFunctions: LookupFunctions);
	interpolate(): void;
	updateOneTimeBindings(): void;
	bind(source: any): void;
	unbind(): void;
}
export declare class ChildInterpolationBinding {
	constructor(target: InterpolationBinding, observerLocator: ObserverLocator, sourceExpression: Expression, mode: bindingMode, lookupFunctions: LookupFunctions, targetProperty?: string, left?: string, right?: string);
	updateTarget(value: any): void;
	call(): void;
	bind(source: any): void;
	unbind(): void;
	connect(evaluate: any): void;
}
/**
 * An object describing information analyzed from an attribute in an Aurelia templates
 */
export interface AttributeInfo {
	command?: string;
	expression?: string | BindingExpression;
	attrName?: string;
	attrValue?: string;
	defaultBindingMode?: bindingMode;
}
export declare class SyntaxInterpreter {
	language: BindingLanguage;
	constructor(parser: Parser, observerLocator: ObserverLocator, eventManager: EventManager, attributeMap: AttributeMap);
	interpret(resources: ViewResources, element: Element, info: AttributeInfo, existingInstruction?: BehaviorInstruction, context?: HtmlBehaviorResource): any;
	handleUnknownCommand(resources: ViewResources, element: Element, info: AttributeInfo, existingInstruction: BehaviorInstruction, context: HtmlBehaviorResource): BehaviorInstruction;
	determineDefaultBindingMode(element: Element, attrName: string, context: HtmlBehaviorResource): bindingMode;
	bind(resources: ViewResources, element: Element, info: AttributeInfo, existingInstruction: BehaviorInstruction, context: HtmlBehaviorResource): BehaviorInstruction;
	trigger(resources: ViewResources, element: any, info: AttributeInfo): ListenerExpression;
	capture(resources: ViewResources, element: any, info: AttributeInfo): ListenerExpression;
	delegate(resources: ViewResources, element: any, info: AttributeInfo): ListenerExpression;
	call(resources: ViewResources, element: any, info: AttributeInfo, existingInstruction: BehaviorInstruction): BehaviorInstruction;
	options(resources: ViewResources, element: Element, info: AttributeInfo, existingInstruction: BehaviorInstruction, context: HtmlBehaviorResource): BehaviorInstruction;
	"for"(resources: ViewResources, element: Element, info: AttributeInfo, existingInstruction: BehaviorInstruction): BehaviorInstruction & {
		attributes: Record<string, any>;
	};
	"two-way"(resources: ViewResources, element: Element, info: AttributeInfo, existingInstruction: BehaviorInstruction): BehaviorInstruction;
	"to-view"(resources: ViewResources, element: Element, info: AttributeInfo, existingInstruction: BehaviorInstruction): BehaviorInstruction;
	"from-view"(resources: ViewResources, element: Element, info: AttributeInfo, existingInstruction: BehaviorInstruction): BehaviorInstruction;
	"one-time"(resources: ViewResources, element: Element, info: AttributeInfo, existingInstruction: BehaviorInstruction): BehaviorInstruction;
}
export declare class TemplatingBindingLanguage extends BindingLanguage {
	constructor(parser: Parser, observerLocator: ObserverLocator, syntaxInterpreter: SyntaxInterpreter, attributeMap: AttributeMap);
	inspectAttribute(resources: ViewResources, elementName: string, attrName: string, attrValue: string): AttributeInfo;
	createAttributeInstruction(resources: ViewResources, element: Element, theInfo: AttributeInfo, existingInstruction: BehaviorInstruction, context: HtmlBehaviorResource): any;
	createLetExpressions(resources: ViewResources, letElement: Element): any[];
	inspectTextContent(resources: ViewResources, value: string): InterpolationBindingExpression;
	parseInterpolation(resources: ViewResources, value: string): any;
}
export declare class LetExpression {
	/**
	 * @param observerLocator
	 * @param targetProperty
	 * @param sourceExpression
	 * @param lookupFunctions
	 * @param toBindingContext indicates let binding result should be assigned to binding context
	 */
	constructor(observerLocator: ObserverLocator, targetProperty: string, sourceExpression: Expression, lookupFunctions: LookupFunctions, toBindingContext: boolean);
	createBinding(): LetBinding;
}
export declare class LetBinding {
	/**
	 * @param observerLocator
	 * @param sourceExpression
	 * @param targetProperty
	 * @param lookupFunctions
	 * @param toBindingContext indicates let binding result should be assigned to binding context
	 */
	constructor(observerLocator: ObserverLocator, sourceExpression: Expression, targetProperty: string, lookupFunctions: LookupFunctions, toBindingContext: boolean);
	updateTarget(): void;
	call(context: any): void;
	/**
	 * @param {Scope} source Binding context
	 */
	bind(source: any): void;
	unbind(): void;
	unobserve(arg0: boolean): void;
	connect(): void;
}
export declare class LetInterpolationBindingExpression {
	/**
	 * @param {ObserverLocator} observerLocator
	 * @param {string} targetProperty
	 * @param {string[]} parts
	 * @param {LookupFunctions} lookupFunctions
	 * @param {boolean} toBindingContext indicates let binding result should be assigned to binding context
	 */
	constructor(observerLocator: ObserverLocator, targetProperty: string, parts: string[], lookupFunctions: LookupFunctions, toBindingContext: boolean);
	createBinding(): LetInterpolationBinding;
}
export declare class LetInterpolationBinding {
	/**
	 * @param observerLocator
	 * @param targetProperty
	 * @param parts
	 * @param lookupFunctions
	 * @param toBindingContext indicates let binding result should be assigned to binding context
	 */
	constructor(observerLocator: ObserverLocator, targetProperty: string, parts: (string | Expression)[], lookupFunctions: LookupFunctions, toBindingContext: boolean);
	/**
	 * @param {Scope} source
	 */
	bind(source: any): void;
	unbind(): void;
	createInterpolationBinding(): ChildInterpolationBinding | InterpolationBinding;
}
export declare function configure(config: any): void;

export {};


text:
import os
import shutil
import bob.io.base
import bob.io.base.test_utils
import bob.db.base
import tempfile
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

regenerate_database = False
dbfile = bob.io.base.test_utils.datafile("test_db.sql3", "bob.db.base")
Base = declarative_base()

class TestFile (Base, bob.db.base.File):
    __tablename__ = "file"
    id = Column(Integer, primary_key=True)
    client_id = Column(Integer, unique=True)
    path = Column(String(100), unique=True)

    def __init__(self):
        bob.db.base.File.__init__(self, path="test/path")
        self.client_id = 5

def create_database():
    if os.path.exists(dbfile):
        os.remove(dbfile)
    import bob.db.base.utils
    engine = bob.db.base.utils.create_engine_try_nolock(
        'sqlite', dbfile, echo=True)
    Base.metadata.create_all(engine)
    session = bob.db.base.utils.session('sqlite', dbfile, echo=True)
    session.add(TestFile())
    session.commit()
    session.close()
    del session
    del engine

class TestDatabase (bob.db.base.SQLiteDatabase):

    def __init__(self):
        super(TestDatabase, self).__init__(dbfile, TestFile, None, None)

    def groups(self, protocol=None):
        return ['group']

    def model_ids(self, groups=None, protocol=None):
        return [5]

    def objects(self, groups=None, protocol=None, purposes=None,
                model_ids=None):
        return list(self.query(TestFile))

    def tmodel_ids(self, groups=None, protocol=None):
        return self.model_ids()

    def tobjects(self, groups=None, protocol=None, model_ids=None):
        return self.objects()

    def zobjects(self, groups=None, protocol=None):
        return self.objects()

    def annotations(self, file):
        assert isinstance(file, TestFile)
        return {'key': (42, 180)}

def test01_annotations():
    # tests the annotation IO functionality provided by this utility class

    # check the different annotation types
    for annotation_type in ('eyecenter', 'named', 'idiap', 'json'):
        # get the annotation file name
        annotation_file = bob.io.base.test_utils.datafile(
            "%s.pos" % annotation_type, 'bob.db.base')
        # read the annotations
        annotations = bob.db.base.read_annotation_file(
            annotation_file, annotation_type)
        # check
        assert 'leye' in annotations
        assert 'reye' in annotations
        assert tuple(annotations['leye']) == (20, 40), annotations['leye']
        assert tuple(annotations['reye']) == (20, 10), annotations['reye']
        if annotation_type == 'named':
            assert 'pose' in annotations
            assert annotations['pose'] == 30
        if annotation_type == 'idiap':
            assert 'gender' in annotations
            assert annotations['gender'] == ['M']

def test02_database():
    # check that the database API works
    if regenerate_database:
        create_database()

    db = TestDatabase()

    def check_file(fs):
        assert len(fs) == 1
        f = fs[0]
        assert isinstance(f, TestFile)
        assert f.id == 1
        assert f.client_id == 5
        assert f.path == "test/path"

    check_file(db.objects())
    check_file(db.tobjects())
    check_file(db.zobjects())
    check_file(db.all_files())
    check_file(db.files([1]))
    check_file(db.reverse(["test/path"]))

    model_ids = db.model_ids()
    assert len(model_ids) == 1
    assert model_ids[0] == 5
    tmodel_ids = db.tmodel_ids()
    assert len(tmodel_ids) == 1
    assert tmodel_ids[0] == 5

    file = db.objects()[0]
    assert db.paths([1], "another/directory",
                    ".other")[0] == "another/directory/test/path.other"

    annots = db.annotations(file)
    assert len(annots) == 1
    assert 'key' in annots.keys()
    assert (42, 180) in annots.values()

    # try file save
    temp_dir = tempfile.mkdtemp(prefix="bob_db_test_")
    data = [1., 2., 3.]
    file.save(data, temp_dir)
    assert os.path.exists(file.make_path(temp_dir, ".hdf5"))
    read_data = bob.io.base.load(file.make_path(temp_dir, ".hdf5"))
    for i in range(3):
        assert data[i] == read_data[i]
    shutil.rmtree(temp_dir)

    # check closing and re-opening database connection
    del db
    db = TestDatabase()
    check_file(db.objects())


text:
namespace disk_cache {

void* MappedFile::Init(const base::FilePath& name, size_t size) {
  DCHECK(!init_);
  if (init_ || !File::Init(name))
    return NULL;

  buffer_ = NULL;
  init_ = true;
  section_ = CreateFileMapping(platform_file(), NULL, PAGE_READWRITE, 0,
                               static_cast<DWORD>(size), NULL);
  if (!section_)
    return NULL;

  buffer_ = MapViewOfFile(section_, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, size);
  DCHECK(buffer_);
  view_size_ = size;

  // Make sure we detect hardware failures reading the headers.
  size_t temp_len = size ? size : 4096;
  std::unique_ptr<char[]> temp(new char[temp_len]);
  if (!Read(temp.get(), temp_len, 0))
    return NULL;

  return buffer_;
}

MappedFile::~MappedFile() {
  if (!init_)
    return;

  if (buffer_) {
    BOOL ret = UnmapViewOfFile(buffer_);
    DCHECK(ret);
  }

  if (section_)
    CloseHandle(section_);
}

void MappedFile::Flush() {
}

}  // namespace disk_cache


text:
/*
 *
 * EmailVerificationPodcastItem
 *
 */

import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import Paper from 'material-ui/Paper';

export class EmailVerificationPodcastItem extends React.Component {

  showPodcast = () => {
    if (this.props.pendingPodcast) {
      const imageUrl = this.props.pendingPodcast.artworkUrl60;
      return (
        <Paper style={{ width: '300px', height: '200px', textalign: 'center' }}>

{this.props.pendingPodcast.collectionName} by {this.props.pendingPodcast.artistName}

        </Paper>
      );
    }
    return (

Select a Podcast

    );
  }

  render() {
    return (

        {this.showPodcast()}

    );
  }
}

EmailVerificationPodcastItem.propTypes = {
  pendingPodcast: PropTypes.object,
};

function mapStateToProps(state) {
  return {
    pendingPodcast: state.podcasts.selectedPodcast.podcast,
  };
}

export default connect(mapStateToProps)(EmailVerificationPodcastItem);


text:
using System;
using AutoMapper;

namespace Benchmark.Flattening
{
    using System.Collections.Generic;
    using System.Linq;

    public class DeepTypeMapper : IObjectToObjectMapper
    {
        private Customer _customer;
        private IMapper _mapper;
        public string Name { get; } = "Deep Types";
        public void Initialize()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Address, Address>();
                cfg.CreateMap<Address, AddressDTO>();
                cfg.CreateMap<Customer, CustomerDTO>();
            });
            config.AssertConfigurationIsValid();
            _mapper = config.CreateMapper();
            _customer = new Customer()
            {
                Address = new Address() { City = "istanbul", Country = "turkey", Id = 1, Street = "istiklal cad." },
                HomeAddress = new Address() { City = "istanbul", Country = "turkey", Id = 2, Street = "istiklal cad." },
                Id = 1,
                Name = "Eduardo Najera",
                Credit = 234.7m,
                WorkAddresses = new List<Address>()
                {
                    new Address() {City = "istanbul", Country = "turkey", Id = 5, Street = "istiklal cad."},
                    new Address() {City = "izmir", Country = "turkey", Id = 6, Street = "konak"}
                },
                Addresses = new List<Address>()
                {
                    new Address() {City = "istanbul", Country = "turkey", Id = 3, Street = "istiklal cad."},
                    new Address() {City = "izmir", Country = "turkey", Id = 4, Street = "konak"}
                }.ToArray()
            };
        }

        public object Map()
        {
            return _mapper.Map<Customer, CustomerDTO>(_customer);
        }

        public class Address
        {
            public int Id { get; set; }
            public string Street { get; set; }
            public string City { get; set; }
            public string Country { get; set; }
        }

        public class AddressDTO
        {
            public int Id { get; set; }
            public string City { get; set; }
            public string Country { get; set; }
        }

        public class Customer
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public decimal? Credit { get; set; }
            public Address Address { get; set; }
            public Address HomeAddress { get; set; }
            public Address[] Addresses { get; set; }
            public List<Address> WorkAddresses { get; set; }
        }

        public class CustomerDTO
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public Address Address { get; set; }
            public AddressDTO HomeAddress { get; set; }
            public AddressDTO[] Addresses { get; set; }
            public List<AddressDTO> WorkAddresses { get; set; }
            public string AddressCity { get; set; }
        }

    }

    public class ManualDeepTypeMapper : IObjectToObjectMapper
    {
        private Customer _customer;
        public string Name { get; } = "Manual Deep Types";
        public void Initialize()
        {
            _customer = new Customer()
            {
                Address = new Address() { City = "istanbul", Country = "turkey", Id = 1, Street = "istiklal cad." },
                HomeAddress = new Address() { City = "istanbul", Country = "turkey", Id = 2, Street = "istiklal cad." },
                Id = 1,
                Name = "Eduardo Najera",
                Credit = 234.7m,
                WorkAddresses = new List<Address>()
                {
                    new Address() {City = "istanbul", Country = "turkey", Id = 5, Street = "istiklal cad."},
                    new Address() {City = "izmir", Country = "turkey", Id = 6, Street = "konak"}
                },
                Addresses = new List<Address>()
                {
                    new Address() {City = "istanbul", Country = "turkey", Id = 3, Street = "istiklal cad."},
                    new Address() {City = "izmir", Country = "turkey", Id = 4, Street = "konak"}
                }.ToArray()
            };
        }

        public object Map()
        {
            var dto = new CustomerDTO();

            dto.Id = _customer.Id;
            dto.Name = _customer.Name;
            dto.AddressCity = _customer.Address.City;

            dto.Address = new Address() { Id = _customer.Address.Id, Street = _customer.Address.Street, Country = _customer.Address.Country, City = _customer.Address.City };

            dto.HomeAddress = new AddressDTO() { Id = _customer.HomeAddress.Id, Country = _customer.HomeAddress.Country, City = _customer.HomeAddress.City };

            dto.Addresses = new AddressDTO[_customer.Addresses.Length];
            for (int i = 0; i < _customer.Addresses.Length; i++)
            {
                dto.Addresses[i] = new AddressDTO() { Id = _customer.Addresses[i].Id, Country = _customer.Addresses[i].Country, City = _customer.Addresses[i].City };
            }

            dto.WorkAddresses = new List<AddressDTO>();
            foreach (var workAddress in _customer.WorkAddresses)
            {
                dto.WorkAddresses.Add(new AddressDTO() { Id = workAddress.Id, Country = workAddress.Country, City = workAddress.City });
            }

            return dto;
        }

        public class Address
        {
            public int Id { get; set; }
            public string Street { get; set; }
            public string City { get; set; }
            public string Country { get; set; }
        }

        public class AddressDTO
        {
            public int Id { get; set; }
            public string City { get; set; }
            public string Country { get; set; }
        }

        public class Customer
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public decimal? Credit { get; set; }
            public Address Address { get; set; }
            public Address HomeAddress { get; set; }
            public Address[] Addresses { get; set; }
            public ICollection<Address> WorkAddresses { get; set; }
        }

        public class CustomerDTO
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public Address Address { get; set; }
            public AddressDTO HomeAddress { get; set; }
            public AddressDTO[] Addresses { get; set; }
            public List<AddressDTO> WorkAddresses { get; set; }
            public string AddressCity { get; set; }
        }

    }

    public class ComplexTypeMapper : IObjectToObjectMapper
    {
        private Foo _foo;
        public string Name { get; } = "Complex Types";
        private IMapper _mapper;

        public void Initialize()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Foo, FooDest>();
                cfg.CreateMap<InnerFoo, InnerFooDest>();
            });
            config.AssertConfigurationIsValid();
            _mapper = config.CreateMapper();
            _foo = Foo.New();
        }

        public object Map()
        {
            var dest = _mapper.Map<Foo, FooDest>(_foo);
            return dest;
        }
    }

    public class Foo
    {
        public static Foo New() => new Foo
        {
            Name = "foo",
            Int32 = 12,
            Int64 = 123123,
            NullInt = 16,
            DateTime = DateTime.Now,
            Doublen = 2312112,
            Foo1 = new InnerFoo { Name = "foo one" },
            Foos = new List<InnerFoo>
                {
                    new InnerFoo {Name = "j1", Int64 = 123, NullInt = 321},
                    new InnerFoo {Name = "j2", Int32 = 12345, NullInt = 54321},
                    new InnerFoo {Name = "j3", Int32 = 12345, NullInt = 54321},
                },
            FooArr = new[]
                {
                    new InnerFoo {Name = "a1"},
                    new InnerFoo {Name = "a2"},
                    new InnerFoo {Name = "a3"},
                },
            IntArr = new[] { 1, 2, 3, 4, 5 },
            Ints = new[] { 7, 8, 9 },
        };

        public string Name { get; set; }

        public int Int32 { get; set; }

        public long Int64 { set; get; }

        public int? NullInt { get; set; }

        public float Floatn { get; set; }

        public double Doublen { get; set; }

        public DateTime DateTime { get; set; }

        public InnerFoo Foo1 { get; set; }

        public List<InnerFoo> Foos { get; set; }

        public InnerFoo[] FooArr { get; set; }

        public int[] IntArr { get; set; }

        public int[] Ints { get; set; }
    }

    public class InnerFoo
    {
        public string Name { get; set; }
        public int Int32 { get; set; }
        public long Int64 { set; get; }
        public int? NullInt { get; set; }
    }

    public class InnerFooDest
    {
        public string Name { get; set; }
        public int Int32 { get; set; }
        public long Int64 { set; get; }
        public int? NullInt { get; set; }
    }

    public class FooDest
    {
        public string Name { get; set; }

        public int Int32 { get; set; }

        public long Int64 { set; get; }

        public int? NullInt { get; set; }

        public float Floatn { get; set; }

        public double Doublen { get; set; }

        public DateTime DateTime { get; set; }

        public InnerFooDest Foo1 { get; set; }

        public List<InnerFooDest> Foos { get; set; }

        public InnerFooDest[] FooArr { get; set; }

        public int[] IntArr { get; set; }

        public int[] Ints { get; set; }
    }

    public class ManualComplexTypeMapper : IObjectToObjectMapper
    {
        private Foo _foo;
        public string Name { get; } = "Manual Complex Types";

        public void Initialize()
        {
            _foo = Foo.New();
        }

        public object Map()
        {
            var dest = new FooDest
            {
                Name = _foo.Name,
                Int32 = _foo.Int32,
                Int64 = _foo.Int64,
                NullInt = _foo.NullInt,
                DateTime = _foo.DateTime,
                Doublen = _foo.Doublen,
                Foo1 = new InnerFooDest { Name = _foo.Foo1.Name },
                Foos = new List<InnerFooDest>(_foo.Foos.Count),
                FooArr = new InnerFooDest[_foo.Foos.Count],
                IntArr = new int[_foo.IntArr.Length],
                Ints = _foo.Ints.ToArray(),
            };
            foreach(var foo in _foo.Foos)
            {
                dest.Foos.Add(new InnerFooDest { Name = foo.Name, Int64 = foo.Int64, NullInt = foo.NullInt });
            }
            ;
            for(int index = 0; index < _foo.Foos.Count; index++)
            {
                var foo = _foo.Foos[index];
                dest.FooArr[index] = new InnerFooDest { Name = foo.Name, Int64 = foo.Int64, NullInt = foo.NullInt };
            }
            Array.Copy(_foo.IntArr, dest.IntArr, _foo.IntArr.Length);
            return dest;
        }
    }

    public class CtorMapper : IObjectToObjectMapper
    {
        private Model11 _model;

        public string Name => "CtorMapper";

        private IMapper _mapper;

        public void Initialize()
        {
            var config = new MapperConfiguration(cfg => cfg.CreateMap<Model11, Dto11>());
            config.AssertConfigurationIsValid();
            _mapper = config.CreateMapper();
            _model = new Model11 { Value = 5 };
        }

        public object Map()
        {
            return _mapper.Map<Model11, Dto11>(_model);
        }
    }

    public class ManualCtorMapper : IObjectToObjectMapper
    {
        private Model11 _model;

        public string Name => "ManualCtorMapper";

        public void Initialize()
        {
            _model = new Model11 { Value = 5 };
        }

        public object Map()
        {
            return new Dto11(_model.Value);
        }
    }

    public class FlatteningMapper : IObjectToObjectMapper
    {
        private ModelObject _source;
        private IMapper _mapper;

        public string Name
        {
            get { return "AutoMapper"; }
        }

        public void Initialize()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Model1, Dto1>();
                cfg.CreateMap<Model2, Dto2>();
                cfg.CreateMap<Model3, Dto3>();
                cfg.CreateMap<Model4, Dto4>();
                cfg.CreateMap<Model5, Dto5>();
                cfg.CreateMap<Model6, Dto6>();
                cfg.CreateMap<Model7, Dto7>();
                cfg.CreateMap<Model8, Dto8>();
                cfg.CreateMap<Model9, Dto9>();
                cfg.CreateMap<Model10, Dto10>();
                cfg.CreateMap<ModelObject, ModelDto>();
            });
            config.AssertConfigurationIsValid();
            _mapper = config.CreateMapper();
            _source = new ModelObject
            {
                BaseDate = new DateTime(2007, 4, 5),
                Sub = new ModelSubObject
                {
                    ProperName = "Some name",
                    SubSub = new ModelSubSubObject
                    {
                        IAmACoolProperty = "Cool daddy-o"
                    }
                },
                Sub2 = new ModelSubObject
                {
                    ProperName = "Sub 2 name"
                },
                SubWithExtraName = new ModelSubObject
                {
                    ProperName = "Some other name"
                },
            };
        }

        public object Map()
        {
            return _mapper.Map<ModelObject, ModelDto>(_source);
        }
    }

    public class ManualMapper : IObjectToObjectMapper
    {
        private ModelObject _source;

        public string Name
        {
            get { return "Manual"; }
        }

        public void Initialize()
        {
            _source = new ModelObject
            {
                BaseDate = new DateTime(2007, 4, 5),
                Sub = new ModelSubObject
                {
                    ProperName = "Some name",
                    SubSub = new ModelSubSubObject
                    {
                        IAmACoolProperty = "Cool daddy-o"
                    }
                },
                Sub2 = new ModelSubObject
                {
                    ProperName = "Sub 2 name"
                },
                SubWithExtraName = new ModelSubObject
                {
                    ProperName = "Some other name"
                },
            };
        }

        public object Map()
        {
            return new ModelDto
            {
                BaseDate = _source.BaseDate,
                Sub2ProperName = _source.Sub2.ProperName,
                SubProperName = _source.Sub.ProperName,
                SubSubSubIAmACoolProperty = _source.Sub.SubSub.IAmACoolProperty,
                SubWithExtraNameProperName = _source.SubWithExtraName.ProperName
            };
        }
    }

    public class Model1
    {
        public int Value { get; set; }
    }

    public class Model2
    {
        public int Value { get; set; }
    }

    public class Model3
    {
        public int Value { get; set; }
    }

    public class Model4
    {
        public int Value { get; set; }
    }

    public class Model5
    {
        public int Value { get; set; }
    }

    public class Model6
    {
        public int Value { get; set; }
    }

    public class Model7
    {
        public int Value { get; set; }
    }

    public class Model8
    {
        public int Value { get; set; }
    }

    public class Model9
    {
        public int Value { get; set; }
    }

    public class Model10
    {
        public int Value { get; set; }
    }

    public class Model11
    {
        public int Value { get; set; }
    }

    public class Dto1
    {
        public int Value { get; set; }
    }

    public class Dto2
    {
        public int Value { get; set; }
    }

    public class Dto3
    {
        public int Value { get; set; }
    }

    public class Dto4
    {
        public int Value { get; set; }
    }

    public class Dto5
    {
        public int Value { get; set; }
    }

    public class Dto6
    {
        public int Value { get; set; }
    }

    public class Dto7
    {
        public int Value { get; set; }
    }

    public class Dto8
    {
        public int Value { get; set; }
    }

    public class Dto9
    {
        public int Value { get; set; }
    }

    public class Dto10
    {
        public int Value { get; set; }
    }

    public class Dto11
    {
        public Dto11(int value)
        {
            _value = value;
        }

        private readonly int _value;

        public int Value
        {
            get { return _value; }
        }
    }

    public class ModelObject
    {
        public DateTime BaseDate { get; set; }
        public ModelSubObject Sub { get; set; }
        public ModelSubObject Sub2 { get; set; }
        public ModelSubObject SubWithExtraName { get; set; }
    }

    public class ModelSubObject
    {
        public string ProperName { get; set; }
        public ModelSubSubObject SubSub { get; set; }
    }

    public class ModelSubSubObject
    {
        public string IAmACoolProperty { get; set; }
    }

    public class ModelDto
    {
        public DateTime BaseDate { get; set; }
        public string SubProperName { get; set; }
        public string Sub2ProperName { get; set; }
        public string SubWithExtraNameProperName { get; set; }
        public string SubSubSubIAmACoolProperty { get; set; }
    }

}


text:
<!DOCTYPE html>

SVG sizing test permutations

  <form>

DOCTYPE:

    <input type="radio" name="docType" value="html5" checked="checked" onchange="handleChange();" />HTML 5
    <input type="radio" name="docType" value="html4quirks" onchange="handleChange();" />HTML 4 Transitional
    <input type="radio" name="docType" value="html4strict" onchange="handleChange()" />HTML 4 Strict

Native / SVG Web Mode:

    <input type="radio" name="svgWebMode" value="pureNative" checked="checked" onchange="handleChange()" />Native SVG
    <input type="radio" name="svgWebMode" value="svgWebNative" onchange="handleChange()" />Native w/SVG Web present
    <input type="radio" name="svgWebMode" value="svgWebFlash" onchange="handleChange()" />SVG Web in Flash mode

Tag Type:

    <input type="radio" name="tagType" value="object" checked="checked" onchange="handleChange()" />object

    <input type="radio" name="tagType" value="svg" onchange="handleChange()" />svg (requires HTML 5 browser)

    <input type="radio" name="tagType" value="script" onchange="handleChange()" />script (requires SVG Web)

    <input type="radio" name="tagType" value="img" onchange="handleChange()" />img (requires HTML 5 browser)

Parent type:

    <input type="radio" name="parentType" value="div" checked="checked" onchange="handleChange()" />div
    <input type="radio" name="parentType" value="body" onchange="handleChange()" />body

Div width:

    <input type="radio" name="divWidthType" value="pixels" checked="checked" onchange="handleChange()" />pixels
    <input type="radio" name="divWidthType" value="percent" onchange="handleChange()" />percent
    <input type="radio" name="divWidthType" value="absent" onchange="handleChange()" />absent

Div height:

    <input type="radio" name="divHeightType" value="pixels" checked="checked" onchange="handleChange()" />pixels
    <input type="radio" name="divHeightType" value="percent" onchange="handleChange()" />percent
    <input type="radio" name="divHeightType" value="absent" onchange="handleChange()" />absent

object/img width:

    <input type="radio" name="objectWidthType" value="pixels" checked="checked" onchange="handleChange()" />pixels
    <input type="radio" name="objectWidthType" value="percent" onchange="handleChange()" />percent
    <input type="radio" name="objectWidthType" value="absent" onchange="handleChange()" />absent

object/img height:

    <input type="radio" name="objectHeightType" value="pixels" checked="checked" onchange="handleChange()" />pixels
    <input type="radio" name="objectHeightType" value="percent" onchange="handleChange()" />percent
    <input type="radio" name="objectHeightType" value="absent" onchange="handleChange()" />absent

SVG viewBox:

    <input type="radio" name="viewBoxMode" value="present" checked="checked" onchange="handleChange()" />present
    <input type="radio" name="viewBoxMode" value="absent" onchange="handleChange()" />absent

SVG preserveAspectRatio:

    <input type="radio" name="preserveAspectRatioType" value="meet" checked="checked" onchange="handleChange()" />meet
    <input type="radio" name="preserveAspectRatioType" value="slice" onchange="handleChange()" />slice
    <input type="radio" name="preserveAspectRatioType" value="none" onchange="handleChange()" />none
    <input type="radio" name="preserveAspectRatioType" value="absent" onchange="handleChange()" />absent

SVG width

    <input type="radio" name="svgWidthType" value="pixels" checked="checked" onchange="handleChange()" />pixels
    <input type="radio" name="svgWidthType" value="percent" onchange="handleChange()" />percent
    <input type="radio" name="svgWidthType" value="absent" onchange="handleChange()" />absent

SVG height:

    <input type="radio" name="svgHeightType" value="pixels" checked="checked" onchange="handleChange()" />pixels
    <input type="radio" name="svgHeightType" value="percent" onchange="handleChange()" />percent
    <input type="radio" name="svgHeightType" value="absent" onchange="handleChange()" />absent

HTML and PHP source code

     Test controller (HTML)

     HTML generator (PHP)

     SVG generator (PHP)

  </form>


text:
class DropFileCategoryModel : public QAbstractItemModel
{
  Q_OBJECT

public:

  DropFileCategoryModel(QObject * a_pParent = nullptr);

  virtual ~DropFileCategoryModel();

  virtual QModelIndex index(int a_row, int a_column,
    const QModelIndex & a_parent = QModelIndex()) const override;

  virtual QModelIndex parent(const QModelIndex & a_child) const override;

  virtual Qt::ItemFlags flags(const QModelIndex & a_index) const override;

  virtual QVariant data(const QModelIndex & a_index,
    int a_role = Qt::DisplayRole) const override;

  virtual QVariant headerData(int a_section, Qt::Orientation a_orientation,
    int a_role = Qt::DisplayRole) const override;

  virtual int rowCount(const QModelIndex & a_parent = QModelIndex())
    const override;

  virtual int columnCount(const QModelIndex & a_parent = QModelIndex())
    const override;

  virtual bool setData(const QModelIndex & a_index, const QVariant & a_value,
    int a_role = Qt::EditRole) override;

  std::vector<DropFileCategory> getCategories() const;

  void setCategories(const std::vector<DropFileCategory> & a_categories);

  void addCategory();

  void deleteCategory(int a_index);

  QString sourceTemplate(int a_index) const;

  void setSourceTemplate(int a_index, const QString & a_text);

private:

  std::vector<DropFileCategory> m_categories;
};

#endif // DROP_FILE_CATEGORY_MODEL_H_INCLUDED


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<TITLE
>it_idwt</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REL="HOME"
TITLE="LIBIT Documentation"
HREF="index.html"><LINK
REL="UP"
HREF="refmanual.html"><LINK
REL="PREVIOUS"
TITLE="it_dwt"
HREF="man.it-dwt.html"><LINK
REL="NEXT"
TITLE="it_wavelet_merge"
HREF="man.it-wavelet-merge.html">

LIBIT Documentation

Prev		Next

it_idwt

Name
it_idwt -- inverse discrete wavelet transform

Synopsis

#include <it/wavelet.h>

vec it_idwt( vec t, it_wavelet_lifting_t const *lifting, int levels
        );

DESCRIPTION

 This function computes the inverse discrete wavelet transform of vt using the lifting steps described by lifting. The input vector of coefficients vt is the concatenation of all the coefficients in each subbands starting from the low-frequency subband. Currently the lifting steps for the usual 5/3 and 9/7 biorthogonal filters are predefined as "it_wavelet_lifting_53" and "it_wavelet_lifting_97", although you can provide your own lifting steps.

RETURN VALUE

    The set of inverse wavelet coefficients

EXAMPLE

#include <wavelet.h>

...

/* analyse a signal 'v' using a 5-level 9/7 wavelet decomposition */
vec vt = it_dwt(v, it_wavelet_lifting_97, 5);
/* clear the high subband */
vec_set_between(vt, (vec_length(v) + 1) / 2, end, 0);
/* recompose the vector by inverse transform */
vec vr = it_idwt(vt, it_wavelet_lifting_97, 5);

Prev	Home	Next

it_dwt	Up	it_wavelet_merge


text:
package com.seongil.mvplife.delegate;

import com.seongil.mvplife.base.MvpPresenter;
import com.seongil.mvplife.base.MvpView;

/**
 * Implements the delegation layer for the fragment using by the MVP architecture.
 *
 * @param <V> The type of {@link MvpView}
 * @param <P> The type of {@link MvpPresenter}
 *
 * @author seong-il, kim
 * @since 17. 1. 6
 */
public class MvpDelegateImpl<V extends MvpView, P extends MvpPresenter<V>> {

    // ========================================================================
    // constants
    // ========================================================================

    // ========================================================================
    // fields
    // ========================================================================
    private final MvpDelegateCallback<V, P> mDelegateCallback;

    // ========================================================================
    // constructors
    // ========================================================================
    public MvpDelegateImpl(MvpDelegateCallback<V, P> delegateCallback) {
        if (delegateCallback == null) {
            throw new NullPointerException("MvpDelegateCallback is null");
        }
        mDelegateCallback = delegateCallback;
    }

    // ========================================================================
    // getter & setter
    // ========================================================================

    // ========================================================================
    // methods for/from superclass/interfaces
    // ========================================================================

    // ========================================================================
    // methods
    // ========================================================================
    public void createPresenter() {
        P presenter = mDelegateCallback.getPresenter();
        if (presenter == null) {
            presenter = mDelegateCallback.createPresenter();
        }
        if (presenter == null) {
            throw new NullPointerException("Presenter is null! " +
                  "You have to return the valid presenter.");
        }
        mDelegateCallback.setPresenter(presenter);
    }

    public void attachView() {
        final P presenter = mDelegateCallback.getPresenter();
        if (presenter == null) {
            throw new NullPointerException("Presenter is null from getPresenter()");
        }
        presenter.attachView(mDelegateCallback.getMvpView());
    }

    public void detachView() {
        final P presenter = mDelegateCallback.getPresenter();
        if (presenter == null) {
            throw new NullPointerException("Presenter is null from getPresenter()");
        }
        presenter.detachView();
    }

    // ========================================================================
    // inner and anonymous classes
    // ========================================================================
}


text:
package logbook.config;

import java.io.IOException;

import logbook.config.bean.ShipGroupBean;
import logbook.config.bean.ShipGroupListBean;
import logbook.constants.AppConstants;
import logbook.gui.ApplicationMain;
import logbook.gui.logic.ShipGroupListener;
import logbook.gui.logic.ShipGroupObserver;
import logbook.util.BeanUtils;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 所有艦娘グループを保存・復元します
 *
 */
public class ShipGroupConfig {
    /** ロガー */
    private static final Logger LOG = LogManager.getLogger(ShipGroupConfig.class);

    /** 所有艦娘グループ */
    private static ShipGroupListBean group;

    /** 変更があったか */
    private static boolean modified = false;

    // 変更検出用
    private static class ChangeListener implements ShipGroupListener {
        @Override
        public void listChanged() {
            modified = true;
        }

        @Override
        public void groupNameChanged(ShipGroupBean group) {
            modified = true;
        }

        @Override
        public void groupShipChanged(ShipGroupBean group) {
            modified = true;
        }
    }

    // 始めてアクセスした時に読み込む
    static {
        load();
        // 変更を検知する
        ShipGroupObserver.addListener(new ChangeListener());
    }

    /**
     * 設定ファイルに書き込みます
     */
    public static void store() throws IOException {
        // 変更があったときだけ書き込む
        if (modified) {
            if (group == null) {
                group = new ShipGroupListBean();
            }
            ApplicationMain.sysPrint("グループファイル更新");
            BeanUtils.writeObject(AppConstants.GROUP_CONFIG_FILE, group);
            modified = false;
        }
    }

    /**
     * 所有艦娘グループを読み込みます
     */
    private static void load() {
        try {
            ShipGroupListBean bean = BeanUtils.readObject(AppConstants.GROUP_CONFIG_FILE, ShipGroupListBean.class);
            if (bean != null) {
                group = bean;
            } else {
                group = new ShipGroupListBean();
            }
        } catch (Exception e) {
            LOG.warn("所有艦娘グループを読み込みますに失敗しました", e);
        }
    }

    /**
     * 所有艦娘グループを取得します
     *
     * @return 所有艦娘グループ
     */
    public static ShipGroupListBean get() {
        return group;
    }
}


text:
"""
Test addr relay
"""

from test_framework.messages import (
    CAddress,
    NODE_NETWORK,
    NODE_WITNESS,
    msg_addr,
)
from test_framework.p2p import P2PInterface
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
    assert_equal,
)
import time

# Keep this with length <= 10. Addresses from larger messages are not relayed.
ADDRS = []
num_ipv4_addrs = 10

for i in range(num_ipv4_addrs):
    addr = CAddress()
    addr.time = int(time.time()) + i
    addr.nServices = NODE_NETWORK | NODE_WITNESS
    addr.ip = "123.123.123.{}".format(i % 256)
    addr.port = 8333 + i
    ADDRS.append(addr)

class AddrReceiver(P2PInterface):
    num_ipv4_received = 0

    def on_addr(self, message):
        for addr in message.addrs:
            assert_equal(addr.nServices, 9)
            if not 8333 <= addr.port < 8343:
                raise AssertionError("Invalid addr.port of {} (8333-8342 expected)".format(addr.port))
            assert addr.ip.startswith('123.123.123.')
            self.num_ipv4_received += 1

class AddrTest(BitcoinTestFramework):
    def set_test_params(self):
        self.setup_clean_chain = False
        self.num_nodes = 1

    def run_test(self):
        self.log.info('Create connection that sends addr messages')
        addr_source = self.nodes[0].add_p2p_connection(P2PInterface())
        msg = msg_addr()

        self.log.info('Send too-large addr message')
        msg.addrs = ADDRS * 101  # more than 1000 addresses in one message
        with self.nodes[0].assert_debug_log(['addr message size = 1010']):
            addr_source.send_and_ping(msg)

        self.log.info('Check that addr message content is relayed and added to addrman')
        num_receivers = 7
        receivers = []
        for _ in range(num_receivers):
            receivers.append(self.nodes[0].add_p2p_connection(AddrReceiver()))
        msg.addrs = ADDRS
        with self.nodes[0].assert_debug_log(
            [
                'Added {} addresses from 127.0.0.1: 0 tried'.format(num_ipv4_addrs),
                'received: addr (301 bytes) peer=0',
            ]
        ):
            addr_source.send_and_ping(msg)
            self.nodes[0].setmocktime(int(time.time()) + 30 * 60)
            for receiver in receivers:
                receiver.sync_with_ping()

        total_ipv4_received = sum(r.num_ipv4_received for r in receivers)

        # Every IPv4 address must be relayed to two peers, other than the
        # originating node (addr_source).
        ipv4_branching_factor = 2
        assert_equal(total_ipv4_received, num_ipv4_addrs * ipv4_branching_factor)

if __name__ == '__main__':
    AddrTest().main()