Friday, April 15, 2016

LIFE EPISODE 2 : ALIEN


How should I go with this ...Should I write this as play ...or should I write a story....

Lets try PLAY.


Scene 1)

Pitch Dark : Someone sitting in a corner , Place seems to be like a space observatory lab.

Faint blue and green light coming out from Monitors. Constant buzzing sound from all the machinery running.

Slowly , Slowly voice can be heard more clearly, the person is talking to himself.

 Unknown@thispoint " What the hell is wrong with us , now a days ? We waste so much money trying to find some alien life...as if we treat our fellow beings nicely . What is they come and conquer us , or eliminate us....why not focus on something on hand"

Stares at the giant screen in front wall, which is displaying some orbits and some numbers are constantly changing at left bottom corner.

Start whistling in low tune, makes action as if enjoying the tune he is playing. Stares at the watch in front, its  14 AM in the morning, still  7 hours to go before sun is out and his shift will end.


Scene 2)

9 AM in morning , sky is bright red , in middle of a place which seems to be desert , there is a building, only top of the building which is dome-spaced is coming out of land.

Faint voices can be heard :

Voice 1)  " Is it possible ?"

Voice 2) " You tell me ? You are the genius ...what do you make of this "

Voice 1) " There has to be some glitch....our satellite has passed that place so many times but we never got anything"

Voice 2) " Is it possible, that something might have come now ? "

Voice 1) " Thats impossible ....our other satellite would have picked it up if that thing entered our zone....Its as if it appeared out of no-where"

Voice 2) " So you believe in magic "

............No reply ..........

Voice 2) " So what to be done next ?"

Voice 1) " Well ....we can inform everyone or we can see how long this thing is visible on our radar"

Voice 2) " I am more comfortable with first option , Answering questions once this thing disappears will be more difficult"


Scene 3)

Inside something which appears like a spacecraft, 2 MEN discussing something.

Man 1) " I think they know we are here "

Man 2) " Hmm ."

Man 1) " But why are they not trying to contact us ? "

Man 2) "Mayb ..they are deciding whats needs to be done "


Scene 4) 

Inside the dome ...multiple voices can be heard and also someone humming.


Voice 1) " I think we should invite him  ?"

Voice 2) " Invite ...seriously ...we don't know anything about them...their intentions...their capabilities.......We should put them in quarantine "

Voice 3) " They might consider that to be hostile act "

Voice 2) " But we need to take adequate precautions "

Humming stops ...Voice 4)  " Why not simply contact them and ask who they are ...where are they from "

  Sound of keyboards buttons being clicked in fast manner.....

Voice 4)  " They don't understand any of our languages "

Voice 2) " Hmm ..try images for communication"

Voice 1) " What are the chances , that meaning of images will be same in our world and theirs "

Voice 4) " I think either they don't understand our images or we are not getting them...I send them smiling face ...and they have send something ...which I haven't seen before...what type of creature is this "


Voice 1 , 2, 3  In unisone)  " What is that "  ....."what is ..................."


Voice 4) " What to be done now ???"

Voice  1) " Let send them some video of our world ...which tell them our way of eating, love , dress , vehicles "

Voice 4) " That might make sense to them"  

keyboards button types in quick succession

Voice 4) " HA HA ...i think they got us ...they have also send some video .....Is that how they eat ....there vehicles are so outdated...Is that ....their female species ??????


Scene 5) 

Spacecraft seems to be landing near dome ... Two men  descending.  A small door in dome opens ...4 shadows falls on ground ...whose lengths start to reduce.

The two men looks at the 4 person in front of them and are startled.   They have one Big Eye and one Small eye ....they are half of them in height...No protuding ears ...long arms ...at end of whose there is web.


MEN 1  to MEN 2 )

" It seems that rather than they coming to our world......we have arrived in theirs "
 



END of PLAY ......A picture of alien will help





Thursday, April 14, 2016

Threads - Android Part -1


Its 00:00 AM , my new favorite time to blog.
Also I am fasting ...NAVRATRI ongoing, and I am very hungry but have to wait till morning.


Now the tittle isn't do justice on what I am going to write. Since it will be series of articles only after that we can have more clear picture of Android Threads.


Basically what happened , I am learning Android and was making Server-Client Chat app. Lot of code I got from google....but as I am working more on it , more questions are pouring in.


Coming straight to topic.  Below is very simple Android code.  It has one button and one textbox.

Also it has only one ACTIVITY i.e one screen, on which our button and textview will be visible.

Now the code I have written like below .


package com.example.chetannrathore.testapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView tv;
    Button bt;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv =(TextView) findViewById(R.id.textView);
        bt=(Button) findViewById(R.id.button);

        tv.setText("before");

        bt.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
               tv.setText("inbetween");
            }
        });

        tv.setText("after");


    }
}


Now when I run the application, on screen I am seeing AFTER being displayed.  Now basically CODE always 
get executed sequentially. 

So after   tv.setText("before") ;      bt.setonClickListener  should get executed. 

Now I was thinking that till we have not pressed the button, the code should be stopped at this point. But it
doesn't happens. 

What happens is ...tv,setTEXT("after")  also get executed. 

So on my screen I can see    after even when button is not pressed. 


So I thought that  button click listener will be running on separate thread.  But that is totally wrong. 


On reading various post, this is what happens. 


Every activity runs on single THREAD  called MAIN thread and also UI thread. 

So even when you have multiple screen application, all of them run on same MAIN thread. 
  --- This needs to be taken care while designing the APPLICATION, else it will be slow --------


Coming back to code,  all the  UI components like button,list,textbox   also known as widget  are part of
VIEW CLASS. 

So when we define button in our application, we are creating a class of it ( which actually android does for us)

We just need to find it and assign it correctly.
             bt=(Button) findViewById(R.id.button);

Now like a normal class, WIDGET CLASS also have methods and interface defined in them.

  For example in case of BUTTON , we have  setOnclickListener method.  This method needs a View object , 
which implements View.OnCLICKListener interface. 

Hence we do  
                                     bt.setOnClickListener(new View.OnClickListener() {

Now if we use interface, we have to implement its methods....in case of onClickListener , that method is
  OnClick hence we write code for that. 

Also , we need to know which button is clicked, hence OnClick has one parameter which is View.

                        public void onClick(View v) {

Now OnClickListener is part of EventListener Interface in Android.  These EventListener 
has callbacks method , for example Onclick.for OnClickListener Interface

Android framework registers these eventlistener interface callbacks. And wheneven a button or
 scrollview or textview is clicked or focused upon,  it calls the respective callback function and also
 passes the VIEW object which is clicked.



In conclusion , whenever we are running Android application , 

APPLICATION MAIN THREAD is running    and   also ANDROID FRAMEWORK always be running. 
If no button is clicked , MAIN THREAD will suspend.

When button is clicked, FRAMEWORK will call the  eventlistener interface function,  which will put MAIN THREAD 
from SUSPENDED state to ACTIVE state.

Once the button functionality is done, again MAIN THREAD will move to SUSPENDED state.

 

Wednesday, April 13, 2016

ASTROLOGY : The old science or new science


Today I was feeling very calm, a perfect flow of energy.  But last two days I was on fire, ready to pick fight.

I was sitting in my room and when looked outside my window , I saw that today moon is half and bloody. This made me wonder , whether my mood swings all governed by moon.

As per my horoscope, moon plays important role , everyone has some planet whose effects will be more dominating than others.

In short ...I am piece of moon :D :D

 But thinking logically and with the information we have in our hand .....even though this will be slight digress from main topic . but I can't help but to bring this point.

*********
Today in office , my friend was telling me that scientist told based on some model, that human cannot  reduce time taken to run 100m  by more than of 9.72s , but then usain bolt did it in 9.58s

They were telling that force which will be exerted in body will be very much for human to sustain, also taller people will have less chance of running fast.

But once usain bolt actually broke the record, scientist would have taken this data in their model and then would have predicted new threshold

******************************


So they thing is , nothing holds true for long. It is simply we have not encountered that and therefore don;t believe in that.

Coming back to main topic.


Now earth rotates , and so do all the planets. Every planet has GRAVITATIONAL force, and this the only force which we know as of now. Currently GRAVITATIONAL force was discovered, which will again change lot of theories, new theories will come, new type of plans will be designed.


So just for sake of argument, let say the force , however tiny does play some kind of role. These all are external forces.  Also since at every moment , considering the vast amount of randomness which will be generated.  { Every planet is rotating and revolving, so at every moment we will have different amount of force coming } .

Don't you think that astrology will be true ????

Suppose I slap you ...which is external force.....but also reaction of person who got slapped will be different per person...some will fight...some will cry....some will be stunned.

So even tough EXTERNAL force is same....we have different reactions.

So as per gravitational law, even though two person at same place will have almost same type of forces exterted upon them,  we cannot guarantee that they will behave or feel same kind of reactions.


So how to validate this ?  DATA ...and LARGE amount of data....if we can save how a person is feeling at same point and see the planetary position at that time ,  after we have large amount of data we can try to see if we are getting some data which is symmetrical ....else if everything is random ...then either we haven't encountered other parameters in our model....or  ASTROLOGY is biggest fraud which every human civilization fall victim to.


Coming to the second part, which is my favorite..... Can future be changed ?

How to see this ???

Scenario 1)  I tell you that today you will feel more angry and should avoid confrontation.
This is based on planet position today .

Very simple and understandable,

Now , we can argue that planet position will not change , hence you will surely feel angry.

But will you fight or not ????

Is your fighting predicted by ASTROLOGY ????

I think this is where most of us ( including me) misunderstand ASTROLOGY, what if it is not a model to predict exactly what will happen, but more of what situation you will found yourself in.



Scenario 2) Most of times we hear astrologers saying that some particular zodiac sign person will face financial loss.


Is that guaranteed ???  Will all the people who fall into one particular zodiac sign, however different ( country living in, their financial status , .....)  will face loss.

I don't think so....but let have some argument.

We can say that job market is better for people working on JAVA , Android and BIG data currently.
So all the people knowing ANDROID will have better chance of changing jobs.

Offcourse no one will argue, even though if we see individual person we will find that the HYPOTHESIS will be made, is not true for everyone.

It same way for ZODIAC sign,  We all know individuals subjected to same type of environment will develop some common habits.

If 100 children are taught dancing when they were small, and 100 more are made to study ....majority of students who were taught dance will have better chance of doing dance better than the group which studied, even though we can't guarantee it to be 100% true.

Same way, when we our born, all the people born in same month or same week, will have some common position of planets , which will develop in them some common characteristics.

Hence they might feel something same. But again the factors are so many, that  PREDICTION made will not hold TRUE on everyone.


Let me conclude this as we move to new DAY . ( its already 00:32 AM)

Astrology doesn't tell future... we have among us people who are VISIONARY ...who sees what is going around them and tell what will sell in future..what is needed in future.

ASTROLOGY is same thing ...it gives you a VISION of your future...but not in terms of what will happen ...but how will you feel ..

So it should not be taken as excuse of what you can't do or acheive ...but how you can be in more control of your feelings/emotions.

But the biggest downfall of human is  their EMOTIONS.

What if I warn you ...that today might bring shame/embarrassment for you .

and then seeing a 100 rupee note laying on a barren road ...wouldn't you be tempted to pick it up ????






Tuesday, April 12, 2016

LIFE - EPISODE 1 . PILOT LOVE


I think few years have been passed.  As I try to remember , actually lot of time has passed, but still I can picture her clearly.
  the spark in her eyes, which made me to turn and look her again.
  her non-stop chit chat, even though half of the time I was not able to catch the speed by which she use to chat , but was happy to look in her eyes which somehow use to speak to me.
  her confidence and trust in me
 
She was not picture-perfect, few pounds extra , but still somehow when I use to be with her, there was a peaceful calmness. Its like with her my soul got connected.

Have you ever observed, when you are thirsty....any drink apart from water will not quench your thirst. It was the same, first our soul got connected , the question of differences never occurred.


Life is very simply yet complicated.  Parents try to do what they think is good for their children, children try to do what good for parents.  Never they sit together and discuss what makes them happy.

Our first fight occurred over a petty matter, ....it seems petty now, on looking back.

She wanted to go home , to see her parents. Me a born recluse, had deep attachment with only one person and hence it appeared terrible to me to be separated from her for 1 week.

Second time we fought when she came back from home and told me she didn't enjoy her stay.
How can you say a person that he is correct after not listening to him ?
Yet within one month she again went home , even though for just 2 days.

I met within an accident, a minor one, just some bruise on hand and leg.  I can't tell my family as they will get worried about me. Friends, all they say is  LARGER wounds were inflicted on MAHARANA PRATAP...........assholes,

I miss her, she would have taken care of me.

I remember , even though it was just bad cold and fever, she made it sure I was taking steam , taking my medicines at correct time.


What went wrong ....mayb the small things which no one care to observe. We are too busy to see only the big details.



COM port and Linux : Part 1



There was a post written about Serial Port communication, this is continuation of that.

Recap:

Serial communication is mechanism of sending data from one device to another. One bit at a time( Well its quite misleading)

The H/W part is RS-232 , which tells about the voltage to be used and other electronic stuff.
Then there is UART  which is software part which tells how data will be converted to bits, how many bits will be required and how to determine the bit-rate.

So COM port is written on top of UART, this is how you will read data and use it.

When you connect your phone to laptop/pc.  In device manager you can see COM port will be present. ( MODEM device is also seen, which will be some COM port).

See the pic below,  MODEM device is showing in Device manager.

On further clicking it and going to MODEM tab,  we can see  COM91 is COM port.

***COM stand for communication*************



Using tools like tera term  , we can send data to MODEM or to any device connected to COM port.

In case of modem, it understands  AT cmds.  So if we pass AT cmds we can see response.

Pic below.

As can be seen, I have selected COM91.
RED text shows data send, and blue the reply from Modem.




In linux, also we can use socat to send data to COM port.

Step  1) Connect the device to laptop/pc.
           
In linux, all the connected device are shown as device file, which are present under /dev folder.
You can use below command to see any external device.

> dmesg | grep tty

For me , 4 devices are showing .  ttyACM*



Step 2) Before sending data , we have to connect with these device file.  In my case ttyACM1 is correct file.  You can try connecting to each device and see which sends response.

Only root has permission to use these files, so we need to change their permission .

> chmod 777  /dev/ttyACM1   // You have to login as root in terminal to run this command.

Step 3) run socat

>  socat  -  /dev/ttyACM1

then type AT cmd needed.                                // See pic below




So this was in short about COM/serial port.  Actually I was trying to learn serial port programming, which doesn't seems to be very tough.  But debugging will be required.

So instead of modem, I will use my Arduino for it, as I can see what data is received.

Sunday, April 3, 2016

X-Files ; Sockets 3rd and last ; TESLA car


Finally this is last of Sockets, in this I am attaching the zip file of Server and Client Code.

Server will open a server socket and listen to client connection.

Client will open a connection with Server and wait for any input data.

server will send "Hello from Server" to client.

The code is very basic, there is no extra line of code which is not required. NOTE : this app will have problems, as optimized coding is not done.


Also UI-wise,  Server has just one text box, in which Server IP address is shown.

Client has two text-box , in one we will input the Server IP address in other Text Box the message send by server will be displayed.


Also you will see implementation of ASYNC task at server side. It is required to create connection and wait for CLIENT request. First I thought that is not required, but my UI was unresponsive without implementing it.

Reason : socket.accept() call is blocking call, until some client doesn't request connection , further code execution will not take place.

That's it amigo's.


Coming to second part, I was watching X-files,  it's not so good. But there was a question which came to my mind.

1) Is apeing greater than pure genius ?


Now I always wanted to do socket programming, but my inherent nature doesn't allow me to understand other people code. My brain just shuts down, when some one tells me how something worked.

I like to learn by my own. But what I have seen, learning by your own , discovering what other have discovered , reinventing the wheel should be attributed to DUMB people.

The very foundation of human society is build on SHARING.We learn from other experience, other mistakes, other success and this learning shortens next generation re-learning curve.

Now I was talking with my roommate, and he was telling me about TELSA car. What was beautiful in that CAR is that they have MACHINE LEARNING.  So if you are taking your car to some place and say it is hilly terrain. You have some sharp turn and did skid, the next time any TELSA car goes on that route will know what speed is dangerous on that turn.



Wow !!!!

Same way , what I coded in socket programming was learning from the 3-4 applications made by others.

But sometimes I feel what if everything we are learning is not natural but artifical ?

Like the matrix movie, where they show everyone is kept in a chamber and their brains are feed with real world image.

Telling even LIES a hundred times, makes it a truth. This is how we humans are.

What if the CASTE, COLOR, COUNTRIES we have created are in interest of FEW people. And we are told/teached whatever they want.

So it also raises one interesting question :


Do we want to live in harsh reality or beautiful truth ? 
`

It seems there is no option of attaching files to blogspot, so here is link for drive

https://drive.google.com/folderview?id=0B6HF3JcgAklva0VsSWIzZDZldG8&usp=sharing

Saturday, April 2, 2016

Sockets : Part 2


Only I know how tuf it is to write the second part. Not because of technical things, but simply because of my nature. I am very curious by nature , but flicking. I started SOCKETS article to make an app, then once I knew how it can be done, I start becoming disinterested.

But PROCRASTINATION , is not going to take me anywhere. So even if universe ends today, I have to complete this before it.

So lets start directly.

Now as I see right now, maybe this article might not end with Article 2, but spill further into one more article.

Now I will try to have code + theory at same time, else interest goes away. As we have seen in last article knowing just SOCKET API/functions are not enuf, we need to know also about OS. So in this article we will see threads and async task, as per our requirement. 

> Layout of our Program.  If anyone has used Android Studio or Eclispe before for Android application they know about

  Manifest.xml , Layour.xml , .java files. We will not see those in here, possibly I give put snapshot of those in my next article.

Now in Android, when we make application, we divide them into Activities, Each Activity which we create has a UI part, which is govern by .xml file  and .java part which has the code.

So in this article we will focus on code part.

So in both the Server and Client application, we will have  1 activity which will be main activity

 Server Main activity will create a Server class which will have function to open socket, accept client socket and send data to client. Server Class will be defined in separate .Java file, we will not need activity for this as we don't need UI for this.

Client Main activity will create a Client class which will have function to create socket, and once connection is created listen to what Server is sending and display it on UI.  Note Client class will be defined in Client.java file,  no activity is needed for it. Display will be done on the Clint Main activity UI.

Now below picture is for Server App in eclipse,

You can see Mainactivity.java which will have code for MAIN activity. Since it is activity it will have a corresponding xml file, which is activity_main.xml which will have UI.

Then the whole server code will go into Server.Java file.  In this article we will see only Server.java and Client.Java.

Then there is a AndroidManifest.xml file which governs the properties of Android app, we will see its use at the end.







So  we have got enuf skeleton of our app,  we will now start with to put flesh and muscles to it.


Now first starting with Server app, Server app has to accept Client socket request and also send data to existing clients.  So we need to have two simultaneous operation ongoing to support this.
So we will need threads. THREADS helps to run task in parallel. In java already THREAD class is present, we need to extend that class to get the work done.

Code wise

  private class ServerSendData extends Thread {    // here ServerSendData is our class in which we will have code for sending data to client and it is extending the thread class, so our class ServerSendData will run as totally independent body with respect to other part of Server program. 


> Now get started

The below code is psuedo-code for understanding , main code files I will try to upload. 


private class Server {

int port_no = 8080;

void opensocket() {

  ServerSocket serverSocket  = new ServerSocket(port_no);   // SERVER socket is created

 Socket socket_c = serverSocket.accept();  // this will accept only ONE  client connections.

  ServerSendData ssd = new ServerSendData(socket_c);  // Here we have create another class to                                                            send data
   ssd.run();   // we called the other class function
   
}

 private class ServerSendData extends Thread {   // this will run indepently to above code

       string msg = " I am server";
       socket client_socket;
     
     ServerSendData(socket clientsocket)
      {
            client_socket = clientsocket;
      }

     public void run()
    {
           OutputStream outputStream = client_socket.getOutputStream();// Here we are getting outstream                                                                    of socket
    PrintStream printStream = new PrintStream(outputStream); // printstream will put all message                                                               pass to it to outstream
    printStream.print(msg);   // Finally we have send message
    }
      
}
}

The above code shows how to achieve functionality of sending  data from Server.  Below we will see code at Client Side.

private class Client{


void opensocket() {

 Socket socket = new Socket(Server IP addressServer Port);  // Client socket is created

  InputStream inputStream = socket.getInputStream();  // this will get data from socket.
  
 BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
String x = "";
x = r.readLine();   // So now in x we have our input data, which we can display
}

NOTE : the client code is very simple, since i wanted to show how to achieve functionality code-wise.

In reality, we at client side also run socket creation/communication code as ASYNC task or seperate thread.

Since , reading /writing data from socket can take time, which will make our whole app to hang. So we do that functionality in background.

A bit about ASYNC task :  Classes which implements ASYNC task will run in background so that they don't affect over-all functionality.

Code wise : Classes implement ASYNC task like below

class ClientTask extends AsyncTask {

And then this class needs to implement some fucntions related to Async task like

1) Preexecute :  Function which will be done before Background function.
2) DoinBackground : The code part of this fucntions execute in background.
3) PostExecute : This will get execute after background function is completed.

4) Progress : If you are reading large amounts of data from socket and periodically wants to display that data , you can call this function from inside of DoinBackground. ( Ever notice , in MYNTRA, flipkart,amazon as we scroll items they gets loaded )

More on Async task can be read from internet like : its return type, parameters  etc.




Finally ...I have written the article.  Its so difficult to sit on your ass from long-time. Its time to massage it .

In third article , there will be zip file of  complete code, possible some video also showing communication between Server and Client.  And ...this is far-fetched ...but how to have continuous communication between Server/Client.