I wrote my previous article about python and python flask. It is needed for this tutorial. So if you are not followed it yet link is [1].
If you already familiar with python and if you already setup your machine for it no need of following it. As mentioned in the title I am going to show you how to implement simple SMS application within few minutes.
First of all it's better to download or clone the source code by using [2] URL.

Now you can see the project structure is same as my previous tutorial. So open the terminal in the location of above source code and type below command.
python app.py

Now server should start if you followed above steps correctly.
After this, You need to start IdeaMart simulator on your machine. Hope you already aware of it. If not you can go through my previous tutorial using [3] link.
After you run IdeaMart simulator using [4] URL, Open the SMS tab and add [5] to URL box in Application data.
Now it's time to test the application. You can send sms with your full name.
Ex - Tharinda Dilshan

Then the results should be appeared.

Now let's move into the implementation.

import logging
import urllib2

from flask import *

app = Flask(__name__)
app.debug = True


@app.route('/')
def hello_world():
    return render_template("index.html")


@app.route('/smsReceiver', methods=["GET", "POST"])
def sms_receiver():
    """
    This method is to retrieve request came from ideamart simulator of dialog and send sms message
    :return:
    """
    if request.method == "GET":
        response = make_response("Telco App is running")
        response.headers['Content-Type'] = 'application/json'
        response.headers['Accept'] = 'application/json'
        return response
    else:
        ideamart_message = json.loads(request.data)
        name = ideamart_message["message"].split(" ")[1]
        res = {'message': "Hi, " + name,
               "destinationAddresses": ideamart_message["sourceAddress"],
               "password": "password",  # This should be replaced with your ideamart app password
               "applicationId": ideamart_message["applicationId"]
               }

        # URL should be  changed to https://api.dialog.lk/sms/send when you host the application
        url = "http://localhost:7000/sms/send"
        req = urllib2.Request(url, data=json.dumps(res),
                              headers={"Content-Type": "application/json", "Accept": "application/json"})
        response = urllib2.urlopen(req)
        ideamart_respones = response.read()
        logging.error("Result content: " + ideamart_respones)

        if response.getcode() == 200:
            logging.info('*** Message delivered Successfully! ****')
            response = make_response("Message delivered Successfully!")
            response.headers['Content-Type'] = 'application/json'
            response.headers['Accept'] = 'application/json'
            return response
        else:
            logging.error(
                '*** Message was not delivered Successfully!! ERROR-CODE: ' + str(response.getcode()) + ' ****')
            response = make_response("Message was not delivered Successfully!")
            response.headers['Content-Type'] = 'application/json'
            response.headers['Accept'] = 'application/json'
            return response


if __name__ == '__main__':
    app.run(host="localhost", port=5000)


Above code is used to run the whole application. Basic functions related to flask framework is explained in my previous tutorial. Hope now you aware of it. When you click send button in ideamart simulator it will send a post request to the URL [5] that is mentioned above. As you can see in the program that request is handled by the function named as sms_receiver. The request message is taken as a variable called ideamart_message. After that, It is split into parts and send the response back to URL [6].

[6] URL should be changed when you host this application. The request should be send as a JSON request and headers should be added as you can see in the program. After sending the request, The response message which will be sent by the simulator can be seen as a log message in the running program console.

That's it! Hope this will help you.
Thanks for reading :)

If you have any problem, feel free to leave a comment and I appreciate any feedback.

For more info and to contact me go to my website.

[1] - https://tharindaehelepola.blogspot.com/2016/05/simple-web-application-using-python.html
[2] - https://github.com/tharinda221/ideamart-sms-application-python
[3] - https://tharindaehelepola.blogspot.com/2015/12/ideamart-simple-application-in-java.html
[4] - http://localhost:10001/
[5] - http://localhost:5000/smsReceiver
[6] - http://localhost:7000/sms/send

Python is awesome programming language. Anyone can learn it easily because its syntax is very simple. Because of that Most of scientist are choosing it for their researches. So that variety of packages available for different areas like image processing, machine learning, AI, etc. Building a web application using python is very import because above mentioned libraries are supported for python other than any other programming language.

In this tutorial I am going to show you how to build a simple web application using python. For that I am going to use flask as a web framework. The reason of using flask is it is easy to use and also it is a micro web framework with lot of features. In order to implement the application you should install python for your computer. I am going to use python 2.7 for this tutorial. For Ubuntu Machines python 2.7 is installed by default.

For windows machines,

Download python 2.7.11 using below link and install it to your computer.
https://www.python.org/ftp/python/2.7.10/python-2.7.10.msi

Then you have to configure the environment variables. If you are not aware of it, Use the below link.
http://www.computerhope.com/issues/ch000549.htm
You should add below line to the path variable.
C:\Python27\;C:\Python27\Scripts\        

Now have python on your computer. Then you have to install flask library to your computer. In order to do that you need to install python PIP to your machine.
For Linux users,
sudo apt-get -y install python-pip

For Windows users,
Go to the below link and select all the text in the page. Open the notepad and paste the text into it and save it as "get-pip.py".
https://bootstrap.pypa.io/get-pip.py
After that open the command prompt in the saved location and type,
python get-pip.py

Now you have python PIP on your computer. In order to install python-flask, Open the command prompt and type,
pip install flask

Now you have python flask on your computer. Now we can moving to the implementation part. I have implemented the application and you can clone it or download it using below link.
https://github.com/tharinda221/simple-flask-web-application
When you download the application exact it. Then open command prompt in the file location and type,
python simple-flask-web-application.py

If you followed above steps correctly below screen should be appeared.

According to the figure server is started at port 5000. If you type below URL on your favorite web browser index page will be appeared.


Now I am moving to the implementation. I have used Pycharm 2016 as a IDE. I recommended it if you are building complex applications in python. In the source code folder there is a file called simple-flask-web-application.py which is included all the implementation. I will go through its line by line.

from flask import *

app = Flask(__name__)


@app.route('/')
def hello_world():
    return render_template("index.html")


if __name__ == '__main__':
    app.run(host="localhost", port=5000)

In the first line flask library is imported. Then the second line is to initiate the application. That means create a Flask instance, in your main module. The idea of the first parameter is to give Flask an idea what belongs to your application. This name is used to find resources on the file system, can be used by extensions to improve debugging information and a lot more. The next line is connected a URL rule. Simply we can say when a request came to the "/" URL it will render "index.html" which is located in the template folder. The next line is to start the application. Host and port values are configured in the program itself. Hope you understand the tutorial. Likewise, We can create a web application using python flask in less amount of time and also you can create more advance applications using python.

IdeaMart

Ideamart is a platform presented by Dialog Axiata PLC to developers and content providers to use the Dialog network based features via shared APIs and monetize their efforts.

Hope you have an idea about what ideamart is. ideamart is a vast popular platform these days. I have seen lot of television advertisements also. But in the mean time I was unable to find any web application (website) which have  used ideamart APIs. So this tutorial will guide you how to use ideamart APIs in a web application. I am using basic java, JSP, servlet for this tutorial. You can extend it to any other framework like spring, vaadin, etc. This tutorial will guide you to implement following scenarios.
  • Receiving a message
  • Sending a message
  • Displaying received messages in a html page     
Prerequisites 
  • java 1.8
  • ideamart simulator 
  • apache tomcat 8
  • apache maven 3
  • IDE  (I am using intellij idea) 
Hope you are familiar with the above stuff. First you need to download or clone the repository. 
after downloading it you can open your favorite IDE and import the pom.xml file. It will download all the dependencies. To run the program you have to configure apache tomcat to your IDE 

How to configure apache tomcat in IntelliJ IDEA

Implementation 

Below image is displaying the source code structure after all the above configurations.
     
receive - This package is to handle the receiving messages. To receive a message and to send a message you need a library given by the ideamart. It is included in the resources directory. By implementing the MoSmsListener class you can handle the receiving messages. I hope you can easily understand it when you look at the Receive class implementation. receiving message URL is configured in the web.xml file. 

operations - when you receive a message you can do any operation for that. In this tutorial I am splitting it and put it into a hashmap. You can do any other operation you need.    

send - This package is to send messages to particular number. SmsRequestSender class can be used for that. 

db - This package is used for database operations. For this implementation i am using a hashmap. You can use any other database like sql or nosql. 

I hope you got some idea about the implementation. Now you are free to run the application. Before you run the program please make sure that all the libraries are included into the artifacts.
For that If you use intellij idea press Shift+ CTRL + ALT + S and then you can see the project structure.
It looks like below.
In the above picture both selected library and the other one are not in the artifacts. To add those into it right click on it and select "put into WEB-INF/lib" 
Then you can start the server and the ideamart simulator. 
You can see the index page and ideamart simulator like below.

                                                                                                             

URL - http://localhost:8080/Receiver
This URL is configured in the web.xml. In this tutorial I am going to get the name and the message with application name as a message. So your message format should have above three details.
ex - <app name> tharinda mymessage

Now you can send this message and wait for the response. When the response message came reload the index page and you will get the result below.
That's it! Hope this will help you. 

Thanks for reading :)

If you have any problem, feel free to leave a comment and I appreciate any feedback. 

For more info and contact me go to my website.

Project can be categorized to my free lancer career. Identifying the distance of a object by using image processing is currently on research level when we considering very accurate value. In this project I have succeed to measure a distance of a object by mapping to points get by user inputs. I used python as a programming language and opencv as a framework for image processing.

Use cases are shown below to measure a distance of two points.

  • Image should be added as a input
  • User should be clicked to point if he/she wants to measure length     
When a user clicks a point its coordinates can be get using image processing techniques. It's not that much difficulty to locate. Image can be considered as a 2d matrix. That means if it is a pixel * b pixel image it can be represented as a a * b matrix. When a user clicks a point its coordinates can be identified by using above mentioned matrix.       

Example

[  .  ] 
[ . . ]
[. . .]

        This image can be represented as a matrix by assigning 255 for black dot and 0 for white dot. According to the above definition image can be represented as below.

[0 0 255 0 0]
[0 255 0 255 0]
[255 0 255 0 255]

Hope you get the better idea about that. So after user clicks two point I calculated the euclidean distance of those two points. Then by using that how can we calculate the actual length.

I solved it using pre-defined value. In order to calculate it I followed below steps.

  • Camera to object distance should be a constant (2 m). I will explain it later.
  • Capture a image of a object.
  • Measure a length of known two points. 
  • Entered above captured image as a input to the program.
  • Calculate its euclidean distance.     
Then we can define a small equation for known euclidean distance. Below variables can be used to represented it.

a - Actual length of known two points
e - Euclidean distance of known two points calculated from the image array (Describe above)
y-  Euclidean distance of unknown two points calculated from the image array 
x - Length of unknown two points 

Equation can be generated according to the above variables.

a / e = x / y

Therefore, x = y * ( a / e )

The value of ( a / e ) is a constant.
So , ( a / e ) = c

x = y * c

If you carefully read my article you are able to realized that you can get very accurate distance for this image.
But the problem is how can we use this equation and the constant for all images that input for the application. 
We defined above constant using a ratio. It's depend on distance of the camera and the object. In order to use this constant for all the images distance of camera to object should be a constant.
That's why I mentioned it above.

Now you should have a problem about this. In order to get the euclidean distance each pixel should be represented to the user to get input click. The problem is if user inputs a image with large number of pixels (Ex - 2000 * 3000) screen is not enough to represent it.

As a solution for the above problem I had to reduced the pixel size of the input image. But this can be harm for our constant. So when you define the constant this step should be added to the above flow too. And the import thing is this reducing factor should be a constant for all the input images. Otherwise our constant not be a constant any more. 

By using below link you can download my source code from GitHub and you can test it using your own input images.
But there is a problem which still not solved. I used a decimal factor for the reducing image pixel size because most of the images lay with 2000 * 3000 pixel size. That's a assumption. So If you input a image with low pixel size my calculations can be wrong. So when you input a image please remember to re-size it to above mentioned pixel size.         

Complete Application - youtube
Spring can be used for pass objects through server to web page. In this article I am going to implement a HTML form as a data source. A java class can be created as a POJO(Plain Over Java Object) for assign the details of the input source. Form details can be assigned to a object and it can be passed to the another HTML page.

For the above task I used

1. Intellij idea
2. Java JDK 1.8
3. Maven 3.0

This Video will guide you how to create a simple application using spring MVC. Then you can gain some brief idea about how spring MVC works.

Here is the implementation for complete the above task.You can clone it or download it. You have to use a tomcat,glassfish or any other container for run this. Code included two main classes. greetMsgMoel class is act as a model and HelloControler  class is act as a controller. If you go through the implementation you can gain some idea about what's happening there. Both Home and simpleForm jsp files are handled by the controller. When you run the program it will scan the input and after you submit it the text you typed will display in another page.

I have used selenium web driver for testing.

" WebDriver is a tool for automating web application testing, and in particular to verify that they work as expected. It aims to provide a friendly API that's easy to explore and understand, easier to use than the Selenium-RC (1.0) API, which will help to make your tests easier to read and maintain."

This is what wiki says about WebDriver.
For further details here is the documentation of the selenium web driver.
http://www.seleniumhq.org/docs/03_webdriver.jsp

Here is the implementation for the above task. You can clone it or download it. First you need to run the spring application  which you have to test. Then you can add the localhost url to the testing implementation for testing. After that you have to run the testing implementation and it will open the firefox window and automatically go to the url of the web application. In the testing implementation I have added some test cases. So program will submit those test cases to the text box and then it will test if the submitted text is equal to the passed text.
If you need to gain some knowledge about spring MVC and selenium webDriver I hope this article can be useful to you.

The requirement of the project is to create a blogging platform that allows users (admins) to create & manage content,
approve public comments and track site statistics

Design
The major specifications were:

  • Admin is able to register/create new users/admins
  • Links to the most recent posts (10 or so) are shown in the homepage
  • Admin can create and edit posts
  • A post contains a title, post text and a unique id, which corresponds to its direct URL
  • The comments added by the public and approved by any admin will be shown in the post
The Design


We used JSON files for each post to store their titles, text, comments, author names and view counts. These were
accessed and viewed (and changed) through servlets and JSPs as needed.
The required core functions were completed. Also the statistics for each post can be viewed.
Form based authentication (instead of Basic auth at its simplest level) was used so that it would be easier to the user
and can be changed to fit the appearance of the site while the credentials can be accessed through JavaScript.

Implementation
Workflow

URL Handler Auth Functionality
/ index.jsp None Shows the posts (10 max) in reverse order. Has buttons for logging-in, adding posts, viewing statistics
/ClickedPost?id=19 ClickedPost (servlet) None Shows the plaintext (or HTML) of the post with title and a comment box
/PendingComments PendingComments (servlet) None Stores the new comment in the corresponding JSON file but does not show it yet in the post
/newpost/approval.jsp approval.jsp FORM Shows the list of posts which point to the comments-approval page
/newpost/Approval?id=19 Approval (servlet) FORM (above) Shows the authoring admin name, a button to view the pending comments and a link to edit the post
/ index.jsp None Shows the posts (10 max) in reverse order. Has buttons for logging-in, adding posts, viewing statistics
/ index.jsp None Shows the posts (10 max) in reverse order. Has buttons for logging-in, adding posts, viewing statistics
/newpost/commentsApproval commentsApproval (servlet) FORM (above) Shows the list of approval-pending comments with checkboxes to approve and a submit button
/newpost/edit editPost (servlet) FORM(above) Shows textboxes to edit the current title and text of the post with a submit button
/newpost/commentsApproval commentsApproval (servlet) FORM (above) Shows the list of approval-pending comments with checkboxes to approve and a submit button
/statPost?id=19 statPost (servlet) None Shows the corresponding post’s title, its total view count and the number of comments
Security


Authentication
We used form authentication to authorize the admins/writers at the loggin-in page (see above). The admins need to

add the entry for the users at tomcat-users.xml.

Non-standard Libraries Used

  • json-simple/simple-json was used for accessing (change & read) post JSONs
  • As the name suggests and with similar requirements of the system, this seemed sufficient
  • Plaintext or CSV files and even XML formats were considered, but eventually this was selected becuase it seemedmuch more simpler

GIT- https://github.com/tharinda221/BloggingSystem

Our Project


Using Android devices communication can be done with 2 or more parties using this application. This project is on developing an android “walkie talkie” app to send voice to other android devices using multicast methods.

How it’s done



This is our design structure. We added five classes. There are shown in the bottom level. Initially the devices you want to communicate should be connected to the same wi-fi network before opening the app. If not the application would not work. All the devices which are in the wifi network and running the app are able to hear and talk.
This is one – to many broadcasting mode.One to one transmitting is simply can be done using above mode.


Record- Records audio and puts it to a queue. Interrupts and waits if pauses.
Play- Plays the audio. Interrupts and waits if pauses.
Client- Receives multicast packets. Resolves and takes to a queue. Makes the stream.
Server- Creates packets to send with the maximum buffer size.Uses multicasts the packets. Uses thread to create and send packets.
AudiocastActivity-Handles the ui Opens new threads for play.java and record.java when buttons are pushed and starts receiving and playing.

Future development.

  •  As the core implementation is successful future development mostly developing the ui class.
  • Developing a Nicer interface.
  • Developing interface such that it works as an actual walkie talkie.      
  • actual walkie talkie enable only one side communication at once. Our implementation is more duplex. By changing the ui it can be achieved.
  • Clearing the audio.



Powered by Blogger.