Howdy, Stranger!

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

  • JSON save/load

    thanks guys. im understanding a little bit better all of json world. now my problem is how to store the type of an Object for later restore this data. I`ve a system with an array. using polymorphism two Obj(sphere, can) extends main Obj. How can indicate what type of object are in JSON to later restore?

      void setData() {
        JSONObject system = new JSONObject();
        JSONArray o = new JSONArray();
        for (int i = 0; i < s.o.size(); i++) {
          Obj obj = s.o.get(i);
          JSONObject objeto = new JSONObject();
          objeto.setFloat("posX", obj.x);
          objeto.setFloat("posY", obj.y);
          objeto.setFloat("posZ", obj.z);
          o.setJSONObject(i, objeto);
        }
        system.setJSONArray("Objetos", o);
        json.setJSONObject("system", system);
      }
    
      void loadData(String path) {
        json = loadJSONObject(path);
        JSONObject system = json.getJSONObject("system");
        JSONArray Objetos = system.getJSONArray("Objetos");
        for (int i = 0; i < Objetos.size(); i++) {
          JSONObject objeto = Objetos.getJSONObject(i);
          float x = objeto.getFloat("posX");
          float y = objeto.getFloat("posY");
          float z = objeto.getFloat("posZ");
    
          s.o.add(new Obj_Sphere(x, y, z));
          //s.o.add(new Obj_Can(x, y, z));
        }
      }
    
    
    class System {
    
      ArrayList<Obj>o;
    
      System() {
        o = new ArrayList<Obj>();
      }
    
      void addObj(int choice) {
    
        if (choice == 0) o.add(new Obj_Sphere(random(-width/2, width/2), random(-height/2, height/2), 0));
        if (choice == 1) o.add(new Obj_Can(random(-width/2, width/2), random(-height/2, height/2), 0));
    
        println(o.getClass());
      }
    
      void update() {
        for (Obj obj : o) {
          obj.display();
        }
      }
    }
    
  • JSON save/load

    full new version with load and save:

    see comments below:

    Chrisir ;-)

    // Escape is de-activated. 
    // using selectInput and selectOutput here. 
    // using also setting path dataPath() and file ending "json".
    // fileNameForScreen shows the current file name throughout.
    // Uses a JSONArray within a JSONObject.
    
    JSONObject json;   // WITHIN this object is an array named animals, see json.setJSONArray("animals", values);
    
    // fileNameForScreen shows the current file name throughout
    String fileNameForScreen = "Not a file";
    
    void setup() {
      size(660, 660);
      background(110);
    
      json = new JSONObject();
    
      // TWO possible test arrays 
      String[] species = { "Capra hircus", "Panthera pardus", "Equus zebra" };
      String[] names   = { "Goat", "Leopard", "Zebra" };
      // String[] species = { "Cw", "Pp", "Ez" };
      // String[] names   = { "G", "Leo", "Z" };
      //
    
      // build values (JSONArray) 
      JSONArray values = new JSONArray();
    
      for (int i = 0; i < species.length; i++) {
    
        JSONObject animal = new JSONObject();
    
        animal.setInt("id", i);
        animal.setString("species", species[i]);
        animal.setString("name", names[i]);
    
        values.setJSONObject(i, animal);
      }//for 
    
      // add values (JSONArray) to json 
      // comment this out to generate an error 
      json.setJSONArray("animals", values);
    
      // generate another error for testing outputJSONArray:
      //json = null;
    }
    
    void draw() {
      background(110);
    
      // show Menu
      noFill();
      stroke(0); 
      rect(width-49, 27, 
        45, 80-27);
      fill(0); 
      text("Load\n\n" + "Save", 
        width-44, 44);
    
      // show file name 
      fill(255); // white 
      text(fileNameForScreen, 
        min(width-44, width - textWidth(fileNameForScreen) - 11), 15);
    
      // show array 
      outputJSONArray(json, "animals");
    }
    
    // --------------------------------------------------------------------------
    
    void keyPressed() {
      // De-activate Escape key 
      if (key==ESC) {
        key=0; // kill Escape
      }
    }
    
    void mousePressed() {
      // println (mouseY);
      // right screen border?
      if (mouseX>width-50) {
        checkMouseOnMenu();
      }
    }
    
    void checkMouseOnMenu() {
    
      // using selectInput and selectOutput here. 
      // also setting path and file ending json. 
    
      if (mouseY>20&&mouseY<47) { 
        //Load
        String fileString = dataPath("") + "\\" +"*.json" ;
        println(fileString);
        File toLoad = new File( fileString ) ;
        selectInput("Load a file:", "fileSelectedForLoad", toLoad);
      } else if (mouseY>48&&mouseY<77) {
        //Save
        String fileString = dataPath("") + "\\*.json" ;
        println(fileString);
        File toSave = new File( fileString ) ;
        selectOutput("Save to a file:", "fileSelectedForSave", toSave);
      } else {
        // ignore
      }
    }
    
    // ---------------------------------------------------------------------------------
    
    void fileSelectedForLoad(File selection) {
      File loading;
      loading = selection;
      if (selection == null) {
        println("Window was closed or the user hit cancel.");
      } else { 
        println("User loaded " + selection.getAbsolutePath());
        if (loading  != null) { 
          json =  loadJSONObject(loading.getAbsolutePath());
          fileNameForScreen=loading.getName();//https://docs.oracle.com/javase/7/docs/api/java/io/File.html
        }
      }//else 
      //
    }
    
    void fileSelectedForSave(File selection) {
      File saving;
      saving = selection;
      if (selection == null) {
        println("Window was closed or the user hit cancel.");
      } else {
        String saveString = saving.getAbsolutePath();
        saveString=saveString.trim();
        // ending json ok? 
        if (saveString.indexOf(".json") < 0) {
          saveString+=".json"; // very rough approach...
          saving = new File(saveString);
        }
        println("User saved to " + selection.getAbsolutePath());
        if (saving != null) { 
          saveJSONObject(json, saving.getAbsolutePath());
          fileNameForScreen=saving.getName();//https://docs.oracle.com/javase/7/docs/api/java/io/File.html
        }
      }//else 
      //
    }
    
    // ---------------------------------------------------------------------------------
    
    void outputJSONArray(JSONObject json, String nameOfJSONArray) {
    
      // output of an JSONArray named "nameOfJSONArray" in an an JSONObject json.
      // The function is not generic since column names "species" etc. must be correct as below. 
    
      // error check I. 
      if (json==null) { 
        fill(255, 33, 0); // red 
        text( "No json object", 30, 30+2);
        return;
      }//if 
    
      JSONArray valuesLoaded =  json.getJSONArray(nameOfJSONArray);
    
      // error check II. 
      if (valuesLoaded==null) { 
        String error = "No json array named "
          + nameOfJSONArray
          + " in json object.";
        fill(255, 33, 0); // red       
        text(error, 30, 30+2);
        return;
      }//if
    
      fill(40, 255, 17); // black 
    
      for (int i = 0; i < valuesLoaded.size(); i++) {
    
        JSONObject animal = valuesLoaded.getJSONObject(i); 
    
        int id = animal.getInt("id");
        String species = animal.getString("species");
        String name = animal.getString("name");
    
        // println(id + ", " + species + ", " + name);
        text(id + ", " + species + ", " + name, 40, 50+35*i); // small table
      }//for 
      //
    }//func 
    // 
    
  • Code coloring for Processing in LaTeX listings package

    This is something I had up on this forum since last summer, but it was in a question thread so I thought I should share this here in the proper category as well.

    Current version: v1.2

    This LaTeX listings template will color your Processing code as you see them in the Processing editor. You can just post your code like you normally would using the listings package, and you will automatically get your code in the proper colors. Except one minor inconvenience, that I will explain here.

    For a function name that is the same as an already defined keyword (Such as "boolean" and "boolean()"), you have to use [escapechar = "char"] and \color{"color"}{"text"} to color them properly. Example:

    \begin{lstlisting}[escapechar = ?]
    boolean;
    ?\color{function}{boolean}?(1);
    \end{lstlisting}
    

    Copy and paste the below template if you want to use it. Alternatively, you can copy only the necessary parts. If in that case, note that \usepackage{listings} and \usepackage{color} is a must for this to work.

    Also note, I have licensed this work with CreativeCommons license CC-BY-SA, so please remember to give some credit to me ;)

    If you find any typos or any other errors, please tell me and I'll try to fix them as much as possible.

    Download version:
    http://www.mediafire.com/file/cw861uy156xftkv/article_listing_Processing_v1.2.tex
    GitHub Gist:
    https://gist.github.com/ebigunso/af355220e932f72d03289c576622aa29

    Full template below:

    \documentclass{article}
    
    \usepackage{graphicx}
    \usepackage{url}
    \usepackage{verbatim}
    \usepackage{listings}
    \usepackage{color}
    
    % Processing language definition template for LaTeX listings package v1.2
    %
    % Credits to ebigunso for creating this LaTeX listings language definition template for Processing
    % This template is licensed with CreativeCommons license CC-BY-SA 4.0
    % license info:
    % https://creativecommons.org/licenses/by-sa/4.0/legalcode
    
    %Define Colors
    \definecolor{black}{RGB}{0,0,0}
    \definecolor{gray}{RGB}{102,102,102}        %#666666
    \definecolor{function}{RGB}{0,102,153}      %#006699 lightblue
    \definecolor{lightgreen}{RGB}{102,153,0}    %#669900
    \definecolor{bluegreen}{RGB}{51,153,126}    %#33997e
    \definecolor{magenta}{RGB}{217,74,122}  %#d94a7a
    \definecolor{orange}{RGB}{226,102,26}       %#e2661a
    \definecolor{purple}{RGB}{125,71,147}       %#7d4793
    \definecolor{green}{RGB}{113,138,98}        %#718a62
    
    \lstdefinelanguage{Processing}{
      %keyword1&2&6
      morekeywords = [3]{abstract, break, class, continue, default, enum, extends, false, final, finally, implements, import, instanceof, interface, native, new, null, package, private, protected, public, static, strictfp, throws, transient, true, void, volatile, length, assert, case, return, super, this, throw},
      %keyword3
      morekeywords = [4]{catch, do, for, if, else, switch, synchronized, while, try},
      %keyword4
      morekeywords = [5]{width, height, pixelHight, displayHeight, displayWidth, focused, frameCount, frameRate, key, keyCode, keyPressed, mouseButton, mousePressed, mouseX, mouseY, pixels, pixelWidth, pmouseX, pmouseY},
      %keyword5
      morekeywords = [6]{Array, ArrayList, Boolean, Byte, BufferedReader, Character, Class, Double, Float, Integer, HashMap, PrintWriter, String, StringBuffer, StringBuilder, Thread, boolean, byte, char, color, double, float, int, long, short, FloatDict, FloatList, IntDict, IntList, JSONArray, JSONObject, PFont, PGraphics, PImage, PShader, PShape, PVector, StringDict, StringList, Table, TableRow, XML},
      %literal2
      morekeywords = [7]{ADD, ALIGN_CENTER, ALIGN_LEFT, ALIGN_RIGHT, ALPHA, ALPHA_MASK, ALT, AMBIENT, ARC, ARROW, ARGB, BACKSPACE, BASELINE, BEVEL, BLEND, BLUE_MASK, BLUR, BOTTOM, BOX, BURN, CENTER, CHATTER, CHORD, CLAMP, CLICK, CLOSE, CMYK, CODED, COMPLAINT, COMPOSITE, COMPONENT, CONCAVE_POLYGON, CONTROL, CONVEX_POLYGON, CORNER, CORNERS, CROSS, CUSTOM, DARKEST, DEGREES, DEG_TO_RAD, DELETE, DIAMETER, DIFFERENCE, DIFFUSE, DILATE, DIRECTIONAL, DISABLE_ACCURATE_2D, DISABLE_DEPTH_MASK, DISABLE_DEPTH_SORT, DISABLE_DEPTH_TEST, DISABLE_NATIVE_FONTS, DISABLE_OPENGL_ERRORS, DISABLE_PURE_STROKE, DISABLE_TEXTURE_MIPMAPS, DISABLE_TRANSFORM_CACHE, DISABLE_STROKE_PERSPECTIVE, DISABLED, DODGE, DOWN, DRAG, DXF, ELLIPSE, ENABLE_ACCURATE_2D, ENABLE_DEPTH_MASK, ENABLE_DEPTH_SORT, ENABLE_DEPTH_TEST, ENABLE_NATIVE_FONTS, ENABLE_OPENGL_ERRORS, ENABLE_PURE_STROKE, ENABLE_TEXTURE_MIPMAPS, ENABLE_TRANSFORM_CACHE, ENABLE_STROKE_PERSPECTIVE, ENTER, EPSILON, ERODE, ESC, EXCLUSION, EXIT, FX2D, GIF, GRAY, GREEN_MASK, GROUP, HALF, HALF_PI, HAND, HARD_LIGHT, HINT_COUNT, HSB, IMAGE, INVERT, JAVA2D, JPEG, LEFT, LIGHTEST, LINE, LINES, LINUX, MACOSX, MAX_FLOAT, MAX_INT, MIN_FOAT, MIN_INT, MITER, MODEL, MOVE, MULTIPLY, NORMAL, NORMALIZED, NO_DEPTH_TEST, NTSC, ONE, OPAQUE, OPEN, ORTHOGRAPHIC, OVERLAY, PAL, PDF, P2D, P3D, PERSPECTIVE, PI, PIE, PIXEL_CENTER, POINT, POINTS, POSTERIZE, PRESS, PROBLEM, PROJECT, QUAD, QUAD_STRIP, QUADS, QUARTER_PI, RAD_TO_DEG, RADIUS, RADIANS, RECT, RED_MASK, RELEASE, REPEAT, REPLACE, RETURN, RGB, RIGHT, ROUND, SCREEN, SECAM, SHAPE, SHIFT, SPAN, SPECULAR, SPHERE, SOFT_LIGHT, SQUARE, SUBTRACT, SVG, SVIDEO, TAB, TARGA, TAU, TEXT, TFF, THIRD_PI, THRESHOLD, TIFF, TOP, TRIANGLE, TRIANGLE_FAN, TRIANGLES, TRIANGLE_STRIP, TUNER, TWO, TWO_PI, UP, WAIT, WHITESPACE},
      %function1
      morekeywords = [8]{start, stop, breakShape, createPath, str, loadMatrix, parseBoolean, parseByte, parseChar, parseFloat, parseInt, saveFile, savePath, sketchFile, sketchPath, abs, acos, alpha, ambient, ambientLight, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginCamera, beginContour, beginRaw, beginRecord, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, binary, blend, blendColor, blendMode, blue, box, brightness, camera, ceil, clear, clip, color, colorMode, concat, constrain, copy, cos, createFont, createGraphics, createImage, createInput, createOutput, createReader, createShape, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, day, degrees, delay, directionalLight, displayDensity, dist, ellipse, ellipseMode, emissive, endCamera, endContour, endRaw, endRecord, endShape, exit, exp, expand, fill, filter, floor, frustum, fullScreen, get, green, hex, hint, hour, hue, image, imageMode, join, launch, lerp, lerpColor, lightFalloff, lights, lightSpecular, line, loadBytes, loadFont, loadImage, loadJSONArray, loadJSONObject, loadPixels, loadShader, loadShape, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, modelX, modelY, modelZ, month, nf, nfc, nfp, nfs, noClip, noCursor, noFill, noise, noiseDetail, noiseSeed, noLights, noLoop, norm, normal, noSmooth, noStroke, noTint, ortho, parseJSONArray, parseJSONObject, parseXML, perspective, list, pixelDnsity, point, pointLight, popMatrix, popStyle, pow, print, printArray, printCamera, println, printMatrix, printProjection, pushMatrix, pushStyle, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, requestImage, resetMatrix, resetShader, reverse, rotate, rotateX, rotateY, rotateZ, round, saturation, save, saveBytes, saveFrame, saveJSONArray, saveJSONObject, saveStream, saveStrings, saveTable, saveXML, scale, screenX, screenY, screenZ, second, selectFolder, selectInput, selectOutput, set, shader, shape, shapeMode, shearX, shearY, shininess, shorten, sin, size, smooth, sort, specular, sphere, sphereDetail, splice, split, splitTokens, spotLight, sq, sqrt, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textMode, textSize, texture, textureMode, textureWrap, textWidth, thread, tint, translate, triangle, trim, unbinary, unhex, updatePixels, vertex, year},
      %function2
      morekeywords = [9]{cache, readLine, close, flush, print, println, charAt, equals, indexOf, substring, toLowerCase, toUpperCase, getDouble, getLong, getColumnTitles, getColumnTypes, getColumnType, setDouble, setLong, add, clear, div, get, hasKey, keyArray, keys, mult, remove, set, size, sortKeys, sortKeysReverse, sortValues, sortValuesReverse, sub, valueArray, values, append, array, hasValue, max, min, mult, remove, reverse, shuffle, sort, sortReverse, increment, getBoolean, getFloat, getInt, getIntArray, getJSONArray, getJSONObject, getString, getStringArray, isNull, setBoolean, setFloat, setInt, setJSONArray, setJSONObject, setString, beginDraw, endDraw, blend, copy, filter, loadPixels, mask, resize, save, updatePixels, addChild, beginContour, beginShape, disableStyle, enableStyle, endContour, endShape, getChild, getChildCount, getVertex, getVertexCount, isVisible, resetMatrix, rotate, rotateX, rotateY, rotateZ, scae, setFill, setStroke, setVertex, setVisible, translate, angleBetween, cross, dist, dot, fromAngle, heading, lerp, limit, mag, magSq, normalize, randm2D, random3D, setMag, lower, upper, addColumn, addRow, clearRows, findRow, findRows, getColumnCount, getRow, getRowcount, getStringColumn, matchRow, matchRows, removeColumn, removeRow, removeTokens, rows, trim, getColumnTitle, format, getAttributeCount, getChildren, getContent, getNam, getParent, hasAttribute, hasChildren, listAttributes, listChildren, removeChild, setContent, setName, toString},
      %function4
      morekeywords = [10]{draw, keyReleased, keyTyped, mouseClicked, mouseDragged, mouseMoved, mouseReleased, mouseWheel, settings, setup},
      keywordstyle = [3]\color{bluegreen},
      keywordstyle = [4]\color{lightgreen},
      keywordstyle = [5]\color{magenta},
      keywordstyle = [6]\color{orange},
      keywordstyle = [7]\color{green},
      keywordstyle = [8]\color{function},
      keywordstyle = [9]\color{function},
      keywordstyle = [10]\color{function},
      sensitive = true,
      morecomment = [l][\color{gray}]{//},
      morecomment = [s][\color{gray}]{/*}{*/},
      morecomment = [s][\color{gray}]{/**}{*/},
      morestring = [b][\color{purple}]",
      morestring = [b][\color{purple}]'
    }
    \renewcommand{\ttdefault}{pcr}
    \lstset{
      language={Processing},
      basicstyle={\small\ttfamily},
      identifierstyle={\small},
      commentstyle={\small\itshape},
      keywordstyle={\small},
      ndkeywordstyle={\small},
      stringstyle={\small\ttfamily},
      frame={tb},
      breaklines=true,
      columns=[l]{fullflexible},
      numbers=left,
      xrightmargin=0em,
      xleftmargin=3em,
      numberstyle={\scriptsize},
      stepnumber=1,
      numbersep=1em,
      lineskip=-0.5ex,
    }
    
    % Use escapechar and \color{<color>}{<text>} to color function names properly, that is already defined as a different color keyword.
    %
    % \begin{lstlisting}[escapechar = ?]
    % boolean;
    % ?\color{function}{boolean}?(1);
    % \end{lstlisting}
    
    \title{}
    \author{}
    \date{}
    
    \begin{document}
    \maketitle
    \section{}
    
    \begin{thebibliography}{9}
    \end{thebibliography}
    \end{document}
    
  • Looking for tutorials on *real-time* data visualisation.

    Check their documentation: https://data.gov.ie/dataset/real-time-passenger-information-rtpi-for-dublin-bus-bus-eireann-luas-and-irish-rail/resource/4b9f2c4f-6bf5-4958-a43a-f12dab04cf61?inner_span=True

    An example code below. Notice you can copy and past the url request directly into a browser to see what data you are getting from the request. For more info, check examples and the reference:

    https://processing.org/reference/loadJSONObject_.html

    Related to your most recent post, please don't post pictures of code. Instead, copy and paste the code here directly in the forum and format that code properly as described in the sticky post in the forum.

    Kf

    //===========================================================================
    // GLOBAL VARIABLES:
    JSONObject json;
    
    
    //===========================================================================
    // PROCESSING DEFAULT FUNCTIONS:
    
    
    //errorcode  "1"
    //errormessage  "No Results"
    //numberofresults  0
    //stopid  "7602"
    //timestamp  "02/04/2018 03:43:46"
    //results  []
    
    
    void setup() {
      size(400,600);
    
      json = loadJSONObject("https://" + "data.smartdublin.ie/cgi-bin/rtpi/realtimebusinformation?stopid=7602&format=json");
    
      int errorCode = json.getInt("errorcode");
      String timeStamp = json.getString("timestamp");
      String stopid = json.getString("stopid");
    
      println(errorCode + ", " + timeStamp + ", " + stopid);
    }
    
    void draw(){
    
    }
    
  • JSON Null Pointer Exception
    1. the forum is killing links

    2. you try to use unDispersed in line 3 but it's only set in line 18, you need a new order:

    (changed http a bit to avoid that forum changes it)

    JSONObject unDispersed;
    
    Float undisperesdLTC;
    
    void setup() {
      size(480, 320);
      frameRate(24);
    
      pullUndispersed();
    }
    
    void draw() {
    
      undisperesdLTC = unDispersed.getJSONObject("data").getFloat("confirmed_balance");
    
      println(undisperesdLTC);
    }
    
    void pullUndispersed() {
    
      String  walletAPI_URL = "http : // chain.so/api/v2/get_address_balance/LTC/LNhixHYiLQF2v6wKyoiizgJaQunuy6d8Jx/6" ;
    
      unDispersed = loadJSONObject(walletAPI_URL);
    }
    

    here I receive in line 23 a http 403 - Forbidden status in response to a request from a client for a web page

    maybe reread documentation of chain.so/api

    https://en.wikipedia.org/wiki/HTTP_403

  • JSON Null Pointer Exception

    Null pointer exception?

    JSONObject unDispersed;
    
      Float undisperesdLTC = unDispersed.getJSONObject("data").getFloat("confirmed_balance");
    
    void setup() {
      size(480, 320);
      frameRate(24);
    }
    
    void draw() {
      pullUndispersed();
      println(undisperesdLTC);
    }
    
    void pullUndispersed() {
        //LTC pool
      String  walletAPI_URL = "https://"+"chain.so/api/v2/get_address_balance/LTC/LNhixHYiLQF2v6wKyoiizgJaQunuy6d8Jx/6";
      unDispersed = loadJSONObject(walletAPI_URL);
    }
    
  • "JSON object is not a number"

    Any idea why this returns "JSON object ["temp_max"]is not a number"?

    JSONObject losAngelesWeather;

    void setup() { size(480, 320);

    } void draw() {

    String weatherLA_URL = "http://api.openweathermap.org/data/2.5/forecast?id=5368361&&cnt=1&APPID= 9972f563fbd40a4148b0b962bc535833"; losAngelesWeather = loadJSONObject(weatherLA_URL);

    float temp = losAngelesWeather.getJSONArray("list").getJSONObject(0).getFloat("temp_max");

    println(temp); }

  • Use an AsyncTask to load PImages

    What I don't like about that thread() example is that it keeps creating a new Thread over & over for something that is supposed to keep ongoing during the whole time the sketch is running. 8-X

    How about invoking thread() once in setup(), and have its code inside an infinite loop w/ delay(): *-:)

    https://Processing.org/reference/thread_.html

    String time = "";
    
    void setup() {
      fill(#FFFF00);
      textAlign(CENTER, CENTER);
      textSize(14);
      thread("requestData");
    }
    
    void draw() {
      background(0);
      text(time, width>>1, height>>1);
    }
    
    void requestData() {
      for (;; delay(1000)) {
        final JSONObject json = loadJSONObject("http://" + "Time.JsonTest.com/");
        time = json.getString("time", "FAILED!");
        println(time);
      }
    }
    
  • Use an AsyncTask to load PImages

    There's also no checking for whether a load is already in progress, ...

    • The variable time is the only data that example is interested in.
    • Which is then displayed via function text().
    • At 1st, time is merely an empty String "".
    • But once the 1st loadJSONObject() completes, time is reassigned via its method getString().
    • I can see 2 ways for it to crash though:
    1. loadJSONObject() fails. Gonna need a try/catch () block for it.
    2. The field "timer" isn't in the JSON. So time is assigned null. Fix, use defaultValue:
      time = json.getString("time", "");
      https://Processing.org/reference/JSONObject_getString_.html
  • Control P5 Library Questions

    I am getting data from a public API and displaying them in a Line Graph. This part of the sketch is working. Now I would like to add a button to press to launch the data and the line graph. I am using Control P5 library for this.

    I have 4 questions:

    • In general, I find the methods ok to find, but not as easy to understand. Do you have tips/ tricks to best approach this?

    • The Line Graph appears when launching the sketch, not when pressing the button, how can I change this?

    • What is the appropriate method for changing the color of the button? I have tried ".setColorValue(color(#7a1018))" and ".setColorForeground(color(#7a1018))", but I cannot get them to work..

    • What is the appropriate method for changing the shape of the button? I cannot find a method for this..

    The code is the following - everything is working as planned, except for the controlP5 part..

    import controlP5.*;
    
    String API_Key = "f77c39703fb6be71e2c5a96e58edc077";
    String url = "http://api.openweathermap.org/data/2.5/forecast?q=Brussels&mode=json";
    float speedBru; 
    float[] winddata, tempdata, clouddata;
    String[] dtdata, ddata_adapted, tdata_adapted; 
    int margin; 
    float graphHeight, graphWidth;
    float XSpacer;
    int size_list;
    float overallMin_windspeed, overallMax_windspeed; 
    PVector[] positions = new PVector[40]; 
    ControlP5 cp5; 
    
    void setup() {
      size(800, 800);
      background(250);
      loadData();
      calculatedraw();
      cp5 = new ControlP5(this);
      cp5.addButton("Wind")
         .setValue(0)
         .setPosition(0,50)
         .setSize(50,50);
         //.setColorValue(color(#7a1018))
         //.setColorForeground(color(#7a1018));
    }
    
    void Wind(){
    
      for (int i=0; i<positions.length; i++){
         stroke (#008080,80); 
         line(positions[i].x, margin, positions[i].x, height-margin); 
         //first put down textSize, then text 
         textSize(5); 
         text(tdata_adapted[i], positions[i].x-2, height-margin+20);
    
        if(i>0){
          stroke(#1A8011);
          line(positions[i].x, positions[i].y, positions[i-1].x, positions[i-1].y);
        }
      }
      //first put down textSize, then text 
      textSize(20);
      text(overallMax_windspeed,5,margin);
      text(overallMin_windspeed,5,height-margin);
    
      fill(200);
       for (int i=0; i<positions.length; i++){
         ellipse (positions[i].x, positions[i].y, 10,10);
       }
    }
    
    void calculatedraw(){
    
      overallMin_windspeed = min(winddata); 
      overallMax_windspeed = max(winddata); 
    
      margin = 50;
      graphHeight = (height - margin)-margin;
      graphWidth = (width- margin)-margin;
      XSpacer = graphWidth/(size_list-1);
    
      for (int i=0; i<size_list; i++){
        float adjScore_windspeed = map(winddata[i], overallMin_windspeed, overallMax_windspeed, 0, graphHeight);  
        float yPos_windspeed = height - margin - adjScore_windspeed; 
        float xPos_windspeed = margin + (XSpacer * i); 
        positions[i] = new PVector(xPos_windspeed, yPos_windspeed);
      } 
    }
    
    void loadData(){
      JSONObject jsonBru = loadJSONObject(url+"&APPID="+API_Key);
      JSONArray listBru = jsonBru.getJSONArray("list");
      size_list = listBru.size();
      winddata = new float[40];
      tempdata = new float[40];
      clouddata = new float[40];
      dtdata = new String[40];
      ddata_adapted = new String[40];
      tdata_adapted = new String[40];
    
      for (int i=0; i<listBru.size(); i++){
         JSONObject data = listBru.getJSONObject(i);
         JSONObject windBru = data.getJSONObject("wind");
         float windspeed = windBru.getFloat("speed");
         winddata[i] = windspeed;
         JSONObject main = data.getJSONObject("main");
         float temperature = main.getFloat("temp");
         tempdata[i] = temperature; 
         JSONObject clouds = data.getJSONObject("clouds");
         float cloud_perc = clouds.getFloat("all");
         clouddata[i] = cloud_perc; 
         String date_time = data.getString("dt_txt");  
         dtdata[i] = date_time;   
         String date_adapted = date_time.substring(8,10)+"/"+date_time.substring(5,7);
         ddata_adapted[i] = date_adapted; 
         String time_adapted = date_time.substring(11,13)+"h";
         tdata_adapted[i] = time_adapted;
      }
    }
    
  • API JSON cannot create reader

    Hmm... Your posted sketch code has worked for me w/o any hassles. 8-|
    Anyways, I've decided to remake it based on a previous p5.js sketch I already had: O:-)

    http://Bl.ocks.org/GoSubRoutine/5fbc03e019c53254a2ba7e7fd3318b45

    /**
     * OpenWeatherMapJSON (v1.0.2)
     * Mod GoToLoop (2018-Feb-13)
     *
     * Forum.Processing.org/two/discussion/26332/
     * api-json-cannot-create-reader#Item_1
     *
     * Bl.ocks.org/GoSubRoutine/5fbc03e019c53254a2ba7e7fd3318b45
     */
    
    static final String
      HTML = "http" + "://", 
      SITE = "api.OpenWeatherMap.org", 
      FOLD = "/data/2.5/weather" + '?', 
      COORDS = "lat=35" + '&' + "lon=139" + '&', 
      API_KEY = "appid=f77c..." + '&', 
      PATH = HTML + SITE + FOLD + COORDS + API_KEY;
    
    JSONObject weather;
    
    void setup() {
      noLoop();
    
      weather = loadJSONObject(PATH);
      final JSONObject wind = weather.getJSONObject("wind");
      final float speed = wind.getFloat("speed");
      println("Wind Speed: " + speed);
    
      exit();
    }
    
  • API JSON cannot create reader

    Hello,

    I am trying to run APIs on a processing sketch to use them as input for data visualization. Got the same error at two open APIs. The error is the following:

    Couldn't create a reader for http:// api.openweathermap.org/data/2.5/weather?lat=35&lon=139&APPID=f77c...
    FATAL EXCEPTION: Animation Thread
    Process: processing.test.jsonprocessingtutorial, PID: 25803
    

    The url + API key string is working, I have tested it.. Seems to be a connection problem, how can I troubleshoot it?

    The sketch loads a JSON and then displays a parameter as a test, float "wind". It seems to go wrong at loading the JSON..

    The code of my sketch is the following:

    String API_Key = "f77c...";
    String url = "http://" + "api.openweathermap.org/data/2.5/weather?lat=35&lon=139";
    //specific url with coordinates for specific city 
    
    void setup() {
          size(480, 360);
          loadData();
    }
    
    void loadData(){
          JSONObject json = loadJSONObject(url+"&APPID="+API_Key);
          JSONObject windData = json.getJSONObject("wind");
          float speed = windData.getFloat("speed");
          println (speed); 
    }
    
  • How should I access JSONObject in order?

    Hi,

    I want to access JSONObject in order like an array. I know that it is actually not in order list like an array but, since my file is in Object I think may be people who has more experiences than me can point what should I do with this situation.

    You can see in my code below in line that says:** JSONArray notes = chord.getJSONArray("g-major");** I have to put string in the () which I do not want to. I would like to make the program random select the value. But since chord is a JSONObject I have to assign string.

    So here are my questions: 1) Are there a way to work around calling the order of jsonobject? 2) if NO.. actually, I have try rewrite my JSON file or create create a new array in the code instead but, have not met any success yet. The problem about making a new array is that I can't extract the "name" of the object. It gives me the whole { xxx:[ 1,2,3] }so I don't know how to put it in. Can I get only the name of the object so I can str(); it somehow and add to new array.

    Here is my sample json:

     {
            "anger": [
                {"f-minor":["C","D","E"]},
                {"g-major":["C","D","E"]}
            ],
            "sadness": [
               {"c-major":["C","D","E"]}
            ]
    
        }
    

    And the code:

    JSONObject json;
    String emotion;
    
    void setup() {
    
      json = loadJSONObject("data.json");
      emotion="anger";
      JSONArray chordList = json.getJSONArray(emotion);
      int i = floor(random(chordList.size()));
      JSONObject chord = chordList.getJSONObject(1);
      //println(chord);
      JSONArray notes = chord.getJSONArray("g-major");
      println(notes.size());
      int n = floor(random(notes.size()));
      String note = notes.getString(0);
      println(note);
    }
    
  • How to draw/visualize data from JSON file?

    Hi, so I have successfully imported my JSON file into processing, but now I am trying to draw plot point or lines that represent the longitude and latitude. I have tried searching on here for solutions, but I am just more confused now. I will paste my current code below...

    JSONObject json, iss_position;
    String message;
    int timestamp;
    float latitude, longitude;
    
    void setup() {
      size(500, 500);
      noStroke();
    }
    
    void draw() {
      background(0);
      json = loadJSONObject("http://api.open-notify.org/iss-now.json");
      iss_position = json.getJSONObject("iss_position");
      message = json.getString("message");
      timestamp = json.getInt("timestamp");
      latitude = iss_position.getFloat("latitude");
      longitude = iss_position.getFloat("longitude");
    
      println(message + ", " + timestamp + ", " + latitude + ", " + longitude);
    
      ellipse(latitude, longitude, 10, 10);
      text("TIME: "+timestamp, 10,450);
      text("LATITUDE: "+latitude, 10,470);
      text("LONGITUDE "+longitude, 10,490);
    
    }
    
  • What color is used for automatic coloring in Processing?

    @gaocegege

    I'm back here since I've finally managed to pull together the language definition! There are a few minor inconveniences though, that I will explain here.

    Firstly, for function names that are the same as an already defined keyword (Such as "boolean" and "boolean()"), you have to use [escapechar = "char"] and \color{"color"}{"text"} to color them properly. Example:

    \begin{lstlisting}[escapechar = ?]
    boolean;
    ?\color{function}{boolean}?(1);
    \end{lstlisting}
    

    Secondly, there is no bold style. In Processing, a few of the function names are defaulted to using bold font, but this could not be implemented. Bold style is now working as of v1.2.

    Copy and paste the below template if you want to use it. Alternatively, you can copy only the necessary parts. If in that case, note that \usepackage{listings} and \usepackage{color} is a must for this to work.

    Also note, I have licensed this work with CreativeCommons license CC-BY-SA, so please remember to give some credit to me ;)

    If you find any typos or any other errors, please tell me and I'll try to fix them as much as possible.

    Download version: http://www.mediafire.com/file/cw861uy156xftkv/article_listing_Processing_v1.2.tex

    Full template below:

    \documentclass{article}
    
    \usepackage{graphicx}
    \usepackage{url}
    \usepackage{verbatim}
    \usepackage{listings}
    \usepackage{color}
    
    % Processing language definition template for LaTeX listings package v1.2
    %
    % Credits to ebigunso for creating this LaTeX listings language definition template for Processing
    % This template is licensed with CreativeCommons license CC-BY-SA 4.0
    % license info:
    % https://creativecommons.org/licenses/by-sa/4.0/legalcode
    
    %Define Colors
    \definecolor{black}{RGB}{0,0,0}
    \definecolor{gray}{RGB}{102,102,102}        %#666666
    \definecolor{function}{RGB}{0,102,153}      %#006699 lightblue
    \definecolor{lightgreen}{RGB}{102,153,0}    %#669900
    \definecolor{bluegreen}{RGB}{51,153,126}    %#33997e
    \definecolor{magenta}{RGB}{217,74,122}  %#d94a7a
    \definecolor{orange}{RGB}{226,102,26}       %#e2661a
    \definecolor{purple}{RGB}{125,71,147}       %#7d4793
    \definecolor{green}{RGB}{113,138,98}        %#718a62
    
    \lstdefinelanguage{Processing}{
      %keyword1&2&6
      morekeywords = [3]{abstract, break, class, continue, default, enum, extends, false, final, finally, implements, import, instanceof, interface, native, new, null, package, private, protected, public, static, strictfp, throws, transient, true, void, volatile, length, assert, case, return, super, this, throw},
      %keyword3
      morekeywords = [4]{catch, do, for, if, else, switch, synchronized, while, try},
      %keyword4
      morekeywords = [5]{width, height, pixelHight, displayHeight, displayWidth, focused, frameCount, frameRate, key, keyCode, keyPressed, mouseButton, mousePressed, mouseX, mouseY, pixels, pixelWidth, pmouseX, pmouseY},
      %keyword5
      morekeywords = [6]{Array, ArrayList, Boolean, Byte, BufferedReader, Character, Class, Double, Float, Integer, HashMap, PrintWriter, String, StringBuffer, StringBuilder, Thread, boolean, byte, char, color, double, float, int, long, short, FloatDict, FloatList, IntDict, IntList, JSONArray, JSONObject, PFont, PGraphics, PImage, PShader, PShape, PVector, StringDict, StringList, Table, TableRow, XML},
      %literal2
      morekeywords = [7]{ADD, ALIGN_CENTER, ALIGN_LEFT, ALIGN_RIGHT, ALPHA, ALPHA_MASK, ALT, AMBIENT, ARC, ARROW, ARGB, BACKSPACE, BASELINE, BEVEL, BLEND, BLUE_MASK, BLUR, BOTTOM, BOX, BURN, CENTER, CHATTER, CHORD, CLAMP, CLICK, CLOSE, CMYK, CODED, COMPLAINT, COMPOSITE, COMPONENT, CONCAVE_POLYGON, CONTROL, CONVEX_POLYGON, CORNER, CORNERS, CROSS, CUSTOM, DARKEST, DEGREES, DEG_TO_RAD, DELETE, DIAMETER, DIFFERENCE, DIFFUSE, DILATE, DIRECTIONAL, DISABLE_ACCURATE_2D, DISABLE_DEPTH_MASK, DISABLE_DEPTH_SORT, DISABLE_DEPTH_TEST, DISABLE_NATIVE_FONTS, DISABLE_OPENGL_ERRORS, DISABLE_PURE_STROKE, DISABLE_TEXTURE_MIPMAPS, DISABLE_TRANSFORM_CACHE, DISABLE_STROKE_PERSPECTIVE, DISABLED, DODGE, DOWN, DRAG, DXF, ELLIPSE, ENABLE_ACCURATE_2D, ENABLE_DEPTH_MASK, ENABLE_DEPTH_SORT, ENABLE_DEPTH_TEST, ENABLE_NATIVE_FONTS, ENABLE_OPENGL_ERRORS, ENABLE_PURE_STROKE, ENABLE_TEXTURE_MIPMAPS, ENABLE_TRANSFORM_CACHE, ENABLE_STROKE_PERSPECTIVE, ENTER, EPSILON, ERODE, ESC, EXCLUSION, EXIT, FX2D, GIF, GRAY, GREEN_MASK, GROUP, HALF, HALF_PI, HAND, HARD_LIGHT, HINT_COUNT, HSB, IMAGE, INVERT, JAVA2D, JPEG, LEFT, LIGHTEST, LINE, LINES, LINUX, MACOSX, MAX_FLOAT, MAX_INT, MIN_FOAT, MIN_INT, MITER, MODEL, MOVE, MULTIPLY, NORMAL, NORMALIZED, NO_DEPTH_TEST, NTSC, ONE, OPAQUE, OPEN, ORTHOGRAPHIC, OVERLAY, PAL, PDF, P2D, P3D, PERSPECTIVE, PI, PIE, PIXEL_CENTER, POINT, POINTS, POSTERIZE, PRESS, PROBLEM, PROJECT, QUAD, QUAD_STRIP, QUADS, QUARTER_PI, RAD_TO_DEG, RADIUS, RADIANS, RECT, RED_MASK, RELEASE, REPEAT, REPLACE, RETURN, RGB, RIGHT, ROUND, SCREEN, SECAM, SHAPE, SHIFT, SPAN, SPECULAR, SPHERE, SOFT_LIGHT, SQUARE, SUBTRACT, SVG, SVIDEO, TAB, TARGA, TAU, TEXT, TFF, THIRD_PI, THRESHOLD, TIFF, TOP, TRIANGLE, TRIANGLE_FAN, TRIANGLES, TRIANGLE_STRIP, TUNER, TWO, TWO_PI, UP, WAIT, WHITESPACE},
      %function1
      morekeywords = [8]{start, stop, breakShape, createPath, str, loadMatrix, parseBoolean, parseByte, parseChar, parseFloat, parseInt, saveFile, savePath, sketchFile, sketchPath, abs, acos, alpha, ambient, ambientLight, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginCamera, beginContour, beginRaw, beginRecord, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, binary, blend, blendColor, blendMode, blue, box, brightness, camera, ceil, clear, clip, color, colorMode, concat, constrain, copy, cos, createFont, createGraphics, createImage, createInput, createOutput, createReader, createShape, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, day, degrees, delay, directionalLight, displayDensity, dist, ellipse, ellipseMode, emissive, endCamera, endContour, endRaw, endRecord, endShape, exit, exp, expand, fill, filter, floor, frustum, fullScreen, get, green, hex, hint, hour, hue, image, imageMode, join, launch, lerp, lerpColor, lightFalloff, lights, lightSpecular, line, loadBytes, loadFont, loadImage, loadJSONArray, loadJSONObject, loadPixels, loadShader, loadShape, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, modelX, modelY, modelZ, month, nf, nfc, nfp, nfs, noClip, noCursor, noFill, noise, noiseDetail, noiseSeed, noLights, noLoop, norm, normal, noSmooth, noStroke, noTint, ortho, parseJSONArray, parseJSONObject, parseXML, perspective, list, pixelDnsity, point, pointLight, popMatrix, popStyle, pow, print, printArray, printCamera, println, printMatrix, printProjection, pushMatrix, pushStyle, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, requestImage, resetMatrix, resetShader, reverse, rotate, rotateX, rotateY, rotateZ, round, saturation, save, saveBytes, saveFrame, saveJSONArray, saveJSONObject, saveStream, saveStrings, saveTable, saveXML, scale, screenX, screenY, screenZ, second, selectFolder, selectInput, selectOutput, set, shader, shape, shapeMode, shearX, shearY, shininess, shorten, sin, size, smooth, sort, specular, sphere, sphereDetail, splice, split, splitTokens, spotLight, sq, sqrt, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textMode, textSize, texture, textureMode, textureWrap, textWidth, thread, tint, translate, triangle, trim, unbinary, unhex, updatePixels, vertex, year},
      %function2
      morekeywords = [9]{cache, readLine, close, flush, print, println, charAt, equals, indexOf, substring, toLowerCase, toUpperCase, getDouble, getLong, getColumnTitles, getColumnTypes, getColumnType, setDouble, setLong, add, clear, div, get, hasKey, keyArray, keys, mult, remove, set, size, sortKeys, sortKeysReverse, sortValues, sortValuesReverse, sub, valueArray, values, append, array, hasValue, max, min, mult, remove, reverse, shuffle, sort, sortReverse, increment, getBoolean, getFloat, getInt, getIntArray, getJSONArray, getJSONObject, getString, getStringArray, isNull, setBoolean, setFloat, setInt, setJSONArray, setJSONObject, setString, beginDraw, endDraw, blend, copy, filter, loadPixels, mask, resize, save, updatePixels, addChild, beginContour, beginShape, disableStyle, enableStyle, endContour, endShape, getChild, getChildCount, getVertex, getVertexCount, isVisible, resetMatrix, rotate, rotateX, rotateY, rotateZ, scae, setFill, setStroke, setVertex, setVisible, translate, angleBetween, cross, dist, dot, fromAngle, heading, lerp, limit, mag, magSq, normalize, randm2D, random3D, setMag, lower, upper, addColumn, addRow, clearRows, findRow, findRows, getColumnCount, getRow, getRowcount, getStringColumn, matchRow, matchRows, removeColumn, removeRow, removeTokens, rows, trim, getColumnTitle, format, getAttributeCount, getChildren, getContent, getNam, getParent, hasAttribute, hasChildren, listAttributes, listChildren, removeChild, setContent, setName, toString},
      %function4
      morekeywords = [10]{draw, keyReleased, keyTyped, mouseClicked, mouseDragged, mouseMoved, mouseReleased, mouseWheel, settings, setup},
      keywordstyle = [3]\color{bluegreen},
      keywordstyle = [4]\color{lightgreen},
      keywordstyle = [5]\color{magenta},
      keywordstyle = [6]\color{orange},
      keywordstyle = [7]\color{green},
      keywordstyle = [8]\color{function},
      keywordstyle = [9]\color{function},
      keywordstyle = [10]\color{function},
      sensitive = true,
      morecomment = [l][\color{gray}]{//},
      morecomment = [s][\color{gray}]{/*}{*/},
      morecomment = [s][\color{gray}]{/**}{*/},
      morestring = [b][\color{purple}]",
      morestring = [b][\color{purple}]'
    }
    \renewcommand{\ttdefault}{pcr}
    \lstset{
      language={Processing},
      basicstyle={\small\ttfamily},
      identifierstyle={\small},
      commentstyle={\small\itshape},
      keywordstyle={\small\bfseries},
      ndkeywordstyle={\small},
      stringstyle={\small\ttfamily},
      frame={tb},
      breaklines=true,
      columns=[l]{fullflexible},
      numbers=left,
      xrightmargin=0em,
      xleftmargin=3em,
      numberstyle={\scriptsize},
      stepnumber=1,
      numbersep=1em,
      lineskip=-0.5ex,
    }
    
    % Use escapechar and \color{<color>}{<text>} to color function names properly, that is already defined as a different color keyword.
    %
    % \begin{lstlisting}[escapechar = ?]
    % boolean;
    % ?\color{function}{boolean}?(1);
    % \end{lstlisting}
    
    \title{}
    \author{}
    \date{}
    
    \begin{document}
    \maketitle
    \section{}
    
    \begin{thebibliography}{9}
    \end{thebibliography}
    \end{document}
    
  • Setting searching scope problem _ google map api

    I'm using unfolding library for processing to retrieve some lodging infos from google map. I made the program search and display the data in 20km of the specific spot on the map. But it has some problem. I extended the restrict area widely but the app can't get the results over 20. It load the google map api JSON by URL. I learn that the search scope is bounded by the radius value of URL. Is there any limitation to get the number of results from the google map? The another problem is that the app sometime can't display the background google map image. I guess that it might be related to the google api key or changed WI-FI environment.

    url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=37.705160,127.447744&radius=20000&type=lodging&key=MYKEY";

    the code is below

            UnfoldingMap map;
            DebugDisplay debugDisplay;
            SimplePointMarker studio527;
    
            String url;
            JSONObject json;
            JSONArray resultData;
            ArrayList<Result> infos;
            PFont font;
    
            // the coordination of 527 Studio
            float loc_lati = 37.705160;
            float loc_longi = 127.447744;
    
    
            void setup() {
                    size(800, 600);
                    background(255);
                    Location artLocation = new Location(37.705160 , 127.447744); // the spot
                    studio527 = new SimplePointMarker(artLocation);
    
                    map = new UnfoldingMap(this, new Google.GoogleMapProvider()); // map style
                    MapUtils.createDefaultEventDispatcher(this, map);
                    map.zoomAndPanTo(artLocation, 17); // How much closer to the spot
                    float maxPanningDistance = 20; // in km
                    map.setPanningRestriction(artLocation, maxPanningDistance);
    
                    //Create debug display 
                    //debugDisplay = new DebugDisplay(this, map);
    
                    //load JSON
                    url = "https://" + "maps.googleapis.com/maps/api/place/nearbysearch/json?location=37.705160,127.447744&radius=2000&type=lodging&key=MYKEY"; // distance unit meter
                    json = loadJSONObject(url);
                    resultData = json.getJSONArray("results");
                    println(" the number of hotel : " + resultData.size());
    
                    infos = new ArrayList<Result>();
    
                    for(int i=0; i<resultData.size(); i++){
                      JSONObject result = resultData.getJSONObject(i);
    
                      // name of hotel
                      String hotel = result.getString("name");
                      JSONObject geometry = result.getJSONObject("geometry");
    
                      // location of hotel
                      JSONObject location = geometry.getJSONObject("location"); //no coordination
                      float lat = location.getFloat("lat");
                      float lng = location.getFloat("lng");  
                      println( " coordination : latitude - " + lat + " , longitude - " + lng );
                      Location loc = new Location(lat, lng);
                      Result info = new Result(hotel, loc);
                      infos.add(info);
    
                      /*// create  markers
                      markers[i] = new SimplePointMarker(loc);
                      map.addMarkers(markers[i]);
                      */
    
                      font = createFont("NanumBarunpen",15);
                      textFont(font);
                      textAlign(LEFT);
                    }
    
            }
    
            void draw() {
                int count = 0;
                background(255);
                //map.draw();
                //debugDisplay.draw();
    
                for(int i =0; i<infos.size(); i++){ 
    
                   //ScreenPosition pos = markers[i].getScreenPosition(map);
                   Result info = infos.get(i);
    
                   String name = info.getHotel();
                   Location coordination = info.getLocation();
                   ScreenPosition pos = info.getPos();
    
                   strokeWeight(16);
                   stroke(67, 211, 227, 100);
                   noFill();
                   ellipse(pos.x, pos.y, 12, 12);
    
                   fill(0);
                   //textSize(13);
                   text(name, pos.x, pos.y);
                   //text("lng : " + coordination.x, pos.x, pos.y+23);
                   //text("lat : " + coordination.y, pos.x +120, pos.y+23);
                   println(" count : " + count++ );
    
                }
                println("done");
    
                ScreenPosition  studioPos = studio527.getScreenPosition(map);
                strokeWeight(12);
                stroke(200, 0, 0, 200);
                strokeCap(SQUARE);
                noFill();
                float s = 44;
                arc(studioPos.x, studioPos.y, s, s, -PI * 0.9, -PI * 0.1);
                arc(studioPos.x, studioPos.y, s, s, PI * 0.1, PI * 0.9);
                fill(0);
                text("527Studio", studioPos.x - textWidth("527 Studio") / 2, studioPos.y + 4);
            }
    
    
            class Result{
              String hotel;
              Location loc;
              SimplePointMarker marker;
    
              Result(String _name, Location _loc){
                hotel = _name;
                loc = _loc;
              }
              String getHotel(){
                return hotel;
              } 
    
              Location getLocation(){
                return loc;
              }
    
              ScreenPosition getPos(){
                marker = new SimplePointMarker(loc);
                map.addMarkers(marker);
                ScreenPosition pos = marker.getScreenPosition(map);
                return pos;
              }
            }
    
  • Online quantum random number generator

    Thanks, I'll follow up the links you gave.

    QRND qrnd=new QRND();
    
    void setup() {
      size(320, 320);  
       for (int i=0; i<1024; i++){
        int r=qrnd.nextInt();
        println(r);
        println(hex(r));
        println(binary(r));
      }
    
      noLoop();
    }
    
    class QRND {
      int pos;
      int[] values;
    
      int nextInt() {
        if (pos==0) {
          JSONObject src = loadJSONObject("htt"+"ps://qrng.anu.edu.au/API/jsonI.php?length=1024&type=uint16"); 
          JSONArray myVals = src.getJSONArray("data");  
          values = myVals.getIntArray();
        }
        int r=values[pos++]<<16;
        r|=values[pos++];
        pos&=1023;
        return r;
      }
    }
    
  • Online quantum random number generator

    You can check previous post related to JSON objects. For example:

    https://forum.processing.org/two/search?Search=loadJSONObject

    The reference also is a good way to start: https://processing.org/reference/JSONArray.html

    Here is a tested example:

    void setup() {
      size(320, 320);  
    
      //JSONObject row = loadJSONObject("data.json");
      JSONObject src = loadJSONObject("https://qrng.anu.edu.au/API/jsonI.php?length=1024&type=uint16");
    
      JSONArray myVals = src.getJSONArray("data");  
      int[] values = myVals.getIntArray();
      println(values);
    
      noLoop();
    }
    

    More in a previous discussion: https://forum.processing.org/two/discussion/comment/100492/#Comment_100492

    Kf

  • Online quantum random number generator

    I'm sure someone who knows more about json can write this code better: (Also I haven't checked this code too well!!!)

    // qrng.anu.edu.au
    
    QRND qrnd=new QRND();
    
    void setup() {
      noLoop();
      for (int i=0; i<1024; i++){
        int r=qrnd.nextInt();
        println(r);
        println(hex(r));
        println(binary(r));
      }
    }
    
    class QRND {
      int pos;
      int[] rData=new int[512];
    
      int nextInt() {
        if (pos==0) {
          JSONObject json=loadJSONObject("https://" + "qrng.anu.edu.au/API/jsonI.php?length=1024&type=uint16");
          String[] tok=splitTokens(json.toString(), "[,");
          for (int i=0; i<512; i++) {
            rData[i]=(int(trim(tok[i*2+1]))<<16) | int(trim(tok[i*2+2]));
          }
        }
        int r=rData[pos];
        pos=(pos+1) & 511;
        return r;
      }
    }
    
  • String letters to numbers

    Hello,

    For my project I'm loading in my browser history that I downloaded from Google. I loaded in the JSON file into Processing and used a for-loop to display the titles. Instead of showing the text I would like to create shapes instead of text. My problem however, is that I don't know how to turn the letters into numbers. Should I start with creating an alfabet and assign numbers to each letter or is there an easier way to do this? And how do I assign these numbers to the string in the JSON file?

    I hope you guys can help me, I'm fairly new to processing. Here is the code so far:

    JSONObject json;
    
    void setup() {
      size(1000, 600);
      background(255);
      json = loadJSONObject("BrowserHistory.json");
    
      JSONArray values = json.getJSONArray("Browser History"); 
    
      for (int i = 0; i < values.size(); i++){
    
        JSONObject name = values.getJSONObject(i);
    
        String title = name.getString("title");
        fill( random(255), random(255), random(255), random(255));
        textSize(random(5,25));
        text(title, random(0,width)/2, random(0, height));
        println(title);
          if( i == 500 ){break;}
      }
    }