text:
#ifndef GFXUTILITY_H
#define GFXUTILITY_H

#include "config.h"
#include "Point.h"
#include "MC2Exception.h"

#include <vector>
#include <list>

class MC2Coordinate;
class LanguageCode;

/**
 *    Define the MC2BoundingBox for the getAdjacentRectangle-method and
 *    the isSegmentInMC2BoundingBox-method.
 *    MC2BoundingBox.h is included in the cpp-file.
 */
class MC2BoundingBox;

/**
 *    This static class contains a lot of utility-methods about
 *    geographical data.
 *
 *    @see     Utility.h Non-geographic utility-methods.
 */
class GfxUtility {
public:
      /**
       *    Get the distance between two points.
       *    @return  The squared linear distance between two points.
       *             In meters squared.
       */
      static float64 squareP2Pdistance_linear(int32 lat1, int32 lon1,
                                              int32 lat2, int32 lon2,
                                              float64 cosLat = 2.0);

      /**
       *    Get the distance between two points.
       *    @return  The squared linear distance between two points.
       *             In meters squared.
       */
      static float64 squareP2Pdistance_linear( const MC2Coordinate& p1,
                                               const MC2Coordinate& p2,
                                               float64 cosLat = 2.0 );

      /**
       *    Get the angle from the north-direction. Used to calculate
       *    the angle described by the figure:
       *    @verbatim
                      (lat2, lon2)
                  |     /
                  |    /
                  |   /
                  |A /
                  |\/
                  |/ (lat1, lon1)
                  |
                  |
                  |
            @endverbatim
       *
       *    @param   lat1  The latitude of the startpoint for the line.
       *    @param   lon1  The longitude of the startpoint for the line.
       *    @param   lat2  The latitude of the endpoint for the line.
       *    @param   lon2  The longitude of the endpoint for the line.
       *    @return  Angle in radians from the north-direction in
       *             clockwise direction. The return value is in the
       *             interval $[0,2\pi[$.
       */
      static float64 getAngleFromNorth( int32 lat1, int32 lon1,
                                        int32 lat2, int32 lon2,
                                        bool useCosLat = true);
      /// see the other getAngleFromNorth function.
      static float64 getAngleFromNorth( const MC2Coordinate& first,
                                        const MC2Coordinate& second );
      /// see the other getAngleFromNorth function.
      static float64 getAngleFromNorthNoCoslat(
               int32 lat1, int32 lon1, int32 lat2, int32 lon2);

   /**
    * Makes sure an angle is in the interval [0, 2*pi[
    *
    * @param angle An angle, any real number.
    * @return a number in [0, 2*pi[
    */
   static double normalizeAngle( double angle );

   /**
    * Calculates the difference between two angles, using the shortest
    * path around the unit circle.
    */
   static double angleDifference( double angle1, double angle2 );

      /**
       *    Convert a string containing WGS 84 latitude or longitude to
       *    an MC2 integer coordinate. The input string would look like
       *    (N/S/E/W) D(D*)MMSS[.ddd], that is the period and the
       *    following numbers are optional.
       *    @param   s  The null terminated lat or lon string in the
       *                format specified by WGS 84.
       *    @return  An integer representing the position in the MC2
       *             coordinate system.
       */
      static int32 convLatLonStringToInt(const char* s);

      /**
       *    Convert a string containing a SWEREF93 latitude or longitude to
       *    a SWEREF93 radians coordinate. The input string would look like
       *    D(D*).ddd(N/S/E/W).
       *    @param   s  The null terminated lat or lon string in the
       *                format specified by WGS 84.
       *    @return  An float64 in SWEREF93 radians.
       */
      static float64 convLatLonStringToDbl(const char* s);

      /**
       *    Calculate the closest distance from a vector (defined by
       *    (x1,y1) and (x2,y2) ) to a point (xpos, ypos).
       *    @param x1 The x-part of the first coordinate of the vector.
       *    @param y1 The y-part of the first coordinate of the vector.
       *    @param x2 The x-part of the second coordinate of the vector.
       *    @param y2 The y-part of the second coordinate of the vector.
       *    @param xpos The x-part of the point to calculate distance to.
       *    @param ypos The y-part of the point to calculate distance to.
       *    @param cosF The cosine factor.
       *    @return The minimum distance to (xpos, ypos) from vector.
       */
      static uint64 closestDistVectorToPoint( int32 x1,   int32 y1,
                                              int32 x2,   int32 y2,
                                              int32 xpos, int32 ypos,
                                              double cosF );
      /**
       *    Calculate the closest distance from a vector (defined by
       *    (x1,y1) and (x2,y2) ) to a point (xpos, ypos) and also the
       *    point, on the line between (x1,y1) and (x2,y2), which is
       *    closest to (xpos, ypos).
       *
       *    @param x1   The x-part of the first coordinate of the vector.
       *    @param y1   The y-part of the first coordinate of the vector.
       *    @param x2   The x-part of the second coordinate of the vector.
       *    @param y2   The y-part of the second coordinate of the vector.
       *    @param xpos The x-part of the point to calculate distance to.
       *    @param ypos The y-part of the point to calculate distance to.
       *    @param xOut Outparameter that is set to the x-part of the
       *                coordinate that are closest to (xpos, ypos)
       *    @param xOut Outparameter that is set to the y-part of the
       *                coordinate that are closest to (xpos, ypos)
       *    @param cosF The cosine factor.
       *    @return The minimum distance to (xpos, ypos) from vector
       */
      static uint64 closestDistVectorToPoint( int32 x1,   int32 y1,
                                              int32 x2,   int32 y2,
                                              int32 xpos, int32 ypos,
                                              int32& xOut, int32& yOut,
                                              double cosF );

      /**
       *    @name Get point on line
       */
      //@{
         /**
          *    Get a point located @c dist meters from <tt>(lat1,lon1)</tt>
          *    and on the line from <tt>(lat1,lon1)</tt> to
          *    <tt>(lat2,lon2)</tt>. Will return false if the distance from
          *    <tt>(lat1,lon1)</tt> to <tt>(lat2,lon2)</tt> is less than
          *    @c dist.
          *
          *    @param lat1    Latitude part of the first point on the line.
          *    @param lon1    Longitude part of the first point on the line.
          *    @param lat2    Latitude part of the second point on the line.
          *    @param lon2    Longitude part of the second point on the line.
          *    @param dist    The distance from <tt>(lat1,lon1)</tt> of the
          *                   returned coordinate.
          *    @param outLat  Outparameter that is set to the coordinate
          *                   described above.
          *    @param outLon  Outparameter that is set to the coordinate
          *                   described above.
          *    @return True if the outparameters are updated, false otherwise.
          */
         static bool getPointOnLine(int32 lat1, int32 lon1,
                                    int32 lat2, int32 lon2, float64 dist,
                                    int32& outLat, int32& outLon);

         /**
          *    Get a point located @c dist meters from <tt>(lat1,lon1)</tt>
          *    and on the line from <tt>(lat1,lon1)</tt> to
          *    <tt>(lat2,lon2)</tt>. Will return false if the distance from
          *    <tt>(lat1,lon1)</tt> to <tt>(lat2,lon2)</tt> is less than
          *    @c dist.
          *
          *    Use this method if the distance between <tt>(lat1,lon1)</tt>
          *    and <tt>(lat2,lon2)</tt> already is calculated.
          *
          *    @param lat1    Latitude part of the first point on the line.
          *    @param lon1    Longitude part of the first point on the line.
          *    @param lat2    Latitude part of the second point on the line.
          *    @param lon2    Longitude part of the second point on the line.
          *    @param dist    The distance from <tt>(lat1,lon1)</tt> of the
          *                   returned coordinate.
          *    @param outLat  Outparameter that is set to the coordinate
          *                   described above.
          *    @param outLon  Outparameter that is set to the coordinate
          *                   described above.
          *    @return True if the outparameters are updated, false otherwise.
          */
         static bool getPointOnLine(int32 lat1, int32 lon1,
                                    int32 lat2, int32 lon2,
                                    float64 dist, float64 totDist,
                                    int32& outLat, int32& outLon);
      //@}

      /**
       *    The types of text representation of a lat or lon in printLatLon.
       */
      enum coordianteRepresentations {
         /** simpleRad, 13.1911N, precision is number decimals.
           * The coordinate is expressed in decimal degrees with a final
           * letter for compass direction (N|S|W|E or N|S|V|Ö ...). */
         simpleRad = 0,
         /** wgs84 style, N 13° 19' 12.96", precision is number decimals.
           * The coordinate is expressed as: compass direction degrees�
           * minutes' seconds". */
         wgs84Style = 1,
         /** wgs84Rad
           * The coordinate is expressed in radians. */
         wgs84Rad = 2,
         /** wgs84Deg
           * The coordinate is expressed in decimal degrees. */
         wgs84Deg = 3,

         /**
          * NMEA.
          */
         nmea = 4,
      };

      /**
       * Prints a sweref93_LLA lat or lon coordinate (expressed in radians)
       * into a string in different formats.
       *
       * @param str        The string to print into.
       * @param latOrLon   The latitude or longitude in sweref93_LLA (radians).
       * @param lang       The language to print compassdirection in.
       * @param lat        If the latOrLon is a latitude, false if longitude.
       * @param precision  Valid numbers of decimals.
       * @param representation In which format should the coordinate be
       *                       printed.
       *
       * @return Number of chars written to str.
       */
      static uint32 printLatLon( char* str,
                                 float64 latOrLon,
                                 bool lat,
                                 LanguageCode lang,
                                 uint32 precision = 3,
                                 coordianteRepresentations representation =
                                 simpleRad );
   /** Same as the printLatLon, but returns two strings directly for
    * lat and lon
    * @see printLatLon
    */
   static void printLatLon( MC2String& latStr, MC2String& lonStr,
                            const MC2Coordinate& coord,
                            const LanguageCode& language,
                            coordianteRepresentations representation =
                            simpleRad );

      /**
       * Same as printLatLon but with default values for precision depending
       * on representation.
       *
       * @param latOrLon The MC2 coordinate.
       * @see printLatLon.
       */
      static uint32 printLatLon( char* str,
                                 int32 latOrLon,
                                 bool lat,
                                 const LanguageCode& lang,
                                 coordianteRepresentations representation );

      /**
       *    Find the intersection between two lines that can be described
       *    by the following coordinates:
       *    Line 1: (x1, y1) - (x2, y2) and \
       *    Line 2: (v1, w1) - (v2, w2).
       *    @param x1   x1 coordinate of line 1.
       *    @param y1   y1 coordinate of line 1.
       *    @param x2   x2 coordinate of line 1.
       *    @param y2   y2 coordinate of line 1.
       *
       *    @param v1   v1 coordinate of line 2.
       *    @param w1   w1 coordinate of line 2.
       *    @param v2   v2 coordinate of line 2.
       *    @param w2   w2 coordinate of line 2.
       *
       *    @param intersectX Output parameter set to the x coordinate
       *                      of the intersection of the two lines.
       *    @param intersectY Output parameter set to the y coordinate
       *                      of the intersection of the two lines.
       *    @return  True if the two lines intersects each other,
       *             false otherwise.
       */
      static bool getIntersection(int32 x1, int32 y1, int32 x2, int32 y2,
                                  int32 v1, int32 w1, int32 v2, int32 w2,
                                  int32& intersectX, int32& intersectY);

      /**
       *    Find the intersection between two lines that can be described
       *    by the following coordinates:
       *    Line 1: (x1, y1) - (x2, y2) and \
       *    Line 2: (v1, w1) - (v2, w2).
       *    @param x1   x1 coordinate of line 1.
       *    @param y1   y1 coordinate of line 1.
       *    @param x2   x2 coordinate of line 1.
       *    @param y2   y2 coordinate of line 1.
       *
       *    @param v1   v1 coordinate of line 2.
       *    @param w1   w1 coordinate of line 2.
       *    @param v2   v2 coordinate of line 2.
       *    @param w2   w2 coordinate of line 2.
       *
       *    @param intersectX Output parameter set to the x coordinate
       *                      of the intersection of the two lines.
       *    @param intersectY Output parameter set to the y coordinate
       *                      of the intersection of the two lines.
       *    @param percentFromx1y1 [Output] How many percent between
       *                           (x1,y1) and (x2,y2)
       *                           the intersection lies.
       *    @param percentFromv1w1 [Output] How many percent between
       *                           (v1,w1) and (v2,w2)
       *                           the intersection lies.
       *    @return  True if the two lines intersects each other,
       *             false otherwise.
       */
      static bool getIntersection(int32 x1, int32 y1, int32 x2, int32 y2,
                                  int32 v1, int32 w1, int32 v2, int32 w2,
                                  int32& intersectX, int32& intersectY,
                                  float64& percentFromx1y1,
                                  float64& percentFromv1w1 );

      /**
       * Calculates the cosine factor using a center for a given latitude
       * range.
       *
       * @param minLat The lower latitude value.
       * @param maxLat The higher latitude value.
       * @return The coslat factor.
       */
      static float64 getCoslat( int32 minLat, int32 maxLat );

      /**
       *  Determines if a given point (x,y) is inside a given
       *  rectangle or not. NOTE: if point is on rectangular
       *  boundary, it is counted as INSIDE.
       *
       *  @param minX x-coordinate of the left  veritical edge in rectangle
       *  @param maxX x-coordinate of the right veritical edge in rectangle
       *  @param minY y-coordinate of the lower horisontal edge in rectangle
       *  @param maxY y-coordinate of the upper horisontaledge in rectangle
       *  @return true if point is inside rectangle, false otherwise
       *
       */
      static bool pointInsideRect( int32 x, int32 y, int32 minX, int32 maxX,
                                   int32 minY, int32 maxY );

      /**
       *  Determines the part of a given line segment, (x1,y1) to (x2,y2),
       *  that is inside a given rectangle.
       *
       *  @param (x1,y1) one endpoint in line segment to be clipped
       *  @param (x2,y2) second endpoint in line segment to be clipped
       *  @param minX x-coordinate of the left  veritical edge in rectangle
       *  @param maxX x-coordinate of the right veritical edge in rectangle
       *  @param minY y-coordinate of the lower horisontal edge in rectangle
       *  @param maxY y-coordinate of the upper horisontaledge in rectangle
       *  @param (x1Out,y1Out) outparameter  one endpoint in clipped
       *                                     line segment
       *  @param  (x2Out,y2Out) outparameter second endpoint in clipped
       *                                     line segment
       *
       *  @return true if at least one point of the line segment is inside
       *               the rectangle, false otherwise
       */
       static bool getClippedLineInRect( int32 x1, int32 y1, int32 x2,
                                         int32 y2, int32 minX, int32 minY,
                                         int32 maxX, int32 maxY,
                                         int32& x1Out, int32& y1Out,
                                         int32& x2Out, int32& y2Out);
       /**
        *  Finds out where a given point is located relative a given
        *  bounding box. The sides of the bounding box is virtually
        *  extended so there are nine rectangles (eight unbounded ones)
        *  including the bounding box itself.
        *
        *  @param  bbox       Bounding box used.
        *
        *  @param  (lat,lon)  Point to determine the location for.
        *
        *  @param  vertPos    Outparameter. Vertical position of (lat,lon).
        *                     Can have the values -1, 0 or 1:
        *
        *                     -1: Somewhere below the bounding box
        *                      0: Inside, left or right of the bounding box
        *                      1: Somewhere above the bounding box
        *
        *  @param  horPos     Outparameter. Vertical position of (lat,lon).
        *                     Can have the values -1, 0 or 1:
        *
        *                     -1: Somewhere to the left of the bounding box
        *                      0: Inside, above or below the bounding box
        *                      1: Somewhere to the right of the bounding box
        */
       static void getAdjacentRectangle(const MC2BoundingBox* bbox, int32 lat,
                                        int32 lon, int& vertPos, int& horPos);

       /*
        *  Finds out if a given segment (the whole or a part of) is inside
        *  a given bounding box. The boundary is not included in the "inside"
        *  so a part of the segment must be in the interor of the bounding
        *  box in order to be counted as inside.
        *
        *  @param  bbox     Bounding box used.
        *
        *  @param  (y1,x1)  One endpoint of the segment
        *
        *  @param  (y2,x2)  Other endpoint of the segment
        *
        *  @return          True if some part of the segment is inside
        *                   the bounding box, false otherwise.
        */
       static bool isSegmentInMC2BoundingBox(const MC2BoundingBox* bbox,
                                             int32 y1, int32 x1, int32 y2,
                                             int32 x2);
       /**
        *  Method used to determine to which map a given segement shall
        *  belong to, if the given segment is on the boundary between
        *  two maps.
        *
        *  @param (y1,x1)       Lat-lon coordinates of one endpoint
        *                       of the segment.
        *  @param (y2,x2)       Lat-lon coordinates of the second
        *                       endpoint of the segment.
        *  @param (yOut,xOut)   Outparameters. Lat-lon coordinates of a point
        *                       not lying on the given segment, and such that
        *                       points (y1,x1) (y2,x2) (yOut,xOut) are
        *                       clockwise oriented
        *
        */
       static void generatePointInMap(int32 y1, int32 x1, int32 y2, int32 x2,int32& yOut, int32& xOut);

       /**
        *
        *
        */
       static float64 convertToDrawAngle(float64 angleFromNorth);

      /**
       *  Given two int32 numbers x and y, let x have the value of y and
       *  vice versa.
       *  @param x     int32 number
       *  @param y     int32 number
       */

      static void swapInt32(int32& x, int32& y);

       /**
        *  Checks if two points are located on the same boundary of
        *  a given rectangle. If the two points are equal, the method
        *  is used to determine if a given point is located somewhere
        *  on the rectangular boundary.
        *
        *  @param (x1,y1)     First point to check
        *  @param (x2,y2)     Second point to check
        *  @param  minX       x-coordinate of left vertical edge in rectangle
        *  @param  maxX       x-coordinate of right vertical edge in rectangle
        *  @param  minY       y-coordinate of lower horizontal edge.
        *  @param  maxY       y-coordinate of upper  horizontal edge.
        *  @return            True if the two points are on the same boundary,
        *                     false otherwise.
        */
       static bool twoPointsOnCommonRectBoundary(int32 x1, int32 y1,
                                                 int32 x2, int32 y2,
                                                 int32 minX, int32 maxX,
                                                 int32 minY, int32 maxY);

       /**
        *  Checks if a given point is located on one of the four
        *  corners of a rectangle.
        *
        *  @param  (x,y)     Point to check
        *  @param  minX       x-coordinate of left vertical edge in rectangle
        *  @param  maxX       x-coordinate of right vertical edge in rectangle
        *  @param  minY       y-coordinate of lower horizontal edge.
        *  @param  maxY       y-coordinate of upper  horizontal edge.
        *  @return            true if the point is  on one of the corners,
        *                     false otherwise.
        */
     static bool pointOnRectCorner(int32 x, int32 y,
                                   int32 minX, int32 maxX,
                                   int32 minY, int32 maxY );

      /**
       * From a max display size in pixels and a boundingbox
       * the boundingbox is streetched to fix the display.
       *
       * @param bbox   The bounding box.
       * @param width The maximun width of the display.
       * @param height The maximun height of the display.
       */
      static void getDisplaySizeFromBoundingbox( MC2BoundingBox& bbox,
                                                 uint16& width,
                                                 uint16& height );

      /**
       * From a max display size in pixels and a boundingbox
       * the boundingbox is streetched to fix the display.
       *
       * @param minLat Upper left latitude of boundingbox.
       * @param minLon Upper left longitude of boundingbox.
       * @param maxLat Lower right latitude of boundingbox.
       * @param maxLon Lower right longitude of boundingbox.
       * @param width The maximun width of the display.
       * @param height The maximun height of the display.
       */
      static void getDisplaySizeFromBoundingbox( int32& minLat,
                                                 int32& minLon,
                                                 int32& maxLat,
                                                 int32& maxLon,
                                                 uint16& width,
                                                 uint16& height );

      /**
       * Calculates the aspect correct view of an arc.
       *
       * @param minLat Upper left latitude of boundingbox.
       * @param minLon Upper left longitude of boundingbox.
       * @param maxLat Lower right latitude of boundingbox.
       * @param maxLon Lower right longitude of boundingbox.
       * @param width The width of the display.
       * @param height The height of the display.
       * @param lat The center of arc.
       * @param lon The center of arc.
       * @param innerRadius The inner radius.
       * @param outerRadius The outer radius.
       * @param startAngle The start angle in degrees.
       * @param stopAngle The stop angle in degrees.
       * @param cx Set center of arc x-value, may be negative or
       *           larger than height.
       * @param cy Set center of arc y-value, may be negative or
       *           larger than height.
       * @param iR Set to the inner radius.
       * @param oR Set to the outer radius.
       */
      static void getArcAspectCoordinates(
         int32 minLat,
         int32 minLon,
         int32 maxLat,
         int32 maxLon,
         uint32 width,
         uint32 height,
         int32 lat, int32 lon,
         uint16 innerRadius, uint16 outerRadius,
         uint16 startAngle , uint16 stopAngle,
         int& cx, int& cy,
         int& iR, int& oR );

      /**
       * Calculates an turn arrow. NB documentation is reverse enginered
       * from source.
       *
       *    @verbatim
         the turn
                  |\¯¯¯¯¯¯¯¯¯¯¯¯¯ after turn
                  | \ cornerDist
                  |  \   angle \ ¯ arrowLength
                  |   \    /¯¯¯/ ¯
                  |    \  /\
                  |     \/
                  |     /\  shortDistance
                  |    /
                  |   /
                  |   |  longDistance
                  |   |_
     before turn  |
            @endverbatim
       *
       * @param src The three turn points, before turn, the turn and
       *            finally after turn.
       * @param dst Set to the four(five if addCenterPoint) spline control
       *            points of the turn arrow line, see addCenterPoint.
       * @param arrow Set to the three points of the arrow, left, center
       *        and then right.
       * @param cornerDistance How far out the turn arrow line should be.
       * @param pointDistance1 Distance before center of spline.
       * @param pointDistance2 Distance after center of spline.
       * @param addCenterPoint If the center of the spline should be added
       *        to dst after the first two spline control points.
       * @param arrowLength The length of the arrow.
       * @param angle The angle of the arrow.
       * @param useCosLat If the horisontal lengths should be cossine
       *        adjusted, default true.
       */
      static void
         calcArrowPoints( POINT* src, POINT* dst, POINT* arrow,
                          int32 cornerDistance,
                          int32 shortDistance,
                          int32 longDistance,
                          bool addCenterPoint,
                          int32 arrowLength,
                          int32 angle,
                          bool useCosLat = true );

      /**
       * Draws a spline.
       * @param x0 The x value of the first controlpoint.
       * @param y0 The y value of the first controlpoint.
       * @param x1 The x value of the second controlpoint.
       * @param y1 The y value of the second controlpoint.
       * @param x2 The x value of the third controlpoint.
       * @param y2 The y value of the third controlpoint.
       * @param x3 The x value of the fourth controlpoint.
       * @param y3 The y value of the fourth controlpoint.
       * @param resX The vector to insert x values into.
       * @param resY The vector to insert y values into.
       * @param bias The amount to move along the spline between each
       *             sample, default 0.02 (1/50 50 points along the curve).
       *             The bias must be in the range ]0.0,1.0].
       * @param endAngle Set to the angle at the endpoint of the spline if
       *                 endAngle is not NULL.
       */
      static void makeSpline( int x0, int y0, int x1, int y1,
                              int x2, int y2, int x3, int y3,
                              vector<int>& resX, vector<int>& resY,
                              float32 bias = 0.02,
                              double* endAngle = NULL );

      /**
       * Calculate the radius of a circle given three coordinates
       * (on the circle border).
       *
       * @param   lat0  The first latitude on the circle border.
       * @param   lon0  The first longitude on the circle border.
       * @param   lat1  The second latitude on the circle border.
       * @param   lon1  The second longitude on the circle border.
       * @param   lat2  The third latitude on the circle border.
       * @param   lon2  The third longitude on the circle border.
       * @return  The radius in mc2-units of the circle. MAX_UINT32 if
       *          no radius could be calculated (ie. infinite radius).
       */
      static float64 calcRadius( int32 lat0, int32 lon0,
                                 int32 lat1, int32 lon1,
                                 int32 lat2, int32 lon2 );

      /**
       *    Clips the specifed closed polygon to a boundingbox and
       *    adds it to the clippedGfxData.
       *
       *    The polygon is clipped by first reducing the number of
       *    vertices outside the boundingbox, and then
       *    Sutherland-Hodgeman clipping is performed.
       *
       *    Note that the result is always a single polygon, even
       *    if the polygon to be clipped is concave. This is the
       *    drawback of using this method.
       *
       *    @param   bbox     The boundingbox to clip the polygon to.
       *    @param   vertices [IN/OUT] The polygon to be clipped.
       *    @return  True if the resulting clipped polygon is not empty,
       *             false otherwise.
       */
      static bool clipPolyToBBoxFast( const MC2BoundingBox* bbox,
                                      vector<POINT>& vertices );

      /**
       *    Clips the first polygon in the polygons vector against
       *    the clipPolygon.
       *
       *    The algorithm used is described in:
       *    "Efficient Clipping of Arbitrary polygons:" by Gunther Greiner
       *    and Kai Hormann from Computer Graphics Group,
       *    University of Erlangen.
       *
       *    The algorithm handles selfintersecting polygons, and can
       *    result in multiple clipped polygons, in case the polygon
       *    to be clipped is concave.
       *
       *    The polygon to be clipped may not have coordinates that are
       *    touching a clip border.
       *
       *    @param   clipPolygon The polygon containing the polygon
       *                         to clip against. The polygon must be closed,
       *                         i.e. the first and last coordinate
       *                         must be the same.
       *    @param   polygons    [IN/OUT] The first polygon of the vector
       *                         is the polygon that will be clipped.
       *                         The resulting polygons will be added
       *                         to the vector, replacing the original
       *                         polygon. The input polygon must
       *                         also be closed.
       *
       *    @return  The number of resulting polygons.
       */
      static int clipToPolygon( const vector<POINT>& clipPolygon,
                               vector< vector<POINT> >& polygons );

      /**
       *    Removes self-intersections. Will fill holes in falukorvs.
       */
      static int cleanSelfintersecting( vector< vector<POINT> >& polygons )
         throw (MC2Exception);

      /**
       *    Removes self-intersections. Will fill holes in falukorvs.
       *    Currently copies all the coordinates into vectors of
       *    POINT, runs cleanSelfintersecting and then copies the
       *    result back.
       */
      static int cleanSelfintersecting(
         vector< vector<MC2Coordinate> >& polygons ) throw (MC2Exception);

      /// Splits self touching polygons. Returns true if splitting was done.
      static bool splitSelfTouching( vector< vector<POINT> >& polygons )
         throw (MC2Exception);
      static bool splitSelfTouching(
               vector< vector<MC2Coordinate> >& polygons )
         throw (MC2Exception);

      /**
       *    Clips the first polygon in the polygons vector against
       *    the boundingbox.
       *
       *    The algorithm used is described in:
       *    "Efficient Clipping of Arbitrary polygons:" by Gunther Greiner
       *    and Kai Hormann from Computer Graphics Group,
       *    University of Erlangen.
       *
       *    The algorithm handles selfintersecting polygons, and can
       *    result in multiple clipped polygons, in case the polygon
       *    to be clipped is concave.
       *
       *    Before clipping is performed,
       *    the number of vertices outside the boundingbox
       *    is reduced and the vertices are slightly perturbed so that
       *    no the polygon to be clipped does not contain any coordinates
       *    on the clip polygon boundary.
       *
       *    @param   bbox        The boundingbox to clip against.
       *    @param   polygons    [IN/OUT] The first polygon of the vector
       *                         is the polygon that will be clipped.
       *                         The resulting polygons will be added
       *                         to the vector, replacing the original
       *                         polygon. The input polygon must
       *                         also be closed.
       *    @return  The number of resulting polygons.
       */
      static int clipToPolygon( const MC2BoundingBox& bbox,
                                vector< vector<POINT> >& polygons );

      /**
       *
       *    Tests if a point is left/on/right of an infinite line.
       *    @param   p0 The first point of the infinite line.
       *    @param   p1 The second point of the infinte line.
       *    @param   p2 The point to check.
       *
       *    @return >0 for P2 left of the line through P0 and P1
       *            =0 for P2 on the line
       *            <0 for P2 right of the line.
       */
      inline static int isLeft( const POINT& p0,
                                const POINT& p1,
                                const POINT& p2 );

      /**
       *    Clips the first polyline (open polygon)
       *    in the polygons vector against the boundingbox.
       *
       *    @param   bbox        The boundingbox to clip against.
       *    @param   polygons    [IN/OUT] The first polygon of the vector
       *                         is the polygon that will be clipped.
       *                         The resulting polygons will be added
       *                         to the vector, replacing the original
       *                         polygon.
       *    @return  The number of resulting polygons.
       */
      static int clipPolylineToBBox( const MC2BoundingBox& bbox,
                                     vector< vector<POINT> >& polygons );
   private:

      /**
       *    Find the intersection between two lines that can be described
       *    by the following coordinates:
       *    Line 1: (x1, y1) - (x2, y2) and \
       *    Line 2: (v1, w1) - (v2, w2).
       *    @param x1   x1 coordinate of line 1.
       *    @param y1   y1 coordinate of line 1.
       *    @param x2   x2 coordinate of line 1.
       *    @param y2   y2 coordinate of line 1.
       *
       *    @param v1   v1 coordinate of line 2.
       *    @param w1   w1 coordinate of line 2.
       *    @param v2   v2 coordinate of line 2.
       *    @param w2   w2 coordinate of line 2.
       *
       *    @param intersectX Output parameter set to the x coordinate
       *                      of the intersection of the two lines.
       *    @param intersectY Output parameter set to the y coordinate
       *                      of the intersection of the two lines.
       *    @param percentFromx1y1 [Output] If not NULL,
       *                           how many percent between
       *                           (x1,y1) and (x2,y2)
       *                           the intersection lies.
       *    @param percentFromv1w1 [Output] If not NULL,
       *                           how many percent between
       *                           (v1,w1) and (v2,w2)
       *                           the intersection lies.
       *    @return  True if the two lines intersects each other,
       *             false otherwise.
       */
      static bool getIntersection(int32 x1, int32 y1, int32 x2, int32 y2,
                                  int32 v1, int32 w1, int32 v2, int32 w2,
                                  int32& intersectX, int32& intersectY,
                                  float64* percentFromx1y1,
                                  float64* percentFromv1w1 );

      /**
       *    Clip the vertices against a boundary of a boundingbox.
       *
       *    Part of the Sutherland-Hodgeman clipping algorithm.
       *
       *    @param   boundaryOutcode   The Cohen-Sutherland
       *                               outcode of boundary of
       *                               the boundingbox to clip to, ie.
       *                               MC2BoundingBox::TOP/BOTTOM/LEFT/RIGHT
       *    @param   bbox              The boundingbox.
       *    @param   vertices          Vector of the vertices to clip.
       *                               The vector is cleared afterwards.
       *    @param   outcodes          Vector of the outcodes of the
       *                               vertices to clip.
       *                               The vector is cleared afterwards.
       *    @param   resVertices       The resulting clipped vertices
       *                               are added to this vector.
       *    @param   resOutcodes       The resulting outcodes of the
       *                               clipped vertices are added to this
       *                               vector.
       *    @return  True if the resulting clipped vertices is a valid
       *             polygon, false otherwise.
       */
      static bool clipToBoundary( const byte boundaryOutcode,
                                  const MC2BoundingBox* bbox,
                                  vector<POINT>& vertices,
                                  vector<byte>& outcodes,
                                  vector<POINT>& resVertices,
                                  vector<byte>& resOutcodes );

      /**
       *    Help-method to clipToBoundary(..).
       *    Clips the two vertices against the boundary of a boundingbox.
       *
       *    @param   prevVertex  The previous vertex.
       *    @param   currVertex  The next vertex.
       *    @param   prevInside  If prevVertex is inside the bbox boundary.
       *    @param   currInside  If currVertex is inside the bbox boundary.
       *    @param   currOutcode The Cohen-Sutherland outcode of
       *                         currVertex.
       *    @param   bbox        The boundingbox.
       *    @param   boundaryOutcode   The Cohen-Sutherland
       *                               outcode of boundary of
       *                               the boundingbox to clip to, ie.
       *                               MC2BoundingBox::TOP/BOTTOM/LEFT/RIGHT
       *    @param   resVertices  The resulting clipped vertices
       *                          are added to this vector.
       *    @param   resOutcodes  The resulting outcodes of the
       *                          clipped vertices are added to this
       *                          vector.
       */
      static void clipSegment( const POINT& prevVertex,
                               const POINT& currVertex,
                               bool prevInside,
                               bool currInside,
                               byte currOutcode,
                               const MC2BoundingBox* bbox,
                               byte boundaryOutcode,
                               vector<byte>& resOutcodes,
                               vector<POINT>& resVertices );

  public:
      /**
       *    Reduces the number of vertices outside the boundingbox and
       *    computes the Cohen-Sutherland outcodes for each of those
       *    vertices.
       *
       *    @param   bbox           The boundingbox to reduce the polygon.
       *    @param   vertices       The input polygon.
       *    @param   reducedVertices   [OUT] The resulting reduced polygon.
       *    @param   outcodes       The Cohen-Sutherland outcodes of the
       *                            reduced vertices are added to this
       *                            vector<byte>.
       *    @return  True if the vectors got filled with any vertices /
       *             outcodes, false otherwise.
       */
     static bool reduceByBBox( const MC2BoundingBox* bbox,
                               const vector<POINT>& vertices,
                               vector<POINT>& reducedVertices,
                               vector<byte>& outcodes );
};

//======================================================================
//                                    Implementation of inline methods =

inline bool
GfxUtility::pointInsideRect( int32 x, int32 y, int32 minX, int32 maxX,
                             int32 minY, int32 maxY )
{
   if (((minX <= x) && (x <= maxX)) && ((minY <= y) && (y <= maxY)))
      return true;
   else
      return false;
}

#endif


text:
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts          #-}

module Language.Grass.Interpreter.VM
  ( Pos(..)
  , Inst(..)
  , RuntimeError(..)
  , Code
  , run
  ) where

import           Control.Monad.Except
import qualified Data.ByteString      as BS
import           Data.Word
import           Safe
import           System.IO

-- instructions
data Pos = forall p. Show p => Pos p

instance Show Pos where
  show (Pos p) = show p

data Inst =
    App Pos Int Int  -- application
  | Abs Pos Int Code -- abstraction

-- values
data Value =
    Char Word8               -- character
  | Prim (Value -> VM Value) -- primitive operation
  | Clos Env Code            -- closure

-- VM
data RuntimeError = RuntimeError Pos String

instance Show RuntimeError where
  show (RuntimeError pos msg) = show pos ++ ":\n" ++ msg

type VM = ExceptT RuntimeError IO

type Code = [Inst]

type Env = [Value]

data VMState = VMState Code Env [(Code, Env)]

-- dummy position
vmPos :: Pos
vmPos = Pos "VM"

-- boolean values
closFalse :: Value
closFalse = Clos [] [Abs vmPos 1 []]

closTrue :: Value
closTrue = Clos [closId] [Abs vmPos 1 [App vmPos 2 1]]
  where
    closId = Clos [] []

-- character 'w'
charLowerW :: Value
charLowerW = Char 119

-- primitive operations
getWord8 :: IO (Maybe Word8)
getWord8 = do
    b <- BS.hGet stdin 1
    if BS.null b then
      return Nothing
    else
      return $ Just (BS.head b)

putWord8 :: Word8 -> IO ()
putWord8 w = BS.hPut stdout (BS.singleton w)

periodicSucc :: Word8 -> Word8
periodicSucc w
    | w == maxBound = minBound
    | otherwise = w + 1

primIn :: Value
primIn = Prim op
  where
    op x = maybe x Char <$> liftIO getWord8

primOut :: Value
primOut = Prim op
  where
    op x@(Char w) = liftIO (putWord8 w) >> return x
    op _          = throwError $ RuntimeError vmPos "OUT: not a character"

primSucc :: Value
primSucc = Prim op
  where
    op (Char w) = return $ Char (periodicSucc w)
    op _        = throwError $ RuntimeError vmPos "SUCC: not a character"

-- evaluation
-- get a value in the environment
envAt :: Pos -> Env -> Int -> VM Value
envAt pos env i = case env `atMay` i of
    Nothing -> throwError $ RuntimeError pos ("index out of range: " ++ show (i + 1))
    Just x  -> return x

-- compare characters
eqChar :: Word8 -> Value -> Value
eqChar w (Char v)
    | w == v = closTrue
    | otherwise = closFalse
eqChar _ _ = closFalse

-- set error position
withPos :: Pos -> VM a -> VM a
withPos pos = withExceptT setPos
  where
    setPos (RuntimeError _ msg) = RuntimeError pos msg

eval :: VMState -> VM Value
eval (VMState [] [x] []) =
    -- terminate
    return x
eval (VMState [] (x : _) ((c', e') : d)) =
    -- back to the call site
    eval (VMState c' (x : e') d)
eval (VMState (App pos m n : c) e d) = do
    f <- envAt pos e m -- function
    a <- envAt pos e n -- argument
    case f of
      Char w ->
        -- compare the character with the argument
        let x = eqChar w a in
        eval (VMState c (x : e) d)
      Prim op -> do
        -- execute the primitive operation
        x <- withPos pos (op a)
        eval (VMState c (x : e) d)
      Clos em cm ->
        -- call the function
        if null c && not (null d) then
          -- tail call optimization
          eval (VMState cm (a : em) d)
        else
          eval (VMState cm (a : em) ((c, e) : d))
eval (VMState (Abs pos n c' : c) e d) =
    -- create a closure
    let
      clos
        | n <= 1 = Clos e c'
        | otherwise = Clos e [Abs pos (n - 1) c']
    in
    eval (VMState c (clos : e) d)
eval _ = throwError $ RuntimeError vmPos "unknown VM state"

run :: Code -> IO (Either RuntimeError ())
run code = runExceptT $ do
    let initState = VMState code initEnv initDump
    _ <- eval initState
    return ()
  where
    initEnv = [primOut, primSucc, charLowerW, primIn]
    initDump = [([App vmPos 0 0], []), ([], [])]

redpajama_set_name: RedPajamaGithub


text:
package maxwell_lt.mobblocker;

import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

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

/**
 * Handles gifting players ChunkProtectors upon first spawn
 */
@Mod.EventBusSubscriber
public class LoginEventHandler {

	@SubscribeEvent
	public static void onPlayerJoinWorld(EntityJoinWorldEvent event) {
		if (!event.getWorld().isRemote && event.getEntity() instanceof PlayerEntity && Config.GIVE_NEW_PLAYERS_PROTECTOR.get()) {
			PlayerEntity player = (PlayerEntity) event.getEntity();
			CompoundNBT persistentTag;
			if (player.getPersistentData().contains(PlayerEntity.PERSISTED_NBT_TAG)) {
				persistentTag = player.getPersistentData().getCompound(PlayerEntity.PERSISTED_NBT_TAG);
			} else {
				persistentTag = new CompoundNBT();
				player.getPersistentData().put(PlayerEntity.PERSISTED_NBT_TAG, persistentTag);
			}
			CompoundNBT tag;
			if (persistentTag.contains("mobblocker")) {
				tag = persistentTag.getCompound("mobblocker");
			} else {
				tag = new CompoundNBT();
				persistentTag.put("mobblocker", tag);
			}
			if (!tag.getBoolean("receivedprotector")) {
				player.inventory.addItemStackToInventory(new ItemStack(ModBlocks.CHUNKPROTECTOR));
				tag.putBoolean("receivedprotector", true);
			}
		}
	}
}


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

namespace RocketLeagueReplayParser.NetworkStream
{
    public class RigidBodyState
    {
        public bool Sleeping { get; private set; }
        public IVector3D Position { get; private set; }

        // I dont like this as an object, but it'll do for now.
        // Can be Vector3D or Quaternion
        public object Rotation { get; private set; }

        public Vector3D LinearVelocity { get; private set; }
        public Vector3D AngularVelocity { get; private set; }

        public static RigidBodyState Deserialize(BitReader br, UInt32 netVersion)
        {
            var rbs = new RigidBodyState();
            rbs.Sleeping = br.ReadBit();
            if (netVersion >= 5)
            {
                rbs.Position = FixedPointVector3D.Deserialize(br, netVersion);
            }
            else
            {
                rbs.Position = Vector3D.Deserialize(br, netVersion);
            }

            if (netVersion >= 7)
            {
                rbs.Rotation = Quaternion.Deserialize(br);
            }
            else
            {
                rbs.Rotation = Vector3D.DeserializeFixed(br);
            }

            if (!rbs.Sleeping)
            {
                rbs.LinearVelocity = Vector3D.Deserialize(br, netVersion);
                rbs.AngularVelocity = Vector3D.Deserialize(br, netVersion);
            }

            return rbs;
        }

        public void  Serialize(BitWriter bw, UInt32 netVersion)
        {
            bw.Write(Sleeping);
            Position.Serialize(bw, netVersion);

            if (netVersion >= 7)
            {
                ((Quaternion)Rotation).Serialize(bw);
            }
            else
            {
                ((Vector3D)Rotation).SerializeFixed(bw);
            }

            if (!Sleeping)
            {
                LinearVelocity.Serialize(bw, netVersion);
                AngularVelocity.Serialize(bw, netVersion);
            }
        }

        public override string ToString()
        {
            if ( !Sleeping )
            {
                return String.Format("Position: {0} Rotation {1} LinearVelocity {2} AngularVelocity {3}", Position, Rotation, LinearVelocity, AngularVelocity);
            }
            return String.Format("Position: {0} Rotation {1}", Position, Rotation);
        }
    }
}


text:
jest.mock("../../api/crud", () => ({
  edit: jest.fn(),
  save: jest.fn(),
  destroy: jest.fn(),
}));

let mockPath = "/app/designer/tools/1";
jest.mock("../../history", () => ({
  push: jest.fn(),
  getPathArray: () => mockPath.split("/"),
}));

import React from "react";
import { mount, shallow } from "enzyme";
import {
  RawEditTool as EditTool, mapStateToProps, isActive,
} from "../edit_tool";
import {
  fakeTool, fakeToolSlot,
} from "../../__test_support__/fake_state/resources";
import { fakeState } from "../../__test_support__/fake_state";
import {
  buildResourceIndex, fakeDevice,
} from "../../__test_support__/resource_index_builder";
import { SaveBtn } from "../../ui";
import { push } from "../../history";
import { edit, destroy, save } from "../../api/crud";
import { clickButton } from "../../__test_support__/helpers";
import { EditToolProps } from "../interfaces";

describe("<EditTool />", () => {
  beforeEach(() => {
    mockPath = "/app/designer/tools/1";
  });

  const fakeProps = (): EditToolProps => ({
    findTool: jest.fn(() => fakeTool()),
    dispatch: jest.fn(),
    mountedToolId: undefined,
    isActive: jest.fn(),
    existingToolNames: [],
    saveFarmwareEnv: jest.fn(),
    env: {},
  });

  it("renders", () => {
    const wrapper = mount(<EditTool {...fakeProps()} />);
    expect(wrapper.text()).toContain("Edit tool");
  });

  it("handles missing tool name", () => {
    const p = fakeProps();
    const tool = fakeTool();
    tool.body.name = undefined;
    p.findTool = () => tool;
    const wrapper = mount<EditTool>(<EditTool {...p} />);
    expect(wrapper.state().toolName).toEqual("");
  });

  it("redirects", () => {
    mockPath = "/app/designer/tools/";
    const p = fakeProps();
    p.findTool = jest.fn(() => undefined);
    const wrapper = mount<EditTool>(<EditTool {...p} />);
    expect(wrapper.instance().stringyID).toEqual("");
    expect(wrapper.text()).toContain("Redirecting...");
    expect(push).toHaveBeenCalledWith("/app/designer/tools");
  });

  it("doesn't redirect", () => {
    mockPath = "/app/logs";
    const p = fakeProps();
    p.findTool = jest.fn(() => undefined);
    const wrapper = mount(<EditTool {...p} />);
    expect(wrapper.text()).toContain("Redirecting...");
    expect(push).not.toHaveBeenCalled();
  });

  it("edits tool name", () => {
    const wrapper = shallow<EditTool>(<EditTool {...fakeProps()} />);
    wrapper.find("input").simulate("change",
      { currentTarget: { value: "new name" } });
    expect(wrapper.state().toolName).toEqual("new name");
  });

  it("disables save until name in entered", () => {
    const wrapper = shallow<EditTool>(<EditTool {...fakeProps()} />);
    wrapper.setState({ toolName: "" });
    expect(wrapper.find("SaveBtn").first().props().disabled).toBeTruthy();
    wrapper.setState({ toolName: "fake tool name" });
    expect(wrapper.find("SaveBtn").first().props().disabled).toBeFalsy();
  });

  it("shows name collision message", () => {
    const p = fakeProps();
    p.existingToolNames = ["tool"];
    const wrapper = shallow<EditTool>(<EditTool {...p} />);
    wrapper.setState({ toolName: "tool" });
    expect(wrapper.find("p").first().text()).toEqual("Name already taken.");
    expect(wrapper.find("SaveBtn").first().props().disabled).toBeTruthy();
  });

  it("saves", () => {
    const p = fakeProps();
    const tool = fakeTool();
    p.findTool = () => tool;
    const wrapper = shallow(<EditTool {...p} />);
    wrapper.find(SaveBtn).simulate("click");
    expect(edit).toHaveBeenCalledWith(expect.any(Object), { name: "Foo" });
    expect(save).toHaveBeenCalledWith(tool.uuid);
    expect(push).toHaveBeenCalledWith("/app/designer/tools");
  });

  it("removes tool", () => {
    const p = fakeProps();
    const tool = fakeTool();
    tool.body.id = 1;
    p.findTool = () => tool;
    p.isActive = () => false;
    p.mountedToolId = undefined;
    const wrapper = shallow(<EditTool {...p} />);
    clickButton(wrapper, 0, "delete");
    expect(destroy).toHaveBeenCalledWith(tool.uuid);
  });

  it("doesn't remove tool: active", () => {
    const p = fakeProps();
    const tool = fakeTool();
    tool.body.id = 1;
    p.findTool = () => tool;
    p.isActive = () => true;
    p.mountedToolId = undefined;
    const wrapper = shallow(<EditTool {...p} />);
    clickButton(wrapper, 0, "delete");
    expect(destroy).not.toHaveBeenCalledWith(tool.uuid);
  });

  it("doesn't remove tool: mounted", () => {
    const p = fakeProps();
    const tool = fakeTool();
    tool.body.id = 1;
    p.findTool = () => tool;
    p.isActive = () => false;
    p.mountedToolId = tool.body.id;
    const wrapper = shallow(<EditTool {...p} />);
    clickButton(wrapper, 0, "delete");
    expect(destroy).not.toHaveBeenCalledWith(tool.uuid);
  });
});

describe("mapStateToProps()", () => {
  it("returns props", () => {
    const state = fakeState();
    const tool = fakeTool();
    tool.body.id = 123;
    state.resources = buildResourceIndex([tool, fakeDevice()]);
    const props = mapStateToProps(state);
    expect(props.findTool("" + tool.body.id)).toEqual(tool);
  });
});

describe("isActive()", () => {
  it("returns tool state", () => {
    const toolSlot = fakeToolSlot();
    toolSlot.body.tool_id = 1;
    const active = isActive([toolSlot]);
    expect(active(1)).toEqual(true);
    expect(active(2)).toEqual(false);
    expect(active(undefined)).toEqual(false);
  });
});


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

from abc import abstractmethod

from pants.util.meta import AbstractClass

class ParseError(Exception):
  """Indicates an error parsing BUILD configuration."""

class SymbolTable(AbstractClass):
  """A one-classmethod interface exposing a symbol table dict.

  SymbolTables exist as named classes because it allows them to be loaded by name as a python
  module, rather than being pickled when they cross between processes.
  """

  @classmethod
  @abstractmethod
  def table(cls):
    """Returns a dict of name to implementation class."""

class Parser(AbstractClass):
  @classmethod
  @abstractmethod
  def parse(cls, filepath, filecontent, symbol_table_cls):
    """
    :param string filepath: The name of the file being parsed. The parser should not assume
                            that the path is accessible, and should consume the filecontent.
    :param bytes filecontent: The raw byte content to parse.
    :param dict symbol_table_cls: A symbol table to expose to the python file being parsed.
    :returns: A list of decoded addressable, Serializable objects. The callable will
              raise :class:`ParseError` if there were any problems encountered parsing the filecontent.
    :rtype: :class:`collections.Callable`
    """


text:
package ec.edu.espe.isi.conjunta.conjuntasoftware1;

import java.util.Scanner;

/**
 * Clase principal.
 *
 * @author Jonathan
 */
public class Started {

    private static Operaciones op = new Operaciones();
    private static OperacionesFloat opf = new OperacionesFloat();

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        System.out.println("MENU PRINCIPAL");
        Scanner sc = new Scanner(System.in);
        int a1 = 0;
        float a2 = 0;
        int b1 = 0;
        float b2 = 0;
        int tipo = 0;
        try {
            System.out.println("Ingrese el tipo de dato:\n1. Enteros\n2. Flotantes");
            do {
                tipo = sc.nextInt();
            } while (tipo < 0 || tipo > 2);
        } catch (Exception ex) {
            System.out.println("Ingrese solo numeros");
        }
        if (tipo == 1) {
            try {
                System.out.print("Ingrese el primer numero: ");
                a1 = sc.nextInt();
                System.out.print("Ingrese el segundo numero: ");
                b1 = sc.nextInt();
            } catch (Exception ex) {
                System.out.println("Ingrese solo numeros");
            }
            menuentero(a1, b1);
        }
        if (tipo == 2) {
            try {
                System.out.print("Ingrese el primer numero: ");
                a2 = sc.nextFloat();
                System.out.print("Ingrese el segundo numero: ");
                b2 = sc.nextFloat();
            } catch (Exception ex) {
                System.out.println("Ingrese solo numeros");
            }
        }
        menuflotante(a2, b2);
    }

    /**
     * Metodo para la muestra del menu con numeros enteros.
     * @param a Numero 1.
     * @param b Numero 2.
     */
    public static void menuentero(int a, int b) {
        int aux = 0;
        do {
            Scanner sc = new Scanner(System.in);
            try {
                System.out.println("Ingrese la operacion deseada: ");
                System.out.println("1. Suma\n2. Resta\n3. Multiplicacion");
                System.out.println("\n4. Divicion\n5. Potencia\n6. Modulo\n7. Salir");
                aux = sc.nextInt();
            } catch (Exception ex) {
                System.out.println("Ingrese solo numeros");
            }
            switch (aux) {
                case 1:
                    System.out.println("Resultado: " + op.suma(a, b));
                    break;
                case 2:
                    System.out.println("Resultado: " + op.resta(a, b));
                    break;
                case 3:
                    System.out.println("Resultado: " + op.multiplicacion(a, b));
                    break;
                case 4:
                    System.out.println("Resultado: " + op.division(a, b));
                    break;
                case 5:
                    System.out.println("Resultado: " + op.potencia(a, b));
                    break;
                case 6:
                    System.out.println("Resultado: " + op.modulo(a, b));
                    break;
                case 7:
                    System.out.println("Fin del Programa");
                    break;
                default:

            }
        } while (aux == 5);
    }

    /**
     * Metodo para la muestra del menu con numeros flotantes.
     * @param a
     * @param b
     */
    public static void menuflotante(float a, float b) {
        int aux = 0;
        do {
            Scanner sc = new Scanner(System.in);
            try {
                System.out.println("Ingrese la operacion deseada: ");
                System.out.println("1. Suma\n2. Resta\n3. Multiplicacion\n4. Divicion\n5. Salir");
                aux = sc.nextInt();
            } catch (Exception ex) {
                System.out.println("Ingrese solo numeros");
            }
            switch (aux) {
                case 1:
                    System.out.println("Resultado: " + opf.suma(a, b));
                    break;
                case 2:
                    System.out.println("Resultado: " + opf.resta(a, b));
                    break;
                case 3:
                    System.out.println("Resultado: " + opf.multiplicacion(a, b));
                    break;
                case 4:
                    System.out.println("Resultado: " + opf.division(a, b));
                    break;
                case 5:
                    System.out.println("Fin del Programa");
                    break;
                default:

            }
        } while (aux == 5);
    }
}


text:
<?php

namespace Go\Aop;

/**
 * Aspect interface marker
 *
 * Aspect is a module that encapsulates a concern. An aspect is composed of pointcuts, advice bodies and inter-type
 * declarations. In some approaches, and aspect may also contain classes and methods.
 *
 * @link http://en.wikipedia.org/wiki/Aspect_%28computer_science%29
 */
interface Aspect
{

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.network.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Contains the IpTag associated with the object. */
@Fluent
public final class IpTag {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(IpTag.class);

    /*
     * Gets or sets the ipTag type: Example FirstPartyUsage.
     */
    @JsonProperty(value = "ipTagType")
    private String ipTagType;

    /*
     * Gets or sets value of the IpTag associated with the public IP. Example
     * SQL, Storage etc
     */
    @JsonProperty(value = "tag")
    private String tag;

    /**
     * Get the ipTagType property: Gets or sets the ipTag type: Example FirstPartyUsage.
     *
     * @return the ipTagType value.
     */
    public String ipTagType() {
        return this.ipTagType;
    }

    /**
     * Set the ipTagType property: Gets or sets the ipTag type: Example FirstPartyUsage.
     *
     * @param ipTagType the ipTagType value to set.
     * @return the IpTag object itself.
     */
    public IpTag withIpTagType(String ipTagType) {
        this.ipTagType = ipTagType;
        return this;
    }

    /**
     * Get the tag property: Gets or sets value of the IpTag associated with the public IP. Example SQL, Storage etc.
     *
     * @return the tag value.
     */
    public String tag() {
        return this.tag;
    }

    /**
     * Set the tag property: Gets or sets value of the IpTag associated with the public IP. Example SQL, Storage etc.
     *
     * @param tag the tag value to set.
     * @return the IpTag object itself.
     */
    public IpTag withTag(String tag) {
        this.tag = tag;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text:
/* */
(function(process) {
  'use strict';
  var ReactLifeCycle = {
    currentlyMountingInstance: null,
    currentlyUnmountingInstance: null
  };
  module.exports = ReactLifeCycle;
})(require('process'));


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Fitopatol. Brasil. 22(3): 446 (1997)

#### Original name
Aecidium maprouneae var. noncrassatum J.F. Hennen & Sotão

### Remarks
null


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Statistics of Polarity in UD_Latin-UDante</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

Treebank Statistics: UD_Latin-UDante: Features: Polarity

This feature is universal.
It occurs with 1 different values: Neg.

1439 tokens (3%) have a non-empty value of Polarity.
184 types (2%) occur at least once with a non-empty value of Polarity.
115 lemmas (2%) occur at least once with a non-empty value of Polarity.
The feature is used with 9 part-of-speech tags: <tt>PART</tt> (737; 1% instances), <tt>ADJ</tt> (188; 0% instances), <tt>CCONJ</tt> (179; 0% instances), <tt>SCONJ</tt> (111; 0% instances), <tt>DET</tt> (84; 0% instances), <tt>PRON</tt> (64; 0% instances), <tt>ADV</tt> (45; 0% instances), <tt>VERB</tt> (17; 0% instances), <tt>NOUN</tt> (14; 0% instances).

PART

737 <tt>PART</tt> tokens (49% of all PART tokens) have a non-empty value of Polarity.

The most frequent other feature values with which PART and Polarity co-occurred: <tt>Form</tt><tt>=EMPTY</tt> (737; 100%).

PART tokens may have the following values of Polarity:

Neg (737; 100% of non-empty Polarity): non, ni, ne

EMPTY (756): nam, enim, autem, igitur, quidem, quoque, etenim, itaque, ne, o

ADJ

188 <tt>ADJ</tt> tokens (5% of all ADJ tokens) have a non-empty value of Polarity.

The most frequent other feature values with which ADJ and Polarity co-occurred: <tt>NameType</tt><tt>=EMPTY</tt> (188; 100%), <tt>Degree</tt><tt>=EMPTY</tt> (186; 99%), <tt>Number</tt><tt>=Sing</tt> (139; 74%), <tt>Case</tt><tt>=Nom</tt> (112; 60%), <tt>InflClass</tt><tt>=IndEurI</tt> (100; 53%).

ADJ tokens may have the following values of Polarity:

Neg (188; 100% of non-empty Polarity): inpossibile, impossibile, iniustum, inmeritus, inconveniens, ignari, impari, impius, incorruptibilis, inopina

EMPTY (3789): humanum, manifestum, necesse, prima, verum, primo, primum, romanorum, illustre, romanus

Polarity seems to be lexical feature of ADJ. 100% lemmas (79) occur only with one value of Polarity.

CCONJ

179 <tt>CCONJ</tt> tokens (6% of all CCONJ tokens) have a non-empty value of Polarity.

CCONJ tokens may have the following values of Polarity:

Neg (179; 100% of non-empty Polarity): nec, neque, necnon, nedum

EMPTY (2858): et, sed, vel, que, sive, atque, scilicet, aut, ac, videlicet

SCONJ

111 <tt>SCONJ</tt> tokens (4% of all SCONJ tokens) have a non-empty value of Polarity.

The most frequent other feature values with which SCONJ and Polarity co-occurred: <tt>Compound</tt><tt>=EMPTY</tt> (111; 100%), <tt>PronType</tt><tt>=EMPTY</tt> (84; 76%).

SCONJ tokens may have the following values of Polarity:

Neg (111; 100% of non-empty Polarity): nisi, ne, quin, ni, necubi

EMPTY (2415): ut, quod, cum, si, quia, quam, sicut, tanquam, quantum, quemadmodum

DET

84 <tt>DET</tt> tokens (2% of all DET tokens) have a non-empty value of Polarity.

The most frequent other feature values with which DET and Polarity co-occurred: <tt>Form</tt><tt>=EMPTY</tt> (84; 100%), <tt>InflClass</tt><tt>=LatPron</tt> (84; 100%), <tt>NumType</tt><tt>=EMPTY</tt> (84; 100%), <tt>Person[psor]</tt><tt>=EMPTY</tt> (84; 100%), <tt>Poss</tt><tt>=EMPTY</tt> (84; 100%), <tt>PronType</tt><tt>=Ind</tt> (83; 99%), <tt>Number</tt><tt>=Sing</tt> (75; 89%).

DET tokens may have the following values of Polarity:

Neg (84; 100% of non-empty Polarity): nulla, nullo, nullum, nulli, nullus, nullius, nullam, nullos, nullis, neutrum

EMPTY (3560): hoc, illa, illud, unum, hec, ipsum, omnes, aliud, sua, quedam

PRON

64 <tt>PRON</tt> tokens (2% of all PRON tokens) have a non-empty value of Polarity.

The most frequent other feature values with which PRON and Polarity co-occurred: <tt>Person</tt><tt>=EMPTY</tt> (64; 100%), <tt>PronType</tt><tt>=Ind</tt> (64; 100%), <tt>Case</tt><tt>=EMPTY</tt> (47; 73%), <tt>Gender</tt><tt>=EMPTY</tt> (47; 73%), <tt>InflClass</tt><tt>=EMPTY</tt> (47; 73%), <tt>Number</tt><tt>=EMPTY</tt> (47; 73%).

PRON tokens may have the following values of Polarity:

Neg (64; 100% of non-empty Polarity): nichil, nemo, nil, neminem, nemini, nihil

EMPTY (2611): quod, que, qui, se, quo, eius, quam, quid, nobis, sibi

ADV

45 <tt>ADV</tt> tokens (1% of all ADV tokens) have a non-empty value of Polarity.

The most frequent other feature values with which ADV and Polarity co-occurred: <tt>Degree</tt><tt>=EMPTY</tt> (45; 100%), <tt>Compound</tt><tt>=EMPTY</tt> (44; 98%), <tt>PronType</tt><tt>=EMPTY</tt> (44; 98%), <tt>AdvType</tt><tt>=EMPTY</tt> (43; 96%).

ADV tokens may have the following values of Polarity:

Neg (45; 100% of non-empty Polarity): nunquam, nondum, inconvenienter, iniuste, nequaquam, nimirum, inconsulte, inmediate, nequicquam, nichil

EMPTY (3070): sic, ergo, etiam, vero, nunc, unde, tamen, bene, iam, magis

Polarity seems to be lexical feature of ADV. 100% lemmas (11) occur only with one value of Polarity.

VERB

17 <tt>VERB</tt> tokens (0% of all VERB tokens) have a non-empty value of Polarity.

The most frequent other feature values with which VERB and Polarity co-occurred: <tt>Number</tt><tt>=Sing</tt> (14; 82%), <tt>Aspect</tt><tt>=Imp</tt> (12; 71%), <tt>Case</tt><tt>=EMPTY</tt> (12; 71%), <tt>Gender</tt><tt>=EMPTY</tt> (12; 71%), <tt>InflClass[nominal]</tt><tt>=EMPTY</tt> (12; 71%), <tt>Voice</tt><tt>=Act</tt> (12; 71%), <tt>InflClass</tt><tt>=LatI</tt> (9; 53%), <tt>Mood</tt><tt>=Ind</tt> (9; 53%), <tt>VerbForm</tt><tt>=Fin</tt> (9; 53%).

VERB tokens may have the following values of Polarity:

Neg (17; 100% of non-empty Polarity): nescio, nescit, ignoscendum, ignoscet, indignata, infirmari, insanisse, insperate, invidere, nesciens

EMPTY (8206): potest, patet, habet, dicimus, videtur, dicit, consequens, dico, habere, oportet

NOUN

14 <tt>NOUN</tt> tokens (0% of all NOUN tokens) have a non-empty value of Polarity.

The most frequent other feature values with which NOUN and Polarity co-occurred: <tt>Number</tt><tt>=Sing</tt> (9; 64%).

NOUN tokens may have the following values of Polarity:

Neg (14; 100% of non-empty Polarity): nefas, negotii, negotium, ignominiam, incertitudine, incertitudo, iniuriam, iniurias

EMPTY (10098): Dei, Deus, natura, terra, parte, mundi, genus, ratio, Deo, iure

Relations with Agreement in Polarity

The 10 most frequent relations where parent and child node agree in Polarity:
<tt>CCONJ –[<tt>fixed</tt>]–> PART</tt> (15; 100%),
<tt>ADJ –[<tt>advcl</tt>]–> ADJ</tt> (2; 67%),
<tt>DET –[<tt>case</tt>]–> PART</tt> (1; 100%),
<tt>DET –[<tt>nsubj</tt>]–> PART</tt> (1; 100%),
<tt>VERB –[<tt>advcl:cmp</tt>]–> VERB</tt> (1; 100%).

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
<!DOCTYPE html>

	<meta charset="utf-8" />
	<title>ax-loader test - node_modules</title>

Expected result (check console):

1. top_module.js: running

2. node_module1.js: running

3. node_module2.js: running

4. sub/node_module2_sub.js: running

5. node_module3.js: running

6. node_module4.js: running


text:
package cn.six.a6x.fingerprint.mine;

import android.app.Activity;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import cn.six.a6x.R;

/**
 * Created by songzhw on 2015/12/25
 */
public class MyFingerprintTestActivity extends FingerpringBaseActivity {
    private ImageView iv;
    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_fingerprint);

        iv = (ImageView) findViewById(R.id.ivMyFingerprint);
        tv = (TextView) findViewById(R.id.tvMyFingerprint);

    }

    public void clickAuthen(View v){
        boolean isFingerprintEnable = isFingerprintAvailable();
        if(isFingerprintEnable){
            tv.setText("Start to authenticate your fingerprint ...");
            iv.setImageResource(R.drawable.ic_fingerprint);
            authenFingerprint();
        }
    }

    // Touch the fingerprint zone will get no response
    // msg is like "尝试次数过多, 请稍后重试 "
    @Override
    public void onAuthenError(CharSequence msg) {
        tv.setText("[Error]" + msg + " ;  Please try again");
        iv.setImageResource(R.drawable.ic_fingerprint_error);
    }

    // After getting this, you can retry and touch the fingerprint zone again.
    @Override
    public void onAuthenFail() {
        tv.setText("[Fail]" );
        iv.setImageResource(R.drawable.ic_fingerprint_error);
    }

    @Override
    public void onAuthenHelp(CharSequence msg) {
        tv.setText("[Help]" + msg);
    }

    @Override
    public void onAuthenSucc(FingerprintManager.AuthenticationResult result) {
        FingerprintManager.CryptoObject crypto = result.getCryptoObject();
        tv.setText("[Succ]" + crypto);
        iv.setImageResource(R.drawable.ic_fingerprint_success);
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Muti Furniture - Handmade Pieces from Uganda</title>

  <meta name="description" content="Muti Furniture" />
  <meta name="keywords" content="shop, furniture, modern, minimalist style, responsive, online store, business, mobile, blog, bootstrap, html5, css3, jquery, js, gallery, slider, touch, creative, clean" />
  <meta name="author" content="Rokaux" />

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

  <link rel="shortcut icon" href="<?php echo base_url('assets/favicon.ico');?>" type="image/x-icon">
  <link rel="icon" href="<?php echo base_url('assets/favicon.ico');?>" type="image/x-icon">

  <link href="<?php echo base_url('assets/css/vendor/material-icons.min.css')?>" rel="stylesheet" media="screen">

  <link href="<?php echo base_url('assets/css/vendor/bootstrap.min.css')?>" rel="stylesheet" media="screen">

  <link href="<?php echo base_url('assets/css/theme.min.css')?>" rel="stylesheet" media="screen">
  <link href="<?php echo base_url('assets/css/custom.css')?>" rel="stylesheet" media="screen">
  <?php echo $map['js']; ?>

      <img src="<?php echo base_url('assets/img/preloader.gif')?>" alt="Preloader">

      <a href="<?php echo base_url('/') ?>" class="site-logo visible-desktop"><img src="<?php echo base_url('assets/img/Muti-images/logocolorweb.png')?>">

      <a href="<?php echo base_url('/')?>" class="site-logo visible-mobile">
        <img src="<?php echo base_url('assets/img/Muti-images/logocolorweb.png')?>">

            For a quote, call us at

          +256 775680435

            For a quote, call us at

          +256 775680435