Reading a URL to html file - html

txt file containing urls that need to be open and display the contents in a 4x4 board in an html file. Having some trouble with this as I am new too html. the first board reads the words and the second is supposed to display the pictures in a randomized order.
this is the .text file
A,ant
B,bear
C,cat
D,dog
E,elephant
F,fox
G,goat
H,horse
I, iguana
J, Jaguar
K,kangaroo
L, lion
M,monkey
N,newt
O,ostrich
P,penguin
A,http://a-z-animals.com/media/animals/images/470x370/ant8.jpg
B,http://a-z-animals.com/media/animals/images/470x370/bear5.jpg
C,http://a-z-animals.com/media/animals/images/470x370/cat1.jpg
D, http://a-z-animals.com/media/animals/images/470x370/dog5.jpg
E, http://a-z-animals.com/media/animals/images/470x370/african_elephant.jpg
F, http://a-z-animals.com/media/animals/images/470x370/fox.jpg
G,goat, http://a-z-animals.com/media/animals/images/470x370/goat.jpg
H, http://a-z-animals.com/media/animals/images/470x370/horse8.jpg
I, http://www.vivanatura.org/Iguana_iguana_juv1.jpg
J, http://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/Jaguar.jpg/800px-Jaguar.jpg
K,http://images.nationalgeographic.com/wpf/media-live/photos/000/005/cache/gray-kangaroo_554_600x450.jpg
L, http://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Lion_waiting_in_Namibia.jpg/800px-Lion_waiting_in_Namibia.jpg
M,http://upload.wikimedia.org/wikipedia/commons/d/d7/Crab-eating_Macaque_tree.jpg http://upload.wikimedia.org/wikipedia/commons/4/49/Notophthalmus_viridescensPCCA20040816-3983A.jpg
O,http://upload.wikimedia.org/wikipedia/commons/9/92/Ostriches_cape_point_cropped.jpg
P,http://upload.wikimedia.org/wikipedia/commons/b/be/Pygoscelis_papua.jpg
heres what i have so far, any hep would be much appreciated.
/*Muhammed Motala
* ics 240 prof. Jasthi
* THis program reads lines from a pre-existing text files and writes the
* contents to an HTMl file, while putting each line of code into a box forming two 4x4 board's.
*/
import java.io.*;
import java.util.*;
import javax.swing.*;
public class TicTacTwice {
public static void main (String [] args) throws IOException {
Scanner sc = new Scanner(new File("/Users/Muhammed/Documents/Tic_Tac_Twice/tic_tac_twice2.txt"));
BufferedWriter output = null;
String myLine = null;
String [] words = new String[100];
int counter = 0;
int counter1 = 0;
boolean run = true;
do {
try {
while(sc.hasNextLine()) { //reads each line in the txt file
String product = sc.nextLine();
myLine = product;
if (product.contains(" ")) { // if the line contains a space
String[] array1 = product.split(" "); // if contains space add to array
words[counter] = array1[1];
counter++;
}
if (product.contains("http://")) {
String [] array1 = product.split(",");
words[counter] = array1[1];
counter++;
System.out.println(array1[1]);
}
else if (product.contains(",")) { // if contains comma split into separate array
String [] array1 = product.split(",");
words[counter] = array1[1];
counter++;
}
}
sc.close();
FileWriter fw = new FileWriter("/Users/Muhammed/Documents/tic_tac_twice.html");
BufferedWriter bw = new BufferedWriter(fw);
bw.write("<html"); // html code upon writing of the file
bw.write("<head>");
bw.write("<table>");
bw.write("<h1> TICK TAC TWICE <h1>");
bw.write("<h1> Board 1 <h1>");
bw.write("</table>");
bw.write("</head>");
bw.write("<body>");
bw.write("<style>table, th, td{border:1px solid black;padding:5px}"
+ "table{border-spacing:15px}</style>");
bw.write("<table style=width:300px>");
for (int i = 0; i < 4; i++) { // array to create board1 and
// populate with the read in lines
bw.write("<tr>");
for (int j = 0; j < 4; j++) {
bw.write("<td>");
bw.write(words[counter1]);
counter1++;
bw.write("</td>");
}
bw.write("<tr>");
}
bw.write("<style>table, th, td{border:1px solid black;padding:5px}"
+ "table{border-spacing:15px}</style>");
bw.write("<table style=width:300px>");
for (int i = 0; i < 4; i++) { // creates board 2 and populates with
// words that are stored in array
bw.write("<tr>");
for (int j = 0; j < 4; j++) {
bw.write("<td>");
bw.write(words[counter1]);
bw.write("<td><img src=\"" + words[counter] +
"\" alt=\"some_text\"width=200 height=200></img>");
counter1++;
bw.write("</td>");
}
bw.write("<tr>");
}
bw.write("<h1> Board 2 <h1>");
bw.write("</body>");
bw.write("</html>");
bw.close();
run = false;
}
catch (Exception e) { // exception handler
System.out.print(e.toString());
}
}
while(run);
}
}

Related

Write a JSON file with cubePosition Data to spawn a 10x10x10 cube

Here I'm trying to write a code that can write and create a JSON File for me with the data I provide like row, column and depth.
For example, I need to spawn a 10 x 10 x 10 cube. And I give this data in unity Inspector also in the code when I'm serializing it.
I tried achieving this in a for loop and writing the JSON file. But I'm not getting the output I wanted. I am expecting output where the cube locations are different and in place what happens instead is all the data or cube position in my data is the one before the number I give. that is if I gave my row, column, and depth to be 10. So my data is like x: 9, y: 9, z:9 for the whole 1000 elements.Better explained in image down below.I know I'm doing a mistake at some point just not able to figure out where. Thanks for the help in Advance
public class JSONWriter : MonoBehaviour
{
[SerializeField] int rows , columns, depth = 10;
[SerializeField] float padding;
public enum CubeType
{
white,
yellow,
blue,
red,
green
}
private readonly IReadOnlyDictionary<CubeType, Color> colors = new Dictionary<CubeType, Color>
{
{CubeType.white, Color.white},
{CubeType.yellow, Color.yellow},
{CubeType.blue, Color.blue},
{CubeType.red, Color.red},
{CubeType.green, Color.green}
};
[System.Serializable]
public class CubeData
{
public Vector3 cubePosition;
public CubeType Cube;
}
[System.Serializable]
public class CubeDataList
{
public CubeData[] cubeDatas;
}
public void outputJSON()
{
string strOutput = JsonUtility.ToJson(myCubeDataList);
File.WriteAllText(Application.dataPath + "/Resources/10x10x10.txt", strOutput);
}
//CubeData myCubeData = new CubeData();
public CubeDataList myCubeDataList = new CubeDataList();
void Start()
{
for (int x = 0; x < myCubeDataList.cubeDatas.Length; x++)
{
//Debug.Log(myCubeDataList.cubeDatas.Length);
for (int i = 0; i < depth; i++)
{
for (int j = 0; j < columns; j++)
{
for (int k = 0; k < rows; k++)
{
myCubeDataList.cubeDatas[x].cubePosition = new Vector3(i, j, k) * padding;
//myCubeDataList.cubeDatas[x].Cube = Random.Range(CubeType, 3f);
}
}
}
}
}
}
You do not want to go through all i, j, k for each and every element x!
What you are doing is basically overwriting each and every element with the values for i=9, j=9, k=9.
Instead of an array I would rather simply use a dynamic List like
[Serializable]
public class CubeDataList
{
public List<CubeData> cubeDatas;
}
and then dynamically add them via
myCubeDataList.cubeDatas = new List<CubeData>(i * j * k);
for (int i = 0; i < depth; i++)
{
for (int j = 0; j < columns; j++)
{
for (int k = 0; k < rows; k++)
{
var data = new CubeData();
data.cubePosition = new Vector3(i, j, k) * padding;
data.Cube = Random.Range(CubeType, 3f);
myCubeDataList.cubeDatas.Add(data);
}
}
}
Or if you really want to go with an array
for (int i = 0; i < depth; i++)
{
for (int j = 0; j < columns; j++)
{
for (int k = 0; k < rows; k++)
{
var data = new CubeData();
myCubeDataList.cubeDatas[x].cubePosition = new Vector3(i, j, k) * padding;
myCubeDataList.cubeDatas[x].Cube = Random.Range(CubeType, 3f);
x++;
}
}
}
Though, from your previous question I know you actually do not want to fill the cube completely!
You actually only want the external shape (like a wall) and leave the cube empty on the inside.
So what you actually want would probably rather be
myCubeDataList.cubeDatas = new List<CubeData>(i * j * k);
for (int i = 0; i < depth; i++)
{
for (int j = 0; j < columns; j++)
{
for (int k = 0; k < rows; k++)
{
if(i == 0 || i == depth - 1
|| j == 0 || j == depth - 1
|| k == 0 || k == depth - 1)
{
var data = new CubeData();
data.cubePosition = new Vector3(i, j, k) * padding;
// TODO random enum (see below)
myCubeDataList.cubeDatas.Add(data);
}
}
}
}
For the random enum vlaue see e.g. this answer and do
private Random random = new Random();
and then where it says // TODO insert
var values = Enum.GetValues(typeof(Bar));
data.Cube = (CubeType)values.GetValue(random.Next(values.Length));

Why is for loop only out putting first and last entries

This is what is being asked to do...
Write an application that inputs five numbers, each between 10 and 100, inclusive. As each number is read, display it only if it’s not a duplicate of a number already read. Provide for the “worst case,” in which all five numbers are different. Use the smallest possible array to solve this problem. Display the complete set of unique values input after the user enters each new value.
This is the code I have. It compiles and runs, but only outputs the first and last entries of the unique list. Any input greatly appreciated! Thanks in advance.
import java.util.Scanner;
public class DuplicateElimination{
// sets helper functions
public static boolean isIn(int x, int[]y)
{
boolean isIn = false;// sets boolean to false
for (int i=0; i<y.length; i++)// sets for loop to run for length of array
{
if(y[i]==x)
{
isIn = true;
}
}
return isIn;
}
public static int[] append(int x, int[] y)// going to change what has already been set. creates integer array
{
int len = y.length +1;// sets length
int[] a = new int[len];// initializes new array
for (int i=0; i<y.length; i++); // goes through length of y
{
int i=0;
a[i] = y[i];
}
a[y.length] =x;
return a;
}
public static void main(String[] args)// sets main
{
Scanner input = new Scanner (System.in);// sets scanner to read input info
int[]uniqueList = new int[1];
uniqueList[0] = 0;// sets unique list to 0
System.out.print("Enter an integer between 10 and 100:");// prompts input from user
int entered = input.nextInt();// inputs value from user
System.out.printf("This is the first time %d has been entered\n", entered);// adds first entered # to unique list
uniqueList[0] = entered;// adds entered value to unique list
for (int i=0; i<4; i++)// sets loop to find unique values
{
System.out.print("Enter an integer between 10 and 100:");// prompts use
entered = input.nextInt();// inputs value
if(isIn (entered, uniqueList) == false)// calls is in function
{
System.out.printf("This is the first time %d has been entered\n", entered);
uniqueList = append(entered, uniqueList);// puts entered values in unique values on list
}
}
System.out.println("The complete list of unique values entered is:");
for(int i =0; i< uniqueList.length; i++)// runs through list to check for unique #s
{
System.out.printf("Unique value %d: is %d\n", i + 1, uniqueList[i]);// outputs list
}
}// ends main
}// ends class
in the append part change your for loop to:
for (int i=0;i<y.length;i++)
a[i]=y[i];
it didn't work because of for (int i=0; i<y.length; i++); the semi-colon is hijacking your loop as for why the result is as it is, your
{
int i=0;
a[i] = y[i];
}
a[y.length] =x;
return a;
part is just copying the first element of y into a and then copying the new element in the last cel of a
import java.util.*;
class Example{
public static void main(String args[]){
int[] xr = new int[5];
Scanner input = new Scanner (System.in);
System.out.println("Input five different integers between 10 and 100 below");
L1: for (int i = 0; i < xr.length; i++){
System.out.print("\tInput number "+(i+1)+" : ");
xr[i] = input.nextInt();
for(;xr[i]<=10 || xr[i]>=100;){
i--;
System.out.println("\t Error : You entered number is not between 10 and 100.");
continue L1;
}
for (int x = 0; x < i; x++){
if(xr[x] == xr[i]){
i--;
System.out.println("\tError : You cannot use duplicate numbers.");
continue L1;
}
}
}
System.out.println(Arrays.toString(xr));
}
}

How can I enumerate an ASP listview control?

Below I take a list and convert it to a data table and bind it to an ASP listview control.
I'd like a function to convert it back to a List from an asp listview control and cannot figure out how to get the items? In Visual Studio debugging, the dataitems are null? It has the proper count but no values? I'd like to enumerate through all rows.
private void createLvwTable(List<string> table)
{
int index = 0;
DataTable dt = new DataTable();
foreach (string row in table)
{
string[] cells = row.Split('|');
if (index == 0) // header column
{
for (int j = 0; j < cells.Length; j++)
{
dt.Columns.Add(cells[j]);
//dt.Rows.Add();
}
}
else
{
DataRow dr = dt.NewRow();
for (int j = 0; j < cells.Length; j++)
{
dr[j] = cells[j];
}
dt.Rows.Add(dr);
}
index++;
}
lvwOutput.DataSource = dt;
lvwOutput.DataBind();
}
This is idiotic IMO so there is most likely a better way, but it appears you have to bind the data to an object during the listview creation. I couldn't find a good answer anywhere, this is a compilation of hours of searching and trying different combinations of semi-related answers.
On the html side you have to set the 'onitemdatabound' to a c# function. The code below also does not need to have the segmentation I'm going with a "|", I left that in to make it easier to read if you copy/paste my function.
I'd be happy to still read replies on how to do this better so I can learn.
html:
<asp:ListView ID="lvwOutput" runat="server" onitemdatabound="lvwOutput_ItemDataBound">
asp:
private List<string> lvwOutputItemsDataBoundToList = new List<string>();
private List<string> lvwOutputItemsDataBoundToListOriginal = new List<string>();
protected void lvwOutput_ItemDataBoundToList(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
object o = (object)dataItem.DataItem;
System.Data.DataRowView rowView = e.Item.DataItem as System.Data.DataRowView;
object[] itemArray = rowView.Row.ItemArray;
string itemBound = "";
foreach(object item in itemArray)
{
itemBound += item.ToString() + "|";
}
if (itemBound.EndsWith("||"))
{
int index = itemBound.Length;
itemBound = itemBound.Remove(index - 2);
}
if (itemBound.EndsWith("|"))
{
int index = itemBound.Length;
itemBound = itemBound.Remove(index - 1);
}
lvwOutputItemsDataBoundToList.Add(itemBound);
}
ViewState["lvwOutputItemsDataBoundToList"] = lvwOutputItemsDataBoundToList;
}
private void filter()
{
lvwOutputItemsDataBoundToList = (List<string>)ViewState["lvwOutputItemsDataBoundToList"];
lvwOutputItemsDataBoundToListOriginal = lvwOutputItemsDataBoundToList;
foreach (string item in lvwOutputItemsDataBoundToList)
{
string[] itemSplit = item.Split('|');
}
}
To enumerate the ListViewItems see ListView.ListViewItemCollection Class and ListViewItem.SubItems Property.
List<string> lstItems = new List<string>():
foreach(ListViewItem itemRow in lvwOutput)
{
for (int i = 0; i < itemRow.SubItems.Count; i++)
{
lstItems.Add(itemRow.SubItems[i].Text);
}
}

Using Prettify with angle brackets

I want to include this java code in my blog (this is with the enclosing pre's):
<pre class="prettyprint">
public Vector<Instruction> decodeTree(Tree<String> gene) {
Vector<Instruction> ret = new Vector<Instruction>();
ret.add(decodeString(gene.getValue()));
Vector<Tree<String>> currentLayer = gene.getChildren();
Vector<Tree<String>> nextLayer = new Vector<Tree<String>>();
for(int i=0; i<currentLayer.size(); i++) {
for(Tree<String> t: currentLayer.get(i).getChildren()) {
nextLayer.add(t);
}
}
</pre>
But because it has several angle brackets, Blogger goes in and autocompletes all the inferred tags, transforming that chunk into the following:
<pre class="prettyprint">public Vector<instruction> decodeTree(Tree<string> gene) {
Vector<instruction> ret = new Vector<instruction>();
ret.add(decodeString(gene.getValue()));
Vector<tree tring="">> currentLayer = gene.getChildren();
Vector<tree tring="">> nextLayer = new Vector<tree tring="">>();
for(int i=0; i<currentlayer .size="" for="" i="" ree="" tring=""> t: currentLayer.get(i).getChildren()) {
nextLayer.add(t);
}
}
</currentlayer></tree></tree></tree></instruction></instruction></string></instruction></pre>
Which then shows up as:
public Vector decodeTree(Tree gene) {
Vector ret = new Vector();
ret.add(decodeString(gene.getValue()));
Vector> currentLayer = gene.getChildren();
Vector> nextLayer = new Vector>();
for(int i=0; i t: currentLayer.get(i).getChildren()) {
nextLayer.add(t);
}
}
Which is different from the code I'm trying to present. I think the problem originates in the html confusing my things with angle brackets with HTML tags. Is there a way I could get the parser to ignore all that? I tried changing all the angle brackets to &gt and &lt and got the following output:
public Vector&ltInstruction&gt decodeTree(Tree&ltString&gt gene) {
Vector&ltInstruction&gt ret = new Vector&ltInstruction&gt();
ret.add(decodeString(gene.getValue()));
Vector&ltTree&ltString&gt&gt currentLayer = gene.getChildren();
Vector&ltTree&ltString&gt&gt nextLayer = new Vector&ltTree&ltString&gt&gt();
for(int i=0; i&ltcurrentLayer.size(); i++) {
for(Tree&ltString&gt t: currentLayer.get(i).getChildren()) {
nextLayer.add(t);
}
}
html entities are terminated with a semicolon:
<
>

How to decode HTML Entities in C?

I'm interested in unescaping text for example: \ maps to \ in C. Does anyone know of a good library?
As reference the Wikipedia List of XML and HTML Character Entity References.
For another open source reference in C to decoding these HTML entities you can check out the command line utility uni2ascii/ascii2uni. The relevant files are enttbl.{c,h} for entity lookup and putu8.c which down converts from UTF32 to UTF8.
uni2ascii
I wrote my own unescape code; very simplified, but does the job: pn_util.c
Function Description: Convert special HTML entities back to characters.
Need to do some modifications to fit your requirement.
char* HtmlSpecialChars_Decode(char* encodedHtmlSpecialEntities)
{
int encodedLen = 0;
int escapeArrayLen = 0;
static char decodedHtmlSpecialChars[TITLE_SIZE];
char innerHtmlSpecialEntities[MAX_CONFIG_ITEM_SIZE];
/* This mapping table can be extended if necessary. */
static const struct {
const char* encodedEntity;
const char decodedChar;
} entityToChars[] = {
{"<", '<'},
{">", '>'},
{"&", '&'},
{""", '"'},
{"'", '\''},
};
if(strchr(encodedHtmlSpecialEntities, '&') == NULL)
return encodedHtmlSpecialEntities;
memset(decodedHtmlSpecialChars, '\0', TITLE_SIZE);
memset(innerHtmlSpecialEntities, '\0', MAX_CONFIG_ITEM_SIZE);
escapeArrayLen = sizeof(entityToChars) / sizeof(entityToChars[0]);
strcpy(innerHtmlSpecialEntities, encodedHtmlSpecialEntities);
encodedLen = strlen(innerHtmlSpecialEntities);
for(int i = 0; i < encodedLen; i++)
{
if(innerHtmlSpecialEntities[i] == '&')
{
/* Potential encode char. */
char * tempEntities = innerHtmlSpecialEntities + i;
for(int j = 0; j < escapeArrayLen; j++)
{
if(strncmp(tempEntities, entityToChars[j].encodedEntity, strlen(entityToChars[j].encodedEntity)) == 0)
{
int index = 0;
strncat(decodedHtmlSpecialChars, innerHtmlSpecialEntities, i);
index = strlen(decodedHtmlSpecialChars);
decodedHtmlSpecialChars[index] = entityToChars[j].decodedChar;
if(strlen(tempEntities) > strlen(entityToChars[j].encodedEntity))
{
/* Not to the end, continue */
char temp[MAX_CONFIG_ITEM_SIZE] = {'\0'};
strcpy(temp, tempEntities + strlen(entityToChars[j].encodedEntity));
memset(innerHtmlSpecialEntities, '\0', MAX_CONFIG_ITEM_SIZE);
strcpy(innerHtmlSpecialEntities, temp);
encodedLen = strlen(innerHtmlSpecialEntities);
i = -1;
}
else
encodedLen = 0;
break;
}
}
}
}
if(encodedLen != 0)
strcat(decodedHtmlSpecialChars, innerHtmlSpecialEntities);
return decodedHtmlSpecialChars;
}
QString UNESC(const QString &txt) {
QStringList bld;
static QChar AMP = '&', SCL = ';';
static QMap<QString, QString> dec = {
{"<", "<"}, {">", ">"}
, {"&", "&"}, {""", R"(")"}, {"'", "'"} };
if(!txt.contains(AMP)) { return txt; }
int bgn = 0, pos = 0;
while((pos = txt.indexOf(AMP, pos)) != -1) {
int end = txt.indexOf(SCL, pos)+1;
QString val = dec[txt.mid(pos, end - pos)];
bld << txt.mid(bgn, pos - bgn);
if(val.isEmpty()) {
end = txt.indexOf(AMP, pos+1);
bld << txt.mid(pos, end - pos);
} else {
bld << val;
}// else // if(val.isEmpty())
bgn = end; pos = end;
}// while((pos = txt.indexOf(AMP, pos)) != -1)
return bld.join(QString());
}// UNESC