Saturday, November 6, 2010

Your First Google Map Application

Sometimes you need to add a map to your location in your site so that the users can reach you easily. what i like about Google maps is their API, it is very structured , easy to understand and the documentation is excellent.

So follow me in the next few steps:

1.You need to register a key

go to http://code.google.com/apis/maps/signup.html , and enter your site URL. your key will be generated and you will find a lot of ways to include Google Maps , here we will include Google Maps into web pages using Javascript.

for example

<script src=http://maps.google.com/maps?file=api&amp;v=2&amp;&amp;key=YourKey type="text/javascript"></script>
2.Documentation 


i totally recommend you to keep an eye on the documentation 


http://code.google.com/apis/maps/documentation/javascript/v2/reference.html
3. Map.html 

<html>
    <head>
        
        <title>My First Google Map</title>
        <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAt_j1jxA-
OrN2zgFscf196hQ81ypfsrwFppodUYGd3WJUYwK81BQMmvl7uCUsxJJdrC9XnVo-dI7fZQ" type="text/javascript"></script> 
<!—Google.js is the file that will define RenderMap(DivID)-->
   <script src="Google.js" type="text/javascript"></script>
        <script type="text/javascript">
            function LoadMap () {
                RenderMap('GoogleMap');  
            }
            window.onload=LoadMap; 
        </script>
    </head>
    <body>
        My Map will be in this Div 
        <div id="GoogleMap" style="width:500px;height:500px;">
        </div>
    </body>
</html>
4. Google.js
function RenderMap(DivID)
{
var MapDiv = document.getElementById(DivID);
var GoogleMap = null; 
if (GBrowserIsCompatible()) {
GoogleMap = new GMap2(MapDiv);

//Add Navigation Control and Zoom Control on the Map
GoogleMap.addControl(new GSmallMapControl());
GoogleMap.addControl(new GMapTypeControl());

//Enable Scrolling on the Mouse Wheel
GoogleMap.enableScrollWheelZoom();

//Next we will add a marker to our company 

//Company Latitude And Longitude
//You can get your Latitude And Longitude From Google Earth , i entered random values
var CompanyLongLat = new  GLatLng(29.449790329784214, 28.9599609375); 

//Company Marker On The Map
var CompanyMarker= new GMarker (CompanyLongLat) ;


//we need to add a "left click" event to the marker 
//when the user click on the marker , a balloon will appear that has the address information 
GEvent.addListener(CompanyMarker,"click", function() {
var AddressInfo= 'My Address Information'; 
CompanyMarker.openInfoWindowHtml(AddressInfo);
});


//Finally , add the Company Marker to the map 
GoogleMap.addOverlay(CompanyMarker);

GoogleMap.setCenter(CompanyMarker.getLatLng(),10);
}

}








That is all , Enjoy


Wednesday, October 20, 2010

AjaxFormSubmitter

when you are using AJAX in your web application , you do a lot of cool stuff but some parts of the application is totally boring like creating a form and get every eleement’s value in that form , create a new XMLHttpObject and handle the result.

So i created this class so that you can pass the form id ,  div id , or any html element that has a data you are interested in and send it  asynchronously to a web page , imagine the line of codes and the time that you will save and the most of it cutting the boring time of .

You Can Download The Class From

          http://www.jsclasses.org/package/26-JavaScript-Submit-Form-Data-asynchronously-.html

You need to include JQuery first , because the class is based on JQuery , you can download one from this link

           http://docs.jquery.com/Downloading_jQuery

The Class is  the file called “AjaxFormSubmitter”

To use the class follow this example

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
 <head>
   <meta http-equiv="Content-Type" content"text/html; charset=iso-8859-1">
   <title>Test Ajax Form</title>
   <Script src="jquery-1.3.2.min.js" type="text/javascript"></Script>
   <Script src="AjaxFormSubmitter.js" type="text/javascript"> </Script>
   <script type="text/javascript">
    function OnLoading () {
       alert("I am loading"); 
    }

    function OnSuccess (data){
       alert ("request completed " ); 
       alert(data); 
    }

    function OnError (XML){
       alert(XML);
    }

    function SendData(){
      var AjaxForm = new AjaxFormSubmitter("MyForm"); 
      AjaxForm.SetURL("data.php");
      AjaxForm.SetMethod("POST");
      
      AjaxForm.SetOnSuccess(
           function(data){
              OnSuccess(data);
           }
      );

     AjaxForm.SetOnFailure (
           function (error){
              OnError(error);
           }
     );

     AjaxForm.SetOnLoading (
            function (){
              OnLoading(); 
            }
    ); 

     AjaxForm.Submit(); 
   }  



  </script>
</head>

  <body>
      <form id="MyForm" action="#" method="post" >
          <input type="text" id="name" name="name" value="Text"/> 
          <input type="hidden" id="hidden" name="hidden" value="hiddenVlaue"/>
          <input type="password" id="password" name="password" value="passwordValue"/> <br>
          <input type="checkbox" id="chbox1" name="chbox1"  checked="checked"/> 
          <input type="checkbox" id="chbox2" name="chbox2" />    <br>      
          <input type="radio" id="radio1" name="choice" value="1" />
          <input type="radio" id="radio2" name="choice" value="2"/>
          <input type="radio" id="radio3" name="choice" value="3" checked="checked"/>
          <input type="radio" id="radio4" name="choice" value="4"/><br>
          <select id="Select" multiple="multiple">
              <option value="option1">option one</option>
              <option value="option2">option two</option>
              <option value="option3">option three</option>
          </select> <br>

          <textarea id="textarea">My Text Area</textarea> <br>
          
          <input type="button" value="Send Data" name="Send" onclick="SendData();"/>
      </form>
    </body>
</html>


In The Example you will find a function called “Send Data” , this is the function that do all the work.
var AjaxForm = new AjaxFormSubmitter("MyForm"); 
  AjaxForm.SetURL("data.php");
  AjaxForm.SetMethod("POST");


We created an object from the class  and pass the Form id to the constructor , then we tell the class the url that will receive the data , and the method that will it use “POST or GET”.



the next steps are optional , in case of you are not interested in handling the results.


AjaxForm.SetOnSuccess(
    function(data){
        OnSuccess(data);
    }
);

AjaxForm.SetOnFailure (
     function(error){
        OnError(error);
     }
);

AjaxForm.SetOnLoading (
    function (){
        OnLoading(); 
   }
); 

In the previous screen shot , you tell the class what to do in the following events: success , error , and loading

OnSuccess will recieve the resutned text from the web page , and will be called after the request is completed 

OnFailure Will recieve an object from the XML http Object , and will be called in case that any error happend

OnLoading : will be called before the data is sent .

what you have to do next , is to call the submit function
AjaxForm.Submit();


You have finished , i hope the class will be useful for you
Listed at Hot Scripts Listed in JavaScript





Saturday, September 4, 2010

Tamer Hosny is singing “Hotel California “

When Idiots Succeed !

 

believe it or not but it happened , tamer hosny is singing in English after the big success in Arabic singing !

our idiot chose to sing “Hotel California” from all the English classics , to show us that he can sing like the eagles , i liked my friend comment on this disaster  “the first step of classics distortion after we have lost the ability of every beautiful damn thing we could make” by hassan.

i don’t know why did tamer choose to sing in English? but whatever his reasons , it is not acceptable , i can't imagine Eminem is singing in Arabic ! , but let us think in different way; why tamer succeeded in the first place ? , it can’t be his chest hair ! , what if we can analyze tamer fans ? what we would get? ,i can’t deny that i listened to tamer songs , and i really liked some of them , but this guys is pushing us to the limits because of his lyrics ! . lets back to the fans , after i did the analysis , i categorized the fans to three levels :

 

Level Type Description
1 absolute supporters tamer hosny is their god father ; they admire every thing about him , his clothes, hair style , …. etc. in addition to every peace of paper he wrote or sang it , plus the 100 poster in their rooms , and some of them went to support tamer in court ! and  attend every concert for him
2 Songs Only they don’t like tamer as a person , but they like every song for him and it remind them with some emotional events in their lives and  they may go to some concerts.
3 Moderate they like some songs , they don’t care about attending tamer concerts , they are just having fun in the car while they are driving or while they are working.

 

is tamer stoppable ?

according to my analysis there are too many people in level 1 even from my relatives , so this guy is not stoppable in the near future , let us pray that tamer wont sing “je suis malade- French ” or  “caruso – italian ”

 


Friday, September 3, 2010

Design Patterns: Singleton

What is Singleton ?
i am not a good person to define things, but any way , when you feel you need only one instance from a class then you need a singleton!
Did computer scientists waste their time to instantiate only one object?
absolutely no , it is a very useful solution , some time having multiple copies of objects can lead to chaos , resource looking , resource over used , …. etc
When it is needed?
Most of the common usage is to handle global setting like database connections , registry settings  , who is online now ? , .etc

here is an example to implement singleton while connecting to MYSQL connection

<?php
//ConnectionConf.php
class ConnectionConf 
{
public $Username; 
public $Password; 
public $ServerAddress; 
public $Database;
}
?>
<?php
require_once 'ConnectionConf.php';
class Connection
{
/**
* Varaible to hold the unique instance  
* @var Connection
*/
private static $UniqueInstance; 
/**
* Connetion User name 
* @var string
*/
private $_strUsername; 
/**
* Connection Password
* @var string
*/
private $_strPassword; 
/**
* Connection Address
* @var string
*/
private $_strServerAddress; 
/**
* Database Name 
* @var string
*/
private $_strDatabase; 
/**
* Last Error happend 
* @var string
*/
private $_strLastError; 
/**
* mysql link identfier 
* @var mysql resource
*/
private $_resConnectionResource; 
/**
* Class constructor , it is private , 
* so no way you can create it using new Connection 
* @param $ConnectionConf ConnectionConf
* @return void
*/
private function __construct($ConnectionConf)
{
$this->_strUsername=$ConnectionConf->Username; 
$this->_strPassword=$ConnectionConf->Password; 
$this->_strServerAddress=$ConnectionConf->ServerAddress; 
$this->_strDatabase=$ConnectionConf->Database;
$this->StartConnection(); 
}
/**
* @param $ConnectionConf ConnectionConf
* @return Connection
*/
public static function GetInstance ($ConnectionConf=null) 
{
if (Connection::$UniqueInstance==null)
{
if ($ConnectionConf==null)
throw new Exception("Connection Configuration Can't be null at first time"); 
Connection::$UniqueInstance = new Connection($ConnectionConf); 
return Connection::$UniqueInstance ; 
}
return Connection::$UniqueInstance ; 
}
/////////////////////////////// Sets and Gets Start/////////////////////////////////// 
public function GetUsername () 
{
return $this->_strUsername;
}
public function GetPassword () 
{
return $this->_strPassword; 
}
public function GetServerAddress () 
{
return $this->_strServerAddress; 
}
public function GetDatabaseName()
{
return $this->_strDatabase;  
}
public function GetConnectionResource () 
{
return $this->_resConnectionResource; 
}
public function GetLastError () 
{
return $this->_strLastError;
}
////////////////////////////Sets And Gets End/////////////////////////////////////////////////////
/**
* 
* @return bool
*/
public function StartConnection () 
{
try{
$this->_resConnectionResource=mysql_connect($this->_strServerAddress,$this->_strUsername,

$this >_strPassword);
mysql_select_db($this->_strDatabase);
}
catch(Exception $e){
$this->_strLastError=$e->getMessage(); 
return 0 ;   
}
return 1; 
}
public function CloseConnection () 
{
try{
mysql_close($this->_resConnectionResource); 
}
catch (Exception $e)
{
$this->_strLastError=$e->getMessage(); 
return 0 ; 
}
return 1; 
}
public function RestartConnection () 
{
$this->CloseConnection(); 
$this->StartConnection(); 
}
}
$Config = new ConnectionConf(); 
$Config->Username= "root"; 
$Config->Password= ""; 
$Config->ServerAddress= "localhost"; 
$Config->Database= "road";
//First instance 
$Connection = Connection::GetInstance($Config);
var_dump($Connection); 
//will return the same instance declared before
$Connection1 = Connection::GetInstance(); 
var_dump($Connection1);
?>



here are the files


http://www.4shared.com/file/9d_RHQ0I/ConnectionConf.html
http://www.4shared.com/file/DoOt0KUh/singleton.html

Do you still have your EX on your facebook account?

don’t ask me why i wrote this ? i keep my reasons for me. but i did  a lot of surveys  and i found that most of us leave his/her EX on facebook account!

here are some reasons :

1- love can turn to friendship:

what i can say about this reason is : liars , liars  ,liars ,liars ,liars , liars .
love can’t turn to friendship , your father cant be your sister !! so as love cant turn to friendship

2- curiosity
most of us are curios what is happening with the others whatever they are to them.

3- i don’t delete a friend form facebook
some said that , they don’t delete a friend from their account whatever happened , but to show him/her that they are upset , they just give them an access to their limited profile.

So What a bout you ?



 

Google Translator is using “Statistical Translation Machine”

Before i start the article , i want to send a message to a group of idiots that said “Google Is using Rule Based” , the amazing thing is they don’t know the difference between them , so if you still don’t know the difference , i will show you the difference in this article so you can be in the safe side not the idiot side.

Rule Based Approach:
you will spend a lot of years building this engine and you wont get  good results in the end.

summary :

at this approach you have a dictionary that contains the two languages that you will translate from and to the other. then you have an engine that contains your language rules and their exceptions. when you translate you keep in mind the subjects , adverbs , verbs , ….etc. in both languages .

Statistical Translation Machine:
All what you need is data !

summary:

it simulates the way humans learn a new language , when you learn a new language you wont necessarily need to know the rules of the language , you will need to know the sentence in Arabic and its English equivalent.
first you need data , the data in this approach is any piece of text and its translation , then the algorithm tries to find a pattern in the data , based on the frequency of the text.
here is a reference
http://translate.google.com/about/intl/en_ALL/


Friday, August 27, 2010

We were developers

Are you a computer science graduate ?

If so , here is the truth; our education in Egypt don't allow us to be a computer scientist! . i have never had the lecture that supposed to tell you "What Computer Scientists do ?" , it is supposed to be the first lecture in a reputable computer science faculty, any way forget about this lecture.

the software industry in Egypt is as follows:
  1. The Clients:  group of idiots that think you are doing the impossible or some magic for them.
  2. Software house companies:  group of idiots that have some information about the field , well you can say "dummies" not idiots , working without any standards or organized process


i don't mean that there are no reputable software companies in Egypt , there are but few. 

where is the problem? 

most of software engineers become plumbers !!, we used to develop like the plumber , he also used to plumb ! ! , we don't think before we develop . we are not working on the science any more !! , most of us googling all the day for examples !!. 

Another problem , when government created scholarships for any graduate to learn programming , they totally missed up !!!, they are teaching tooooooools not science , so you can hear some one saying "i am studding .Net right now" , what the hell is that !
  
i remembered a discussion between me and a friend , we were talking about MVC , he was telling me that MVC makes websites too slow, and there are some kind of web applications  that cant be implemented  using this design pattern , can you imagine that !!! , we were discussing a topic that was closed in the seventies.

another problem , employers don't know the right qualifications to hire a software engineer , most of the employers  are focusing on the experience  !! , big shit , experience  can be useful , but without science! , you have just hired a new plumber!

i dont mean that learning new tools is not something good, but learning based on knowledge and science is much better

There are hot topics in  science that can be useful to the business , science is created to solve problems , real life problems , guys if we didn't keep up with the science not the tool we will be obsolete and we will say


"WE WERE DEVELOPERS"


Saturday, August 21, 2010

First AJAX Application

Introduction : What Is AJAX

AJAX is very interesting now a days , and a lot of developers want to know what is AJAX , AJAX stands for "Asynchronous JavaScript And XML" which means it is all about Javascript and XML.
Most of people thought that AJAX is a web programming language like PHP , ASP , .. etc. but it is not , whatever the language you are using for your web application , AJAX is totally independent.
we use AJAX when we need to do something asynchronously and don't make the page flashes. Gmail and Google Earth are a good example of AJAX.

What i need to know before i start working with AJAX ?


  1. a web programming language like PHP , ASP , JSP or whatever you want .
  2. JavaScript , and it is actually not a big deal to specify time to learn JavaScript , if you have a small programming background you can learn JavaScript from tracing others code .
  3. XML , also you won't need anytime for XML , for the simplicity sake XML let you express the data using your own tags
  4. DOM : "Document Object Model" , every element in the HTML Page is actually an object of the document , DOM actually is not a different language , you can think of it as a concept


The First Application : Sign Up Using AJAX the HTML Page < span id="Message"> </span> < from action="#" id="SignUpForm" method="POST"> Username :< input id="Form_Username" type="text" value="" /> Email:<input id="Form_Email" type="text" value=""/> Passwoed:<input id="Form_Password" type="password" value="" /> <input id="SignUpButton" onclick="return SignUp();" type="submit" value="Sign Up" /> <form> The goal of the "span" is to use it for printing the messages related to the sign up process. onClick="return SignUp();" will call the javaScript function - we will create it latter- which is responsible to send the request asynchronously The PHP Page
<?php
// SignUp.php
$UserName = $_REQUEST["Form_Username"];
$Password= $_REQUEST["Form_Password"];
$Email=$_REQUEST["Form_Email"]
$Connect= mysql_connect("localhost","root","password");
mysql_select_db("database");
$SQL = "insert into users 
set 
user_name = '$Username',
user_password= '$Password';                                                  
user_email='$Email'; "
$Query = mysql_query($SQL) 
if( mysql_affected_rows() ==1) 

echo "1"; //user added successfully else

echo "0" // //failed

?>
as you see you have to organize your code in a way that only the intended function will respond and print a text that should be displayed Now The JavaScript Part
function XMLHTTPRequest()
{
var xhr=false;
// if running Internet Explorer
if(window.XMLHttpRequest)
{
try
{
xhr= new XMLHttpRequest();
}
catch (e)
{
xhr= false;
}
}
// if running Mozilla or other browsers
else
{
try
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");  
}
catch (e)
{
xhr = false;
}
}
return xhr;
}
function SignUp()
{
var Username=document.getElementById("Form_Username");
var Password=document.getElementById("Form_Password");
var Email=document.getElementById("Form_Email");
var Xml=new XMLHTTPRequest(); 
if (xhr){
var Link=" SignUp.php";
xhr.open("GET",Link,true);
xhr.onreadystatechange = function () { CheckState(xhr);};
xhr.send(null);
}else
return true;
}
function CheckState(xhr)
{
var Message=document.getElementById("Status");
Message.innerHTML="";
if (xhr.readyState == 1)
{
Message.innerHTML="Loading , Please Wait";
}
if (xhr.readyState == 4)
{
if (xhr.status == 200)
{
if(hr.responseText=="1")
Message.innerHTML="User Added";
}
else
{
Message.innerHTML="Error occurred";
}
}
}

Friday, August 20, 2010

Eminem Recovery

Eminem is not kidding ! , this guy writes almost all of his songs , in some way the song touches you, The last album Eminem released is recovery! , you can't say anything but wow , the most interesting thing in Eminem is that he can choose his topics , he is not singing bla bla bla bla love , he talks about Iraq war , bad relationships with his mother , recover from addiction ,careers effect on the family ,  ...etc.

i hope that in Egypt we can find something that is similar to Eminem , Ahmed Mekky is a great start in the Arabic rap , also MTM is trying. i don't want to hear Arabic songs talking about loooooove  any more  , for god sake life is not about love only !! , video clips sucks , a lot of sexuality content nothing interested !!!! ,

there is also a light of hope like hamza numera , maher zain , sami youssef , and even black theama.

Amr Diab "The Montain" is not telling us any useful shit! , he is working on his muscle more than he works on his songs, the same thing for tamer hosni , they killed all the topics of love songs , their religious songs suck , you simply cant feel any thing while they are signing , the melody and the lyrics can meet in hell !!! ,  bad lyrics and bad melody and they are not serving the song at all



here is a list of songs that i recommend you to hear :


1- i love the way you lie - Recovery
2- i'am not afraid - Recovery
3- Space Bound - Recovery
4- when i am gone -  Curtain Call: The Hits

Listen and Enjoy

Rihab City is not what you think !

a couple of friends visited me in rehab , they came to have a walk and "sohor" , we were celebrating Ramadan days, they told me that Ramadan hasn't come yet to rehab , people is not giving a shit about any religious activities, actually i was sad because i looked at the people and i felt so shame ! what happened ?! is this the end!

my friends left , and it was too late and there wasn't much time till "fajar" so i decided to pray in the mosque . guess what ! it was like a Friday prayer ! , the mosque is almost full ,and there was competition in the mosque about remembering the last six discussed "hadeth" , the winner was a kid ! , did you believe we still have good people , the good will remain in this nation till The Day of Resurrection.

Start be your self first and every thing will change , we should keep trying till the last drop of our blood ,   people don't lose hope please, and please before making any judgments be sure that you can the see the things from more than one point of view

Monday, August 2, 2010

Respect

well, this is my first article in the blog and it is not even technical, but it is an important thing; most of us forgot it.

Respect definition according to wikipedia is : denotes both a positive feeling of esteem for a person or other entity (such as a nation or a religion), and also specific actions and conduct representative of that esteem. Respect can be a specific feeling of regard for the actual qualities of the one respected (e.g., "I have great respect for her judgment"). It can also be conduct in accord with a specific ethic of respect. Rude conduct is usually considered to indicate a lack of respect, disrespect, whereas actions that honor somebody or something indicate respect.
 in these days we are judging people on their look , money they have , what kind of car they are driving ,.... bla bla bla. we missed the core of people , why we cant simply respect anyone poor , rich , cute , ugly , whatever his/her religion ,...?

the reason behind this article that i have found a lot of people which are good persons but not treated well ,  in Egypt some of us forgot what they were before , we lost our identity , we don't know if we are Africans or Arabians or what !


prophet Mohammed peace upon him said " there are no differences between people except in piety", really amazing , we knew that along time before but as i told you we forgot a lot of things , jascues chriac said "every one has something to say , so listen carefully"


Respect each other , listen to the others point of view , that is what we are missing