Пример #1
0
  public void mouseClicked(MouseEvent e) {
    int x;
    int y;

    e.consume();

    if (mouseEventsEnabled) {

      x = Math.round(e.getX() / scale);
      y = Math.round(e.getY() / scale);

      // allow for the canvas margin
      y -= margin;

      // System.out.println("Mouse Click: (" + x + ", " + y + ")");

      if (e.getClickCount() < 2) {
        if (nativeSelectItem(x, y)) {
          parentFTAFrame.updateFrame();
        }
      } else {
        if (nativeSelectItem(x, y)) {
          parentFTAFrame.updateFrame();
        }

        editSelected();
        parentFTAFrame.updateFrame();
      }

      if (focusEventsEnabled) {
        // tell the main Canvas to point to this coordinate
        parentFTAFrame.setCanvasFocus(x, y);
      }
    }
  }
Пример #2
0
  /**
   * Reads image meta data.
   *
   * @param oimage
   * @return
   */
  public static Map<String, String> readImageData(IIOImage oimage) {
    Map<String, String> dict = new HashMap<String, String>();

    IIOMetadata imageMetadata = oimage.getMetadata();
    if (imageMetadata != null) {
      IIOMetadataNode dimNode = (IIOMetadataNode) imageMetadata.getAsTree("javax_imageio_1.0");
      NodeList nodes = dimNode.getElementsByTagName("HorizontalPixelSize");
      int dpiX;
      if (nodes.getLength() > 0) {
        float dpcWidth = Float.parseFloat(nodes.item(0).getAttributes().item(0).getNodeValue());
        dpiX = (int) Math.round(25.4f / dpcWidth);
      } else {
        dpiX = Toolkit.getDefaultToolkit().getScreenResolution();
      }
      dict.put("dpiX", String.valueOf(dpiX));

      nodes = dimNode.getElementsByTagName("VerticalPixelSize");
      int dpiY;
      if (nodes.getLength() > 0) {
        float dpcHeight = Float.parseFloat(nodes.item(0).getAttributes().item(0).getNodeValue());
        dpiY = (int) Math.round(25.4f / dpcHeight);
      } else {
        dpiY = Toolkit.getDefaultToolkit().getScreenResolution();
      }
      dict.put("dpiY", String.valueOf(dpiY));
    }

    return dict;
  }
Пример #3
0
 // Give the string and horizontal and verical offsets so that the label is
 // drawn in the center.
 public void drawLabel(Graphics g, String label, int hoffset, int voffset) {
   g.setColor(Color.black);
   int pixelsPerNm = DrawPanel.PIXELS_PER_NM;
   int xint = (int) Math.round(pixelsPerNm * z);
   int yint = (int) Math.round(pixelsPerNm * y);
   g.drawString(label, xint - hoffset, yint + voffset);
 }
Пример #4
0
 public static String formatLocation(Location location) {
   return String.format(
       "%s: (%d, %d, %d)",
       location.getWorld().getName(),
       Math.round(location.getX()),
       Math.round(location.getY()),
       Math.round(location.getZ()));
 }
Пример #5
0
  /**
   * Creates Gaussian derivative kernels.
   *
   * @param sigmas DOCUMENT ME!
   */
  private void makeKernels2D(float[] sigmas) {
    int xkDim, ykDim;
    int[] derivOrder = new int[2];

    kExtents = new int[2];
    derivOrder[0] = 2;
    derivOrder[1] = 0;

    xkDim = Math.round(8 * sigmas[0]);

    if ((xkDim % 2) == 0) {
      xkDim++;
    }

    if (xkDim < 3) {
      xkDim = 3;
    }

    kExtents[0] = xkDim;

    ykDim = Math.round(8 * sigmas[1]);

    if ((ykDim % 2) == 0) {
      ykDim++;
    }

    if (ykDim < 3) {
      ykDim = 3;
    }

    kExtents[1] = ykDim;

    GxxData = new float[xkDim * ykDim];

    GenerateGaussian Gxx = new GenerateGaussian(GxxData, kExtents, sigmas, derivOrder);

    Gxx.calc(false);

    derivOrder[0] = 0;
    derivOrder[1] = 2;
    GyyData = new float[xkDim * ykDim];

    GenerateGaussian Gyy = new GenerateGaussian(GyyData, kExtents, sigmas, derivOrder);

    Gyy.calc(false);

    float tmp;

    for (int i = 0; i < GyyData.length; i++) {
      tmp = -(GxxData[i] + GyyData[i]);

      if (tmp > 0) {
        tmp *= amplificationFactor;
      }

      GxxData[i] = tmp;
    }
  }
Пример #6
0
  private int[] quad_eq(double a, double b, double c) {
    int[] roots = new int[2];
    double body = Math.sqrt(b * b - 4.0 * a * c);

    roots[0] = (int) Math.round((-b + body) / (2.0 * a));
    roots[1] = (int) Math.round((-b - body) / (2.0 * a));

    return roots;
  }
Пример #7
0
 public void drawNotOK(Graphics g, int widthX, int heightX) {
   int pixelsPerNm = DrawPanel.PIXELS_PER_NM;
   int xint = (int) Math.round(pixelsPerNm * z);
   int yint = (int) Math.round(pixelsPerNm * y);
   int rint = (int) Math.round(pixelsPerNm * type.getRadius());
   g.setColor(Color.white);
   g.fillRect(xint - rint, yint + rint - heightX, widthX, heightX);
   g.setColor(Color.black);
   g.drawRect(xint - rint, yint + rint - heightX, widthX, heightX);
   g.drawString("X", xint - rint, yint + rint);
 }
Пример #8
0
  /**
   * Draw picture (gif, jpg, or png) centered on (x, y).
   *
   * @param x the center x-coordinate of the image
   * @param y the center y-coordinate of the image
   * @param s the name of the image/picture, e.g., "ball.gif"
   * @throws RuntimeException if the image is corrupt
   */
  public static void picture(double x, double y, String s) {
    Image image = getImage(s);
    double xs = scaleX(x);
    double ys = scaleY(y);
    int ws = image.getWidth(null);
    int hs = image.getHeight(null);
    if (ws < 0 || hs < 0) throw new RuntimeException("image " + s + " is corrupt");

    offscreen.drawImage(
        image, (int) Math.round(xs - ws / 2.0), (int) Math.round(ys - hs / 2.0), null);
    draw();
  }
Пример #9
0
 public void drawSelected(Graphics2D g2) {
   double r = type.getRadius();
   Color c = type.getColor();
   g2.setColor(c);
   int pixelsPerNm = DrawPanel.PIXELS_PER_NM;
   // In the drawPanel we map the z-coordinate to the x-coordinate
   int xint = (int) Math.round(pixelsPerNm * z);
   int yint = (int) Math.round(pixelsPerNm * y);
   int rint = (int) Math.round(pixelsPerNm * r);
   g2.fillOval(xint - rint, yint - rint, 2 * rint, 2 * rint);
   g2.setColor(Color.BLACK);
   g2.drawOval(xint - rint, yint - rint, 2 * rint, 2 * rint);
 }
Пример #10
0
 public static BufferedImage scaleImage(BufferedImage bi, double scale) {
   int w1 = (int) (Math.round(scale * bi.getWidth()));
   int h1 = (int) (Math.round(scale * bi.getHeight()));
   BufferedImage image = new BufferedImage(w1, h1, BufferedImage.TYPE_INT_RGB);
   Graphics2D g2 = image.createGraphics();
   g2.setRenderingHint(
       RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
   g2.setPaint(Color.white);
   g2.fillRect(0, 0, w1, h1);
   g2.drawImage(bi, 0, 0, w1, h1, null); // this);
   g2.dispose();
   return image;
 }
Пример #11
0
  /**
   * Конвертация строки типа: 5 Minutes
   *
   * @param str
   * @return
   */
  private static int parseDuration(String str) throws ParseException {
    int idx = str.indexOf(' ');
    float num = DF.parse(str.substring(0, idx)).floatValue();
    switch (str.substring(idx + 1)) {
      case "Seconds":
        return Math.round(num);

      case "Minutes":
        return Math.round(num * 60);

      default:
        throw new ParseException("Неизвестный формат единиц: " + str, idx + 1);
    }
  }
  /** Creates Gaussian derivative kernels. */
  private void makeKernels2D() {
    int xkDim, ykDim;
    int[] derivOrder = new int[2];

    kExtents = new int[2];
    derivOrder[0] = 2;
    derivOrder[1] = 0;

    xkDim = Math.round(8 * sigmas[0]);

    if ((xkDim % 2) == 0) {
      xkDim++;
    }

    if (xkDim < 3) {
      xkDim = 3;
    }

    kExtents[0] = xkDim;

    ykDim = Math.round(8 * sigmas[1]);

    if ((ykDim % 2) == 0) {
      ykDim++;
    }

    if (ykDim < 3) {
      ykDim = 3;
    }

    kExtents[1] = ykDim;

    GxxData = new float[xkDim * ykDim];

    GenerateGaussian Gxx = new GenerateGaussian(GxxData, kExtents, sigmas, derivOrder);

    Gxx.calc(false);
    Gxx.finalize();
    Gxx = null;

    derivOrder[0] = 0;
    derivOrder[1] = 2;
    GyyData = new float[xkDim * ykDim];

    GenerateGaussian Gyy = new GenerateGaussian(GyyData, kExtents, sigmas, derivOrder);

    Gyy.calc(false);
    Gyy.finalize();
    Gyy = null;
  }
Пример #13
0
  private void loadHint(TTGlyph a_glyph, EContourPoint a_point, int a_index) {
    double x = a_point.getX();
    double y = a_point.getY();

    XHint[] hints = a_point.getHint();

    for (int i = 0; i < hints.length; i++) {
      EHint hint = (EHint) hints[i];
      double xHint = hint.getX();
      double yHint = hint.getY();

      if (x == xHint && y == yHint) {
        continue;
      } // if

      double xDelta = xHint - x;
      double yDelta = yHint - y;
      int instruction = TTGlyph.DELTAP1;
      double deltaStep = ((double) Engine.getEm()) / hint.getPpem() / 8;
      int xShift = (int) Math.round(xDelta / deltaStep);
      int yShift = (int) Math.round(yDelta / deltaStep);

      if (xShift == 0 && yShift == 0) {
        continue;
      } // if

      a_glyph.addInstruction(TTGlyph.PUSHB000);
      a_glyph.addInstruction((int) hint.getPpem());
      a_glyph.addInstruction(TTGlyph.SDB);

      if (xShift != 0) {
        a_glyph.addInstruction(TTGlyph.SVTCA1);
        a_glyph.addInstruction(TTGlyph.PUSHB010);
        a_glyph.addInstruction(TTGlyph.toDeltaArg(0, xShift));
        a_glyph.addInstruction(a_index);
        a_glyph.addInstruction(1);
        a_glyph.addInstruction(TTGlyph.DELTAP1);
      } // if

      if (yShift != 0) {
        a_glyph.addInstruction(TTGlyph.SVTCA0);
        a_glyph.addInstruction(TTGlyph.PUSHB010);
        a_glyph.addInstruction(TTGlyph.toDeltaArg(0, yShift));
        a_glyph.addInstruction(a_index);
        a_glyph.addInstruction(1);
        a_glyph.addInstruction(TTGlyph.DELTAP1);
      } // if
    } // for i
  }
Пример #14
0
  /**
   * Draw picture (gif, jpg, or png) centered on (x, y), rotated given number of degrees
   *
   * @param x the center x-coordinate of the image
   * @param y the center y-coordinate of the image
   * @param s the name of the image/picture, e.g., "ball.gif"
   * @param degrees is the number of degrees to rotate counterclockwise
   * @throws IllegalArgumentException if the image is corrupt
   */
  public static void picture(double x, double y, String s, double degrees) {
    Image image = getImage(s);
    double xs = scaleX(x);
    double ys = scaleY(y);
    int ws = image.getWidth(null);
    int hs = image.getHeight(null);
    if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + s + " is corrupt");

    offscreen.rotate(Math.toRadians(-degrees), xs, ys);
    offscreen.drawImage(
        image, (int) Math.round(xs - ws / 2.0), (int) Math.round(ys - hs / 2.0), null);
    offscreen.rotate(Math.toRadians(+degrees), xs, ys);

    draw();
  }
Пример #15
0
          public Value eval(RCvalue args) throws EvalException {
            if ((args.size() < 0) || (3 < args.size()))
              throw new EvalException("usage: reduce(polygon, [errtol,[edgeReducible] ] ])");
            if (!(args.value(0) instanceof PolygonValue))
              throw new EvalException("reduce: first operand must be a polygon");

            double errtol = defaultErrtol;
            if (args.size() >= 2) { // get error tolerance
              if (!(args.value(1) instanceof DoubleValue))
                throw new EvalException("reduce: second operand must be an integer");
              errtol = ((DoubleValue) (args.value(1))).value();
            }
            boolean edgeReducible = true;
            if (args.size() >= 3) {
              double temp = ((DoubleValue) (args.value(2))).value();
              edgeReducible = (temp > 0); // temp = 1, edge reducible, otherwise, not
            }

            Polygon.EndCondition ec = new Polygon.CostEndCondition(errtol);
            if (errtol >= 3) {
              int maxV = (int) Math.round(errtol);
              ec = new Polygon.DegreeEndCondition(maxV);
            }
            PolygonValue p = (PolygonValue) (args.value(0));
            Polygon poly = p.polygon();
            if (poly instanceof ConvexPolygon) { // NOTE: connection for reduce
              if (edgeReducible) return new PolygonValue(((ConvexPolygon) poly).reduce(ec));
              else return p; // can't reduce because convex polygon can only reduce edge
            } else {
              return new PolygonValue(poly.reduce(ec, true, edgeReducible));
            }
          }
Пример #16
0
  //	public void savePDF(){
  //		 Rectangle suggestedPageSize = getITextPageSize(page1.getPageSize());
  //		  Rectangle pageSize = rotatePageIfNecessary(suggestedPageSize);
  //		  //rotate if we need landscape
  //		  Document document = new Document(pageSize);
  //
  //		  PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
  //		  document.open();
  //		  Graphics2D graphics = cb.createGraphics(pageSize.getWidth(), pageSize.getHeight());
  //
  //		  // call your GTRenderer here
  //		  GTRenderer draw = new StreamingRenderer();
  //		  draw.setMapContent(mapContent);
  //
  //		  draw.paint(graphics, outputArea, mapContent.getLayerBounds() );
  //
  //		  // cleanup
  //		  graphics.dispose();
  //
  //		  //cleanup
  //		  document.close();
  //		  writer.close();
  //	}
  public void saveImage(final MapContent map, final String file, final int imageWidth) {

    GTRenderer renderer = new StreamingRenderer();
    renderer.setMapContent(map);

    Rectangle imageBounds = null;
    ReferencedEnvelope mapBounds = null;
    try {
      mapBounds = map.getMaxBounds();
      double heightToWidth = mapBounds.getSpan(1) / mapBounds.getSpan(0);
      imageBounds = new Rectangle(0, 0, imageWidth, (int) Math.round(imageWidth * heightToWidth));

    } catch (Exception e) {
      // failed to access mapContent layers
      throw new RuntimeException(e);
    }

    BufferedImage image =
        new BufferedImage(imageBounds.width, imageBounds.height, BufferedImage.TYPE_INT_RGB);

    Graphics2D gr = image.createGraphics();
    gr.setPaint(Color.WHITE);
    gr.fill(imageBounds);

    try {
      renderer.paint(gr, imageBounds, mapBounds);
      File fileToSave = new File(file);
      ImageIO.write(image, "jpeg", fileToSave);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #17
0
  public static void main(String[] s) throws IOException {
    char moves[] = new char[9], player = (int) Math.round(Math.random() * 1) == 1 ? 'X' : 'O';

    int move = 0;

    boolean winner = false, draw = false, init = false;

    for (int i = 0; i < moves.length; i++) moves[i] = '*';

    drawScreen(moves, player, move, init);

    init = true;

    while (!winner && !draw) {
      player = (player == 'X') ? 'O' : 'X';
      move = checkMove(moves, getInput());
      drawScreen(moves, player, move, init);
      winner = checkForWinner(moves, player);
      draw = checkForDraw(moves);
    }

    if (winner) {
      newLine(3);
      System.out.println("Winner!");
      System.out.println("Player " + player + " wins!");
    } else {
      newLine(3);
      System.out.println("Draw!");
      System.out.println("Nobody wins.");
    }
  }
Пример #18
0
  /** Signals that a PooledThread has started. Creates the Thread's line and buffer. */
  protected void threadStarted() {
    // wait for the SoundManager constructor to finish
    synchronized (this) {
      try {
        wait();
      } catch (InterruptedException ex) {
      }
    }

    // use a short, 100ms (1/10th sec) buffer for filters that
    // change in real-time
    int bufferSize =
        playbackFormat.getFrameSize() * Math.round(playbackFormat.getSampleRate() / 10);

    // create, open, and start the line
    SourceDataLine line;
    DataLine.Info lineInfo = new DataLine.Info(SourceDataLine.class, playbackFormat);
    try {
      line = (SourceDataLine) AudioSystem.getLine(lineInfo);
      line.open(playbackFormat, bufferSize);
    } catch (LineUnavailableException ex) {
      // the line is unavailable - signal to end this thread
      Thread.currentThread().interrupt();
      return;
    }

    line.start();

    // create the buffer
    byte[] buffer = new byte[bufferSize];

    // set this thread's locals
    localLine.set(line);
    localBuffer.set(buffer);
  }
Пример #19
0
 protected double roundToThreeDigits(double val) {
   val = Math.round(1000 * val) / 1000.0;
   if (val == 0) {
     val = 0.001;
   }
   return val;
 }
Пример #20
0
 public void extractionProgress(String identifier, float percentageDone) {
   int trackableProgress = Math.round(percentageDone * range);
   if (trackableProgress > lastProgressUpdate) {
     parent.extractionProgress(identifier, trackableProgress);
     lastProgressUpdate = trackableProgress;
   }
 }
Пример #21
0
 public static Element ranking_Genes(Document doc, IndividualStat is, int number) {
   Element genes = doc.createElement(Consts.XML_TAG_GENES);
   doc.getElementsByTagName(Consts.DATA_ROOT).item(0).appendChild(genes);
   float[] scores = null;
   Integer[] index;
   if (number > Symbols.length) number = Symbols.length;
   if (is != null) {
     index = is.get_Order();
     scores = is.get_GeneScores(Symbols.length - 1, 0);
     for (int i = Symbols.length - 1; i >= Symbols.length - number; i--) {
       Element gene = doc.createElement(Consts.XML_TAG_GENE);
       gene.setAttribute(Consts.XML_TAG_ID, Symbols[index[i]]);
       XmlWriter.append_text_element(
           doc, gene, Consts.XML_TAG_CHROMOSOME, ChrList[Chrs[index[i]]]);
       XmlWriter.append_text_element(
           doc, gene, Consts.XML_TAG_FROM, Integer.toString(Starts[index[i]] + 1));
       XmlWriter.append_text_element(
           doc, gene, Consts.XML_TAG_TO, Integer.toString(Ends[index[i]]));
       XmlWriter.append_text_element(
           doc,
           gene,
           Consts.XML_TAG_SCORE,
           Float.toString(Math.round(scores[index[i]] * 10) / 10));
       genes.appendChild(gene);
     }
   }
   return genes;
 }
Пример #22
0
 public static Element overlap_Genes(
     Document doc, String chr, int start, int end, IndividualStat is) {
   Element genes = doc.createElement(Consts.XML_TAG_GENES);
   doc.getElementsByTagName(Consts.DATA_ROOT).item(0).appendChild(genes);
   if (ChrMap.containsKey(chr)) {
     int[] range = binarySearchOverlap(ChrMap.get(chr), start, end);
     if (range != null) {
       float[] scores = null;
       if (is != null) scores = is.get_GeneScores(range[1], range[0]);
       for (int i = range[0]; i <= range[1]; i++) {
         Element gene = doc.createElement(Consts.XML_TAG_GENE);
         gene.setAttribute(Consts.XML_TAG_ID, Symbols[i]);
         XmlWriter.append_text_element(
             doc, gene, Consts.XML_TAG_FROM, Integer.toString(Starts[i] + 1));
         XmlWriter.append_text_element(doc, gene, Consts.XML_TAG_TO, Integer.toString(Ends[i]));
         if (is != null)
           XmlWriter.append_text_element(
               doc,
               gene,
               Consts.XML_TAG_SCORE,
               Float.toString(Math.round(scores[i - range[0]] * 10) / 10));
         genes.appendChild(gene);
       }
     }
   }
   return genes;
 }
Пример #23
0
 public static void main(String args[]) throws IOException {
   Scanner sf = new Scanner(new File("D:\\IB CS\\temp_Aman\\StudentsScores.in.txt"));
   int maxIndx = -1;
   String text[] = new String[1000];
   while (sf.hasNext()) // this allows the program to assign each line in the text file a variable
   {
     maxIndx++;
     text[maxIndx] = sf.nextLine();
   }
   for (int j = 0; j <= 4; j++) {
     Scanner sc = new Scanner(text[j]);
     String name =
         sc.next(); // this helps identify the Strings, which are the names of students, in each
     // line
     double sum =
         0.0; // it starts the sum and count variables with zero because they change as they move
     // along with the while loop
     int count = 0;
     while (sc.hasNext()) {
       sum = sum + sc.nextDouble(); // this while loop helps find out the number of integers in the
       // line and adds all of these numbers as well
       count = count + 1;
     }
     double avg = sum / count;
     int y = (int) Math.round(avg); // this converts the double variable avg to an integer
     System.out.println(name + "," + " average = " + y);
   }
 }
 double oblicz_wage(int x1, int y1, int x2, int y2) {
   double x = (double) Math.pow(Math.abs((x1 - x2)), 2);
   double y = (double) Math.pow(Math.abs((y1 - y2)), 2);
   double wynik = Math.sqrt(x + y) * 1000;
   wynik = Math.round(wynik);
   return (wynik / 1000);
 }
Пример #25
0
  private void func_22181_a(
      File file, ArrayList arraylist, int i, int j, IProgressUpdate iprogressupdate) {
    Collections.sort(arraylist);
    byte abyte0[] = new byte[4096];
    int i1;
    for (Iterator iterator = arraylist.iterator();
        iterator.hasNext();
        iprogressupdate.setLoadingProgress(i1)) {
      ChunkFile chunkfile = (ChunkFile) iterator.next();
      int k = chunkfile.func_22323_b();
      int l = chunkfile.func_22321_c();
      RegionFile regionfile = RegionFileCache.func_22193_a(file, k, l);
      if (!regionfile.func_22202_c(k & 0x1f, l & 0x1f)) {
        try {
          DataInputStream datainputstream =
              new DataInputStream(
                  new GZIPInputStream(new FileInputStream(chunkfile.func_22324_a())));
          DataOutputStream dataoutputstream =
              regionfile.getChunkDataOutputStream(k & 0x1f, l & 0x1f);
          for (int j1 = 0; (j1 = datainputstream.read(abyte0)) != -1; ) {
            dataoutputstream.write(abyte0, 0, j1);
          }

          dataoutputstream.close();
          datainputstream.close();
        } catch (IOException ioexception) {
          ioexception.printStackTrace();
        }
      }
      i++;
      i1 = (int) Math.round((100D * (double) i) / (double) j);
    }

    RegionFileCache.func_22192_a();
  }
Пример #26
0
  public static void main(String[] args)
      throws
          IOException // This class will not handle IO error but throws them to the calling program
      {

    // declare and construct variables
    String sHeight, sWeight;
    int iInches = 0, iPounds = 0;
    double dKilograms = 0.0, dMeters = 0.0, dIndex = 0.0;
    BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));

    // print prompts and get input
    System.out.println("\tTHE SUN FITNESS CENTER BODY MASS INDEX CALCULATOR");
    System.out.println();
    System.out.print("\tEnter your height to the nearest inch: ");
    sHeight = dataIn.readLine();
    iInches = Integer.parseInt(sHeight);
    System.out.print("\tEnter your weight to the nearest pound: ");
    sWeight = dataIn.readLine();
    iPounds = Integer.parseInt(sWeight);

    // Calculations
    dMeters = iInches / 39.36;
    dKilograms = iPounds / 2.2;
    dIndex = dKilograms / Math.pow(dMeters, 2);

    // Output
    System.out.println();
    System.out.println("\tYOUR BODY MASS INDEX IS: " + Math.round(dIndex) + " ");
    System.out.println();
  } // end main method
Пример #27
0
 /** Computes and returns the distance between two entities */
 public int getDistance(WorldEntity e) {
   Point wp = e.getPosition();
   Point mep = getPosition();
   int dx = wp.x - mep.x;
   int dy = wp.y - mep.y;
   return ((int) Math.round(Math.sqrt(dx * dx + dy * dy)));
 }
Пример #28
0
  private void indexFiles(ArrayList<String> images, DocumentBuilder builder, String indexPath)
      throws IOException {
    // eventually check if the directory is there or not ...
    IndexWriter iw = LuceneUtils.createIndexWriter(testIndex, false);
    int count = 0;
    long time = System.currentTimeMillis();
    for (String identifier : images) {
      // TODO: cut toes from the image ... -> doesn't work out very well. Stable at first,
      // decreasing then.
      // TODO: Joint Histogram ...
      // TODO: LSA / PCA on the vectors ...-> this looks like a job for me :-D
      // TODO: local features ...
      Document doc = null;
      if (cutImages) {
        BufferedImage bimg =
            ImageUtils.cropImage(ImageIO.read(new FileInputStream(identifier)), 0, 0, 200, 69);
        doc = builder.createDocument(bimg, identifier);
      } else doc = builder.createDocument(new FileInputStream(identifier), identifier);
      iw.addDocument(doc);
      count++;
      if (count % 100 == 0) {
        int percent = (int) Math.floor(((double) count * 100.0) / (double) images.size());
        double timeTemp = (double) (System.currentTimeMillis() - time) / 1000d;
        int secsLeft =
            (int) Math.round(((timeTemp / (double) count) * (double) images.size()) - timeTemp);
        System.out.println(percent + "% finished (" + count + " files), " + secsLeft + " s left");
      }
    }
    long timeTaken = (System.currentTimeMillis() - time);
    float sec = ((float) timeTaken) / 1000f;

    System.out.println(sec + " seconds taken, " + (timeTaken / count) + " ms per image.");
    iw.commit();
    iw.close();
  }
Пример #29
0
  public SVGTileProvider(File file, float dpi) throws IOException {
    mScale = Math.round(dpi + .3f); // Make it look nice on N7 (1.3 dpi)
    mDimension = BASE_TILE_SIZE * mScale;

    mPool = new TileGeneratorPool(POOL_MAX_SIZE);

    SVG svg = new SVGBuilder().readFromInputStream(new FileInputStream(file)).build();
    mSvgPicture = svg.getPicture();
    RectF limits = svg.getLimits();

    // These values map the SVG file to world coordinates.
    // See: http://stackoverflow.com/questions/21167584/google-io-2013-app-mystery-values
    mBaseMatrix = new Matrix();
    mBaseMatrix.setPolyToPoly(
        new float[] {
          0,
          0, // North-West
          limits.width(),
          0, // North-East
          limits.width(),
          limits.height() // South-East
        },
        0,
        BuildConfig.MAP_FLOORPLAN_MAPPING,
        0,
        3);
  }
  private void parseMeasure(String value, double measures[]) {
    for (int i = 0; i < 360; i++) {
      measures[i] = 100.0;
    }

    if (value.length() >= 5) {
      value = value.substring(5); // removes the "SCAN " keyword

      StringTokenizer tokenizer = new StringTokenizer(value, " ");

      double distance;
      int direction;
      while (tokenizer.hasMoreTokens()) {
        distance = Double.parseDouble(tokenizer.nextToken().substring(2));
        direction =
            (int)
                Math.round(Math.toDegrees(Double.parseDouble(tokenizer.nextToken().substring(2))));
        if (direction == 360) {
          direction = 0;
        }
        measures[direction] = distance;
        // Printing out all the degrees and what it encountered.
        System.out.println("direction = " + direction + " distance = " + distance);
      }
    }
  }