Backup and Restore MySql Database to remote server

Backup and restore MySQL database to and from the remote server is very essential and basic necessary task as a freelance developer to create test server, migrate/upgrade to the new server.

For codebeautify, I have been doing this every month to test data with the new code on a test server.

Here are steps requires to backup, send and restore the database on new servers.

  • Creating A Backup

First, we need to create a backup of existing database using MySQL’s dump command. this command will help you to the backup single database

mysqldump database-name > database-name.sql

For multiple databases,

mysqldump --databases database_1 database_2 > multi_databases.sql

if the backup file size is large enough, we can zip/archive the file using tar command. This will also save bandwidth and time.

tar -czvf db.tar.gz database.sql
  • Transfer file to new server

Using sftp command it’s very faster way to transfer the file to remote server.

Here is the list of command to transfer file.

this command will login to remote server via sftp.

sftp [email protected]_hostname_or_IP

Enter the password to login to the server. Once the login is successful, move to a directory where would you like to copy the backup file using the cd command.

Now to send the file to remote server use put command.

put database.sql

If you have zip/archive the file use this command to unzip.

tar -xvzf database.tar.gz
  • Restore a database backup on the new server and you are all set.
mysql database_name < database.sql

These are very useful commands to migrate MySQL database to other servers to do the backup and restore of MySQL database.

I hope this article will help beginners to backup and restore MySQL database.

Reverse String in Python – Best Approach Given

There are many ways to reverse string in Python. If you are familiar with c , c++ and java and don’t want to use any reverse function then someone could write the logic like:

1. Using the swapping last char with first and do that until the middle character. Remember we used to do this kind of exercise in C, 101?

2. Second would be like to take a new string and add 1 by 1 character from the opposite order of the String. This may take up too much space if you have Essay to reverse.

Note: String is immutable in Python similar to in Java. So it will not change the string if you try to modify, it will create the new String.

Firstly I have not seen a use case where I need to reverse a string unless you are trying to work on Cryptography.

This is enough talking.

Let’s do the reverse string with Python.

Reverse String in Python – Best Approach

This is the best and effective way to reverse a string.

string_sample = "Hello World"

reversed_string  = string_sample[::-1]

print(reversed_string)

This is the very astonished result by writing [::-1] it reverse the String and this is the fastest way to reverse a string.

This is called extended slice syntax. It works by writing [begin:end:step] – (minus sign) by leaving begin and end off and by writing a step of -1 , this will reverse a string.

Here are some other ways to reverse a string in python.

Reverse a String using the recursive function.

def reverse(string):
    if len(string) <= 1:
        return string

    return reverse(string[1:]) + string[0]

string_sample = "Hello World"

print(reverse(string_sample))

 

Reverse a string by using another string variable and adding character one by one in the opposite of the given string.

def reverse(string):
    new_string = ''
    index = len(string)
    while index:
        index -= 1                    
        new_string += string[index] 
    return new_string

string_sample = "Hello World"
print(reverse(string_sample))

This approach may hurt the performance of the application based on the string length.

Strings concatenation and Formatting in Python

Strings concatenation and Formatting in Python is the process for joining small string to make the bigger. For example, you can create a full name by joining two string like Firstname and Lastname. Formatting will help to display variable in or end of the string.

Strings Concatenation in Python

Python provides the easy way to concatenate Strings by using + (plus)  and * (star) Sign. There are other methods such as append(), join() and format().

Using + 

+ will adds values on either side of the operator

Here is an example :

Using *

*  Creates new strings, concatenating multiple copies of the same string.

Here is an example :

String Formatting in Python

You might have the experience to use C language to print String and Integer using %s and %d. Python has similar string formatting to create new, formatted strings. The % operator is used to format variables.

Here are the examples:

String formatting using two and more than values using the tuple. A tuple is a sequence of immutable Python objects. Tuples use parentheses.

Python is supporting other function like append and join to manipulate String data.

Python Interpreter : The Best Language Interpreter

Python language is written by Guido van Rossum in late 1980 is one of the Best interpreted languages. Python is used as the first programming choice of both Google, Ubuntu, RedHat. Python Interpreter is the best interpreter.

The Python interpreter

The Python interpreter is a program that reads Python program statements and executes them immediately. To use interpreter it requires opening the command prompt or terminal windows in your development environment and write command python, and it will show this result and start interpreter. I am using Window 10’s Ubuntu shell.

Python interpreter executes program statements immediately. To Experiment python statements , Python command will start interactive mode and it will be very useful to try out things.

Here are some Examples of one-line commands:

In above examples, one will print Hello World, other will do multiplication and the third one calculates Decimal to Binary using bin().

The >>> prompt is used to enter one-line commands or code blocks that define classes or functions . In above example, only one-liner commands are given. In next example please find multi-line code blocks.

Here are some Examples of multi-line code block:

In above example, it will compare two strings.

help() function is another awesome way to get help on python keywords, functions, etc.

Here is the example of checking syntax and guide of bin command. Press q to return to python interactive interpreter.

I love the way Python Interactive Interpreter works. How about you?

 

10 Python Tips and Tricks for Beginner and 9th is interesting

Today Python is one of the most popular languages for coding in Unix/Linux world. You can find it everywhere from Web development to Server Component development, XML parsing to configuration management. Here I will be mentioning 10 Python tips and tricks for developers.

Python is pre-installed in many Operating Systems which released in last two year. Ubuntu, Redhat, Mac OS, Free BSD , Solaris, etc.

To check which version of python is installed go to shell and type:

$ python

This command will give you the version information of Python and start Python’s interactive interpreter.

Here are the few famous applications which are built using Python such as :

  • Youtube
  • OpenStak
  • Dropbox
  • Instagram

Here are 10 Python tips and tricks for Beginners and Experts.

1. Use Python Development Environment

By using Development Environment or IDE it will increase your productivity and easy to resolve error and warning. It will also help to debug the code, easy to navigate , integrate source control such as SVN, Git.

These are the recommended IDEs for Python Development.

  • PyDev – It’s free and Open Source Eclipse-based IDE . http://www.pydev.org/
  • IDLE : The Python built-in IDE, with auto-completion, helps to Format , Run and Debug python code.
  • Other commercial versions are PyCharm, WingIDE.

2. Calculate days between Today and Date.

import datetime

today = datetime.date.today()

someday = datetime.date(2017, 1, 1)

diff = someday - today

print (str(diff.days) +" days")

datetime module is used to find the days between two dates. this example will find the days between today and 1 Jan 2017.

3.Command line arguments while running Python Scripts

#file name is commandlinetest.py
import sys

print 'No of arguments passed:', len(sys.argv)
print 'List of arguments :', str(sys.argv)

run this script:

$ python commandlinetest.py 10 20 30

Output
No of arguments passed: 3
List of argumenrs : ['commandlinetest.py', '10', '20', '30']

sys module will have the information about arguments passed by accessing sys.argv variable. sys.argv is a list of strings representing the arguments on the command-line.

4. String Searching made easy

First Method will check if a string contains another string by using the in syntax. in takes two arguments, first on the left and second on the right, and returns True if the left argument is contained within the right argument.

s = "This is a String finding program"

# Method 1
if 'String' in s:
    print('String is found in this program')
    
# Method 2    
if s.find('String') != -1:
    print('String is at ' , s.index('String'))

Second Method offers a Library method called find(). This method is used with String Variable and it returns the position of the index of desired string. If the string is not found then -1 is returned.

5. Generating Random Numbers

Python is having the random library for generating random numbers. By default random library uses system time to generate random numbers.

import random
 
print('Random number:->' , random.randrange(10));

print('Random Range Between 10 to 20:->' , random.randrange(10,20));

print('Random with Floating values:->' , random.uniform(0,10));

Output :
Random number:-> 9
Random Range Between 10 to 20:-> 13
Random with Floating values:-> 5.012076169955613

random.randrange(10) sets the limit from 0 to 10 and return numbers between 0 to 10.

random.randrange(10,20) gives random values between 10 to 20.

random.uniform gives the result with floating value.

6. Opening WebBrowser from Python Script

import webbrowser

webbrowser.open('http://codebeautify.org')

webbrowser module provides the easy way to open system’s default browser with URL mention in open method.

7. Calculate Program Execution time

import time
    
start_time = time.time()

add = 0
for i in range(1, 10000):
    add =add + i
print(add)

print("\n--- %s seconds ---" % (time.time() - start_time))

Many applications require a very precise time measurement. For this purpose, Python provides methods in time module. These methods will help you to measure execution time taken by the block of code.

In Linux and Unix, this command can let us know the execution of the python program.

$ time python nameofprogram.py

8. Converting the List to a String for Print

#declaring List
mylist = ['one', 'two', 'three']

print (', '.join(mylist))
print ('\n'.join(mylist))

To combine any list of strings into a single string, use the join method of a string object. First print statement will join string with ” , ” and second will add new line.

Output:
one, two, three
one
two
three

9. Strings Concatenating using ” + ” and more.

Python uses + and * from manipulating String.

Using +

$ python
>>> print "Jhon" + "Doe"
JhonDoe

Using *

$python
>>> print "Jhon" * 3
JhonJhonJho

10. Sorting Array of String

mylist = ['one', 'two', 'three', 'four', 'five']

mylist.sort()

for x in mylist:
    print (x);

Output:
five
four
one
three
two

Let me know your views and best Python tips in comment below.

Validate JSON using Python

Python has built-in JSON module to work with JSON data. Python is getting popular and becoming the first choice of startup development. JSON is used widely because it easy to understand, compact and built in support in JavaScript.

Validating JSON Using Python.

json.loads() method is used to validate JSON data.

Here is the function which will validate JSON data.

#JSON Validator function
import json

def json_validator(data):
    try:
        json.loads(data)
        return True
    except ValueError as error:
        print("invalid json: %s" % error)
        return False

json.loads()

json.loads() loads the JSON data to parse, it will return true or it will fail and raised the exception. This function will work as EAFP (Easier to ask for forgiveness than permission). EAFP is python’s ideology to handle this kind of situation.

Here is the Example of Validating JSON data using Python.

#Validating JSON using Phython Code
import json

def json_validator(data):
    try:
        json.loads(data)
        return True
    except ValueError as error:
        print("invalid json: %s" % error)
        return False
    

#Valid JSON Data
""" {
  "actors": {
    "actor": [
      {
        "id": "1",
        "firstName": "Tom",
        "lastName": "Cruise"
      }
    ]
  }
}
"""

#Invalid JSON Data
"""
 {
    {
    "actor": [
      {
        "id": "1",
        "firstName": "Tom",
        "lastName": "Cruise"
      }
    ]
  }
}
 """


print(json_validator('{"actors":{"actor":[{"id":"1","firstName":"Tom","lastName":"Cruise"}]}}' ))#prints True

print (json_validator('{{"actor":[{"id":"1","firstName":"Tom","lastName":"Cruise"}]}}')) #prints Error message and False

#End

These ready-made tools can be used to validate JSON data online JSON Validator on CodeBeautify. and Json Validator.

Validate JSON String Using PHP

JSON is the popular data format to transfer data between client and server. There are many JSON validators are available online such as JSON Validator and JSON Validator on CodeBeautify to validate JSON.

As a programmer, I am curious to know how these tools are working. Here I am going to explain.

json_decode() is the function which is been introduce in PHP 5.3 to validate JSON String.

About json_decode

Here is the description is given in PHP specification.

mixed json_decode ( string [, bool = false [, int = 512 [, int = 0 ]]] )

This function takes a JSON encoded the string and converts it into a PHP variable.

Here is the function which works as JSON Validator.

//JSON Validator function
function json_validator($data=NULL) {
	
	if (!empty($data)) {
		
                @json_decode($data);
		
                return (json_last_error() === JSON_ERROR_NONE);
	
        }
	
        return false;
}

Let’s see how does this work.

if (!empty($data))

This condition will check the $data variable is not empty. If $data is empty, then it will return false.

@json_decode($data)

json_decode parses the data and return the PHP variable if the string is valid. If the string is not valid it will generate the error. Character “@” will suppress the error.

return (json_last_error() === JSON_ERROR_NONE);

This will check if $data is valid JSON string by comparing with JSON_ERROR_NONE. json_last_error() return the last error when json_decode() has called if there are any.

Here is the Example of Validating JSON data

<?php
//JSON Validator function
function json_validator($data=NULL) {
	
	if (!empty($data)) {
		
                @json_decode($data);
		
                return (json_last_error() === JSON_ERROR_NONE);
	
        }
	
        return false;
}


//valid JSON Data
/*
 {
  "actors": {
    "actor": [
      {
        "id": "1",
        "firstName": "Tom",
        "lastName": "Cruise"
      }
    ]
  }
}
 */

$sampleJSONData1 = '{"actors":{"actor":[{"id":"1","firstName":"Tom","lastName":"Cruise"}]}}' ; 


//invalid JSON Data
/*
 {
    {
    "actor": [
      {
        "id": "1",
        "firstName": "Tom",
        "lastName": "Cruise"
      }
    ]
  }
}
 */
 

$sampleJSONData2 = '{{"actor":[{"id":"1","firstName":"Tom","lastName":"Cruise"}]}}' ;

echo (json_validator($sampleJSONData1) ? "JSON is Valid" : "JSON is Not Valid");

echo "
";

echo (json_validator($sampleJSONData2) ? "JSON is Valid" : "JSON is Not Valid");

All about AJAX – From Beginners to Experts – Part 1

Brief History of Web Development

Let’s go 18 years back 1996, We have just started to create web pages, static with text, static with images and wowed the world. The browser was in demand to display web pages which render HTML. Later on using Perl or C dynamic content has started to serve to a browser. As HTML and Browser evolved, Web becoming interesting, to stream video, playing games, online chatting, pay the bills, find a date and lots of other fun/work activity.

Flash Player was the key part in 2000 to the 2010 year. By using it, Advertiser has started creating animated ads and born of Rich Internet Application. With the use of Adobe Flex technology and instantly became famous. But Flash Player is not supported by Apple on Mobile devices and HTML 5 seems promising.

HTML 5 has gain popularity and started to use as to make Richer Internet Application using JavaScript and it’s framework introduced by many giants. i.e JQuery, DOJO, Backbone, Sencha , Angular.

New Trend came and that’s Single Page Application without refreshing the page, render dynamic data like Gmail does. To get data, Browser needs to send the request to the server using JavaScript and that’s called AJAX.

Brief History of AJAX

Microsoft has introduced Internet Explorer to beat Netscape Navigator and got succeed. IE become the world famous browser and introduced many functionalities like ActiveX and Iframe to load asynchronous data. In 1998 IE introduce XMLHTTP for outlook web app. Another browser like Mozilla, Safari has introduced XMLHttpRequest and IE has supported in IE 7.

JavaScript was not widely supported and trusted language in those days. So the world was adopting Adobe Flex to develop Enterprise Rich Internet Application and it grew a lot in 2007-2008. In 2010 Apple wrote a letter in regarding supporting flash player in Iphone, IPAD and IOS supported devices and that was not a good news for Adobe for more info click here. From that day the Big company would hesitate to build an application in Flex and search for new approach rises.

Google continued to develop an application in that approach and gave the world GMail, GMap, Google+, Picasa etc using AJAX and others followed.

What is AJAX?

AJAX stands for Asynchronous JavaScript and XML. AJAX is a technique to send the request and get data asynchronously with the refreshing web page which happens in the traditional application like Wikipedia.

With Ajax, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. – Wikipedia

XMLHttpRequest is used to make a call to server and retrieve the data. It’s an API provided by the browser to support AJAX technology.

This JavaScript code is to make ajax call to server.

function myAjax() {
 var xmlHttp = new XMLHttpRequest();
 var url="serverStuff.php";
 var parameters = "first=barack&last=obama";
 xmlHttp.open("POST", url, true);

 //Black magic paragraph
 xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 xmlHttp.setRequestHeader("Content-length", parameters.length);
 xmlHttp.setRequestHeader("Connection", "close");

 xmlHttp.onreadystatechange = function() {
  if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
   document.getElementById('ajaxDump').innerHTML+=xmlHttp.responseText+"<br />";
  }
 }

 xmlHttp.send(parameters);
} //from stackoverflow

Here is the php code.

<?php
 //serverStuff.php
 //from stackoverflow
$lastName= $_POST['last']; $firstName = $_POST['first']; //everything echo'd becomes responseText in the JavaScript echo "Welcome, " . ucwords($firstName).' '.ucwords($lastName); ?>

And here is HTML code.

<!--Just doing some ajax over here... from stackoverflow-->
<a href="#" onclick="myAjax();return false">
Just trying out some Ajax here....</a>
<br />
<br />
<span id="ajaxDump"></span>

This is an example without any framework or library. Just plain JavaScript.

In next blog, it will be in more detail to make a different kind of ajax call with JQuery.

 

Understanding JMeter Results

JMeter is the best and free Performance testing tool.

When I started working on JMETER for performance testing of Code Beautify, I got confused when got the result. All JMETER results terms are gibberish to me. So I have started searching Google to find and understand what this reports wants to say. What I have learned would like to share with you.

This is a snapshot of sample JMETER results.

jmeter performance test results
Jmeter Performance Test Results

Let’s decode this results:

This an aggregated Report of JMeter having these columns Label, # Samples, Average, Median, 90% Line, Max, Min, Error %, Throughput, KB/Sec.

  • Label : Label column display HTTP request created for test. i.e for me the request is http://127.0.0.1/jsonviewer and give label as jsonviewer.
  • # Samples : Samples shows the number of http request runs for given thread. In this case jsonviewer makes 682 requests.
  • Median : is a number which divides the samples into two equal halves. Half of the samples are smaller than the median, and half are larger.
  • 90% Line : is the value below which 90% of the samples fall. The remaining samples too at least as long as the value. This is a standard statistical measure.
  • Max / Min : These are the minimum and maximum value of time required for receiving the web page.
  • Error % : This column indicated the percentage of error. For HTML Viewer made 641 requests and failed each and every request, so it gave 100% error rate. If Server is not able to serve the request, this column will help to determine the capability of the server to serve the requests.
  • Throughput : is calculated as requests/unit of time. The time is calculated from the start of the first sample to the end of the last sample. This includes any intervals between samples, as it is supposed to represent the load on the server. Formula : Throughput = (number of requests) / (total time).
  • KB/Sec : The throughput measured in Kilobytes per second.

I hope this may help to understand JMeter’s results.

 

Accessing instance method of JavaScript using this keyword inside each()

As a Java or C# developer, this keyword can we be used in instance method or in constructor to access variables or instance methods.

JavaScript is a prototype-based scripting language and supports Object-Oriented features and this keyword too.

JQuery is most popular JavaScript Cross-Platform library and 99.99% developers uses it for web development. JQuery has $.each() to iterate jQuery object.

Like

var sum = 0;

var values = [ 10, 20, 30, 40, 50 ];

$.each( values, function(){
sum += this;
});

console.log( sum ); //sum would be 150

In above example, when elements iterate with each, it create dynamic object inside the method named this. Now using this object we can have the access of each element. in this example using this we can get the value.

How this can be used in Javascript class. Here is the example.

function Employee (position,name) {
    this.position = position;
    this.name = name;
    this.getInfo = function() {
         return this.name + ' ' + this.position +" earns "+this.getSalary();
    };

    this.getSalary = function(){
      return "$10,000";
    }
}

var employee = new Employee("Spy","James Bond");
console.log( employee.getInfo() );  // James Bond Spy earns $10,000 

Now what if we use $.each() in Javascript class and want to use <strong>this </strong>keyword as Javascript class’s instance as well as to get element in the $.each iterator?

function Employee (position,name) {
    this.position = position;
    this.name = name;
    
    this.getInfo = function() {
        return this.name + ' ' + this.position +" earns "+this.getSalary();
    };

    this.getSalary = function(){
      return "$10,000";
    }

    this.printInfoIfSalary=function(salary){

      var salaryList = {"Manager": 20000, "Spy": 10000, "mentor": 5000};

      $.each( salaryList, function(key){
          if(salary==this){

           //Now what If I want to call getInfo from here   
            this.getInfo(); //Wont Work
            getInfo(); //wont work

          }               
      });
    }
}

var employee = new Employee("Spy","James Bond");
console.log( employee.getInfo() );  // James Bond Spy earns $10,000 
employee.printInfoIfSalary(10000);

When employee.printInfoIfSalary(10000) executed, there is no way using this or with this to call getInfo() method within each method of jQuery and it will throw uncaught TypeError: undefined is not a function.

using this Uncaught TypeError: undefined is not a function

How can we fix this? I have spent more than 1 hour to solve this problem. but finally I figured it out. Here is working code.

Working code to fix above issue.

function Employee (position,name) {
    this.position = position;
    this.name = name;
    //define thisObj as globle variable and give this reference
    //now thisObj can used as this if class instance
    var thisObj = this;
    this.getInfo = function() {
        return this.name + ' ' + this.position +" earns "+this.getSalary();
    };

    this.getSalary = function(){
      return "$10,000";
    }

    this.printInfoIfSalary=function(salary){

      var salaryList = {"Manager": 20000, "Spy": 10000, "mentor": 5000};

      $.each( salaryList, function(key){
          if(salary==this){
        
          //Now what If I want to call getInfo from here   

          console.log(  thisObj.getInfo() ); //will Work

            //getInfo(); or this.getInfo() //wont work
          }               
      });
    }
}
var employee = new Employee("Spy","James Bond");
console.log(employee.printInfoIfSalary(10000));

In this example we define thisObj = this, reference of this variable to thisObj, and now thisObj can be reference as instance of this class.

I hope this example with help you to understand when jQuery and OOPs concepts needs to use together.

Code for this example:  http://codebeautify.org/htmlviewer/e1ce80