Friday, 10 July 2015

How to browse root user directories with nautilus file browser in Linux.

linux nautilus
If you are logged in with restricted permission you may be able to navigate to other directory through terminal switching to root, but without been logged in as root how can you browse windows directory of root and other users. It can simply be done with nautilus. Nautilus is a utility in Linux to browse your computer. 



Steps to browse other root and other user's directory.

1. Open terminal
2. Switch to root user (su -)
3. type nautilus -browser pathOfYourDesiredDirectory
    e.g. nautilus --browser /root/Documents/

Disadvantages of using nautilus.

You cannot browse network using nautilus browser.

Nautilus is mainly required when you need to access some important files / directories of other users, or need to open some file, which is always very tiresome from the command line. 

#linux #redhat #gnome #nautilus

Wednesday, 8 July 2015

Add, Update, Delete Oracle data with AngularJS and JSP

angularjs jsp
In a few posts a few months back I have tried to retrieve data from Oracle database 12c through JSP and using $http.get retrieve that data to view in table format. Now what about inserting, updating or deleting data from oracle database. It's a wonder how much powerful angularjs is, data retrieving and page rendering is so fast. In the section below both the jsp code and angularjs code is provided. You can run the jsp file alone with parameters and see the result which is actually retrieved by $http.get.
All you need to do is create a table called emp with two fields emp_code and emp_name. And on the connection string change the hostname / ipaddress,

1. Table emp

   create table emp
   (
     emp_code number not null,
     emp_name varchar2(100) not null
   ); 

2. test.html

<html>
<script src= "
"http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="src/app.js">
</script>
<body ng-app="app">   <!-- ng-app on BODY scope -->
<div id="divCtrl" ng-controller="MyCtrl">  
<!-- ng-controller on div scope --> 

<!-- ng-model empCode and empName is used for http get and post -->

<input type="text" name="empCode" ng-model="empCode" value="" />
<input type="text" name="empName"  ng-model="empName" value="" /><br/>
 

<!-- Two buttons having ng-click each calling addData and updateData. updateData updates the record with emp_code value in where condition-->
 

<input type="button" value="Add" ng-click="addData()" /><br/>
<input type="button" value="Update" ng-click="updateData()" />
<table border=1>
<tr><th>Emp Code</th><th>Emp Name</th>
<tr ng-repeat="emp in empArr">


<!-- Remove eclosed in <a> tag having ng-click calling dalateData to delete the current row from the view as well from the database -->

 <td>{{emp.EMP_CODE}}</td><td>{{emp.EMP_NAME}}</td><td> 
<a href="" ng-click="deleteData(emp)">Remove</a></td>
</tr>
</table>
</div>
</body>
</html>


3. app.js 

  app = angular.module('app',[]);
  app.controller('MyCtrl',function($scope,$http) {
     refreshData();

/*     This function is called from ng-click in button "Add"  which adds data in table EMP and updates the view */
     $scope.addData = function() {
       $http.post("insertUpdateDelete.jsp?empCode=" + $scope.empCode + "&empName=" + 

         $scope.empName + "&dmlType=Ins")
        .success(function(response) {
             refreshData();
        });

/* dmlType checks the type of DML transaction to perform, this prevents from creating separate JSP files for insert, update and delete */
      }




/*     This function is called from ng-click in button "Update"  which updates data in table EMP and updates the view */     $scope.updateData = function() {
       $http.post("insertUpdateDelete.jsp?empCode=" + $scope.empCode + "&empName=" + 

       $scope.empName + "&dmlType=Upd")
        .success(function(response) {
           refreshData();
        });
     }




/*     This function is called from the link Remove in the third column of HTML table  which adds data in table EMP and updates the view */
     $scope.deleteData = function(curData) {
        $http.post("insertUpdateDelete.jsp?empCode=" + curData.EMP_CODE + 

         "&empName=" + curData.EMP_NAME + "&dmlType=Del")
        .success(function(response) {
               $scope.empArr.splice($scope.empArr.indexOf(curData),1);
                refreshData();
        });
     }



/*     This function gets fresh data from table  and updates the view */
/* get_oracle_data.jsp is explained in Oracle 12c data generator in JSON by dynamic sql using JSP */
      function refreshData() {
       $http.get("get_oracle_data.jsp?sqlStr=select * from emp")
       .success(function(response) {
          $scope.empArr = response;
        })
       .error(function(response) {
      alert("");
      $scope.empArr={};
       });
     }
  });


4. insertUpdateDelete.jsp
/* This section is not explained here check this url http://techgigsonline.blogspot.in/2015/01/oracle-12c-data-generator-in-json-by.html for jsp oracle tutorial*/
<%@ page import = "java.sql.*" %>
<% Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@192.168.100.1:1521:orcl", 

"username","password");
String dml_type = request.getParameter("dmlType");
String emp_code = request.getParameter("empCode");
String emp_name = request.getParameter("empName");
String sql="";
if("Ins".equals(dml_type))
  sql = "insert into emp values(" + emp_code + ",'" + emp_name + "')";
else if("Del".equals(dml_type))
  sql = "delete from emp where emp_code = " + emp_code + " and emp_name = '" + emp_name + "'";
else if("Upd".equals(dml_type))
  sql = "update emp set emp_name = '" + emp_name + "' where emp_code = " + emp_code;
out.println(dml_type);   
try
{
 Statement stmt = con.createStatement();
 stmt.executeQuery(sql);
}
catch(SQLException e)
{
 out.print("SQL Error encountered " + dml_type  + "," + e.getMessage());
}
con.close();
con=null;
%>


   

Tuesday, 7 July 2015

Creating a Button toolbar with AngularJS

angularjs
I am working on a project where I have used one button toolbar.It is probably the simplest way I have created button toolbar. AngularJS made it simple. It's only JSON data and ngRepeat and my button toolbar is ready to work. I am sharing the code with you and will try to explain as much as I can. This project consists of three files.



1. Index.jsp
2. button.jsp
3. button.js
4. Menu.css

The original project is written on JSP with back-end database as Oracle 12c. All the dynamic page design is done with AngularJS and Ajax. Just check out the code below.

Index.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html ng-app="myApp">
<head>
<meta http-equiv="Content-Type" charset=utf-8" />
<link rel="stylesheet" type="text/css" href="stylesheet/menu.css">
<link rel="stylesheet" type="text/css" href="stylesheet/main.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js">
</script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-route.min.js">
</script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-animate.js">
</script>
<script src="src/menu.js"></script> <!-- Menu.js contains the JSON data to build the toolbar -->
<title>ABC Industries Limited</title>
</head>
<body>
<div class="mainDiv" id="mainDiv">
<div width=80% id="divHeader" ng-controller="RouteController">
    <jsp:include page="button.jsp" /> <!-- This is the section where button.jsp is included -->
    <jsp:include page="menu.jsp" />
</div>
<div id="ngviewDiv" ng-view=""> <!-- This is where the invoked templated are embedded -->
</div>
<!--<img width=84% class="image1" src="Images/BACK.jpg" />-->
</div>
</body>
</html>


Button.jsp

<div class="mnuContainer">
<table id="btntable" width=40% height=20% border=1>
<tr id="mnuButton">
<td width=10% ng-repeat="bmenu in buttonMenu"><center><a href="" ng-click="buttonOption('{{bmenu.funcLink}}')"><img width=30% height=30% ng-src="{{bmenu.Link}}" class="btnsubmnu" /></a></center></td>
</tr></table>
</div>

Menu.js


myApp=angular.module('myApp',['ngRoute']);

myApp.controller('RouteController',function($scope,$http) {
/* I have not defined the linked function (funcLink) newRecord, deleteRecord, etc. for it will make the code to lengthy to understand. Button images is the directory where all the button images are located.*/

    $scope.buttonMenu=[
    {'Name':'New','Link':'Images/new.ico','funcLink':'newRecord'},
    {'Name':'Delete','Link':'Images/delete.ico','funcLink':'deleteRecord'},
    {'Name':'Query','Link':'Images/query.ICO','funcLink':'queryRecord'},
    {'Name':'Execute','Link':'Images/execute.ico','funcLink':'executeRecord'},
    {'Name':'First','Link':'Images/First.ICO','funcLink':'firstRecord'},
    {'Name':'Previous','Link':'Images/Prev.ICO','funcLink':'prevRecord'},
    {'Name':'Next','Link':'Images/Next.ICO','funcLink':'nextRecord'},
    {'Name':'Last','Link':'Images/Last.ICO','funcLink':'lastRecord'},
    {'Name':'Print','Link':'Images/print.ico','funcLink':'printRecord'}
    ];
});


Menu.css

div.btnDiv
{
padding:5px;
opacity:0.8;
box-shadow: 2px 2px 1px 2px #999;
background:white;
cursor:pointer;
cursor:hand;
border-radius: 5px;
width:60%;
height:60%;
}
img.imgsubmnu
{
width:100%;
height:100%;
}


   

Monday, 6 July 2015

Changing background opacity of DOM Element dynamically with JQuery

jquery
Background opacity can be hard coded, but what about if you need to change the opacity dynamically!. JQuery makes your page more dynamic and interactive. In this section of code you can see how you can change the background opacity of a H1 element dynamically by changing the value in a combo list. Combo list consists of numbers from 0 to 100. 0 means fully transparent and 100 means fully opaque. Whenever you change the value opacity change. Try this code.

<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function() {

   /* select list is dynamically created within a div with classname divOption, to fill it up with 0 to 100 using loop */
   var s="<select id='pct'>";
   for(i=0;i<=100;i++)
     s+="<option value=" + i + ">" + i + "</option>";
   s+="</select>";
   $("div.divOption").html(s);
   $("#pct").val("100"); // Set the current value to 100 that means fully opaque

   /* Initially when loading opacity is set to 1 i.e. fully opaque */
   $("h1").css({"color":"00FF00","fontSize":"36px","background-color":"rgba(0,0,255,1)"});

   $("#pct").change(function() {
 /* Follow the calculation in the change event,
since our combo value is 0 to 100, we divide it by 100 to get the fractional value */
     $("h1").css({"background-color":"rgba(0,0,255," + $(this).val()*1.0/100 + ")"});
   });
});   
</script>
<title>
</title>
</head>
<body>
<div class="divOption"></div>
<h1>Hello Subhroneel</h1>
</ br>
</body>
</html>


     

Hello Subhroneel

</ br>

Sunday, 5 July 2015

Order of parameters in controller and custom directive link function in AngularJS

Have you ever tried changing the order of parameters of AngularJS app controller or link function in Angularjs directive?. If you have done so you will find something important difference between the two. Controller callbacks parameters are strict naming convention. Although it does not depends on it's order but directive link function parameters are maintains order of the parameters though it does not maintain naming convention.

 
Suppose say we have this controller defined.

var app = angular.module('app',[]);

app.controller('MyCtrl',function($scope,$http) {

});

Now if you change the order like say
app.controller('MyCtrl',function($http, $scope) {

});

$http and $scope does not change there property. 

But now take one app directive link function say

A.
app.directive('panel',function(scope,element, attrs, ctrl, transclude) {
});

If you change the order like say

B.
app.directive('panel',function(element,scope, ctrl, attrs, transclude) {
});

Then here element meant to be scope, scope meant to be element, ctrl meant to be attrs and attrs 
meant to be ctrl. This means in case of directive link function order of argument is very important.
The order mentioned at below point A. is actually the order and if you change the names it will not change the order. You can even change there name then also it will retain the same order. You can 
write like this 

C.
app.directive('panel,function(a, b, c, d, e) {
});

Here a means scope, b means element, c means attrs, d means ctrl and e means transclude.


But in case of controller callback function name cannot be change so you can change the order.

But you can change the name or order in this case also for that you have to define your controller 
like this.

app.controller('MyCtrl',[$http,$scope, function($http, $scope) {
}]);

You can even change their name or to say put alias like this.

app.controller('MyCtrl',[$http,$scope, function(a, b) {
}]);

Here a means $http and b means $scope.

---------------------------------------------------------------------------------------------------------------------------

#angularjs #javascript #jquery #ajax #controller #directive

Saturday, 4 July 2015

Basic calculator with AngularJS filter

www.angularjs.org/
Today I have been trying to build a calculator. No there is no buttons, but only Addition, Subtraction, Multiplication and Division. I have created 4 filters Add, Subtract, Multiply and Divide. I have used these filter in four different input box. Textbox  parse input in 

Addition : i.e. 5+4+2+8+3
Subtraction : i.e. 5-4-2-8-3
Multiplication : i.e. 5*4*2*8*3
Division : i.e. 5/4/2/8/3  -- this will return float value


<!DOCTYPE html>
<html>
<head>
    <title>Calculators with Filters </title>
    <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('app',[]);
        app.controller('MyCtrl',function($scope){
      $scope.addTxt="1+4+5+6"
      $scope.subTxt="1-4-5-6"
      $scope.multTxt="1*4*5*6"
      $scope.divTxt="1/4/5/6"
        });

        app.filter('Add',function()
        {
            return function(text) {
                var arr = text.split("+");
                var result = 0;
                for(i=0;i<arr.length;i++)
                    result+=Number(arr[i]);
                return result;
            }
        });

        app.filter('Subtract',function()
        {
            return function(text) {
                var arr = text.split("-");
                var result = 0;
                for(i=0;i<arr.length;i++)
                    result-=Number(arr[i]);
                return result;
            }
        });

        app.filter('Multiply',function()
        {
            return function(text) {
                var arr = text.split("*");
                var result = 1;
                for(i=0;i<arr.length;i++)
                    result*=Number(arr[i]);
                return result;
            }
        });

        app.filter('Divide',function()
        {
            return function(text) {
                var arr = text.split("/");
                var result = 1.0;
                for(i=0;i<arr.length;i++)
                    if(Number(arr[i])>0)
                        result/=Number(arr[i]);
                return result;
            }
        });
    </script>
</head>
    <body>
        <div id="divApp" ng-app="app">
            <div ng-controller="MyCtrl">
                Addition : <input type="text" ng-model="addTxt" />
                Result : {{addTxt|Add}} <br />



                Subtraction : <input type="text" ng-model="subTxt" />
                Result : {{subTxt|Subtract}} <br />

                Addition : <input type="text" ng-model="multTxt" />
                Result : {{multTxt|Multiply}} <br />

                Addition : <input type="text" ng-model="divTxt" />
                Result : {{divTxt|Divide}} <br />
            </div>
        </div>
    </body>
</html>


#angularjs #javascript #js #jquery #ajax #customfilter

Using transclude in AngularJS.

angularjs
What happens when you put some content straight into your custom element (i.e. custom element name say panel and you put like this <panel>This is my content</panel> and when you define the directive in you script the content above in your html code is overwritten by the template value. So what can be done, angularjs provides a transclude option which lets you display the content along with the template. So I am writing a small program which let you gain a little concept about how you can retain your html content.
I have used transclude in two different  ways. In the first one I have used ng-transclude directive in a div and added it with existing template value. In the second option I have injected transclude, invoking it as a function which clones the html content value. With loop you can view the content multiple times. Only if you remove transclude:false then you can hide the content.


<!DOCTYPE html>
<html>
    <head>
        <title>Hell with this world</title>
        <meta charset="utf-8">
        <style type="text/css">
            h1.first
            {
                color:#FF0000;
            }
            h1.second
            {
                color:#0000FF;
            }
        </style>
        <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
        <script>
            var myApp = angular.module('myApp',[]);
            myApp.controller('MyCtrl',function($scope){

            });


            myApp.directive("panel1",function(){
                return {
                    restrict: "E",
                    transclude: true,
                    template: '<h1 class="second">This panel1 div meant to see if ng-transclude included... </h1><div ng-transclude></div>'               

                         }
            });

            myApp.directive("panel2",function(){
                return {
                    restrict: "E",
                    transclude: true,
                    template: '<h1 class="second">This panel2 div meant to see if ng-transclude included...</h1>',
                    link: function(scope, element, attrs, ctrl, transclude){
                        transclude(function(clone){
                            element.append(clone);
                        });
                    }
                }
            });
        </script>

    </head>
    <body>
    <div ng-app="myApp">
        <div ng-controller="MyCtrl">
            <panel1>   
                <h1 class="first"> This is in my first HTML section, cannot see if transclude is set to 

                 false!!!!
                </h1>
            </panel1>

            <panel2>   
                <h1 class="first"> This is in my second HTML section, cannot see if transclude is set to 

                 false!!!!
                </h1>
            </panel2>

        </div>
    </div>
    </body>
</html>


Youtube Tutorial

#AngularJS #mvc #javascript #googleapi #ngtransclude 

Friday, 3 July 2015

Building custom filters in AngularJS

As working on AngularJS we are very accustomed with using filters. But generally the filters we used are in built filter like orderby upper lower and many more. Here I have tried to build two custom filters one of which will reverse the string and another will toggle the letter case. So not extending any more lets jump into the code below and see what it's doing. I have not used a separate script and put everything within an HTML page.



<html ng-app="myApp">
<head>
<title>
</title>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script>
    myApp = angular.module('myApp',[]);    //Angular module

    myApp.controller('MyCtrl',function ($scope) {   //Controller
        $scope.message="Subhroneel";
        $scope.message1="SuBhRoNeEl";
        $scope.message2 = "Join, all, text";
    });

    myApp.filter('reverse',function() {                          //Custom filter reverse
        return function(text){
            return text.split("").reverse().join("");
        }

    });

    myApp.filter('toggle',function() {                          // Custom filter toggle
        return function(text) {
            var s="";
            for(i=0;i<text.length;i++)
            {

               // If a letter is upper case then it is converted to lower case, if it is lower case then converted 
               // to upper case and every letter is stored in a separate string and returned finally without 
              // disturbing the original string.
 

                if(text.charAt(i)==text.charAt(i).toLowerCase())
                    s+=text.charAt(i).toUpperCase()
                else if(text.charAt(i)==text.charAt(i).toUpperCase())
                    s+=text.charAt(i).toLowerCase()
                else
                    s+=text.charAt(i);
            }
            return s;
        }
    });



    myApp.filter('concat',function(){
        return function(text) {
            var s=text.split(",");
            var ret = "";
            for(i=0;i<s.length;i++)
                ret+=s[i];
            return ret;
        }
    });


</script>
</head>
<body ng-controller="MyCtrl">
    <input type="text" ng-model="message" name="message" />
    Reverse : {{message|reverse}} </br>
    <input type="text" ng-model="message1" name="message1" />
    Toggle : {{message1|toggle}}
    <input type="text" ng-model="message2" name="message2" />
    Added Strings : {{message2|concat}} </br>
</body>
</html>


#angularjs #customfilter #javascript #mvc
Reverse : {{message|reverse}} Toggle : {{message1|toggle}} Added Strings : {{message2|concat}}

Microsoft Windows Pro 64 bit torrent download

 Microsoft Windows 10 Pro 64 bit torrent download link

Torrent file Link

Magnetic Link

Hash : 1DBD65DA4D0AC0E6916DBD00941D582634E05912

Tuesday, 30 June 2015

Enable parsing of python code in Web browser with Lighttp server in Ubuntu Mate


python

For a couple of days I am trying to run python script in Web browser. For that I need to enable cgi for web browser, so that it enable to parse .py script. I am using lighttpd (light weight http daemon on my Ubuntu mate). After I installed lighttpd with sudo apt-get install lighttpd, I opened /var/etc/lighttpd/lighttpd.conf.




At the begining of the file it has this lines where "mod_cgi" is being commented.
So I uncommented the  "mod_cgi"

server.modules = (
    "mod_access",
    "mod_alias",
    "mod_compress",
     "mod_redirect",
        "mod_rewrite",
        "mod_cgi"
)
 

if you don't like to uncomment "mod_cgi" there is another option to enable cgi module. Go to terminal and type "lighty-enable-mod cgi".

But I recommend the first option.

After you uncomment the line go to the bottom of the file and add this line.

$HTTP["url"] =~ "^/cgi-bin/" {
        cgi.assign = ( ".py" => "/usr/bin/python" ).


 Close the file and create a directory named cgi-bin on /var/www/.
You can also create it in /var/www/html, but you have to change the path in lighttpd.conf :

server.document-root        = "/var/www/html", 
which is by default server.document-root        = "/var/www/"

After you make this changes restart lighttp daemon. Make sure you put all your python script in the folder cgi-bin in /var/www/html.


 

#python #pythonscript #pythonprogramming #webserver

Socket based chat application using UDP.

python




In last post on socket based application TCP protocol is used. This section describes how to create a socket for message exchange using User Datagram Protocol a simple connectionless transmission model with a minimum of protocol mechanism. The main advantage of using UDP is that no connection instance is required to build up for client as it requires in case of TCP. Socket itself received data from client with recvfrom function which returns data and address of the client. Server only waits for the client message and no connection request is required, it only receives and sends data without even identifying client individually.

udpServer.py


import socket  # Socket library 

def Main():    # main function

   host = "127.0.0.1"                           # host loop back address to test in 

                                                           # adapter-less machine.
   port = 5001                                    # port for server




  # socket object.
  s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
  s.bind((host,port))                            # binding to host ip and port
 
  print "Server Started.."
  while True:                                      # infinite loop, server always waits for data
    data, addr = s.recvfrom(1024)    # Receiving data from client.
    print "message from: " + str(addr)   
    print "from connected user: " + str(data)
    data = str(data).upper()              # Converting data to upper case
    print "sending: " + str(data)        

    s.sendto(data,addr)                     # sending data back to client
  s.close();                                        # Socket closed when loop terminates.

if __name__ == '__main__':             # Main module invoked.
  Main()


udpClient.py

import socket  # Socket library 

def Main():    # main function

   host = "127.0.0.1"  # host loop back address to test in adapter-less machine.

   port = 5001            # port for server


   server = ('127.0.0.1',5000)


# socket object.
   s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 
   s.bind((host,port))

   message = raw_input('->')                               
# Waits for user input      
   while message != 'q':
      s.sendto(message,server)                              # User input data send to server
      data, addr = s.recvfrom(1024)                     # data received from server
      print "Received from server: " + str(data);
      message = raw_input('->')                           # Waits for user input
   s.close()

if __name__ == '__main__':                 
# Main module invoked.  
  Main()

#python #pythoprogramming #pythoscript #socketprograming

Monday, 29 June 2015

Socket based chat application with Python




Python socket library is powerful and can be for socket based data transfer for both TCP and UDP protocol. This tutorial with TCP. I have created two modules. One tcpServer.py and other is tcpClient.py. 

1. tcpServer.py
  
     This module simply bind the socket object to the server ipaddress to a particular port.
     Then it's listen for incoming connection from the client. It does nothing until it receives any 
     request. Once it receive request it accepts and enter into data exchange (chat). The server does 
     nothing but receives data send by the client and send back the same to client converting it to 
     uppercase. If the client terminates the server again go back to the state where it again listen for 
     some new connection request. Server can be stopped by pressing Ctrl+C. The program is included 
     inside Main() function to make it executable only. Cannot be used as library in any other module.

tcpServer.py code

import socket  # Socket library 

def Main():    # main function

 host = "127.0.0.1"  # host loop back address to test in adapter-less machine.
 port = 5000            # port for server

 s = socket.socket()  # socket object.
 s.bind((host,port))  # binding to server ip and port mentioned.


 while True:  # infinite loop ends on Ctrl+C by user.

    print "Server is waiting for connection...."  # waiting message displayed 

    s.listen(1)    # listening for incoming connection request.

    c, addr = s.accept()    #  Connection request accepted and connection object and client ip address 
                                       # returned

    print "Connection accepted from: " + str(addr) # message printed for connection success

    while True:  # infinite loop to exchange message with client

           data = c.recv(1024)            # receiving if any data send by client
           if not data:                          # checking if data exists, this condition is only false when 
                   break                         # client program terminates. 
                   

           print "Data recieved from user: " + str(data)
           print "Sending data to client"
          data = str(data).upper()              # received data converted to  uppercase.
          c.send(data)                               # received data send to client

       c.close()                                       # connection closed.

if __name__ == '__main__':              # Main is not called automatically but with this statement.
 Main()



2. tcpClient.py.

   TCP client takes host ip and host port  to connect (server binds and client connects). It asks input 
   from user (message) and it is send to the server until user enters quit in input. 


import socket

def Main():

 host = "127.0.0.1"
 port = 5000

 s = socket.socket()
 s.connect((host,port))                                          # Connects to server host and port.

 message = raw_input("==>")                             # Input from user.

 while message!= "quit":                                    # Loop until user enters quit

      s.send(message)                                           # Entered message send to server.
      data = s.recv(1024)                                      # Received data from server as response.
      print "Message from server: " + str(data)    # print the received message
      message = raw_input("==>")                      # Waits for the next user input

 s.close()                                                            # socket closed.

if __name__ == '__main__':                                                     
 Main()

------------------------------------------------------------------------------------------------------------------------------------

#python #pythoprogramming #pythoscript #socketprogramming

Friday, 26 June 2015

Export oracle data to Microsoft Excel from Oracle forms.


 
A few days back I have been requested 
by one of my youtube viewer to make 
an oracle forms tutorial that will 
exports oracle database data to excel 
file with a single button click. 
Alas.. I am not talking about exporting 
data to CSV, but instead exporting 
directly to excel file. This has a 
few advantages. You can place your 
data in your desired format. Format 
your cell, with colors, style, and 
other excel features. So just go 
through this code given below, 
you can also copy paste the code, all you need to change is the column heading 
and sql string as per your requirement. It have nothing but one forms in-build 
package ole2.
 

declare
 application ole2.obj_type;
 workbooks ole2.obj_type;
 workbook ole2.obj_type;
 worksheets ole2.obj_type;
 worksheet ole2.obj_type;
 cell ole2.obj_type;
 arglist ole2.list_type;
 row_num number;
 col_num number;
 fontObj ole2.obj_type;
 cursor rec is select emp_code,emp_name,to_char(date_of_birth,'dd/mm/rrrr') date_of_birth from employee_master where date_of_birth is not null;
 procedure SetCellValue(rowid number,colid number,cellValue varchar) is
 begin
  arglist := ole2.create_arglist;
  ole2.add_arg(arglist,rowid);
  ole2.add_arg(arglist,colid);
  cell:= ole2.get_obj_property(worksheet,'Cells',arglist);
  fontObj := ole2.get_obj_property(cell,'Font');
  ole2.destroy_arglist(arglist);
  ole2.set_property(cell,'value',cellValue);
  ole2.set_property(fontObj,'Size',16);
  ole2.set_property(fontObj,'BOLD',1);
  ole2.set_property(fontObj,'ColorIndex',7);
  ole2.release_obj(cell);
 end SetCellValue;
 procedure app_init is
  begin
   application := ole2.create_obj('Excel.Application');
   ole2.set_property(application,'Visible',true);
   workbooks := ole2.get_obj_property(application,'workbooks');
   workbook := ole2.invoke_obj(workbooks,'add');
   worksheets := ole2.get_obj_property(application,'worksheets');
   worksheet := ole2.invoke_obj(worksheets,'add');
   ole2.set_property(worksheet,'Name','Emp Sheet');
 end app_init;
 
 procedure save_excel(path varchar,filename varchar) is
  begin
    OLE2.Release_Obj(worksheet);
    OLE2.Release_Obj(worksheets);
    -- Save the Excel file created
    If path is not null then
       Arglist := OLE2.Create_Arglist;
       OLE2.Add_Arg(Arglist,path||'\'||file_name||'.xls');
       OLE2.Invoke(workbook, 'SaveAs', Arglist);
       OLE2.Destroy_Arglist(Arglist);
    end if;
 end save_excel;

 begin
  app_init;
    row_num:=1;
    col_num:=1;
    SetCellValue(row_num,col_num,'Emp Code');
    col_num:=col_num + 1;
    SetCellValue(row_num,col_num,'Emp Name');
    col_num:=col_num + 1;
    SetCellValue(row_num,col_num,'Date of Birth');
    for i in rec loop
     row_num:=row_num + 1;
     col_num:=1;
     SetCellValue(row_num,col_num,i.emp_code);    
     col_num:=2;
     SetCellValue(row_num,col_num,i.emp_name);    
     col_num:=3;
     SetCellValue(row_num,col_num,i.date_of_birth);    
    end loop;    
   save_excel('d:\excel_export','emp_data');       
    OLE2.Release_Obj(workbook);
    OLE2.Release_Obj(workbooks);
    OLE2.Release_Obj(application); 
end;

Sunday, 31 May 2015

Using Google Map Geolocation API with AngularJS..

When I first start working on google map  for Angular JS, excitement went through my nerves and started realizing how angular js made everything so simple. This is probably the second one on google map and I came to learn about this from one of JSFiddle. So I have tried to make a little modification and finally came out with this.
This module contains two utilities. 1. Finding your current location 2. Searching a particular location. Markers are also added with hard-coded array elements containing name of cities and it's coordinates. Filters are also applied to convert decimal coordinated to degree minutes and seconds. I hope you find this angularjs tutorial helpful.

<!-- HTML module -->

<!DOCTYPE html>
<html>
<body ng-app="app" ng-controller="appCtrl">
<script
    src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<script
    src="http://maps.googleapis.com/maps/api/js?sensor=false&language=en"></script>
  <script type="text/javascript" src="geoLoc.js"></script>
<h3>Google Maps</h3>

    <!-- search/go to current location -->
    <div class="text-right">
        <div class="input-append text-right">
            <input type="text" ng-model="search"/>
            <button class="btn" type="button" ng-click="geoCode()" ng-disabled="search.length == 0" title="search" >
              &nbsp;<i class="icon-search"></i>Where is this place?
            </button>
            <button class="btn" type="button" ng-click="gotoCurrentLocation()" title="current location">
              &nbsp;<i class="icon-home"></i>Where am I now?
            </button>
        </div>
    </div>

    <!-- map -->
    <app-map style="height:400px;margin:12px;box-shadow:0 3px 25px black;"
        center="loc"
        markers="cities"  >
    </app-map>

    <!-- current location -->
    <div class="text-info text-right">
        {{loc.lat | lat:0}}, {{loc.lon | lon:0}}
    </div>

    <!-- list of cities -->
    <div class="container-fluid">
        <div class="span3 btn"
            ng-repeat="a in cities"
            ng-click="gotoLocation(a.lat, a.lon)">
            <b>{{a.place}}</b>: {{a.desc}}
        </div>
    </div>
</body>
</html
/* JS module */

var app = angular.module("app", []);

app.controller("appCtrl", function ($scope) {

    // current location
    $scope.loc = { lat: 23, lon: 79 };
    $scope.gotoCurrentLocation = function () {
        if ("geolocation" in navigator) {
            navigator.geolocation.getCurrentPosition(function (position) {
                var c = position.coords;
                $scope.gotoLocation(c.latitude, c.longitude);
            });
            return true;
        }
        return false;
    };
    $scope.gotoLocation = function (lat, lon) {
        if ($scope.lat != lat || $scope.lon != lon) {
            $scope.loc = { lat: lat, lon: lon };
            if (!$scope.$$phase) $scope.$apply("loc");
        }
    };

    // geo-coding
    $scope.search = "";
    $scope.geoCode = function () {
        if ($scope.search && $scope.search.length > 0) {
            if (!this.geocoder) this.geocoder = new google.maps.Geocoder();
                  this.geocoder.geocode({ 'address': $scope.search }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    var loc = results[0].geometry.location;
                    $scope.search = results[0].formatted_address;
                    $scope.gotoLocation(loc.lat(), loc.lng());
                } else {
                    alert("Sorry, this search produced no results.");
                }
            });
        }
    };

 $scope.cities = [
              {
                  place : 'India',
                  desc : 'A country of culture and tradition!',
                  lat : 23.200000,
                  lon : 79.225487
              },
              {
                  place : 'New Delhi',
                  desc : 'Capital of India...',
                  lat : 28.500000,
                  lon : 77.250000
              },
              {
                  place : 'Kolkata',
                  desc : 'City of Joy...',
                  lat : 22.500000,
                  lon : 88.400000
              },
              {
                  place : 'Mumbai',
                  desc : 'Commercial city!',
                  lat : 19.000000,
                  lon : 72.90000
              },
              {
                  place : 'Bangalore',
                  desc : 'Silicon Valley of India...',
                  lat : 12.9667,
                  lon : 77.5667
              }
          ];   
});

// formats a number as a latitude (e.g. 20.46... => "20°27'44"N")
app.filter('lat', function () {
    return function (input, decimals) {
        if (!decimals) decimals = 0;
        input = input * 1;
        var ns = input > 0 ? "N" : "S";
        input = Math.abs(input);
        var deg = Math.floor(input);
        var min = Math.floor((input - deg) * 60);
        var sec = ((input - deg - min / 60) * 3600).toFixed(decimals);
        return deg + "°" + min + "'" + sec + '"' + ns;
    }
});

// formats a number as a longitude (e.g. -80.02... => "80°1'24"W")
app.filter('lon', function () {
    return function (input, decimals) {
        if (!decimals) decimals = 0;
        input = input * 1;
        var ew = input > 0 ? "E" : "W";
        input = Math.abs(input);
        var deg = Math.floor(input);
        var min = Math.floor((input - deg) * 60);
        var sec = ((input - deg - min / 60) * 3600).toFixed(decimals);
        return deg + "°" + min + "'" + sec + '"' + ew;
    }
});

// - Documentation: https://developers.google.com/maps/documentation/
app.directive("appMap", function () {
    return {
        restrict: "E",
        replace: true,
        template: "<div></div>",
        scope: {
            center: "=",        // Center point on the map (e.g. <code>{ latitude: 10, longitude: 10 }</code>).
            markers: "=",       // Array of map markers (e.g. <code>[{ lat: 10, lon: 10, name: "hello" }]</code>).
            width: "@",         // Map width in pixels.
            height: "@",        // Map height in pixels.
            zoom: "@",          // Zoom level (one is totally zoomed out, 25 is very much zoomed in).
            mapTypeId: "@",     // Type of tile to show on the map (roadmap, satellite, hybrid, terrain).
            panControl: "@",    // Whether to show a pan control on the map.
            zoomControl: "@",   // Whether to show a zoom control on the map.
            scaleControl: "@"   // Whether to show scale control on the map.
        },
        link: function (scope, element, attrs) {
            var toResize, toCenter;
            var map;
            var currentMarkers;

            // listen to changes in scope variables and update the control
            var arr = ["width", "height", "markers", "mapTypeId", "panControl", "zoomControl", "scaleControl"];
            for (var i = 0, cnt = arr.length; i < arr.length; i++) {
                scope.$watch(arr[i], function () {
                    cnt--;
                    if (cnt <= 0) {
                        updateControl();
                    }
                });
            }

            // update zoom and center without re-creating the map
            scope.$watch("zoom", function () {
                if (map && scope.zoom)
                    map.setZoom(scope.zoom * 1);
            });
            scope.$watch("center", function () {
                if (map && scope.center)
                    map.setCenter(getLocation(scope.center));
            });

            // update the control
            function updateControl() {

                // update size
                if (scope.width) element.width(scope.width);
                if (scope.height) element.height(scope.height);

                // get map options
                var options =
                {
                    center: new google.maps.LatLng(23, 79),
                    zoom: 6,
                    mapTypeId: "roadmap"
                };
                if (scope.center) options.center = getLocation(scope.center);
                if (scope.zoom) options.zoom = scope.zoom * 1;
                if (scope.mapTypeId) options.mapTypeId = scope.mapTypeId;
                if (scope.panControl) options.panControl = scope.panControl;
                if (scope.zoomControl) options.zoomControl = scope.zoomControl;
                if (scope.scaleControl) options.scaleControl = scope.scaleControl;

                // create the map
                map = new google.maps.Map(element[0], options);

                // update markers
                updateMarkers();

                // listen to changes in the center property and update the scope
                google.mapTypeIds.event.addListener(map, 'center_changed', function () {

                    // do not update while the user pans or zooms
                    if (toCenter) clearTimeout(toCenter);
                    toCenter = setTimeout(function () {
                        if (scope.center) {

                            // check if the center has really changed
                            if (map.center.lat() != scope.center.lat ||
                                map.center.lng() != scope.center.lon) {

                                // update the scope and apply the change
                                scope.center = { lat: map.center.lat(), lon: map.center.lng() };
                                if (!scope.$$phase) scope.$apply("center");
                            }
                        }
                    }, 500);
                });
            }

            // update map markers to match scope marker collection
            function updateMarkers() {
                if (map && scope.markers) {

                    // clear old markers
                    if (currentMarkers != null) {
                        for (var i = 0; i < currentMarkers.length; i++) {
                            currentMarkers[i] = m.setMap(null);
                        }
                    }

                    // create new markers
                    currentMarkers = [];
                    var markers = scope.markers;
                    if (angular.isString(markers)) markers = scope.$eval(scope.markers);
                    for (var i = 0; i < markers.length; i++) {
                        var m = markers[i];
                        var loc = new google.maps.LatLng(m.lat, m.lon);
                        var mm = new google.maps.Marker({ position: loc, map: map, title: m.name });
                        currentMarkers.push(mm);
                    }
                }
            }

            // convert current location to Google maps location
            function getLocation(loc) {
                if (loc == null) return new google.maps.LatLng(23, 79);
                if (angular.isString(loc)) loc = scope.$eval(loc);
                return new google.maps.LatLng(loc.lat, loc.lon);
            }
        }
    };
});


You can also find the code in : Google Drive

And can also check out for the video tutorial on : Youtube - Using Google Map Geolocation API with AngularJS

Google Maps



{{loc.lat | lat:0}}, {{loc.lon | lon:0}}

{{a.place}}: {{a.desc}}