Showing posts with label Coding Scripts. Show all posts
Showing posts with label Coding Scripts. Show all posts

Topics

1) Code your Server.js - Node.js main file
        i) Importing libraries
        ii) Create Server and Handle Request
        iii) Play with Socket.io to do MultiChatting
2) Develop Webpage with Socket Javascript
3) Download Project here


1) Code your Server.js - Node.js main file

i) Importing libraries


 var http = require("http");
 var url = require('url');
 var fs = require('fs');
 var io = require('socket.io');

ii) Create Server and Handle Request

var server = http.createServer(function(request, response){
 
 var path = url.parse(request.url).pathname;
 console.log('Path='+path);
 switch(path){
  case '/':   
   fs.readFile(__dirname + "/index.html", function (error, data) {
    if (error) {
     response.writeHead(404);
     response.write("opps this doesn't exist - 404");
     response.end();  
    }  
    else{ 
     response.writeHeader(200, {"Content-Type": "text/html"});  
     response.write(data, "utf8");
     response.end();  
    }
   });
   break;
   
  case '/socket.html':
   fs.readFile(__dirname + path, function (error, data) {
    if (error) {
     response.writeHead(404);
     response.write("opps this doesn't exist - 404");
     response.end();  
    }  
    else{ 
     response.writeHeader(200, {"Content-Type": "text/html"});  
     response.write(data, "utf8");
     response.end();  
    }
   });
   break;
   
  default:
   console.log(path +"- Not found");
   response.writeHead(404);
   response.write("opps this doesn't exist - 404");
   response.end();
   break;
 }
 
});
server.listen(8001);

iii) Play with Socket.io to do MultiChatting


var serv_io = io.listen(server);
var textarea="";
var name="";
serv_io.sockets.on('connection', function(socket){
 //send data to client
 setInterval(function(){  
        socket.emit('date', {'date': getCurrentTime()}
 );
  
    }, 1000);
 
 socket.on('client_data', function(data){
  textarea=data.textarea;
  name=data.name;
  console.log("name="+name);
  //socket.emit('textarea', {'textarea': data.textarea});
  emitData(socket);
 });
 
    
});

function emitData(socket){ 
 socket.broadcast.emit('message', 
  {'date': getCurrentTime(),
   'name' : name,
   'textarea':textarea
  }
 );
}

function getCurrentTime(){
 var d = new Date();
 var curr_date = d.getDate();
 var curr_month = d.getMonth()+1;
 var curr_year = d.getFullYear();
 var curr_hour = d.getHours()%12 +"";
 var curr_min = d.getMinutes() + "";
 var curr_sec = d.getSeconds() + "";
 if(curr_hour.length == 1)
  curr_hour="0"+curr_hour;
 if(curr_min.length == 1)
  curr_min="0"+curr_min;
 if(curr_sec.length == 1)
  curr_sec="0"+curr_sec;
 
 //var dateString = sprintf("%2s-%2s-%s %2s:%2s:%2s ",curr_date,curr_month,curr_year,curr_hour,curr_min,curr_sec);
 var dateString = curr_date + "-" + curr_month + "-" + curr_year + "  " + curr_hour +":"+ curr_min +":"+ curr_sec;
 
 return dateString;
}

2) Develop Webpage with Socket Javascript

<html>
  <head>
    <script src="/socket.io/socket.io.js"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script> 
 <style>
 .common{
  width: 200px;
  height: 30px;
  padding-left: 10px;
  
 }
 #date{
  color: green;
 }
 </style>
  </head>
  <body>
    <script>
  var socket = io.connect();
  socket.on('date', function(data){
   $('#date').text(data.date);
  });
  
  socket.on('message', function(data){   
   message=data.textarea;
   len=message.length;
   if(len > 0){
    printMessage(data.name,message);     
   }
  });
  
  
  $(document).ready(function(){
   $('#textarea').keypress(function(e){
   if ( event.which == 13 ) {
    message=$('#textarea').val();
    len=message.length;
    strname = $('#name').val();
    if(len > 0){
     socket.emit('client_data', {'name':strname,'textarea': message}); 
     printMessage(strname,message);     
    }
    $('#textarea').val("");
   }    
  });
  }); 
  
 function printMessage(strname,message){
  $('#messagearea').html($('#messagearea').html()+"<br/><span style='color:blue;font:18px;'>"+strname+"</span> : "+message);
 }
    </script>
    <div><h1>Welcome to Node.js Socket.io - Simple Multi Chat Application</h1></div>
 <b> Get tutorial here (Post your comments and query)</b> - <a href='http://www.coolcomputerpctricks.com'>www.coolcomputerpctricks.com</a><br><br>
 <b> Get Latest Code here </b> - <a href='https://github.com/karthikeyan98'>https://github.com/karthikeyan98</a>
 <br><br>Current Time: <span id="date"></span><br/>
 <input type="text" id="name" value="Guest" class="common"> - Type Name here<br/><br/>
 <textarea id="textarea" class="common"></textarea> - Type Message here and press Enter.
 <div id="messagearea"></div>
  </body>
</html>

3)  Download Project here

GitHub - https://github.com/karthikeyan98/SimpleMultiChat

Post your comments and query for any help.

Develop your first Android Game

How to develop android games?

Developing android games is simpler than you think.

Check out this android game. Which is built using this technique.
Save Super Penguins
https://play.google.com/store/apps/details?id=com.positivesthinking.parachutepenguinsfree


Before starting the tutorial familiar yourself with android.

1. Set up the Android Workspace
https://developer.android.com/training/basics/firstapp/index.html

2. Create your Hello World Android application
https://developer.android.com/training/basics/firstapp/creating-project.html

Lets start the game development.

Just follow this Four Steps to start your first simple android game.
Step 1: Create a Game Loop Thread that renders the Frames.
Step 2: Create a SurfaceView class that will show the game UI and controls the game.
Step 3: Create a Image handler class that will help you in collision detection and loading bitmap images.
Step 4: Wire up your MainActivity.

Post your comments in case of any difficulty and help.

Step 1: Create a Game Loop Thread that renders the Frames.
MainThread.java.
package com.coolcomputerpctricks.tutorialgame;
import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;

/** 
 *  www.coolcomputerpctricks.com
 *  Android Game development tutorial * 
 */

public class MainThread extends Thread {
 
 private static final String TAG = MainThread.class.getSimpleName();
 
 // Frames Per seconds
 public  int MAX_FPS = 150; 
 private  int FRAME_PERIOD = 1000 / MAX_FPS; 
 private SurfaceHolder surfaceHolder;
 private ViewGamePlay gamePanel;
 private boolean running;
 
 public void setRunning(boolean running) {
  this.running = running;
 }

 public MainThread(SurfaceHolder surfaceHolder, ViewGamePlay gamePanel) {
  super();
  this.surfaceHolder = surfaceHolder;
  this.gamePanel = gamePanel;
 }

 @Override
 public void run() {
  Canvas canvas;
  long beginTime;  
  long timeDiff;  
  int sleepTime;  
  sleepTime = 0;
  while (running) {   
   canvas = null;
   try {
    canvas = this.surfaceHolder.lockCanvas();
    synchronized (surfaceHolder) {
     beginTime = System.currentTimeMillis();
     this.gamePanel.render(canvas);    
     timeDiff = System.currentTimeMillis() - beginTime;
     sleepTime = (int)(FRAME_PERIOD - timeDiff);
     if (sleepTime > 0) { 
      try {
       Thread.sleep(sleepTime); 
      } catch (InterruptedException e) {}
     }
     
    }
   } finally {
    if (canvas != null) {
     surfaceHolder.unlockCanvasAndPost(canvas);
    }
   } 
  }
 } 
}

Step 2: Create a SurfaceView class that will show the game UI and controls the game.
ViewGamePlay.java
package com.coolcomputerpctricks.tutorialgame;

import java.util.Random;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/** 
 *  www.coolcomputerpctricks.com
 *  Android Game development tutorial * 
 */

public class ViewGamePlay extends SurfaceView{

 
 MainThread thread;
 ItemImages bgImage,parachute;
 int max,min;
 
 public ViewGamePlay(Context context) {
  super(context);
  thread = new MainThread(getHolder(), this);
  getHolder().addCallback(new SurfaceHolder.Callback() {
   public void surfaceDestroyed(SurfaceHolder holder) {
    boolean retry = true;
    while (retry) {
     try {
      thread.setRunning(false);
      thread.join();
      retry = false;
     } catch (Exception e) {
      e.printStackTrace();      
     }
    }
   }
   public void surfaceCreated(SurfaceHolder holder) {
           
     Canvas c = holder.lockCanvas(null);
     initializeGame(c);
     drawGame(c);
     holder.unlockCanvasAndPost(c); 
     thread.setRunning(true);
     try{
      thread.start();
     }catch(Exception e){
      e.printStackTrace();
     }
   }

   public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    //Surface changed
   }
  });  

 }



 public void initializeGame(Canvas canvas){
  
  bgImage =  new  ItemImages(BitmapFactory.decodeResource(getResources(), R.drawable.sky),0,0);
  parachute = new  ItemImages(BitmapFactory.decodeResource(getResources(), R.drawable.parachute),0,0);
  
  //Random left position for the parachute
  max=(int) (canvas.getWidth()-parachute.getWidth());
  min=0;
  Random rand = new Random();  
  int randomNum = rand.nextInt((max - min) + 1) + min;
  parachute.setLeft(randomNum);
 
 }
 
 protected void drawGame(Canvas canvas) { 
  
  bgImage.drawBMP(canvas);
  parachute.drawBMP(canvas);
   
 } 
 
 
 public boolean onTouchEvent(MotionEvent event) {
  float x = event.getX();
  float y = event.getY();
  if(parachute.isCollition(x, y))
   {
    // If player touched, reset the parachute location
    parachute.setTop(0);
    Random rand = new Random();  
    int randomNum = rand.nextInt((max - min) + 1) + min;
    parachute.setLeft(randomNum);
    
   }
  return true;
 }
 
 public void render(Canvas canvas) {
  
  parachute.setTop(parachute.getTop()+2);
  
  if(parachute.getTop()>canvas.getHeight()){
   parachute.setTop(0);
   // Reset the parachute location
   parachute.setTop(0);
   Random rand = new Random();  
   int randomNum = rand.nextInt((max - min) + 1) + min;
   parachute.setLeft(randomNum);
  }  
  drawGame(canvas);
 }
 
 
}


Step 3: Create a Image handler class that will help you in collision detection and loading bitmap images.
ItemImages.java
package com.coolcomputerpctricks.tutorialgame;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;


/** 
 *  www.coolcomputerpctricks.com
 *  Android Game development tutorial * 
 */

public class ItemImages {
 private float width;
    private float height;
    private float left;
    private float top;
    private Bitmap bmp;
    private boolean visible; 
    
    public ItemImages(Bitmap bmp,float left, float top)
    {
     this.width = bmp.getWidth();  
        this.height = bmp.getHeight();
        this.bmp=bmp;
  this.left=left;
  this.top=top;
  this.setVisible(true);
    }
    public void setBmp(Bitmap bmp) {
  this.bmp = bmp;
 }
 public void drawBMP(Canvas canvas) {
  if(canvas!=null && bmp!=null)
   canvas.drawBitmap(bmp, left, top, null);
    }
    public void drawBMP(Canvas canvas,Rect src,Rect dst) {
  if(canvas!=null && bmp!=null)
   canvas.drawBitmap(bmp, src, dst, null);
    }
    public boolean isCollition(float x2, float y2) {
        return x2 > left && x2 < left + width && y2 > top && y2 < top + height;
    }
 public float getWidth() {
  return width;
 }
 public void setWidth(float width) {
  this.width = width;
 }
 public float getHeight() {
  return height;
 }
 public void setHeight(float height) {
  this.height = height;
 }
 public float getTop() {
  return top;
 }
 public void setTop(float top) {
  this.top = top;
 }
 public float getLeft() {
  return left;
 }
 public void setLeft(float left) {
  this.left = left;
 }
 public boolean isVisible() {
  return visible;
 }
 public void setVisible(boolean visible) {
  this.visible = visible;
 } 
}

Step 4: Wire up your MainActivity.
MainActivity.java


package com.coolcomputerpctricks.tutorialgame;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
/** 
 *  www.coolcomputerpctricks.com
 *  Android Game development tutorial * 
 */

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  
  setContentView( new ViewGamePlay(this)); 
 }


}

Here is the two images used in this tutorial


Sky.png

parachute.png




Download Project here

GitHub - https://github.com/karthikeyan98/SimpleGame-AndroidExample

Post your comments for any doubts and helps.





Are we trusting Google too much?

Are we trusting Google too much?

1. why should chrome warn us with a message when we clear browsing history?


Whenever we try to clear browsing history, chromes tells that there is incognito mode to use, is Google worried if you clear your entire browsing history from chrome?

What does Google do with your browsing history?
Here's a clear evidence, "YouTube", Google's YouTube shows video contents relevant to our browsing history stored in chrome. that's how your information is used to make you use their product(YouTube) more than what you do normally.
you can find the difference when you go to "YouTube" home page in both conditions
1. first without browsing history - everything cleared in chrome- visit YouTube home page
2. after doing couple of Google searches, let chrome shows some history and visit YouTube, you will feel the difference

2. why should chrome has separate log in session separating it from other google products.

when you logged in chrome, also when you logged in some of other google product like gmail, when you signout of gmail,chrome logged in session wont go.

chrome separate login session stores all your data ( you can control it by visiting settings, how many of us do that, what about people who doesn't have enough computer experience to change the settings ) user specific data stored in each of our google account right from browsing history to form input data's.

3. How does google map works - showing traffic information in the road we travel.



It does collect our location information including in which speed we are traveling, it collects every one who uses android mobile or signed in to google map atleast once and using some algorithm it gives back.


4. What will happen with Google Glass?

                    XX_____XX 

5. Not just above four items, there are lot more things.. like

     At first time when you open Google Chrome, it asks you to sign in with Google account. How many of you signed in without knowing that it is a log in for Google chrome to save your personal browsing data  in your account?
      Many would have no idea initially that it is a log-in specially for Google Chrome. and would have signed in directly thinking it is normal google product sign-in.

 Obviously, we are very much benefited and addicted to all those products, and there are ways we can control sharing our data to a certain level, but how many of us are really concerned about it, going to settings, searching where it is and switching it off?

convert string to dictionary in python

Cool trick to convert strings into dictionary object in Python Programming

Method 1: Using ast.literal_eval

## Example

import ast
strr = "{'a': 1, 'b': 2, 'c': 3}"
strr_dict=ast.literal_eval(strr)

Method 2: Using json
## Example

Interesting !!! Google Vs Bing , Unbelievable Trick try it yourself.

Interesting !!! Google Vs Bing , Unbelievable Trick try it yourself.
Have you ever tried Automattic currency Conversion in Google or Bing search, There lies this interesting fact.Just have a look at it.. perhaps wait! how about Exploring this interesting crazy fact on your own with the help of following steps.

Step 1: Open your favourite Web browser twice (two windows or two tabs) open www.google.com in one and www.bing.com In another.


Step 2: Type the following in both the search bar and hit Enter.

1 euros in usd

Step 3: Well I searched at this time December 5 2010 8.24 pm look what I get. Having two different answers for same question

Google said 1 Euro = 1.3382 US $

Bing said 1 Euro = 1.34246 US $


Step 4: Which one is correct??????????!!!!!!!?????????

Step 5: Well According to Yahoo (OMG!!! another search engine) Currency convertion at this page http://finance.yahoo.com/currency-converter/#from=USD;to=EUR;amt=1.3399 says both are wrong.

Step 6: Well Let’s try some other site to verify it http://www.xe.com/ucc/convert.cgi?Amount=1&From=EUR&To=USD&image.x=63&image.y=21&image=Submit which says Google Data is better than bing and yahoo but not Accurate though !!!!!!.

Finding IP Via Javascript - PHP - ASP

Computer tips - To Get And Show The Ip Via Javascript - PHP - ASP

1. To show the ip via JavaScript

var ip= '';
document.write("Your IP Address is :"+ip+" ");

2. To show IP via ASP
request.ServerVariables("REMOTE_ADDR")

3. TO SHOW IP VIA PHP
$remote_address = getenv("REMOTE_ADDR");echo "Your IP address is $remote_address.";$browser_type = getenv("HTTP_USER_AGENT");echo "You are using $browser_type.";?>