arrayoutofboundsexception when using flickr api - arrays

i have a piece of code thats makes a image search on flickr and returns the URL of the first image with that name. certain words i search on flickr doesn't have any matching images so because there are no images to get i get an ArrayOutOfBoundsException [0]. is there a way that i can make the program skip that particular words and keep on searching with next words?
this is my code so far:
PImage[] images;
int imageIndex;
XML xml;
String tag = "rutte";
String tag_mode = "all";
String words[];
void setup() {
size(50, 50);
String lines[] = loadStrings("text.txt");
words = split(lines[0], " ");
for (int k = 0; k<words.length; k++) {
String query = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=MY API KEY&tags="+ words[k] + "&sort=relevance&tag_mode="+ tag_mode +"format=rest";
xml = loadXML(query);
XML[] children = xml.getChildren("photos");
if(children.length > 0){
XML[] childPhoto = children[0].getChildren("photo");
for (int i = 0; i < 1; i++) {
String id = childPhoto[i].getString("id"); // this line generates the error :(
String title = childPhoto[i].getString("title");
String user = childPhoto[i].getString("owner");
String url = "https://www.flickr.com/photos/"+user+"/"+id;
println(url);
println("=====================");
}
}
}
textAlign(CENTER, CENTER);
smooth();
}
void draw() {
}

Just use the length field of your array. Something like this:
XML[] children = xml.getChildren("photos");
if(children.length > 0){
XML[] childPhoto = children[0].getChildren("photo");
if(childPhoto.length > 0){
String id = childPhoto[0].getString("id");
//rest of your code
}
You can find more info in the Processing reference.
In fact, you're already doing this with your words array!

Related

Copying all Lines from One file to other file in a Fair Random Manner in Big O(n) running time complexity

you have a file with multiple string lines and u have to put it into another file in fair random manner, how would you implement it with linkedlist and array only given as constraint.
the distribution should be random i.e. should not follow any pattern which is guessable i.e. round-robbin or something like that.
public class FairRandomDistributionDataFromOneToOtherFile {
public static void main(String[] args) {
// Driver Program to read the lines into the String Array.
FileReader fr = null;
LineNumberReader lnr = null;
try {
// Please Pass the File Path to the below filereader to run this program
fr = new FileReader("/home/sgarg/Documents/workspace-spring-tool-suite-4-4.10.0.RELEASE/Interveiw/src/com/sunil/stringfile");
lnr = new LineNumberReader(fr);
lnr.mark(500); // some random read ahead limit, I just choose 5000 randomly
lnr.skip(Integer.MAX_VALUE);
int totalLines = lnr.getLineNumber();
String[] data = new String[totalLines];
// resetting to mark, basically start of the file
lnr.reset();
for (int i=0; i<totalLines; i++) {
data[i] = lnr.readLine();
}
shuffleAndWriteDataToNewFile(data);
System.out.println(Arrays.toString(data));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* #param data - All lines of the files read and passed as String into this String[]
*
*/
public static String[] shuffleAndWriteDataToNewFile(String[] data) {
int len = data.length;
int rand= 0;
for (int i=0; i < len; i++) {
// choose the next random number between the all current valid lines
rand = getNextRandomNumber(len - i);
// Now whatever the random line we get, we will move it to the end of the array and assume that
// next random number generator will generate random lines from 0 to len - i
swapLine(data, i, rand);
// this way our random lines getting settled in the last index of the array which keeps decrementing with loop iteration
// this way we dont need to take a 2nd array to store the lines and complexity vise it is an O(N) solution as we are iterating
// over the array once.
}
return data;
}
/**
* Swap two String Objects in the given String Array.
*/
public static void swapLine(String[] data, int curr, int rand) {
int len = data.length;
String temp = data[len-1 - curr];
data[len -1 -curr] = data[rand];
data[rand] = temp;
}
public static int getNextRandomNumber(int numOfElements) {
return (int)(Math.random() * numOfElements);
}
}

How to fix method printing null for some iterations?

Write a program that shall calculate the vocabulary richness of a text in a file and the frequency of the most common word. The vocabulary richness is the number of words in the text divided by the number of distinct words. The frequency of a word is the number of times the word is mentioned in the text divided by the total number of words in the text.
Define and implement class WordCounter with two private fields String word and int count, constructor WordCounter(String word), and public methods String getName(), int getCount(), and void addToCounter().
Define and implement class Corpus (as in text corpus) with one private field ArrayList<WordCounter> words, constructor Corpus(BufferedReader infile), and public methods double getVocabularyRichness() and String getMostFrequentWord().
Implement a test program (as the public static void main method in Corpus) that reads all files in a specific folder, creates a Corpus object from each (previously opened) file, and saves the requested statistics into another file stats.csv. You can either create a new Corpus object for each file or define an ArrayList<Corpus> of the corpora.
Each line of the CSV file must consist of three fields separated by commas (but no spaces!): the file name, the vocabulary richness, and the most frequently used word. Run your program on all Shakespeare's plays. Submit the CSV file together with the Java file.
I wrote what I think is the correct implementation of the HW problem because it works properly for some of the text files, however only the words.get(i).getName() (I tested with words.get(i).getCount()) method will print a blank space for some of the files. I have tried everything, and can't seem to figure it out. Can you please give me a hint or some guidance as to how to fix this issue?
public class Corpus {
private ArrayList<WordCounter> words = new ArrayList <WordCounter>() ;
Corpus(BufferedReader infile){
String ln;
try {
while((ln = infile.readLine()) != null) {
for (String word : ln.toLowerCase().split("([,.\\s]+)")) {
int reference = 0;
for(int i = 0; i < words.size(); i++) {
if (word.equals(words.get(i).getName())) {
reference++;
words.get(i).addToCounter();
} }
if (reference==0) { words.add(new WordCounter(word)); }
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public double getVocabularyRichness() {
int word_count=0;
for(int i = 0; i < words.size(); i++) {
word_count=word_count+words.get(i).getCount();
}
return (double)word_count/(double)words.size();
}
public String getMostFrequentWord() {
String winner = "*AN ERROR OCCURRED*";
int max_count = 0;
for(int i = 0; i < words.size(); i++) {
if(words.get(i).getCount() > max_count){
max_count = words.get(i).getCount();
}
}
for(int i = 0; i < words.size(); i++) {
if(words.get(i).getCount() == max_count){
winner = words.get(i).getName();
}
}
//winner="Test " + String.valueOf(words.get(i).getName());;
//return String.valueOf(max_count);
return winner;
}
public static void main(String [] args) throws Exception{
BufferedWriter writer = null;
File folder_location = new File("/Users/joaquindelaguardia/Desktop/Shakespeare");
File[] file_array = folder_location.listFiles();
for(File iteration_file: file_array) {
FileReader current_file = new FileReader(iteration_file);
BufferedReader infile = new BufferedReader(current_file);
Corpus obj1 = new Corpus(infile);
String file_name = iteration_file.getName();
String frequent_word = obj1.getMostFrequentWord();
String vocabulary_richness = String.valueOf(obj1.getVocabularyRichness());
System.out.println(file_name);
System.out.println(frequent_word);
System.out.println(vocabulary_richness);
System.out.println("-----------------------------");
//FileWriter file_writer = new FileWriter("/Users/joaquindelaguardia/Desktop/stats.csv");
//writer = new BufferedWriter(file_writer);
//String output = file_name+", "+frequent_word+", "+vocabulary_richness + "\n";
//writer.append(output);
}
//writer.close();
}
}
public class WordCounter {
private String word;
private int count=1;
WordCounter(String word){
this.word=word;
}
public String getName() {
return word;
}
public int getCount() {
return count;
}
public void addToCounter() {
count++;
}
}
Im testing the information by printing before appending to file, and as you can see with the small fragment of the output included below, for some cases it prints the most common word (and) while in the second case it doesn't print anything.
shakespeare-lovers-62.txt
and
2.2409948542024014
shakespeare-julius-26.txt
6.413205537806177

how can i store a text file into an array?

so that later i can parse the array and if the line contains 3 doubles store it into an array of object type? ill later have to store the lines with 3 doubles into another array.
here's an example of my code so far
public static void readFile(){
Scanner scnr = null;
File info = new File("info.txt");
try {
scnr = new Scanner(info);
} catch (FileNotFoundException e) {
System.out.println("file not found");
e.printStackTrace();
}
int counterLines = 0;
String nextLine = "";
while(scnr.hasNextLine()){
nextLine = scnr.nextLine();
counterLines ++;
}
System.out.println(counterLines);
String[] infoArray = new String[counterLines];
for(int i = 0; i < counterLines; i++){
infoArray[i] = scnr.nextLine();
System.out.println(infoArray[i]);
You can probably spilt the text of the file into individual words using String.split() which gives you a String array.

Could not find a part of the path using File.Copy(source,destination,true) in C# console app

I continue to get the (Could not find a part of the path 'C:\Users(user profile)\VirtualStore\Program Files (x86)\E!PC\Macros) exception. The directory is there on the drive but im not sure why i continue to get this exception.
Extra6DestPath = "C:\Users\(user profile)\VirtualStore\Program Files (x86)\E!PC\Macros\"
static void copyMacrosAndBitmaps(string ExtraSourcePath, string Extra6xDestPath )
{
//counter for total Macro count on network
int Count = 0;
//counter for total bitmap count on network
int iCount = 0;
//Get File information to use for copy
FileInfo[] macrosArray;
FileInfo[] iconArray;
//Get Directory information to use for copy
DirectoryInfo di = new DirectoryInfo(ExtraSourcePath);
DirectoryInfo diIcon = new DirectoryInfo(ExtraIconPath);
//set all macro paths as a string from directory into an array
macrosArray = di.GetFiles("*.ebm");
Count = macrosArray.Length;
//set all bitmaps from directory into an array
iconArray = diIcon.GetFiles("*.bmp");
iCount = iconArray.Length;
//copy macros into destination folder
if (Count == 0)
{
throw new FileNotFoundException("No Macros found to copy");
}
else
{
for (int i = 0; i < Count; i++)
{
File.Copy(Extra6xSourcePathW7 + macrosArray[i].ToString(), Extra6xDestPath + iconArray[i].Name, true);
}
//Copy the bitmaps into destination folder
if (iCount == 0)
{
throw new FileNotFoundException("No bitmaps found to copy");
}
else
{
for (int i = 0; i < Count; i++)
{
File.Copy(ExtraIconPath + iconArray[i].ToString(), Extra6xDestPath + iconArray[i].Name, true);
}
}
}
}
I would first try declaring the path with # symbol, to handle characters that need to be escaped:
Extra6DestPath = #"C:\Users\(user profile)\VirtualStore\Program Files (x86)\E!PC\Macros\"

Parsing data from txt file in J2ME

Basically I'm creating an indoor navigation system in J2ME. I've put the location details in a .txt file i.e.
Locations names and their coordinates.
Edges with respective start node and end node as well as the weight (length of the node).
I put both details in the same file so users dont have to download multiple files to get their map working (it could become time consuming and seem complex).
So what i did is to seperate the deferent details by typing out location Names and coordinates first, After that I seperated that section from the next section which is the edges by drawing a line with multiple underscores.
Now the problem I'm having is parsing the different details into seperate arrays by setting up a command (while manually tokenizing the input stream) to check wether the the next token is an underscore.
If it is, (in pseudocode terms), move to the next line in the stream, create a new array and fill it up with the next set of details.
I found a some explanation/code HERE that does something similar but still parses into one array, although it manually tokenizes the input. Any ideas on what to do? Thanks
Text File Explanation
The text has the following format...
<--1stSection-->
/**
* Section one has the following format
* xCoordinate;yCoordinate;LocationName
*/
12;13;New York City
40;12;Washington D.C.
...e.t.c
_________________________ <--(underscore divider)
<--2ndSection-->
/**
* Its actually an adjacency list but indirectly provides "edge" details.
* Its in this form
* StartNode/MainReferencePoint;Endnode1;distance2endNode1;Endnode2;distance2endNode2;...e.t.c
*/
philadelphia;Washington D.C.;7;New York City;2
New York City;Florida;24;Illinois;71
...e.t.c
package filereader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Vector;
public class FileReader {
String locationSection;
String edgeSection;
Vector locations;
Vector edges;
public FileReader(String fileName) {
// read the contents into the string
InputStream is = getClass().getResourceAsStream(fileName);
StringBuffer sb = new StringBuffer();
int ch;
try {
while ((ch = is.read()) != -1) {
sb.append((char) ch);
}
} catch (IOException e2) {
e2.printStackTrace();
}
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
String text = sb.toString();
// separate locations and edges
String separator = "_________________________";
// read location section, without last end-of-line char
int endLocationSection = text.indexOf(separator) - 1;
locationSection = text.substring(0, endLocationSection);
// read edges section, without end-of-line char after separator
int startEdgeSection = endLocationSection + separator.length() + 3;
edgeSection = text.substring(startEdgeSection, text.length());
// parse locations and edges
locations = getLocationsVector(locationSection);
edges = getEdgesVector(edgeSection);
}
// parse locations section
public Vector getLocationsVector(String section) {
Vector result = new Vector();
int startLine = 0;
int endLine = section.indexOf('\n');
while (endLine != -1) {
String line = section.substring(startLine, endLine);
result.addElement(parseLocationsLine(line, ';'));
startLine = endLine + 1;
if (endLine == section.length() - 1)
break;
endLine = section.indexOf('\n', startLine);
// if no new line found, read to the end of string
endLine = (-1 == endLine) ? section.length() - 1 : endLine;
}
return result;
}
// parse edges section
public Vector getEdgesVector(String section) {
Vector result = new Vector();
int startLine = 0;
int endLine = section.indexOf('\n');
while (endLine != -1) {
String line = section.substring(startLine, endLine - 1);
result.addElement(parseEdgesLine(line, ';'));
startLine = endLine + 1;
if (endLine == section.length() + 1)
break;
endLine = section.indexOf('\n', startLine);
// if no new line found, read to the end of string
endLine = (-1 == endLine) ? section.length() + 1 : endLine;
}
return result;
}
// parse locations line
public Hashtable parseLocationsLine(String value, char splitBy) {
Hashtable result = new Hashtable();
int xCEnd = value.indexOf(splitBy);
int yCEnd = value.indexOf(splitBy, xCEnd + 1);
result.put("x", value.substring(0, xCEnd));
result.put("y", value.substring(xCEnd + 1, yCEnd));
result.put("location", value.substring(yCEnd + 1,
value.length() - 1));
return result;
}
// parse edges line
public Hashtable parseEdgesLine(String value, char splitBy) {
Hashtable result = new Hashtable();
int snEnd = value.indexOf(splitBy);
result.put("startnode", value.substring(0, snEnd));
int n = 1;
int start = snEnd + 1;
int enEnd = value.indexOf(splitBy, snEnd + 1);
int dstEnd = value.indexOf(splitBy, enEnd + 1);
while (enEnd != -1 && dstEnd != -1) {
result.put("endnode" + String.valueOf(n),
value.substring(start, enEnd));
result.put("distance" + String.valueOf(n), value.substring(
enEnd + 1, dstEnd));
start = dstEnd + 1;
enEnd = value.indexOf(splitBy, start);
if (dstEnd == value.length())
break;
dstEnd = value.indexOf(splitBy, enEnd + 1);
// if last endnode-distance pair, read to the end of line
dstEnd = (-1 == dstEnd) ? value.length() : dstEnd;
n++;
}
return result;
}
// getters for locations and edges
public Vector getLocations() {
return locations;
}
public Vector getEdges() {
return edges;
}
}
and somewhere in application screen:
fr = new FileReader("/map.txt");
Vector vct1 = fr.getLocations();
for (int i = 0; i < vct1.size(); i++) {
Hashtable location = (Hashtable) vct1.elementAt(i);
Enumeration en = location.keys();
String fv = "";
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String value = (String)location.get(key);
fv = fv + value + "-";
}
this.add(new LabelField(fv));
}
Vector vct2 = fr.getEdges();
for (int i = 0; i < vct2.size(); i++) {
Hashtable location = (Hashtable) vct2.elementAt(i);
Enumeration en = location.keys();
String fv = "";
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String value = (String)location.get(key);
fv = fv + value + "-";
}
this.add(new LabelField(fv));
}
it will be easy to get values from hashtable by keys:
(String)location.get("x")
(String)location.get("y")
(String)location.get("location")
(String)edge.get("startnode")
(String)edge.get("endnode1")
(String)edge.get("distance1")
(String)edge.get("endnode2")
(String)edge.get("distance2")
...

Resources