Wednesday, 28 March 2012

A function for the main file with doxygen,c programming

This is the function fu.c (I am worse at naming stuff ,sorry)

 ...................................................................................................


/*!
*
 * 
\see a4.c
*/

/**
 * \brief   The function is intended to alter the arrays as per the rule depending on the user input in the file b1.txt,Temporary arrays are internally generated and which holds the intermediate data ,eventually the content of the temporary array is transfered to the main array.And similar process is carried out in the next iteration
 *
 * \details   Three iterations are performed and at each iteration the corresponding number of characters in the user chosen card is provided in the array "co" which is utilised,The iteration eventually causes the desired card to arrive at the slot as premised.
 *
 *
 *
 *
 * @param a
 *  The <a href="en.wikipedia.org/wiki/Pointer"> pointer</a>  to an <a href="en.wikipedia.org/wiki/Array"> array</a> is passed here,the array content being the card list ,As the approach illustrates representation of datum of cards as a two one dimensional array rather than a single two dimensional array.
 *   The array holds one component of a two component list which uniquely identifies the card
 *  
 *  
 * @param d
 *   It represent a pointer to an array which holds the other half of the card representation parameter
 * @param co
 *   It also represents an array which is used to hold the length of the spoken word by the user which being indicated in the file b1.txt
 *   Only optional parameters are explicitly stated as such. The description
 *   should clarify the default value if omitted.
 *
 * @return
 *   No return is required as the pointer data is
 *   <a href="http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/topic/com.ibm.xlcpp8l.doc/language/ref/cplr233.htm"> passed by reference</a>
 */

void fu(char *a,char *d,char *co)
{char tmp1[9],tmp2[9];
char b[9];
int i=0,j=0,k=0,l=0;
char t;
for(k=0;k<3;k++)
{printf("--------------------------------------%d iteration\n",k);
for(i=0;i<co[k];i++)
{tmp1[8-i]=a[i];
tmp2[8-i]=d[i];

}


for(l=0,j=i;j<9;j++,l++)
{tmp1[l]=a[j];
tmp2[l]=d[j];
}
for(i=0;i<9;i++)
{a[i]=tmp1[i];
d[i]=tmp2[i];
printf("%c(%c)\n",a[i],d[i]);}

}
return;

}


c program file with doxygen ,makefile provided

The main file i'll call it a4.c to the lack of a better name,(actually it was my fourth assignemnt,or to quote the bard "What's in a name ?")

Make a header file by adding

#include<stdio.h>

and save it as head.h    The motive here is to follow a good programming practice where we keep all the headers in a single file and all functions(some if not all,as the case is) in another file and incorporate them into the main file


Though i can no way compete against a simpler explanation for make files ,refer this link



 save it as mf



all: a4

a4: a4.o fu.o
    gcc a4.o -o a4

a4.o: a4.c head.h
    gcc -c -g a4.c

fu.o: fu.c
    gcc -c -g fu.c

clean:
    rm -rf *o a4



So in all we have a main file a4.c provided here,a function fu.c provided  here
and the makefile mf

to run execute " make -f mf "
and " ./a4 " in terminal


..............................................................................................................


#include"head.h"
#include"fu.c"

/*! \mainpage Welcome to the much awaited card game
 *
 * \section welcome Introducing a program for your gaming pleasure please do check the files
 *
 * \image html index.jpeg
 *

 * \section  install  To run you need the ubiquitous
* <a href="en.wikipedia.org/wiki/Linux"> linux</a> OS and the
 * <a href="en.wikipedia.org/wiki/GNU_Compiler_Collection">  gcc</a> <a href="en.wikipedia.org/wiki/Compiler"> compiler </a>
 *\section usage Follow the specified steps to get it going
 * \subsection step1 Step 1:Enter the list of cards in the a1.txt file one after the other ,The desired card is entered at third slot
* \subsection step2 Step 2:Enter the user desired card statement into the b1.txt parse the ending with a '$'
* \subsection step3 Step 3:Run the make file and execute the .exe thus generated and you are good to go   
 *
 *
 */

/*!
 *  \brief    program to implementation of mathematical card spell out trick in c
 *  \details   The program accepts the set of cards in a certain order from a file named a1.txt and also gets the user choice for the card.
it then based on the user choice of card realters the original order of cards read from file a1.txt to generate the list of card in order dictated by the program such that the card arrives at the fifth slot as the case demands
 *  \author    Vinayak
 *  \image html images.jpeg
 *  \version   1.0
 *  \date      2-2011
 *  \pre       First initialize the a1.txt and b1.txt files.
 *  \bug       Altering the file format may provide unknown results.
 *  \warning   Improper use can crash your application
 *  \copyright  Public License.
 *  \see fu.c
 * 
 *  
 */


void main()
{char a[9],c[20],d[9],tmp1[9],tmp2[9];
char b[9],co[3];
int i=0,j=0,k=0,l=0;
char t;
FILE *f;
f=fopen("a1.txt","rt");
if(f==NULL)
{printf("cant open file of cards");
exit(0);
}
//Read from the file the list of cards


while(t=fgetc(f))
{if(t==EOF)
break;
c[i]=t;i++;
}
i=0;
/*store the list of cards into two single dimension arrays if needed a two *dimension array can be used,as well.
*/
while(c[l]!='\0' && l<26 && k<=8 && j<=8)
{
if(c[l]!=10 && c[l+1]!=10)
{a[j]=c[l];
l++;
d[j]=c[l];
j++;}
l++;
}

printf("The cards before you are\n");
for(l=0;l<9;l++)
printf("%c(%c)\n",a[l],d[l]);

l=0;
fclose(f);

//It now reads user choice of cards from another file
f=fopen("b1.txt","rt");

if(f==NULL)
{printf("cant open file of your input");
exit(0);
}

i=0;
while(t=fgetc(f))
{if(t==EOF)
break;
c[i]=t;i++;
}
l=0;
printf("your lucky call is\n");
while(c[l]!='$')
{
printf("%c  ",c[l]);
l++;
}
/*Calculate the legth of each word demarcated by space ,an additional *delimiter '$' is used at the end for convienience.The calculated word *length is stored in an array
*/
i=0;k=0;j=0;
for(;k<3;k++)co[k]=0;
k=0;l=0;

while(c[i]!='$' )
{
if(c[i]==32 )
{

l++;
}
else co[l]+=1;
i++;

}

/*Perform three iterations each time using the length of respective word *the card array content is realtered as per the rule
*/

fu(a,d,co);

//The result is displayed for the users viewing pleasure
printf("\nThe final results for The bet\n");
for(i=0;i<9;i++)
{
printf("  %c(%c) \n ",a[i],d[i]);

}

//The end!!!!!!!
return;
}

Sunday, 25 March 2012

A shell script for Xml to json , Json to Xml converter and parser for accessing record data

This script can also be used to convert RSS to JSON , or any XML to JSON

The shell script does the following things:

1. Display the records to the user.
2. User can query for value of any particular record.
3. Convert from one format to other.

The Designing strategy followed was
The designing algorithm for xml to json conversion and vice versa involves
the mapping from one format to other after identifying the tag nodes and
their elements the identification of which follows certain regular expression
statements ,which in this case is implemented by utlisation of a foreign sript
in the shell , a python script and a javascript are utilised ,they being procured
from a public open source domain and tailored to the needs of this problem.
Both of this scripts invariably use the regular expression for parsing the xml
and json for conversion as the tags their attributes and the elements are
converted from the xml to their respective place holders in the json.However
the attribute in the xml is treated as one more of its element ,though in the
data transfer by utilisation of the xml this does not alter the originality or
the information of the xml content.Thus the conversion process treats the
attributes just as same as the elements.
A linux tool is used for xml parsing this being the xmllint which allows the
utilisation of xpath wherin the user has to provide the path data for accessing
the record data. Another tool of importance is rhino which allows the js file
to run in the linux environment.
The shell script as such utilises certain temporary files to store the xml
and json data and the partially parsed values also grep functions are used to
eliminate certain redundant data to appreciate the pretty printing for xml
and json files. A separate json parser is not implemented as the motivation
was to use the xmllint itself thus the conversion of the json to xml before its
parsing is carried out

Apart from xmllint another intersting tool was the rhino from mozilla guys ,it allows you to run a javascript in the linux terminal
You just got to install rhino by using "sudo apt-get install rhino" then specify to run the javascript

rhino "path to .js file"  "any argument if any "

To use this shell script you need to install python and xmllint ,use the sudo apt-get to do so.

Xml file parser



Json file parser


Xml to json converter

note here you can actually save the display in a file by using the >filename command in the shellscript where required




Json to xml converter


The shell script code

The python script code

The javascript,code


Shell script code for xml to json and json to xml converter ,and parser


flg=0
xmlv ()
{
xmllint --shell /home/proton/ass7/assignment7/$1 <<<"du" >a
for i in 1 2
do
mv a b
sed 1d b >a
rm b

done
mv a b
sed '$d' b >a
rm b
cat a
echo "enter the path of the record whose entity interests you "
read pat
xmllint --shell /home/proton/ass7/assignment7/$1 <<< "xpath "$pat"" > c
grep -q "0 nodes" c
if [ $? -eq 0 ] ; then
echo "no such path exist"
exit 1
fi
grep -q "ATTRIBUTE " c
if [ $? -eq 0  ] ; then

flg=1
for i in 1 2 3 4
do
mv c b
sed 1d b >c
rm b
done
mv c b
sed '$d' b >c
rm b
cat c
fi
grep -q "1  ELEMENT" c
if [ $? -eq 0 ] ; then
#echo "1 elem"
flg=1
xmllint --shell --noblanks /home/proton/ass7/assignment7/$1 <<< "xpath  "$pat/'text()'"" > c
for i in 1 2 3
do
mv c b
sed 1d b >c
rm b
done
mv c b
sed '$d' b >c
rm b
cat c

r1=`grep -c "content= " c`
r2=`grep -c "content" c`
r3=`grep -c "contains 0 nodes" c`

if [ $? -gt 0 ]; then
if [ $flg -eq 0 ]
then
echo "no datum"
fi
fi
[ -s c ]
if [ $? -eq 0 ]; then
if [ $flg -eq 0 ]
then
echo "no datum"
fi
fi


fi
}

clear

echo "Xml | json reader @ 1"
echo "xml -> json @ 2"
echo "json -> xml @ 3"
read cho
if [ $cho -eq 1 ]
then
echo "file list"
ls /home/proton/ass7/assignment7/files

echo "enter file name"
read fil


if [ "${fil#*.}" = "xml" ]
then
echo "File type is xml"
echo " "
echo "listing the records"
cp "/home/proton/ass7/assignment7/$fil" d
xmlv d

elif [ "${fil#*.}" = "json" ]
then
echo "File type is json"
JSON=`cat "/home/proton/ass7/assignment7/$fil"`

echo "$JSON" | ./try.py -r vin >d
mv d b
sed 1d b >d
rm b
mv d b
sed '$d' b >d
rm b
xmlv d
else
echo "error in file type "
exit 1
fi

fi

if [ $cho -eq 3 ]
then
echo "enter file name"
read fil
JSON=`cat "/home/proton/ass7/assignment7/$fil"`

echo "$JSON" | ./try.py -r vin >d
mv d b
sed 1d b >d
rm b
mv d b
sed '$d' b >d
rm b
cat d


fi
if [ $cho -eq 2 ]
then
echo "enter file name"
read fil
xmllint --noblanks /home/proton/ass7/assignment7/d >a
mv a b
sed 1d b >a
rm b
tr -d '\n' < a >b
tr -d ' ' < b >a
rm b
xmlx=`cat "/home/proton/ass7/assignment7/a"`

rhino '/home/proton/ass7/assignment7/xml2json.js' "$xmlx"

fi

 if [ $cho -gt 3 ]
then
echo "error"
fi

 if [ $cho -lt 0 ]
then
echo "error"
fi





Please note /home/proton/ass7/assignment7 is a folder path ,you may use your path here

 " mv a b
sed 1d b >a
rm b "
is used to remove certain lines from the temporary file before parsing sed $d refer to the last line,There are efficient methods to use the same without looping but this being easy to illustrate and understand is hence used.

"<<<" in the xmllint instruction refers to the shell instruction "shell within the terminal"

 `grep -c "content= " c` are used to identify the pattern and please note the quotes are found below the tilde sign in the keyboard indicating its an instruction and not a string

$? -gt 0 usage in " if " after grep will cause by default to store the return value of grep instruction in $?



Python script for json to xml conversion

The code is obtained from: check


#!/usr/bin/python

import sys
import json
import traceback
import getopt
import numbers

from xml.dom.minidom import Document

def parse_element(doc, root, j):
  if isinstance(j, dict):
    for key in j.keys():
      value = j[key]
      if isinstance(value, list):
        for e in value:
          elem = doc.createElement(key)
          parse_element(doc, elem, e)
          root.appendChild(elem)
      else:
        if key.isdigit():
          elem = doc.createElement('item')
          elem.setAttribute('value', key)
        else:
          elem = doc.createElement(key)
        parse_element(doc, elem, value)
        root.appendChild(elem)
  elif isinstance(j, str) or isinstance(j, unicode):
    text = doc.createTextNode(j)
    root.appendChild(text)
  elif isinstance(j, numbers.Number):
    text = doc.createTextNode(str(j))
    root.appendChild(text)
  else:
    raise Exception("bad type '%s' for '%s'" % (type(j), j,))


def parse_doc(root, j):
  doc = Document()
  if root is None:
    if len(j.keys()) > 1:
      raise Exception('Expected one root element, or use --root to set root')
    root = j.keys()[0]
    elem = doc.createElement(root)
    j = j[root]
  else:
    elem = doc.createElement(root)
  parse_element(doc, elem, j)
  doc.appendChild(elem)
  return doc



def parse_json_stdin(root):
  js = "".join(sys.stdin.readlines())
  j = json.loads(js)
  doc = parse_doc(root, j)
  print doc.toprettyxml(encoding="utf-8", indent=" ")




def main():

  root = None

  if len(sys.argv[1:]):
    try:
      (opts, args) = getopt.getopt(sys.argv[1:], 'r:', ['root'])
      if (len(args)):
        raise getopt.GetoptError('bad parameter')
    except getopt.GetoptError:

      sys.exit(0)

    for (opt, arg) in opts:
      if opt in ('-r', '--root'):
        root = arg

  parse_json_stdin(root)

if __name__ == '__main__':
  try:
    main()
  except:
      print >> sys.stderr, '\nException!!!'
      print >> sys.stderr, '-' * 50
      traceback.print_exc()
      print >> sys.stderr, '-' * 50












save it as try.py