PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label processing. Show all posts
Showing posts with label processing. Show all posts

Tuesday, September 20, 2022

[FIXED] How do I pull text into a hashmap as an arraylist value for a specific key in a file in java

 September 20, 2022     for-loop, hashmap, java, processing, text     No comments   

Issue

I have a text file which contains multiple titles and descriptive text below each title. I am trying to add each title to a hashmap key and the descriptive text to the value but cannot figure out how to iterate over this text file and properly parse the information. The title will ALWAYS contain an empty line before and after the title (unless it is the first line) and the value will ALWAYS be the text immediately after the respective title UNTIL the next title is reached in the file. The user will be given a list of keys to choose from in the program and the corresponding value will be printed.

Example Text File

Title

text
text
text

text
text

Title

text
text
text
text

The text file has multiple titles in the file and must be a single file.

Code

  private static HashMap<String, ArrayList<String>> hashmap = new HashMap<>();
  public static void processTextFile(ArrayList array) {
//Place first line in hashmap key
    hashmap.put((String) array.get(0), new ArrayList<>());
//Iterate over text file and add titles which have null spaces before and after as a key
    for (int i = 0; i < array.size(); i++) {
      if (array.get(i).equals("") && array.get(i + 2).equals("")) {
        hashmap.put((String) array.get(i + 1), new ArrayList<>());
      }
    }
  }

Desired Result

Please select a Title:
*user types a specific title*
Title

text
text
text

text
text

Solution

Assuming that there would be no single-line paragraphs (that can be confused with a title) and you don't need to store empty strings (if you need them remove the condition if (!list.get(i).isEmpty())), you can apply the following logic to populate the map with titles used a keys and Lists containing lines of text as values:

private static Map<String, List<String>> textByTitle = new LinkedHashMap<>();

public static void processText(List<String> list) {
    List<String> text = new ArrayList<>(); // text
    textByTitle.put(list.get(0), text);    // the first line is treated as a title
    
    for (int i = 1; i < list.size(); i++) {
        if (i < list.size() - 1 && list.get(i - 1).isEmpty() && list.get(i + 1).isEmpty()) {
            text = new ArrayList<>();           // reinitializing the text
            textByTitle.put(list.get(i), text); // adding an entry that correspond to a new title
        } else if (!list.get(i).isEmpty()) {
            text.add(list.get(i));              // adding the next line of text
        }
    }
}

main()

public static void main(String[] args) {
    List<String> myText = List.of(
        "Title1",
        "",
        "line1",
        "line2",
        "",
        "Title2",
        "",
        "line1",
        "line2",
        "line3"
    );
    // populating the map
    processText(myText);
    // displaying the result
    textByTitle.forEach((title, text) -> System.out.println(title + " -> " + text));
}

Output:

Title1 -> [line1, line2]
Title2 -> [line1, line2, line3]

Note:

  • Use LinkedHashMap to preserve the order of titles.
  • Avoid using collections of row type (without generic type variable specified).
  • Leverage abstractions, write your code against interfaces. Don't make your code dependent on concrete classes like HashMap, ArrayList, etc. See What does it mean to "program to an interface"?
  • Avoid meaningless names like hashmap. The name of the variable should convey what it is meant to store (See Self-documenting code).


Answered By - Alexander Ivanchenko
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, July 11, 2022

[FIXED] How to manage several Serial messages in processing

 July 11, 2022     arduino, io, messages, processing     No comments   

Issue

I am reading the UID of my RFID card and storing it in a variable called myUID.

After that I am authorizing to the card with the factory key and read block number 4 (which has been written to earlier) and store it in a string readBlock.

On the Arduino, I print out the variables onto the serial interface like so.

Serial.println(myUID);
Serial.println(readBlock);

On the client side, I use a Java program that reads in serial data. My program uses the Processing Library.

Serial mySerial;
PrintWriter output;

void setup() {
 output = createWriter( "data.txt" );
 mySerial = new Serial( this, Serial.list()[0], 9600 );
 mySerial.bufferUntil('\n');
}

void draw(){
  while (mySerial.available() > 0) {
  String inBuffer = mySerial.readString();   
  if (inBuffer != null)
    output.println(inBuffer); 
  }
}
void keyPressed() { // Press a key to save the data
  output.flush(); // Write the remaining data
  output.close(); // Finish the file
  exit(); // Stop the program
}

Now my data.txt is expected to look like

xxx xxx xxx xxx (uid of card)
00 00 00 00 00 00 00 00 ... (read block from card)

but looks like

237 63 58 1
07
37 37 95
 37 
97 98 50 54 37 5
4 55 102 55 52 
45 98

I have tried several things like readStringUntil('\n'); in the Processing Library but without success.


Solution

For everyone interested, I have fixed the problem myself with many hours of searching Google, so maybe this will help someone in the future:

I could fix it with this code:

import processing.serial.*;
int count = 0;
String input = "";
String fileName = dataPath("SET FILEPATH HERE");

Serial mySerial;

import java.io.*;

void setup() {
  mySerial = new Serial(this, Serial.list()[0], 9600);
  mySerial.bufferUntil('\n');

  File f = new File(fileName);
  if (f.exists()) {
    f.delete();
  }
}

void draw(){}

// listen to serial events happening
void serialEvent(Serial mySerial){
  input = mySerial.readStringUntil('\n'); 
  write(input, count);
  count++;
}

// function for writing the data to the file
void write(String inputString, int counter) {
  // should new data be appended or replace any old text in the file?  
  boolean append = false;

  // just for my purpose, because I have got two lines of serial which need to get written to the file 
  //(Line 1: UID of card, Line 2: Read block of card)  
  if(counter < 2){
    append = true;  
  }
  else{
    count = 0;
  }


  try {
    File file = new File("D:/xampp/htdocs/pizza/src/rfid/data.txt");

    if (!file.exists()) {
      file.createNewFile();
    }

    FileWriter fw = new FileWriter(file, append);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter pw = new PrintWriter(bw);

    pw.write(inputString + '\n');
    pw.close();
  }
  catch(IOException ioe) {
    System.out.println("Exception ");
    ioe.printStackTrace();
  }
}


Answered By - TheEarthkin
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, June 27, 2022

[FIXED] How can I extract information from Arduino graph.Or from the Processing software connected with Arduino

 June 27, 2022     arduino, arduino-uno, graph, processing     No comments   

Issue

I am using AD8232 ECG sensor and I need PR interval, OT interval, R peak etc. I can generate the graph. But from the graph, I need these parameters to extract programmatically Can anyone help me.


Solution

The Arduino software was actually based in part off of Processing - that’s the beauty of open-source projects. Once we have an open sketch, our first step is to import the Serial library. Go to Sketch->Import Library->Serial

You should now see a line like import processing.serial.*; at the top of your sketch. Magic! Underneath our import statement, we need to declare some global variables. All this means is that these variables can be used anywhere in our sketch. Add these two lines beneath the import statement:

Serial myPort;  // Create object from Serial class
String val;     // Data received from the serial port

In order to listen to any serial communication, we have to get a Serial object (we call it myPort but you can it whatever you like), which lets us listen in on a serial port on our computer for any incoming data. We also need a variable to receive the actual data coming in. In this case, since we’re sending a String (the sequence of characters ‘Hello, World!’) from Arduino, we want to receive a String in Processing. Just like Arduino has setup() and loop(), Processing has setup() and draw() (instead of loop).

For our setup() method in Processing, we’re going to find the serial port our Arduino is connected to and set up our Serial object to listen to that port.

void setup()
{
  String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port
  myPort = new Serial(this, portName, 9600);
}

Remember how we set Serial.begin(9600) in Arduino? Well, if we don’t want that gobbledy-gook I was talking about, we had better put 9600 as that last argument in our Serial object in Processing as well. This way Arduino and Processing are communicating at the same rate. Happy times!

In our draw() loop, we’re going to listen in on our Serial port and we get something, stick that something in our val variable and prints it to the console (that black area at the bottom of your Processing sketch).

void draw()
{
  if ( myPort.available() > 0) 
  {  // If data is available,
  val = myPort.readStringUntil('\n');         // read it and store it in val
  } 
println(val); //print it out in the console
}

Ta-Da! If you hit the ‘run’ button (and your Arduino is plugged in with the code on the previous page loaded up), you should see a little window pop-up, and after a sec, you should see `Hello, World!‘ appear in the Processing console. Over and over.Excellent! We’ve now conquered how to send data from Arduino to Processing. Our next step is to figure out how to go the opposite way - sending data from Processing to Arduino.



Answered By - Arshdeep Kharbanda
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing