Cross Domain Ajax Call


Web security policy restrict the cross-domain XMLHttpRequest (Ajax) request, for better, safer mash-up within the web application. There is work around to make Ajax request across domain.

I have created sample server-client application to demonstrate this using jquery.

Server side program which send server information in JSON format (JSON is must) .

Server Side JSP (test.jsp) on server [ cdacmumbai.in ]


<%@ page import="java.util.Date" %>
<%@page import="java.net.InetAddress;" %>
<%
        Date date = new Date();
        InetAddress inetAddress = InetAddress.getLocalHost();

        response.setContentType("application/x-javascript; charset=UTF-8");

        String data = "{\"hostname\":\""+inetAddress.getHostName()+"\", \"serverip\":\""+inetAddress.getHostAddress()+"\", \"servertime\":\""+date.toString()+"\"}";
        String foutput = request.getParameter("callback")+ "("+data+");";
        out.println( foutput.trim() );  
        out.close();
%>

Client code (test.html) on Server[ cdac.in ]

<html>
        <head>
                <script type="text/javascript" src="./jquery-latest.js"></script>
                <script>
                function fun(){
                        $.ajax({
                                url : "http://cdacmumbai.in/test.jsp?out=json&callback=?",
                                dataType: "json",
                                contentType: "application/json;charset=utf-8",
                                type: "GET",
                                success: function ( output ) {
                                        var data = eval( output );
                                        document.getElementById("datetime").innerHTML = "Server Date&Time: "+data.servertime;
                                        document.getElementById("hostname").innerHTML = "Server Hostname: "+data.hostname;
                                        document.getElementById("serverip").innerHTML = "Server IP Address: "+data.serverip;
                                }
                        });

                }
                </script>
        </head>
        <body>
                <input type="submit" value="getServerInformation()" onclick="return fun()">
                <br>
                <br>
                <div>
                        <div id="datetime">
                        </div>
                        <br>
                        <div id="hostname" >
                        </div>
                        <br>
                        <div id="serverip">
                        </div>
                </div>
        </body>
</html>
Advertisements

Enable Your Website To Write In Hindi, Marathi, Kannada, Urdu…


We at C-DAC Mumbai, have developed a Transliteration tool ‘Xlit’  to write in Indian Languages; currently the system supports Hindi, Kannada and Urdu.

Xlit : It is a framework which can be used for developing transliteration system for any language pair provided the bilingual corpus of names/words is available for that language pair (for training), This system is developed using statistical learning technique.

The system can be used for enabling local languages support on websites.

Use following steps to enable your website for Writing in Hindi, Kannada and Urdu…

Step1: Download the following files 

Step2:  Include the downloaded file in your webpage as following 

<script type="text/javascript" src="./jquery-latest.js" ></script>
<script type="text/javascript" src="./xhr.js"> </script>;

Step3: Write a java-script in your page as following
Use setTargetLanguage(“hin”); for setting the target (output) language eg. hin for Hindi
Use setSourceLanguage(“eng”);
for setting the target (input) language eg. eng for English

Now use class xlitfield where you want to enalbe the writing in local language like Hindi, Kannada or Urdu; see the example below.

<!DOCTYPE html>
<html>
<head>
		<link rel=stylesheet type="text/css" href="./xhr.css">
<script type="text/javascript" src="./jquery-latest.js"></script>
<script type="text/javascript" src="./xhr.js"></script>
<script type="text/javascript">
 setTargetLanguage("hin"); // Hind: 'hin' , Urdu: 'ud', Kannada: 'kn'
 setSourceLanguage("eng");
});
</script>
</head>
<body>
<div>
 <span>Enter your word :
 <input id="textfield1" class="xlitfield" type="text" name="word" />
 </span>

 Enter your text: 

 <textarea id="textarea" class="xlitfield" name="testing" rows="10" columns="20"> </textarea></div>
</body>
</html>

Screenshot of the above code

Please feel free to comment, suggest and share ….

— धन्यवाद, ಧನ್ಯವಾದ, دھانیواد

Translate subtitles using Machine Translation (google-api)


The following code is using google translation API which you can download form
google-api-translate-java-0.95.jar

Uses: java GoogleSubTitle [subtitle-file]

import java.io.BufferedReader;
import java.io.FileReader;
import com.google.api.translate.Language;
import com.google.api.translate.Translate;

class GoogleSubTitle{

        private void translate(String inputfile){
                try{
                        String line  = null;
                        BufferedReader br = new BufferedReader(new FileReader(inputfile));
                        Translate.setHttpReferrer("en-hi");
                        while( (line = br.readLine())!= null ){
                                if( line.trim().length() > 0 &&
                                    "0123456789".indexOf( line.trim().charAt(0) ) < 0 ){
                                     String translatedText = Translate.execute(line.trim().toLowerCase(),Language.ENGLISH, Language.HINDI);
/* currently the system is translating english to hindi , source and target language you can change here */
                                     System.out.println(translatedText);
                                }
                                else{
                                        System.out.println(line);
                                }
                                Thread.sleep(250);
                        }
                        br.close();
                }catch(Exception e){
                        e.printStackTrace();
                }
        }
        public static void main(String[] args){
                GoogleSubTitle st = new GoogleSubTitle();
                if(args.length > 0){
                        st.translate( args[0] );
                }else{
                        System.out.println("Input File is missing");
                }
}

Translate English subtitles to Hindi (using MaTra)


Following source-code is using C-DAC Mumbai’s Machine Translation System MaTra. It also need json-org.jar for json parsing which you can download from json-org.jar

Uses: java MaTraSubTitle [english-subtitle-file]

import org.json.JSONObject;
import java.net.URL;
import java.net.URLConnection;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;

public class MaTraSubTitle{

        private void translate(String inputfile){
                try{
                        String line  = null;
                        BufferedReader br = new BufferedReader(new FileReader(inputfile));

                        while( (line = br.readLine())!= null ){

                                if( line.trim().length() > 0 &&
                                    "0123456789".indexOf( line.trim().charAt(0) ) < 0 ){
                                        String translation = getTranslate(line.trim());
                                        String parseT  = parse( translation );
                                        parseT = parseT.replaceAll("&#x","\\\\u");
                                        parseT = parseT.replaceAll("&#","\\\\U");
                                        System.out.println(convert(parseT) );
                                }
                                else{
                                        System.out.println(line);
                                }
                                Thread.sleep(250);
                        }
                        br.close();

                }catch(Exception e){
                        e.printStackTrace();
                }
        }

        private String getTranslate(String sent){
                String translation = "";
                sent = sent.replaceAll(" ","%20");
                try{
                        URL matra = new URL("http://www.cdacmumbai.in/matra/matra_ajax.jsp?sentence='"+sent+"'");
                        URLConnection uc = matra.openConnection();
                        BufferedReader in = new BufferedReader( new InputStreamReader( uc.getInputStream()));
                        String inputLine;
                        while ((inputLine = in.readLine()) != null)
                                translation += " "+ inputLine;
                        in.close();

                }catch(Exception e){
                        e.printStackTrace();
                }
        return translation.trim();
        }
        public static String convert(String s)
        {
                int i=0,len=s.length();
                char c;
                StringBuffer sb = new StringBuffer(len);
                while (i<len) {
                        c = s.charAt(i++);
                        if (c=='\\') {
                                if (i<len) {
                                        c = s.charAt(i++);
                                        if (c=='u') {
                                                c = (char) Integer.parseInt(s.substring(i,i+4).trim(),16);
                                                i += 4;
                                        } // add other cases here as desired...
                                        else if( c== 'U'){
                                                c = (char) Integer.parseInt(s.substring(i,i+4).trim(),10);
                                                i += 4;
                                        }
                                }
                        } // fall through: \ escapes itself, quotes any character but u
                        sb.append(c);
                }
                return sb.toString().replaceAll(";","");

        }


        private String parse(String translation){
                 String value = translation;
                 try{
                        JSONObject obj = new JSONObject( translation ) ;
                        value = obj.getString("Devanagari");
                }catch(Exception e){
                        e.printStackTrace();
                }
        return value;
        }

        public static void main(String[] args){
                MaTraSubTitle st = new MaTraSubTitle();
                if(args.length > 0){
                        st.translate( args[0] );
                }else{
                        System.out.println("Input File is missing");
                }
        }
}

Installing R (A language and environment for statistical computing and graphics) on Debian GNU/Linux


  • How to tell the Debian/Ubuntu tools where to look for the R packages (a line in /etc/apt/sources.list)
    e.i. deb http://cran.r-project.org/bin/linux/debian lenny-cran/
  • $sudo apt-get update
    
  • If you get following error while running the above command

    GPG error: http://cran.us.r-project.org lenny-cran/ Release: The following signatures couldn’t be verified because the public key is not available: NO_PUBKEY 06F90DE5381BA480

    Do the following steps:

    1. you can search for the key at http://keyserver.noreply.org/ and copy it into a plain text file, named, for instance, jranke_cran.asc
    2. Entering “0x381BA480” (NB the prefix “0x” which has to be added to the key “381BA480” as given in CRAN) as the search string, and clicking on “Submit Query” initially gave
    3. pub 1024D/381BA480 2007-02-15 Johannes Ranke (CRAN Debian archive) Fingerprint=6212 B7B7 931C 4BB1 6280 BA13 06F9 0DE5 381B A480″
    4. Clicking on the highlighted “381BA480” in the above then returned

      —–BEGIN PGP PUBLIC KEY BLOCK—–
      Version: SKS 1.1.0
      mQGiBEXUFiURBADkTqPqcRYdLIguhC6fnwTvIxdkoN1UEBuPR6NYW4iJzvRSas/g5bPo5ZxE
      2i5BXiuVfYrSk/YiU+/lc0K6VYNDygbOfpBgGGhtfzYfFRTYNq8QsdD8L8BMYtOu5rYo5BYt
      AwIDFQIDAxYCAQIeAQIXgAAKCRAG+Q3lOBukgM09AKCuapN6slttAFRjs2/mgtaMMwO9sgCf
      ZD2au39Oo8QLXZhZTipN8c7j9mM=
      =BRgm
      —–END PGP PUBLIC KEY BLOCK—–
    5. which duly copied into “ranke_cran.asc” (all of it, including the header abd trailer). Then the recommended command
      $apt-key add jranke_cran.asc
      
  • Install the most recent R version

    $sudo apt-get install r-base-dev r-recommended
    
  • Install Java Development Kit

    $sudo apt-get install sun-java6-jdk
    
  • Enable Java support in R

    $sudo R CMD javareconf
    or 
    $sudo R CMD javareconf JAVA_HOME=/home/shekhar/packages/jdk1.6.0_16
    
  • Install JGR

    sudo R
    > install.packages(‘JGR’)
    > library(JGR)
    > JGR()
    quit R
    
  • Update JGR

    $sudo R
    > library(JGR)
    > JGR(update=TRUE)
    >q() 
    
  • Run once more R as root user to write all script files

    $sudo R
    > library(JGR)
    > JGR()
    >q()
    

Unicode to string conversion in Java


To convert the given Unicode to an character:
i.e String unicode = “0”+91+D1+””; to a Unicode character

Following method can use in Java

char getUnicode(String codePoint) {
   return (char)  Integer.parseInt(codePoint, 16);
}
or 

String string = "0061";
char c = (char) Integer.parseInt(string, 16);
System.out.println(c);

Shortest PATH [using DFS]


/**
* @author shekhar
* @date   12/05/2010
* @description a function to print shortest path using dfs 
**/

int min = MAX_VALUE;                        // sum of total distance 
String finalP = "";                         // store the shortest path 
int vtex = NUMBER_VERTEX;                  // total number of vertex 
boolean[] visited = new boolean[vtex];     // for cycle detection
int [][]graph;

void dfs (String path, int start, int destination, int distance){
            if( start == destination){
                    if( min >= distance){
                            min = distance;
                            finalP = path;
                     }
              return;
             }  
             visited[start] = true;
             for(int i = 0; i < vtex; i++ ){
                     if( visited[i]  || graph[start][i] == 9999) // here 9999 is infinity/no-path
                             continue;
                     dfs(path +" > "+vertex[i], i,destination,distance + graph[start][i]);
            }
            visited[start] = false;
}

Blog at WordPress.com.

%d bloggers like this: