Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

  • Clustering pixels in an image by colour over time

    Not quite what I was going for but should get you along your way. Even this reduced version runs very slowly, so to do this per pixel on large images it would need to be done in a shader.

    String http = "http://";
    PImage img;
    final int w = 400, h = 300;
    final int max = (w-1)*(h-1);
    int dotSize = 3;
    int skip = 3;
    float time = 0;
    
    ArrayList<Organism> critters = new ArrayList<Organism>();
    
    class Organism {
      color c;
      PVector loc, finish;
      Organism(color nc, int x, int y) {
        c = nc;
        loc = new PVector(x, y);
      }
    
      float colorDifference(Organism o) {
        float d = 1+abs(red(c) - red(o.c)) +
          abs(green(c) - green(o.c)) +
          abs(blue(c) - blue(o.c));
        return pow(1.0/d,0.8);
      }
    
      void planFinish(ArrayList<Organism> others) {
        finish = loc.copy();
        for (Organism o : others) {
          finish.sub ( finish.copy().sub(o.loc).normalize().mult(colorDifference(o)));
        }
      }
    
      void move() {
        loc.lerp(finish, time);
      }
    
      void draw() {
        fill(c);
        ellipse(loc.x, loc.y, dotSize, dotSize);
      }
    }
    
    void settings() {
      size(w, h);
    }
    
    void setup() {
      img = loadImage(http + "image.shutterstock.com/z/stock-photo-red-glossy-shiny-bird-fiery-throated-hummingbird-panterpe-insignis-colorful-bird-sitting-on-660194176.jpg");
      img.resize(w, h);
      img.loadPixels();
      print("loading");
      for (int x = 0; x < w-1; x+=skip) {
        print(".");
        for (int y = 0; y < h-1; y+=skip) {
          critters.add(new Organism(img.pixels[x+y*w], x, y));
        }
      }
      ellipseMode(CENTER);
      noStroke();
      for (Organism critter : critters) {
        critter.planFinish(critters);
      }
    }
    
    void draw() {
      time = frameCount/10000.0;
      clear();
      for (Organism critter : critters) {
        critter.move();
        critter.draw();
      }
      //saveFrame("frames/####.png");
    }
    

    Edit: Made some fixes that got it working more like how I thought it should, however aesthetically I kind of prefer the first version.

    String http = "http://";
    PImage img;
    final int w = 400, h = 300;
    final int max = (w-1)*(h-1);
    int dotSize = 3;
    int skip = 5;
    float time = 0;
    
    ArrayList<Organism> critters = new ArrayList<Organism>();
    
    class Organism {
      color c;
      PVector loc, finish, origin;
      Organism(color nc, int x, int y) {
        c = nc;
        loc = new PVector(x, y);
        origin = loc.copy();
      }
    
      float colorDifference(Organism o) {
        float d = 1+abs(red(c) - red(o.c)) +
          abs(green(c) - green(o.c)) +
          abs(blue(c) - blue(o.c));
        return pow(1.0/d,0.66);
      }
    
      void planFinish(ArrayList<Organism> others) {
        finish = loc.copy();
        for (Organism o : others) {
          finish.sub ( finish.copy().sub(o.loc).normalize().mult(colorDifference(o)));
        }
      }
    
      void move() {
        loc.lerp(finish, time);
      }
    
      void draw() {
        fill(c,170);
        ellipse(loc.x, loc.y, dotSize, dotSize);
      }
    }
    
    void settings() {
      size(w, h);
    }
    
    void shuffleCritters(){
      int s = critters.size();
      ArrayList<Organism> tempc = critters;
      critters = new ArrayList<Organism>();
      for (int i = 0; i < s;i++){
        Organism q = tempc.get(floor(random(tempc.size())));
        critters.add(q);
        tempc.remove(q);
      }
    }
    
    void setup() {
      println("getting img");
      img = loadImage(http + "image.shutterstock.com/z/stock-photo-red-glossy-shiny-bird-fiery-throated-hummingbird-panterpe-insignis-colorful-bird-sitting-on-660194176.jpg");
      img.resize(w, h);
      img.loadPixels();
      println("initalize points");
      for (int x = 0; x < w-1; x+=skip) {
        for (int y = 0; y < h-1; y+=skip) {
          critters.add(new Organism(img.pixels[x+y*w], x, y));
        }
      }
      ellipseMode(CENTER);
      noStroke();
     println("shuffle points");
      shuffleCritters();
       println("calc finish");
       int i = 0;
      for (Organism critter : critters) {
        critter.planFinish(critters);
        i++;
        if (i%100==0)println((int)(100*((float)i/critters.size())) + "%");
      }
    }
    
    void keyPressed(){
      time = 0;
       for (Organism critter : critters) {
        critter.loc = critter.origin.copy();
      }
    }
    
    void draw() {
      time += 0.001;
      clear();
      for (Organism critter : critters) {
        critter.move();
        critter.draw();
      }
      //saveFrame("frames/####.png");
    }
    

    last one

    import java.util.*;
    import java.awt.*;
    
    String http = "http://";
    PImage img;
    final int w = 400, h = 300;
    final int max = (w-1)*(h-1);
    float dotSize = 1.5;
    int skip = 3;
    float time = 0;
    
    ArrayList<Organism> critters = new ArrayList<Organism>();
    
    class Organism implements Comparable<Organism>{
      color c;
      PVector loc, finish, origin;
      Organism(color nc, int x, int y) {
        c = nc;
        loc = new PVector(x, y);
        origin = loc.copy();
      }
    
      float colorDifference(Organism o) {
        float d = 1+abs(red(c) - red(o.c)) +
          abs(green(c) - green(o.c)) +
          abs(blue(c) - blue(o.c));
        return pow(1.0/d,0.8);
      }
    
      void planFinish(ArrayList<Organism> others) {
        finish = loc.copy();
        for (Organism o : others) {
          finish.sub ( finish.copy().sub(o.loc).normalize().mult(colorDifference(o)));
        }
      }
    
      void move() {
        loc.lerp(finish, time);
      }
    
      void draw() {
        fill(c);
        ellipse(loc.x, loc.y, dotSize, dotSize);
      }
    
        public int compareTo(Organism o) {
        int r = (int)red(c);
        int g = (int)green(c);
        int b = (int)blue(c);
        float[] hsv = new float[3];
        Color.RGBtoHSB(r,g,b,hsv);
        float h1 = hsv[0];
    
         r = (int)red(o.c);
         g = (int)green(o.c);
         b = (int)blue(o.c);
         hsv = new float[3];
        Color.RGBtoHSB(r,g,b,hsv);
        float h2 = hsv[0];
    
          if (h2<h1) return 1;
          if (h2>h1) return -1;
          return 0;
        }
    
    }
    
     void shuffleCritters(){
      int s = critters.size();
      ArrayList<Organism> tempc = critters;
      critters = new ArrayList<Organism>();
      for (int i = 0; i < s;i++){
        Organism q = tempc.get(floor(random(tempc.size())));
        critters.add(q);
        tempc.remove(q);
      }
    }
    
    void settings() {
      size(w, h);
    }
    
    void setup() {
      img = loadImage(http + "image.shutterstock.com/z/stock-photo-red-glossy-shiny-bird-fiery-throated-hummingbird-panterpe-insignis-colorful-bird-sitting-on-660194176.jpg");
      img.resize(w, h);
      img.loadPixels();
      print("loading");
      for (int x = 0; x < w-1; x+=skip) {
        for (int y = 0; y < h-1; y+=skip) {
          critters.add(new Organism(img.pixels[x+y*w], x, y));
        }
      }
      ellipseMode(CENTER);
      noStroke();
        shuffleCritters();
        Collections.sort(critters);
    
      int i = 0;
      for (Organism critter : critters) {
        critter.planFinish(critters);
        i++;
        if (i%100==0)println((int)(100*((float)i/critters.size())) + "%");
      }
    }
    
    void keyPressed(){
      time = 0;
       for (Organism critter : critters) {
        critter.loc = critter.origin.copy();
      }
    }
    
    void draw() {
      time += 0.001;
      clear();
      for (Organism critter : critters) {
        critter.move();
        critter.draw();
      }
     // saveFrame("frames/####.png");
    }
    

  • Sorting a hashmap by value

    The best way would be to create a simple inner class which has just two attributes, the word and the frequency the word appears. The class should implement comparable so we can easily order the words by popularity.

    Simply iterate over the map and add each map entry (key-value pair) to a list. Finally sort the list.

    This is what the sketch below does

    import java.util.*;
    
    Map<String, Integer> map;
    
    void setup() {
      map = new HashMap<String, Integer>();
      createDummyData(map);
      List<WordCountFreqItem> list = getWordsInPopularityOrder(map);
      // Display word counts
      for (WordCountFreqItem wcfi : list) {
        println(wcfi);
      }
    }
    
    /**
      For a given map create a list of word frequencies in popularity order
    */
    List<WordCountFreqItem> getWordsInPopularityOrder(Map<String, Integer> map) {
      List<WordCountFreqItem> list = new ArrayList<WordCountFreqItem>();
      for (Map.Entry<String, Integer> entry : map.entrySet()) {
        list.add(new WordCountFreqItem(entry.getKey(), entry.getValue()));
      }
      Collections.sort(list);
      return list;
    }
    
    /**
      Utility class to hold the frequency a word appears in some text.
    */
    class WordCountFreqItem implements Comparable<WordCountFreqItem> {
      public final String word;
      public final Integer count;
    
      public WordCountFreqItem(String word, int count) {
        this.word = word;
        this.count = count;
      }
    
      // This will order the words so the most popular come first. Words that
      // occur with the same frequency are placed in alphabetical order
      public int compareTo(WordCountFreqItem wco) {
        int result = wco.count.compareTo(this.count);
        return result != 0 ? result : this.word.compareToIgnoreCase(wco.word);
      }
    
      public String toString() {
        return count + "\t" + word;
      }
    }
    
    void createDummyData(Map<String, Integer> map) {
      map.put("Peter", 12);
      map.put("quark", 9);
      map.put("the", 22);
      map.put("and", 10);
      map.put("popular", 3);
      map.put("wonderful", 2);
      map.put("ocean", 1);
      map.put("place", 5);
      map.put("whales", 7);
      map.put("a", 24);
      map.put("blue", 8);
      map.put("majesty", 7);
    }
    
  • Sorting a hashmap by value

    My attempt. To use the following code, you need to create a file inside the sketch folder called MapUtilities.java and add the following code:

    //REFERENCE: https://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java
    //REFERENCE: https://stackoverflow.com/questions/16370305/error-in-eclipse-the-method-from-the-type-refers-to-the-missing-type-en
    //REFERENCE: https://memorynotfound.com/sorted-map-example/
    
    import java.util.*;
    import java.util.Map.Entry;
    
    public class MapUtilities {
    
      public static <K, V extends Comparable<V>> List<Entry<K, V>> sortByValue(Map<K, V> map) {
        List<Entry<K, V>> entries = new ArrayList<Entry<K, V>>(map.entrySet());
        Collections.sort(entries, new ByValue<K, V>());
        Collections.reverse(entries);
        return entries;
      }
    

    To test it, in the sketch tab add the code below.

    Kf

    import java.util.Map;
    import java.util.*;
    
    
    final int N=10;
    HashMap<String, Integer> hm = new HashMap<String, Integer>();
    
    void setup() {
    
      for (int i=0; i<N; i++) {   
        hm.put(""+i, (int)random(N));
      }
    
    
      for (Map.Entry<String, Integer> entry : hm.entrySet()) {
        println(entry.getKey()+" ==== "+entry.getValue());
      }
    
      List<Map.Entry<String, Integer> > sorted = MapUtilities.sortByValue(hm);
    
    
      Iterator it = sorted.iterator();
    
      println("\n\n\nSorting results");
    
      while (it.hasNext()) {
        Map.Entry<String, Integer> r = (Map.Entry<String, Integer>)it.next();
        println( r.getKey()+" " + r.getValue()        );
      }
    }
    
    
      private static class ByValue<K, V extends Comparable<V>> implements Comparator<Entry<K, V>> {
        public int compare(Entry<K, V> o1, Entry<K, V> o2) {
          return o1.getValue().compareTo(o2.getValue());
        }
      }
    
    }
    
  • TF-IDF algorithm

    Inspired by Daniel Shiffman "Coding Challenge # 40: 3" https://youtube.com/watch?v=RPMYV-eb6lII made this code to calculate the TF-IDF algorithm. The TF is normalized to avoid biases towards long texts. The words are ordered by their IDF. I'm thinking about how to present the results in a nice way. Ideas are welcome. You can find the complete file with the texts in GitHub: https://github.com/Rayle26/TF-IDF

    import java.util.*;
    import java.io.*; 
    
    Words[] wordData;
    
    File[] files;
    
    Links[] enlace;
    
    String sourceFile = "texts/"; //directory of texts
    
    String[] erase;
    String[] nums = {"1","2","3","4","5","6","7","8","9","0"}; // to remove digits from the texts
    String[] theWord;
    String[] allTheWords;
    String[][] textWords;
    int[] times;
    
    String[] fileName;
    int numFiles;
    int textoSelec = 0;
    
    String[][] textWordsPerTxt;
    int[][] timesPerTxt;
    
    int[] resultTable;
    
    int[] resultTableTextVal;
    
    
    PFont font;
    int sizeOfText = 12; 
    
    void setup() {
    
      size(500, 700);
      font = createFont("SourceCodePro-Regular.ttf", sizeOfText);
    
      erase = loadStrings("stopwords-en.txt");
      String path = dataPath(sourceFile);
      files = listFiles(path); 
      numFiles = files.length;
      String[][] texto = new String[numFiles][0];
      allTheWords = new String[numFiles];
      textWords = new String[numFiles][0];
      IntDict totalDict = new IntDict();
      IntDict[] dictionary = new IntDict[numFiles];
      textWordsPerTxt = new String[numFiles][0];
      timesPerTxt = new int[numFiles][0];
    
    
     //******loads texts from the directory*****//
    
      for (int i = 0; i <numFiles; i ++) {
        texto[i]= loadStrings(sourceFile + files[i].getName());
        allTheWords[i] = join(texto[i], " ").toLowerCase();
      }
    
      //******removes digits*****//
    
      for (int i = 0; i <nums.length; i ++) {
        for(int j = 0; j <allTheWords.length; j ++) {
          allTheWords[j] = allTheWords[j].replaceAll(nums[i], "");
        }
      }
    
    
      for(int i = 0; i < numFiles; i ++) {
        textWords[i] = splitTokens(allTheWords[i], " -,.:;¿?¡!/_\"");
      }
    
      //******counts words******//
    
      for (int i = 0; i <numFiles; i ++) {
        dictionary[i] = new IntDict();
        for(int j = 0; j <textWords[i].length; j ++) {
          dictionary[i].increment(textWords[i][j]);
        }
      }
    
      //******counts words in all the texts******//
    
      for (int i = 0; i <numFiles; i ++) {
        for(int j = 0; j <textWords[i].length; j ++) {
          totalDict.increment(textWords[i][j]); //da el total de una palabra en todos los textos
        }
      }
    
      //******removes junk words******//
    
        for(int i = 0; i <erase.length; i ++) {
          if(totalDict.hasKey(erase[i]) == true)
          totalDict.remove(erase[i]);
            for(int j = 0; j < numFiles; j ++) {
              if(dictionary[j].hasKey(erase[i]) == true)
              dictionary[j].remove(erase[i]);
              dictionary[j].sortValuesReverse();
            }
      }
    
        theWord = totalDict.keyArray();
        times = totalDict.valueArray();
    
        for(int i = 0; i <numFiles; i ++) {
          textWordsPerTxt[i] = dictionary[i].keyArray();
          timesPerTxt[i] = dictionary[i].valueArray();
        }
    
       //******document frequency******//     
    
      resultTable = new int [theWord.length];
    
      for(int j = 0; j <allTheWords.length; j ++) {
        for(int i = 0; i <theWord.length; i ++) {
          if(allTheWords[j].contains(theWord[i]) == true)
          resultTable[i] = resultTable[i] + 1;
        }
      }
    
      //******selects only .txt files******//
    
    File Directorio = new File(path);
    FilenameFilter ff = new FilenameFilter() {
          public boolean accept(File Directorio, String name) {
             return name.endsWith(".txt");
              }
            };
         fileName = Directorio.list(ff);
    
      //******creates the links to texts******//
    
    enlace = new Links[numFiles];
       for (int i = 0; i < fileName.length; i ++) {
         enlace[i] = new Links(60, 68+(sizeOfText*i), textWidth(fileName[i]), sizeOfText, i);
             }
    
          }
    
    
      void draw() {
    
        background(255);
        fill(0);
        textFont(font);
    
     //*****counts the texts where word appears******//   
    
      resultTableTextVal = new int [textWordsPerTxt[textoSelec].length];
      for(int i = 0; i <allTheWords.length; i ++) {
        for (int j = 0; j < textWordsPerTxt[textoSelec].length; j ++) {
            if(allTheWords[i].contains(textWordsPerTxt[textoSelec][0]) == true)
              resultTableTextVal[j] = resultTableTextVal[j] + 1;
          }    
        }
    
      //******the core of the code: creates an object (word) with TF and IDF******//   
    
        int index = 0;
        float idf = 0;
        wordData = new Words[textWordsPerTxt[textoSelec].length];
        for(int i = 0; i< textWordsPerTxt[textoSelec].length; i ++) {
          idf = (float(timesPerTxt[textoSelec][i])/timesPerTxt[textoSelec][0])*log(numFiles/resultTableTextVal[i]); //algoritmo para calcular IDF
          wordData[index++] = new Words(textWordsPerTxt[textoSelec][i],timesPerTxt[textoSelec][i],idf);
        }
    
          //******sorts objects in ascending order******//
          //java.util.Arrays.sort(wordData);
    
    
          //******sorts objects in descending order******//
          Words.isDescent = true;
          java.util.Arrays.sort(wordData);
    
          //******shows the list of texts******//
    
          text("Click to select:", 60, 60);
          for (int i = 0; i < fileName.length; i ++) {
            enlace[i].clickableArea();
            String nombreArchivo = fileName[i].replaceFirst("\\.txt", "");
            pushMatrix();
            translate(60, 80);
            text("- " + nombreArchivo, 0, sizeOfText*i);
            popMatrix();
            }
    
          //******shows the title of text******//
    
            pushMatrix();
            translate(200, 20);
            textAlign(LEFT);
            String titulo = fileName[textoSelec].replaceFirst("\\.txt", "");
            text(titulo, 0, 0); 
            text("Words: " + textWords[textoSelec].length,0, 20);
            popMatrix();
    
          //******shows TF-IDF******//
    
          for(int i = 0; i<wordData.length; i ++ ) {
            pushMatrix();
            translate(200, 60); 
            textAlign(LEFT);
            text(wordData[i].toString(), 0, sizeOfText*i);
            popMatrix();
            }
    
        noLoop();
      }
    
    void mousePressed() {
      for (int i = 0; i <numFiles; i ++) {
        if(enlace[i].isHovering){
        textoSelec = enlace[i].textSelector();
        }
      }
        redraw();
    }
    
    void mouseMoved() {
      for (int i = 0; i <numFiles; i ++) {
        enlace[i].isInside();
        }
        redraw();
    }
    
    class Links {
    
      boolean isHovering;
      float textWidth;
      int textHeight;
      int xpos, ypos;
      int textFile;
    
      Links(int xpos_, int ypos_, float textWidth_, int textHeight_, int textFile_) {
        textWidth = textWidth_;
        textHeight = textHeight_;
        xpos = xpos_;
        ypos = ypos_;
        textFile = textFile_;
        }
    
      int textSelector() {  
        return textFile;
      }
    
      void clickableArea() {
        noFill();
        noStroke();
        rect(xpos, ypos, textWidth, textHeight);
      }
      boolean isInside() {
        return isHovering = mouseX > xpos & mouseX < (xpos+textWidth) & mouseY > ypos & mouseY < (ypos + textHeight);
      }
    }
    
    static class Words implements Comparable<Words> {
    
       static boolean isDescent;
    
       String whichFile;
       String word;
       Integer frequency;
       float inversFreq;
    
      Words(String word_, Integer frequency_, float inversFreq_) {
        word = word_;
        frequency = frequency_;
        inversFreq = inversFreq_;
      }
    
      @ Override int compareTo(Words c) {
        return Float.compare(inversFreq, c.inversFreq) * (isDescent? -1 : 1);
      }
    
      @ Override String toString() {
        return word + " (TF: " + frequency + ", " + "IDF: " + inversFreq + ")";
      }
    
    }
    

    And this is the outcome:

    TF_IDF

  • 3.3.7 on ARM & Raspberry Pi: What's New

    @gohai the key thing was you said current Oracle 64-bit was headless?! I haven't tried Zulu Embedded yet, though plan to in the next few weeks. It's meant to be feature and performance comparable, and with GUI support. I use Zulu with Processing / Praxis LIVE on Windows and MacOS though, and hand it out at workshops if people don't have a JDK. It's a good drop-in replacement. Matching specific versions should be doable - think the version numbers line up these days.

    The warning is going to have to go soon anyway, seen as Oracle will be shipping OpenJDK (as I mentioned) as their free Java option - https://blogs.oracle.com/java-platform-group/faster-and-easier-use-and-redistribution-of-java-se

  • Sketch updating from a live-edited text file

    I am interested in making a sketch that periodically checks an open text file that is being edited live, and updates the screen based on the live changing text contents. For example, as a person types a list of words into a text file, the sketch periodically shows the new words on the screen.

    Comparable examples I've seen have been live preview modes for e.g. markdown or livecoding.

    Question: how would you recommend implementing a listening / updating mechanism?

    For example, consider this starting sketch running on OS X. It is a working sketch that checks the contents of list.txt any time an in-focus key is pressed, and detects new words typed into a file open in TextEdit. This works even without explicitly saving the file -- just type new things and the sketch picks them up when manually refreshed.

    /**
     * FileDaemon
     * 2017-10-23
     */
    String[] lines;
    String filename = "list.txt";
    float x, y;
    
    void setup(){
      noLoop();
    }
    void draw(){
      background(0);
      reload();
      drawText();
    }
    void drawText(){
      for (int i = 0 ; i < lines.length; i++) {
        x = random(width);
        y = random(height);
        text(lines[i],x,y);
        print(lines[i], ". ");
      }
      println("" + lines.length + " drawn");
    }
    void reload(){
      lines = loadStrings(filename);
    }
    void keyReleased(){
      redraw();
    }
    

    How to make this automatic? I could imagine adding a clock to this (just running a check periodically without manual intervention) -- but I'm not sure if this approach would work with other editors, or if it is cross platform, or if there is simply a better way, perhaps built in to Java.

    Thanks for any advice.

  • Alternative to FloatDict

    Oops, I've ended up forgetting you still need to associate a name to each score. How forgetful I am! #-o

    In this case, the class solution proposed at 1st by @jeremydouglass is the simplest.

    However, it's a good idea to make that class implements Comparable too:
    http://Docs.Oracle.com/javase/8/docs/api/java/lang/Comparable.html

    Then having a List container to store each object of the ScoreEntry class.

    And finally, create a getTop10() helper function which calls Collections::sort() over that List container:
    http://Docs.Oracle.com/javase/8/docs/api/java/util/Collections.html#sort-java.util.List-

    And collect the 10 1st entries after that, returning everything as 1 String, ready to be println(). \m/

    /**
     * Sorted 10 Top Score Entries (v1.0)
     * GoToLoop (2017-Oct-15)
     * Forum.Processing.org/two/discussion/24564/alternative-to-floatdict#Item_8
     */
    
    import java.util.List;
    import java.util.Collections;
    
    static final int TOPS = 10, MAX_SCORE = 100;
    final List<ScoreEntry> topScores = new ArrayList<ScoreEntry>();
    
    void setup() {
      for (int i = 0; i < TOPS; ++i) {
        topScores.add(new ScoreEntry("John", (int) random(1 + MAX_SCORE)));
        topScores.add(new ScoreEntry("Lisa", (int) random(1 + MAX_SCORE)));
        topScores.add(new ScoreEntry("Dave", (int) random(1 + MAX_SCORE)));
      }
    
      println(getTop10(topScores));
      exit();
    }
    
    static final String getTop10(final List<ScoreEntry> list) {
      final StringBuilder sb = new StringBuilder();
    
      Collections.sort(list);
    
      for (int i = 0; i < TOPS; 
        sb.append(nf(i+1, 2)).append(". ").append(list.get(i++)).append(ENTER));
    
      return sb.substring(0, sb.length() - 1);
    }
    
    class ScoreEntry implements Comparable<ScoreEntry> {
      final String name; 
      final int score; 
    
      ScoreEntry(final String entry, final int value) {
        name = entry; 
        score = value;
      }
    
      @ Override int compareTo(final ScoreEntry entry) {
        return entry.score - score;
      }
    
      @ Override String toString() {
        return "Player: " + name + "  -  Score: " + score;
      }
    }
    
  • compareTO in processing

    How did you fix the "Word must implement the inherited abstracted method Comparable<..>" error. I'm getting it too, even though I've implemented the compareTo method

    int compareT0(Car compareCar) { float compareFitness = ((Car)compareCar).fitness; if (fitness > compareFitness) { return 1; } else { return 0; } }

    Thanks

  • how to sort 2 arrays using java implement?

    If your class implements Comparable then you have to add the compareTo method which provides natural ordering. For instance the words in a dictionary have a natural ordering and numbers have a natural ordering but a particular type (class) can only have one natural ordering.

    The solution is to create a special class that implements the Comparator interface. This classes will contain a single method to compare two objects in a similar way to compareTo. An object of the class is used by the Arrays.sort method to order the objects in the array.

    The advantage of this approach is that we can have as many comparators with different implementations used to compare objects.

    The code below produced this output and demonstrates the use of comparators.

    Unsorted array
    [0] Height: 1.9367965       Weight: 117.41198
    [1] Height: 1.8318218       Weight: 82.51117
    [2] Height: 2.097329        Weight: 106.100266
    [3] Height: 1.8637967       Weight: 116.23966
    [4] Height: 2.001055        Weight: 96.52715
    Sorted by WEIGHT
    [0] Height: 1.8318218       Weight: 82.51117
    [1] Height: 2.001055        Weight: 96.52715
    [2] Height: 2.097329        Weight: 106.100266
    [3] Height: 1.8637967       Weight: 116.23966
    [4] Height: 1.9367965       Weight: 117.41198
    Sorted by HEIGHT
    [0] Height: 1.8318218       Weight: 82.51117
    [1] Height: 1.8637967       Weight: 116.23966
    [2] Height: 1.9367965       Weight: 117.41198
    [3] Height: 2.001055        Weight: 96.52715
    [4] Height: 2.097329        Weight: 106.100266
    
    import java.util.*;
    
    Person[] people;
    
    // The comparators used for sorting
    Comparator<Person> weightCompare;
    Comparator<Person> heightCompare;
    
    void setup() {
      // Create some random Persons
      people = new Person[5];
      for (int i = 0; i < people.length; i++) {
        people[i] = new Person();
      }
      // Create the comparitor objects
      weightCompare = new WeightComparator();
      heightCompare = new HeightComparator();
    
      println("Unsorted array");
      printArray(people);
      println("Sorted by WEIGHT");
      Arrays.sort(people, weightCompare);
      printArray(people);
      println("Sorted by HEIGHT");
      Arrays.sort(people, heightCompare);
      printArray(people);
    }
    
    // Simple class to test the comparators
    class Person {
      float weight;
      float height;
    
      Person() {
        weight = random(80, 120);
        height = random(1.8, 2.2);
      }
    
      public String toString() {
        return "Height: " + height + "    \tWeight: " + weight;
      }
    }
    
    // Compare Persons based on their weight
    class WeightComparator implements Comparator<Person> {
    
      public int compare(Person ind1, Person ind2) {
        if (ind1.weight < ind2.weight)
          return -1;
        if (ind1.weight > ind2.weight)
          return 1;
        return 0;
      }
    }
    
    // Compare Persons based on their height
    class HeightComparator implements Comparator<Person> {
    
      public int compare(Person ind1, Person ind2) {
        if (ind1.height < ind2.height)
          return -1;
        if (ind1.height > ind2.height)
          return 1;
        return 0;
      }
    }
    
  • Exception Handling

    @jameswest -- you said:

    I'm wanting to wrap some int parsing in a try catch

    Without seeing your code (which you can share if you like) you probably want NumberFormatException. Here is a Java discussion that might be comparable to your Processing case:

    In Processing, catch uses Java built-in exceptions. You can see this from the catch reference documentation

    The catch keyword is used with try to handle exceptions. Sun's Java documentation defines an exception as "an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions." [...] exception: the Java exception that was thrown

    Here is a general tutorial on Java exceptions and a list of the builtin exceptions:

  • How can I loop Sin0sc-generated audio?

    Hmmm, that makes sense! I haven't found anything comparable for Processing yet. Do you have any more ideas? Thank you so much for helping, I'm so easily bamboozled by programming.

  • How do I sort an array of objects by their attribute?

    http://docs.Oracle.com/javase/8/docs/api/java/util/Arrays.html#sort-java.lang.Object:A-

    http://docs.Oracle.com/javase/8/docs/api/java/lang/Comparable.html

    https://forum.Processing.org/two/discussions/tagged?Tag=compareto()

    /**
     * Comparable Dots (v1.0)
     * GoToLoop (2017-Feb-19)
     *
     * https://forum.Processing.org/two/discussion/20852/
     * how-do-i-sort-an-array-of-objects-by-their-attribute#Item_1
     */
    
    static final short DOTS = 5;
    final Dot[] dots = new Dot[DOTS];
    
    void setup() {
      size(300, 200);
      noLoop();
      for (int i = 0; i < DOTS; dots[i++] = new Dot());
      mousePressed();
    }
    
    void draw() {
      background((color) random(#000000));
      frame.setTitle("Frame: " + frameCount);
    }
    
    void keyPressed() {
      mousePressed();
    }
    
    void mousePressed() {
      for (final Dot d : dots) {
        final int x = (int) random(width);
        final int y = (int) random(height);
        d.setXY(x, y);
      }
    
      println();
      println(dots);
    
      java.util.Arrays.sort(dots);
      println(dots);
    
      redraw = true;
    }
    
    class Dot implements Comparable<Dot>, Cloneable {
      short x, y;
    
      Dot() {
      }
    
      Dot(final int x, final int y) {
        setXY(x, y);
      }
    
      Dot setXY(final int px, final int py) {
        x = (short) px;
        y = (short) py;
        return this;
      }
    
      @Override int compareTo(final Dot d) {
        //return x - d.x; // Ascending
        return d.x - x; // Descending
      }
    
      @Override int hashCode() {
        return x | y << 020;
      }
    
      @Override boolean equals(final Object o) {
        return o.hashCode() == hashCode();
      }
    
      @Override String toString() {
        return "[" + x + ", " + y + "]";
      }
    
      @Override Dot clone() {
        try {
          return (Dot) super.clone();
        }
        catch (final CloneNotSupportedException cause) {
          throw new RuntimeException(cause);
        }
      }
    }
    
  • Rearrange coordinate so the shape has the form of the perimeter

    The code is still a bit sloppy, but it works! Thanks for the advice!

    import java.util.Arrays;
    
    int num[][]=new int[2][5];
    int star[][]=new int[2][2];
    PVector pent1[]=new PVector[5];
    PVector pent2[]=new PVector[5];
    Penta[] pentax1= new Penta[5];
    Penta[] pentax2= new Penta[5];
    float xMean1;
    float yMean1;
    float xMean2;
    float yMean2;
    
    void setup(){
      size(241,595);
      background(255);
      noStroke();
      colorMode(HSB,16);
      num[0][0]=3;
      num[0][1]=12;
      num[0][2]=17;
      num[0][3]=20;
      num[0][4]=33;
    
      star[0][0]=3;
      star[0][1]=6;
    
      num[1][0]=37;
      num[1][1]=39;
      num[1][2]=43;
      num[1][3]=47;
      num[1][4]=49;
    
      star[1][0]=11;
      star[1][1]=12;
    
      for(int i=0; i<5; i++){
        pent1[i]= new PVector(X(num[0][i]),Y(num[0][i]));
        pent2[i]= new PVector(X(num[1][i]),Y(num[1][i]));
      }
      xMean1=meanX(pent1);
      yMean1=meanY(pent1);
      xMean2=meanX(pent2);
      yMean2=meanY(pent2);
      for(int i=0; i<pentax1.length; i++){
        pentax1[i]= new Penta(pent1[i],xMean1,yMean1);
        pentax2[i]= new Penta(pent2[i],xMean2,yMean2);
      }
      Arrays.sort(pentax1);
      Arrays.sort(pentax2);
    
      for (int i=0;i<5;i++){
        pent1[i]=pentax1[i].co;
        pent2[i]=pentax2[i].co;
      }
    }
    
    void draw(){
      fill(star[0][0]*1.3,star[0][1]+5,11,8);
      poly(pent1);
      fill(star[1][0]*1.3,star[1][1]+5,11,8);
      poly(pent2);
    }
    
    void poly(PVector p[]){
      beginShape();
      for (int i=0; i<5; i++){
        vertex(p[i].x,p[i].y);
      }
      endShape(CLOSE);
    }
    
    int X(int c){
      int X=((c-1)%5)*(width/4);
      return X;
    }
    
    int Y(int c){
      int Y=(int((c-1)/5))*(height/9);
      return Y;
    }
    
    float meanX(PVector[] co){
      float min=width;
      float max=0;
      for (int i=0; i<co.length; i++){
        if(co[i].x<min){min=co[i].x;}
        if(co[i].x>max){max=co[i].x;}
      }
      float mean=(min+max)/2;
      return mean;
    }
    
    float meanY(PVector[] co){
      float min=width;
      float max=0;
      for (int i=0; i<co.length; i++){
        if(co[i].y<min){min=co[i].y;}
        if(co[i].y>max){max=co[i].y;}
      }
      float mean=(min+max)/2;
      return mean;
    }
    
    class Penta implements Comparable<Penta>{
      PVector co;
      float no;
      int iNo;
      float transX;
      float transY;
    
      Penta(PVector tempCo, float tX, float tY){
        co=tempCo;
        transX=tX;
        transY=tY;
        no=atan2(co.x-transX,co.y-transY);
        iNo=int(no*100);
      }
    
      @ Override int compareTo(Penta p) {
      return iNo - p.iNo;
      }
    }
    
  • Rearrange coordinate so the shape has the form of the perimeter

    I'm trying out the angle approach, but i'm a bit stuk on array-sorting (using comparable class). Today I don't have much time anymore to work on this. I'm giving it another go on Friday.

    I was thinking to set the angle to 0 if atan2() fails. Then it becomes the point from where the shape starts.

    How would you not allow crossing lines?

  • SVG rotation based on pixel value

    It would help testing and feedback if you can provide links to pic.png / module_1.svg, or point to comparable files online.

    Or should the sketch work the same with any images of any size / type?

  • Is there a list of file types that are compatible to import into Processing ?

    Hi Kevin,

    So I have come to two conclusions regarding the bird flocking program that I am working on.

    1) python mode in processing

    In this case I would take the base code and run it first then I would make additions.

    This option would allow for real time visual effects like adding more birds into the simulation with a mouse click etc.

    2) import a CVS file or comparable data file into processing and script around it.

    This would mean that the data from the initial simulation would be static and the code that I would write would purely a visualization of the data. Perhaps a benefit of this is that it would be faster to run considering the data is just being imported and the visualization is a separate code.

    At this point I don't know which one would be a better option but in general I would like to learn how to realize data visualization in processing so this seems like a good opportunity to try it out.

    So my question is: what is the best format for the simulated data? CVS?

    Best, Janet

  • camera() in processing vs camera postion in After Effects

    Hi All,

    Would any of you know how comparable the camera() function in processing matches to the one in After effects position wise?

  • Concordance_txt_loadString_

    Hi all, here we are with the first type of generator.

     //  SPECIAL THANKS AND SUPPORT - Alessandro Vissani - Davide Riboli
     //  DON'T BE SCARED HAVE FUN WITH (SOME) PARAMETERS 
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    import java.util.Collections;
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.ArrayList;
    import java.util.Comparator;
    import java.util.List;
    import java.util.*;
    
    import processing.pdf.*;
    import java.text.*;
    import java.io.Serializable;
    import java.text.CollationKey;
    import java.text.Collator;
    import java.util.Locale;
    import java.text.*;
    import java.util.Scanner;
    import java.util.Locale;
    
    import java.util.*;
    import java.io.*;
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    
    
    
    //  OLD VAR CODE 
    String lines[];
    String[] allwords;    // THIS ARRAY HOLDS ALL THE WORDS
    
    //  VAR FONT
    PFont font;
    
    //  DELIMITER - ADD OR ELIMINATE ALL YOU WANT - FOR NOW YOU CANNOT DELIMIT WORDS
    String delimiters = " ,.?=#@°!&%£^$_§\';:*`()[]-\""; // DO NOT USE "/" AS DELIMITER
    
    IntDict concordance;
    
    boolean savePDF = false;
    PImage img;
    color[] colors;
    
                            // CHOOSE THREE DIFFERENT SORT TYPE
    int SortMode = 3;      //  1 OCCURRENCES SORT ---- 2 INTERNATIONAL ALPHABET SORT ---- 3 ITALIAN LATIN ALPHABET SORT
    
    
    //****************************//
    // LET'S BEGING - START SETUP //
    //****************************//
    
    
    void setup()
    {
      size(440, 737, PDF, "type_name_output.pdf");   //  SIZE PAGE - NAME PDF FILE - CARE IT WILL OVERRIDE THE OLDER ONE - CHANGE NAME BEFORE RUNNING            
    
     ArrayList<MyStruct> list = new ArrayList<MyStruct>();
     list.add(new MyStruct("","",0, 3));
    
      //********************************************************
      // LOAD FILE TXT INTO ARRAY STRING - WRITE HERE THE FILE *
      //********************************************************
      String url2 = "type_name_input.txt";         //  CHANGE FILE HERE - THE FILE MUST BE UTF-8
      String[] rawtext2 = loadStrings(url2);
    
      //*****************************
      // CREATE FILE TEMP ***********
      //*****************************
      Writer writer = null;
      try 
      {
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("filetemp.txt"), "utf-8"));
    
        for (int i = 0; i < rawtext2.length; i++) 
        {
          writer.write(rawtext2[i]);
          writer.write(" / ");
        }
        writer.close();
      }
      catch(IOException e)
      {
      }
    
      String url = "filetemp.txt";
      String[] rawtext = loadStrings(url);
    
      // Join the big array together as one long string.
      // ***********************************************
      String everything = join(rawtext, "" );
    
      // Note the use of splitTokens() since we are using spaces and punctuation marks all as delimiters.  
      // ************************************************************************************************
      allwords = splitTokens(everything, delimiters);
    
      // Make a new empty dictionary.
      // ****************************
      concordance = new IntDict();
    
    
      for (int i = 0; i < allwords.length; i++) 
      {
        String s = allwords[i].toLowerCase();
        concordance.increment(s);
      }
    
    
      //*************************
      //* **** MEGA OBJECT **** *
      //*************************
    
      String word = "";
      int dimlist = 1;
      boolean found = false;
      int verse = 1;  // THIS VARIABLE NEED TO BE SETTLED BASED ON THE ORIGINAL TEXT LINE
    
      //***********************************
      // SEARCHING WORDS, STORING FUNCT   *
      //***********************************
      for (int i = 0; i < allwords.length; i++) 
      {
        word = allwords[i].toLowerCase(); // MAKES ALL WORDS LOWERCASE TO NOT CREATE DUPLICATES BETWEEN SAME WORDS: "Hello" "hello" on the same counter
                                          // ANYWAY YOU CAN CHANGE IT TO TRY NEW INSIGHTS ON SENSITIVE CASES
    
        if(word.equals("/") == true)
        {
          verse ++;
        }
    
        found = false; 
    
        for (int g = 0; g < dimlist; g++)
        {
          if(list.get(g).parola.equals(word) == true)  //  IT CHECKS IF WORD IS PRESENT INTO THE ARRAYLIST
          {                                                                        
            found = true; 
    
            list.get(g).occurrences ++;
    
            list.get(g).versi = list.get(g).versi + ", ";
    
            list.get(g).versi = list.get(g).versi + String.valueOf(verse);
    
          }
    
        }
    
        if(found == false)
        {
          list.add(new MyStruct(word,String.valueOf(verse),1, 3));
          dimlist ++ ;
        }  
    
      }
    
      //***********************//
      // ALPHABET SWITCH FUNCT //
      //*********************//
    
      switch(SortMode)
      {
        case 1:
          Collections.sort(list, MyStruct.Comparators.OCCORRENZE); // OCCURRENCES
        break;
    
        case 2:
          Collections.sort(list, MyStruct.Comparators.PAROLA); // WORD
        break;
    
        case 3:
          Collections.sort(list);
        break;
    
        default:
          Collections.sort(list, MyStruct.Comparators.PAROLA); // WORD
          break;
      }  
    
    
      //*****************************//
      // GRAPHIC INFOS - PRINT PDF  //
      //****************************//
    
      PGraphicsPDF pdf = (PGraphicsPDF) g;  // GETTING THE RENDER PDF
    
      font = createFont ("Titillium-Regular.otf", 15);
      textFont(font);
    
      pdf.background(255);          // #1 PAPER COLOR FOR THE FIRST PAGE - SEE BEYOND FOR NEXT PAGES
      pdf.fill(60, 60, 60);           // FONT COLOR
      pdf.textFont(font, 11);
      pdf.textSize(11);             // FONT SIZE
    
      String row;
      String pages;
      int counterrow;
    
    
      pages= "";
      row = "";       // LINES OR ROW
      counterrow=0;   // LINES LIMITER - DON'T CHANGE IT HERE - BUT BEYOND
    
    
      //******************************
      // COUNTER LINES FUNCT (VERSI) *
      //******************************
    
          for(int h = 2; h < (dimlist-1) ; h ++)
          {
             if((list.get(h).parola.equals("/") == false) && (list.get(h).parola.equals("") == false) && (list.get(h).parola.equals("?") == false))
             {
                 row = list.get(h).parola + ": " + list.get(h).occurrences + "; vers.  " + list.get(h).versi + "." + "\n" + "\n";  // WHAT HE MUST WRITE ON THE PDF
                 pages = pages + row; 
    
                 if(counterrow >= 17)              //SETUP HERE HOW MANY LINES SHOULD BE PRINT ON PDF PER PAGE//
                 {
    
                   //rect(40, 60, 300, 630);      // CAGE VISIBILE OR NOT
                   //stroke(1);
                   pdf.background(255);            // #2 PAPER COLOR FOR EACH NEW PAGE - USUALLY SETTED WITH THE SAME VALUE ABOVE (#1 BACKGROUND)
                   noFill();
                   text(pages, 40, 60, 250, 1000);  // CAGE TEXT - POSITION X-Y | WIDTH LENGHT X-Y
                   counterrow = 0;
                   pdf.nextPage();
                   pages = "";
                 }
    
                 counterrow++;
    
             } 
          }
          noFill();                         // THIS IS THE LAST PAGE
          text(pages, 40, 60, 250, 1000);  // CAGE TEXT - POSITION X-Y | WIDTH LENGHT X-Y
    
    
      println("I'm done. Please check your PDF located on the sketch folder."); // DONE MESSAGE - FILE READY!!!
    
    }//SETUP FINISHED
    
    
    
    //*******************************
    //OBJECT WORD - LINES - COUNTER *
    //*******************************
    public static class MyStruct implements Comparable<MyStruct> 
    {
    
        private String parola;
        private String versi;
        private int occurrences;
        private int newline;
    
        Collator collator = Collator.getInstance(Locale.ITALY); // PUT THE REGION REGARDING THE TXT LANGUAGE - ACCENTS RECO *
        private final CollationKey key;
    
        public MyStruct(String parola, String versi, int occurrences, int newline)
        {
            this.parola = parola;
            this.versi = versi;
            this.occurrences = occurrences;
            this.newline = newline;
            this.key = collator.getCollationKey(parola);
        }
    
        public int compareTo(MyStruct oggetto) 
        {                
         return key.compareTo(oggetto.key);
        }
    
        public static class Comparators 
        {
    
          public static Comparator<MyStruct> PAROLA = new Comparator<MyStruct>() 
            {
    
                public int compare(MyStruct o1, MyStruct o2) 
                {
                    return o1.parola.compareTo(o2.parola);
                }
            };
    
    
            public static Comparator<MyStruct> OCCORRENZE = new Comparator<MyStruct>() 
            {
    
                public int compare(MyStruct o1, MyStruct o2) 
                {
                    return o1.occurrences - o2.occurrences;
                }
            };
    
        }
    }