পৃষ্ঠাসমূহ

.

Search Your Article

Total Pageviews

Friday, March 31, 2017

Ruby Quick Reference Guide

Here is a quick reference guide for Ruby developers:

What is Ruby ?

Ruby is a pure object-oriented programming language. It was created in 1993 by Yukihiro Matsumoto of Japan. Ruby is a general-purpose, interpreted programming language like PERL and Python.

Ruby Built-in Functions

Since the Kernel module is included by Object class, its methods are available everywhere in the Ruby program. They can be called without a receiver (functional form). Therefore, they are often called functions.
A complete list of Built-in Functions is given here for your reference:

Ruby Predefined Variables

Ruby's predefined variables affect the behavior of the entire program, so their use in libraries is not recommended.
The values in most predefined variables can be accessed by alternative means.
Following table lists all the Ruby's predefined variables.

Ruby Predefined Constants

The following table lists all the Ruby's Predefined Constants:
NOTE: TRUE, FALSE, and NIL are backward-compatible. It's preferable to use true, false, and nil.
Constant NameDescription
TRUESynonym for true.
FALSESynonym for false.
NILSynonym for nil.

Ruby Associated Tools

Standard Ruby Tools:

The standard Ruby distribution contains useful tools along with the interpreter and standard libraries:
These tools help you debug and improve your Ruby programs without spending much effort. This tutorial will give you a very good start with these tools.

Ruby - Useful Resources

The following resources contain additional information on Ruby. Please use them to get more in-depth knowledge on this topic.

Useful Links on Ruby

Discuss Ruby

Ruby is a scripting language designed by Yukihiro Matsumoto, also known as Matz. It runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.
This tutorial gives a complete understanding on Ruby.

RSpec - Introduction

RSpec is a unit test framework for the Ruby programming language. RSpec is different than traditional xUnit frameworks like JUnit because RSpec is a Behavior driven development tool. What this means is that, tests written in RSpec focus on the “behavior” of an application being tested. RSpec does not put emphasis on, how the application works but instead on how it behaves, in other words, what the application actually does.

RSpec - Basic Syntax

Let’s take a closer look at the code of our HelloWorld example. First of all, in case it isn’t clear, we are testing the functionality of the HelloWorld class. This of course, is a very simple class that contains only one method say_hello().
Here is the RSpec code again −

RSpec - Writing Specs

In this chapter, we will create a new Ruby class, save it in its own file and create a separate spec file to test this class.
First, in our new class, it is called StringAnalyzer. It’s a simple class that, you guessed it, analyzes strings. Our class has only one method has_vowels? which as its names suggests, returns true if a string contains vowels and false if it doesn’t. Here’s the implementation for StringAnalyzer

RSpec - Matchers

If you recall our original Hello World example, it contained a line that looked like this −
expect(message).to eq "Hello World!"
The keyword eql is an RSpec “matcher”. Here, we will introduce the other types of matchers in RSpec.

RSpec - Test Doubles

In this chapter, we will discuss RSpec Doubles, also known as RSpec Mocks. A Double is an object which can “stand in” for another object. You’re probably wondering what that means exactly and why you’d need one.

RSpec - Stubs

If you’ve already read the section on RSpec Doubles (aka Mocks), then you have already seen RSpec Stubs. In RSpec, a stub is often called a Method Stub, it’s a special type of method that “stands in” for an existing method, or for a method that doesn’t even exist yet.
Here is the code from the section on RSpec Doubles −

RSpec - Hooks

When you are writing unit tests, it is often convenient to run setup and teardown code before and after your tests. Setup code is the code that configures or “sets up” conditions for a test. Teardown code does the cleanup, it makes sure that the environment is in a consistent state for subsequent tests.

RSpec - Tags

RSpec Tags provide an easy way to run specific tests in your spec files. By default, RSpec will run all tests in the spec files that it runs, but you might only need to run a subset of them. Let’s say that you have some tests that run very quickly and that you’ve just made a change to your application code and you want to just run the quick tests, this code will demonstrate how to do that with RSpec Tags.

RSpec - Subjects

One of RSpec’s strengths is that it provides many ways to write tests, clean tests. When your tests are short and uncluttered, it becomes easier to focus on the expected behavior and not on the details of how the tests are written. RSpec Subjects are yet another shortcut allowing you to write simple straightforward tests.
Consider this code −

RSpec - Helpers

Sometimes your RSpec examples need an easy way to share reusable code. The best way to accomplish this is with Helpers. Helpers are basically regular Ruby methods which you share across examples. To illustrate the benefit of using helpers, let’s consider this code −

RSpec - Metadata

RSpec is a flexible and powerful tool. The Metadata functionality in RSpec is no exception. Metadata generally refers to “data about data”. In RSpec, this means data about your describe, context and it blocks.
Let’s take a look at an example −

RSpec - Filtering

You may want to read the section on RSpec Metadata before reading this section because, as it turns out, RSpec filtering is based on RSpec Metadata.
Imagine that you have a spec file and it contains two types of tests (Examples): positive functional tests and negative (error) tests. Let’s define them like this −

RSpec - Expectations

When you learn RSpec, you may read a lot about expectations and it can be a bit confusing at first. There are two main details you should keep in mind when you see the term Expectation −
  • An Expectation is simply a statement in an it block that uses the expect() method. That’s it. It’s no more complicated than that. When you have code like this: expect(1 + 1).to eq(2), you have an

RSpec - Quick Guide

RSpec - Introduction

RSpec is a unit test framework for the Ruby programming language. RSpec is different than traditional xUnit frameworks like JUnit because RSpec is a Behavior driven development tool. What this means is that, tests written in RSpec focus on the “behavior” of an application being tested. RSpec does not put emphasis on, how the application works but instead on how it behaves, in other words, what the application actually does.

RSpec - Useful Resources

The following resources contain additional information on RSpec. Please use them to get more in-depth knowledge on this.

Discuss RSpec

RSpec is a unit test framework for the Ruby programming language. RSpec is different than traditional xUnit frameworks like JUnit because RSpec is a Behavior driven development tool. What this means is that, tests written in RSpec focus on the "behavior" of an application being tested. RSpec does not put emphasis on, how the application works but instead on how it behaves, in other words, what the application actually does. This tutorial will show you, how to use RSpec to test your code when building applications with Ruby.

What is New in Python 3

The __future__ module

Python 3.x introduced some Python 2-incompatible keywords and features that can be imported via the in-built __future__ module in Python 2. It is recommended to use __future__ imports, if you are planning Python 3.x support for your code.
For example, if we want Python 3.x's integer division behavior in Python 2, add the following import statement.
from __future__ import division

Python 3 - Overview

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently whereas the other languages use punctuations. It has fewer syntactical constructions than other languages.

Python 3 - Environment Setup

Try it Option Online

We have set up the Python Programming environment online, so that you can compile and execute all the available examples online. It will give you the confidence in what you are reading and will enable you to verify the programs with different options. Feel free to modify any example and execute it online.

Python 3 - Basic Syntax

The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages.

First Python Program

Let us execute the programs in different modes of programming.

Python 3 - Variable Types

Variables are nothing but reserved memory locations to store values. It means that when you create a variable, you reserve some space in the memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to the variables, you can store integers, decimals or characters in these variables.

Python 3 - Basic Operators

Operators are the constructs, which can manipulate the value of operands. Consider the expression 4 + 5 = 9. Here, 4 and 5 are called the operands and + is called the operator.

Types of Operator

Python language supports the following types of operators −
  • Arithmetic Operators
  • Comparison (Relational) Operators
  • Assignment Operators

Python 3 - Decision Making

Decision-making is the anticipation of conditions occurring during the execution of a program and specified actions taken according to the conditions.
Decision structures evaluate multiple expressions, which produce TRUE or FALSE as the outcome. You need to determine which action to take and which statements to execute if the outcome is TRUE or FALSE otherwise.

Python 3 - Loops

In general, statements are executed sequentially − The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times.
Programming languages provide various control structures that allow more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. The following diagram illustrates a loop statement −

Python 3 - Numbers

Number data types store numeric values. They are immutable data types. This means, changing the value of a number data type results in a newly allocated object.
Number objects are created when you assign a value to them. For example −
var1 = 1
var2 = 10

Python 3 - Strings

Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable. For example −
var1 = 'Hello World!'
var2 = "Python Programming"

Python 3 - Lists

The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number - its position or index. The first index is zero, the second index is one, and so forth.
Python has six built-in types of sequences, but the most common ones are lists and tuples, which we would see in this tutorial.

Python 3 - Tuples

A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The main difference between the tuples and the lists is that the tuples cannot be changed unlike lists. Tuples use parentheses, whereas lists use square brackets.

Python 3 - Dictionary

Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

Python 3 - Date & Time

A Python program can handle date and time in several ways. Converting between date formats is a common chore for computers. Python's time and calendar modules help track dates and times.

What is Tick?

Time intervals are floating-point numbers in units of seconds. Particular instants in time are expressed in seconds since 12:00am, January 1, 1970(epoch).

Python 3 - Functions

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.

Python 3 - Modules

A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code.

Python 3 - Files I/O

This chapter covers all the basic I/O functions available in Python 3. For more functions, please refer to the standard Python documentation.

Printing to the Screen

The simplest way to produce output is using the print statement where you can pass zero or more expressions separated by commas. This function converts the expressions you pass into a string and writes the result to standard output as follows −
#!/usr/bin/python3

Python 3 - Exceptions Handling

Python provides two very important features to handle any unexpected error in your Python programs and to add debugging capabilities in them −
  • Exception Handling − This would be covered in this tutorial. Here is a list standard Exceptions available in Python − Standard Exceptions.
  • Assertions − This would be covered in Assertions in Python 3 tutorial.

Python 3 - Object Oriented

Python has been an object-oriented language since the time it existed. Due to this, creating and using classes and objects are downright easy. This chapter helps you become an expert in using Python's object-oriented programming support.
If you do not have any previous experience with object-oriented (OO) programming, you may want to consult an introductory course on it or at least a tutorial of some sort so that you have a grasp of the basic concepts.

Python 3 - Regular Expressions

A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world.
The module re provides full support for Perl-like regular expressions in Python. The re module raises the exception re.error if an error occurs while compiling or using a regular expression.

Python 3 - CGI Programming

The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script. The CGI specs are currently maintained by the NCSA and NCSA.

What is CGI?

  • The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers.
  • The current version is CGI/1.1 and CGI/1.2 is under progress.

Python 3 - MySQL Database Access

The Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere to this standard.
You can choose the right database for your application. Python Database API supports a wide range of database servers such as −

Python 3 - Network Programming

Python provides two levels of access to the network services. At a low level, you can access the basic socket support in the underlying operating system, which allows you to implement clients and servers for both connection-oriented and connectionless protocols.

Python 3 - Sending Email using SMTP

Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending an e-mail and routing e-mail between mail servers.
Python provides smtplib module, which defines an SMTP client session object that can be used to send mails to any Internet machine with an SMTP or ESMTP listener daemon.
Here is a simple syntax to create one SMTP object, which can later be used to send an e-mail −
import smtplib

Python 3 - Multithreaded Programming

Running several threads is similar to running several different programs concurrently, but with the following benefits −
  • Multiple threads within a process share the same data space with the main thread and can therefore share information or communicate with each other more easily than if they were separate processes.
  • Threads are sometimes called light-weight processes and they do not require much memory overhead; they are cheaper than processes.

Python 3 - XML Processing

XML is a portable, open source language that allows programmers to develop applications that can be read by other applications, regardless of operating system and/or developmental language.

Python 3 - GUI Programming (Tkinter)

Python provides various options for developing graphical user interfaces (GUIs). The most important features are listed below.
  • Tkinter − Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would look this option in this chapter.

Python 3 - Extension Programming with C

Any code that you write using any compiled language like C, C++, or Java can be integrated or imported into another Python script. This code is considered as an "extension."
A Python extension module is nothing more than a normal C library. On Unix machines, these libraries usually end in .so (for shared object). On Windows machines, you typically see .dll (for dynamically linked library).

Python 3 - Questions and Answers

Python Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations.

Python 3 - Quick Guide

What is New in Python 3?

The __future__ module

Python 3.x introduced some Python 2-incompatible keywords and features that can be imported via the in-built __future__ module in Python 2. It is recommended to use __future__ imports, if you are planning Python 3.x support for your code.
For example, if we want Python 3.x's integer division behavior in Python 2, add the following import statement.
from __future__ import division

Python 3 - Tools/Utilities

The standard library comes with a number of modules that can be used both as modules and as command-line utilities.

The dis Module:

The dis module is the Python disassembler. It converts byte codes to a format that is slightly more appropriate for human consumption.

Python 3 - Useful Resources

The following resources contain additional information on Python 3. Please use them to get more in-depth knowledge on this topic.

Useful Links on Python 3

  • Python.org − Official Python site. Find a complete list of all documentation, installation, tutorials, news etc.
  • Web Programming in Python − This topic guide attempts to cover every aspect of programming Web applications (both clients and servers) using Python.

Discuss Python 3

Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL). Python is named after a TV Show called ‘Monty Python’s Flying Circus’ and not after Python-the snake.

Python Overview

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.

Python - Environment Setup

Python is available on a wide variety of platforms including Linux and Mac OS X. Let's understand how to set up our Python environment.

Local Environment Setup

Open a terminal window and type "python" to find out if it is already installed and which version is installed.
  • Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX, etc.)

Python Basic Syntax

The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages.

First Python Program

Let us execute programs in different modes of programming.

Python Variable Types

Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables.

Python Basic Operators

Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.

Types of Operator

Python language supports the following types of operators.
  • Arithmetic Operators
  • Comparison (Relational) Operators
  • Assignment Operators

Python Decision Making

Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You need to determine which action to take and which statements to execute if outcome is TRUE or FALSE otherwise.
Following is the general form of a typical decision making structure found in most of the programming languages −

Python Loops

In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. The following diagram illustrates a loop statement −

Python Numbers

Number data types store numeric values. They are immutable data types, means that changing the value of a number data type results in a newly allocated object.
Number objects are created when you assign a value to them. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The syntax of the del statement is −

Python Strings

Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable. For example −
var1 = 'Hello World!'
var2 = "Python Programming"

Python Lists

The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number - its position or index. The first index is zero, the second index is one, and so forth.
Python has six built-in types of sequences, but the most common ones are lists and tuples, which we would see in this tutorial.

Python Tuples

A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also. For example −

Python Dictionary

Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

Python Date & Time

A Python program can handle date and time in several ways. Converting between date formats is a common chore for computers. Python's time and calendar modules help track dates and times.

Python Functions

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.

Python Modules

A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code.

Python Files I/O

This chapter covers all the basic I/O functions available in Python. For more functions, please refer to standard Python documentation.

Printing to the Screen

The simplest way to produce output is using the print statement where you can pass zero or more expressions separated by commas. This function converts the expressions you pass into a string and writes the result to standard output as follows −

Python Exceptions Handling

Python provides two very important features to handle any unexpected error in your Python programs and to add debugging capabilities in them −
  • Exception Handling: This would be covered in this tutorial. Here is a list standard Exceptions available in Python: Standard Exceptions.
  • Assertions: This would be covered in Assertions in Python tutorial.

Python Object Oriented

Python has been an object-oriented language since it existed. Because of this, creating and using classes and objects are downright easy. This chapter helps you become an expert in using Python's object-oriented programming support.

Python Regular Expressions

A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world.
The module re provides full support for Perl-like regular expressions in Python. The re module raises the exception re.error if an error occurs while compiling or using a regular expression.

Python CGI Programming

The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script. The CGI specs are currently maintained by the NCSA.

What is CGI?

  • The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers.
  • The current version is CGI/1.1 and CGI/1.2 is under progress.

Python MySQL Database Access

The Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere to this standard.
You can choose the right database for your application. Python Database API supports a wide range of database servers such as −

Python Network Programming

Python provides two levels of access to network services. At a low level, you can access the basic socket support in the underlying operating system, which allows you to implement clients and servers for both connection-oriented and connectionless protocols.
Python also has libraries that provide higher-level access to specific application-level network protocols, such as FTP, HTTP, and so on.

Python Sending Email using SMTP

Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending e-mail and routing e-mail between mail servers.
Python provides smtplib module, which defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon.
Here is a simple syntax to create one SMTP object, which can later be used to send an e-mail −
import smtplib

Python Multithreaded Programming

Running several threads is similar to running several different programs concurrently, but with the following benefits −
  • Multiple threads within a process share the same data space with the main thread and can therefore share information or communicate with each other more easily than if they were separate processes.
  • Threads sometimes called light-weight processes and they do not require much memory overhead; they are cheaper than processes.

Python XML Processing

XML is a portable, open source language that allows programmers to develop applications that can be read by other applications, regardless of operating system and/or developmental language.

What is XML?

The Extensible Markup Language (XML) is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard.
XML is extremely useful for keeping track of small to medium amounts of data without requiring a SQL-based backbone.

Python GUI Programming (Tkinter)

Python provides various options for developing graphical user interfaces (GUIs). Most important are listed below.
  • Tkinter: Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would look this option in this chapter.
  • wxPython: This is an open-source Python interface for wxWindows http://wxpython.org.
  • JPython: JPython is a Python port for Java which gives Python scripts seamless access to Java class libraries on the local machine http://www.jython.org.

Python Extension Programming with C

Any code that you write using any compiled language like C, C++, or Java can be integrated or imported into another Python script. This code is considered as an "extension."
A Python extension module is nothing more than a normal C library. On Unix machines, these libraries usually end in .so (for shared object). On Windows machines, you typically see .dll (for dynamically linked library).

Python Questions and Answers

Python Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations.

Python Quick Guide

Python Overview:

Python is a high-level, interpreted, interactive and object oriented-scripting language.
  • Python is Interpreted
  • Python is Interactive
  • Python is Object-Oriented
  • Python is Beginner's Language

Python Tools/Utilities

The standard library comes with a number of modules that can be used both as modules and as command-line utilities.

The dis Module:

The dis module is the Python disassembler. It converts byte codes to a format that is slightly more appropriate for human consumption.

Python Useful Resources

The following resources contain additional information on Python Please use them to get more in-depth knowledge on this topic.

Useful Links on Python

  • Python.org − Official Python site. Find a complete list of all documentation, installation, tutorials, news etc.

Discuss Python

Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL). This tutorial gives enough understanding on Python programming language.

PyQt - Introduction

PyQt is a GUI widgets toolkit. It is a Python interface for Qt, one of the most powerful, and popular cross-platform GUI library. PyQt was developed by RiverBank Computing Ltd. The latest version of PyQt can be downloaded from its official website − riverbankcomputing.com

PyQt - Hello World

Creating a simple GUI application using PyQt involves the following steps −
  • Import QtGui module.
  • Create an application object.
  • A QWidget object creates top level window. Add QLabel object in it.
  • Set the caption of label as “hello world”.
  • Define the size and position of window by setGeometry() method.
  • Enter the mainloop of application by app.exec_() method.

PyQt - Major Classes

PyQt API is a large collection of classes and methods. These classes are defined in more than 20 modules. Following are some of the frequently used modules −
S.No. Modules & Description
1 QtCore
Core non-GUI classes used by other modules
2 QtGui
Graphical user interface components

PyQt - Using Qt Designer

The PyQt installer comes with a GUI builder tool called Qt Designer. Using its simple drag and drop interface, a GUI interface can be quickly built without having to write the code. It is however, not an IDE such as Visual Studio. Hence, Qt Designer does not have the facility to debug and build the application.
Creation of a GUI interface using Qt Designer starts with choosing a top level window for the application.

PyQt - Signals & Slots

Unlike a console mode application, which is executed in a sequential manner, a GUI based application is event driven. Functions or methods are executed in response to user’s actions like clicking on a button, selecting an item from a collection or a mouse click etc., called events.

PyQt - Layout Management

A GUI widget can be placed inside the container window by specifying its absolute coordinates measured in pixels. The coordinates are relative to the dimensions of the window defined by setGeometry() method.

setGeometry() syntax

QWidget.setGeometry(xpos, ypos, width, height)
In the following code snippet, the top level window of 300 by 200 pixels dimensions is displayed at position (10, 10) on the monitor.

PyQt - Basic Widgets

Here is the list of Widgets which we will discuss one by one in this chapter.
Sr.No Widgets & Description
1 QLabel A QLabel object acts as a placeholder to display non-editable text or image, or a movie of animated GIF. It can also be used as a mnemonic key for other widgets.
2 QLineEdit

PyQt - QDialog Class

A QDialog widget presents a top level window mostly used to collect response from the user. It can be configured to be Modal (where it blocks its parent window) or Modeless (the dialog window can be bypassed).
PyQt API has a number of preconfigured Dialog widgets such as InputDialog, FileDialog, FontDialog, etc.

PyQt - QMessageBox

QMessageBox is a commonly used modal dialog to display some informational message and optionally ask the user to respond by clicking any one of the standard buttons on it. Each standard button has a predefined caption, a role and returns a predefined hexadecimal number.
Important methods and enumerations associated with QMessageBox class are given in the following table −

PyQt - Multiple Document Interface

A typical GUI application may have multiple windows. Tabbed and stacked widgets allow to activate one such window at a time. However, many a times this approach may not be useful as view of other windows is hidden.
One way to display multiple windows simultaneously is to create them as independent windows. This is called as SDI (single Document Interface). This requires more memory resources as each window may have its own menu system, toolbar, etc.

PyQt - Drag & Drop

The provision of drag and drop is very intuitive for the user. It is found in many desktop applications where the user can copy or move objects from one window to another.
MIME based drag and drop data transfer is based on QDrag class. QMimeData objects associate the data with their corresponding MIME type. It is stored on clipboard and then used in the drag and drop process.

PyQt - Database Handling

PyQt API contains an elaborate class system to communicate with many SQL based databases. Its QSqlDatabase provides access through a Connection object. Following is the list of currently available SQL drivers −
Driver Type Description
QDB2 IBM DB2
QIBASE Borland InterBase Driver

PyQt - Drawing API

All the QWidget classes in PyQt are sub classed from QPaintDevice class. A QPaintDevice is an abstraction of two dimensional space that can be drawn upon using a QPainter. Dimensions of paint device are measured in pixels starting from the top-left corner.

PyQt - BrushStyle Constants

Predefined QColor Styles

Qt.NoBrush No brush pattern
Qt.SolidPattern Uniform color
Qt.Dense1Pattern Extremely dense brush pattern
Qt.HorPattern Horizontal lines

PyQt - QClipboard

The QClipboard class provides access to system-wide clipboard that offers a simple mechanism to copy and paste data between applications. Its action is similar to QDrag class and uses similar data types.
QApplication class has a static method clipboard() which returns reference to clipboard object. Any type of MimeData can be copied to or pasted from the clipboard.

PyQt - QPixmap Class

QPixmap class provides an off-screen representation of an image. It can be used as a QPaintDevice object or can be loaded into another widget, typically a label or button.
Qt API has another similar class QImage, which is optimized for I/O and other pixel manipulations. Pixmap, on the other hand, is optimized for showing it on screen. Both formats are interconvertible.
The types of image files that can be read into a QPixmap object are as follows −

PyQt - Quick Guide

PyQt - Introduction

PyQt is a GUI widgets toolkit. It is a Python interface for Qt, one of the most powerful, and popular cross-platform GUI library. PyQt was developed by RiverBank Computing Ltd. The latest version of PyQt can be downloaded from its official website − riverbankcomputing.com

PyQt - Useful Resources

The following resources contain additional information on PyQt. Please use them to get more in-depth knowledge on this.

Useful Links on PyQt

Discuss PyQt

PyQt is a GUI widgets toolkit. It is a Python interface for Qt, one of the most powerful, and popular cross-platform GUI library. PyQt is a blend of Python programming language and the Qt library. This introductory tutorial will assist you in creating graphical applications with the help of PyQt.

Thursday, March 30, 2017

PyGTK - Introduction

PyGTK is a set of wrappers written in Python and C for GTK + GUI library. It is part of the GNOME project. It offers comprehensive tools for building desktop applications in Python. Python bindings for other popular GUI libraries are also available.
PyQt is a Python port of QT library. Our PyQt tutorial can be found here. Similarly, wxPython toolkit is Python binding for wxWidgets, another popular cross-platform GUI library. Our wxPython tutorial is available here.

PyGTK - Environment

PyGTK for Microsoft Windows

The installation of PyGTK for Microsoft Windows involves the following steps −
  • Step 1 − Install a 32-bit Python interpreter (latest Python 2.7 distribution)
  • Step 2 − Download and install GTK+ runtime.

PyGTK - Hello World

Creating a window using PyGTK is very simple. To proceed, we first need to import the gtk module in our code.
import gtk
The gtk module contains the gtk.Window class. Its object constructs a toplevel window. We derive a class from gtk.Window.
class PyApp(gtk.Window):

PyGTK - Important Classes

The PyGTK module contains various widgets. gtk.Object class acts as the base class for most of the widgets as well as for some non-widget classes. The toplevel window for desktop applications using PyGTK is provided by gtk.Window class. The following table lists the important widgets and their functions −

PyGTK - Window Class

An object of the gtk.Window class provides a widget that users commonly think of as a Wwindow. This widget is a container hence, it can hold one child widget. It provides a displayable area decorated with title bar and resizing controls.
gtk.Window class has the following constructor −

PyGTK - Button Class

The gtk.Button widget is usually displayed as a pushbutton with a text label. It is generally used to attach a callback function or method that is called when the button is clicked.
The gtk.Button class has the following constructor −
gtk.Button(label = None, stock = None, use_underline = True)
Wherein,

PyGTK - Label Class

A Label widget is useful to display non-editable text. Label is used by many other widgets internally. For example, Button has a label to show text on the face. Similarly, MenuItem objects have a label. A label is a windowless object, so it cannot receive events directly.
Label class has a simple constructor −

PyGTK - Entry Class

Entry widget is a single-line text entry widget. If the entered text is longer than the allocation of the widget, the widget will scroll so that the cursor position is visible.
Entry field can be converted in password mode using set_visibility() method of this class. Entered text is substituted by character chosen by invisible_char() method, default being '*'.
The Entry class has the following constructor −

PyGTK - Signal Handling

Unlike a console mode application, which is executed in a sequential manner, a GUI-based application is event driven. The gtk.main() function starts an infinite loop. Events occurring on the GUI are transferred to appropriate callback functions.

PyGTK - Event Handling

In addition to the signal mechanism, window system events can also be connected to callback functions. Window resizing, key press, scroll event etc. are some of common window system events. These events are reported to application's main loop. From there, they are passed along via signals to the callback functions.
Some of the system events are listed below −

PyGTK - Containers

PyGTK library provides different container classes to control the placement of widgets inside a window. The easiest way is to use a fixed container class and place a widget inside it by specifying its absolute coordinates measured in pixels.
Let us now follow these steps −

PyGTK - Box Class

The gtk.Box class is an abstract class defining the functionality of a container in which widgets are placed in a rectangular area. gtk.HBox and gtk.VBox widgets are derived from it.
Child widgets in gtk.Hbox are arranged horizontally in the same row. On the other hand, child widgets of gtk.VBox are arranged vertically in the same column.

PyGTK - ButtonBox Class

The ButtonBox class in gtk API serves as a base class for containers to hold multiple buttons either horizontally or vertically. Two subclasses HButtonBox and VButtonBox are derived from the ButtonBox class, which itself is a subclass of gtk.Box class.

PyGTK - Alignment Class

This widget proves useful in controlling alignment and size of its child widgets. It has four properties called xalign, yalign, xscale and yscale. The scale properties specify how much of free space will be used by the child widgets. The align properties areused to place the child widget within available area.

PyGTK - EventBox Class

Some widgets in PyGTK tool kit do not have their own window. Such windowless widgets cannot receive event signals. Such widgets, for example a label, if put inside an eventbox can receive signals.
EventBox is an invisible container that provides window to windowless widgets. It has a simple constructor without any argument −
gtk.EventBox()

PyGTK - Layout Class

The gtk.Layout is a container widget similar to gtk.Fixed. Widgets are placed in Layout widget by specifying absolute coordinates. However, the Layout differs from fixed widget in the following ways −
  • The layout widget can have infinite width and height. The maximum value of width and height is limited by the size of unsigned integer.

PyGTK - ComboBox Class

ComboBox is a powerful and popular widget in any GUI toolkit. It provides a dropdown list of items from which a user can choose. The gtk.ComboBox widget implements the CellLayout interface and provides a number of methods to manage the display of items.

PyGTK - ToggleButton Class

ToggleButton widget is a gtk.Button with two states — a pressed or active (or on) state and a normal or inactive (or off) state. Every time the button is pressed, the state alternates. The state of the ToggleButton can also be changed programmatically by set_active() method. To switch the state of the button, the toggled() method is also available.

PyGTK - CheckButton Class

A CheckButton widget is nothing but a ToggleButton styled as a checkbox and a label. It inherits all properties and methods from the ToggleButton class. Unlike ToggleButton where the caption is on the button's face, a CheckButton displays a small square which is checkable and has a label to its right.
Constructor, methods, and signals associated with gtk.CheckButton are exactly the same as gtk.ToggleButton.

PyGTK - RadioButton Class

A single RadioButton widget offers functionality similar to CheckButton. However, when more than one radio button is present in the same container, then a mutually exclusive choice is available for the user to choose from one of the available options. If every radio button in the container belongs to the same group, then as one is selected, others are automatically deselected.

PyGTK - MenuBar,Menu and MenuItem

A horizontal bar just below the title bar of a toplevel gtk.Window is reserved to display series of menus. It is an object of gtk.MenuBar class in PyGTK API.
An object of the gtk.Menu class is added to the menu bar. It is also used to create context menu and popup menu. Each menu may contain one or more gtk.MenuItem widgets. Some of them can be a submenu.and have cascaded MenuItem buttons.

PyGTK - Toolbar Class

Toolbar class is inherited from the gtk.Container class. It holds and manages a set of buttons and other widgets. One or more horizontal strips of buttons are normally seen just below the menu bar in a top level window. The Toolbar can also be put in a detachable window called HandleBox. By default, the buttons in the gtk.Toolbar widget are laid horizontally. Vertical toolbar can be set up by setting the orientation property

PyGTK - Adjustment Class

Some widgets in PyGTK toolkit are such that their properties can be adjusted over a specified range by the user by using a mouse or a keyboard. A widget like Viewport is used to display some adjustable portion of a large data, for example, a multiline text in TextView control.

PyGTK - Range Class

This class acts as a base class for widgets which let the user to adjust the value of a numeric parameter between the lower and upper bounds. Scale widgets (gtk.Hscale and gtk.Vscale) and scrollbar widgets (gtk.HScrollbar and gtk.VScrollbar) derive functionality from the Range class. These Range widgets work in conjunction with the Adjustment object.

PyGTK - Scale Class

This class acts as an abstract base class for HScale and VScale widgets. These widgets work as a slider control and select a numeric value.
The following methods of this abstract class are implemented by the HScale class and the VScale class −

PyGTK - Scrollbar Class

This class is an abstract base class for gtk.Hscrollbar and gtk.Vscrollbar widgets. Both are associated with an Adjustment object. The position of the thumb of the scrollbar is controlled by scroll adjustments. The attributes of adjustment object are used as follows −

PyGTK - Dialog Class

A Dialog widget is normally used as a pop-up window on top of a parent window. The objective of a Dialog is to collect some data from the user and send it to the parent window. Dialog can be modal (where it blocks the parent frame) or modeless (dialog frame can be bypassed).

PyGTK - MessageDialog Class

A Messagedialog widget is a Dialog window configured to display an image representing the type of message, i.e., error, question, or some informational text. A MessageDialog object is declared by using the following constructor −
gtk.MessageDialog(parent = None, flags = 0, type = gtk.MESSAGE_INFO, 
   buttons = gtk.BUTTONS_NONE, message_format = None)

PyGTK - AboutDialog Class

A simple way to display information about a program like its logo, name, copyright, website and license is offered by the gtk.AboutDialog widget. An about dialog is typically opened when the user selects the About option from the Help menu. All parts of the dialog are optional.
The About Dialog can contain URLs and email addresses. gtk.AboutDialog offers global hooks when the user clicks URLs and email ID

PyGTK - Font Selection Dialog

The gtk.FontSelection widget allows users to select and apply the font of a particular name, size and style. The dialog has a preview box containing some text which will be displayed in selected font description, and two buttons CANCEL and OK.

PyGTK - Color Selection Dialog

This is a preconfigured Dialog in PyGTK API which lets the user to select and apply color. It internally embeds a gtk.ColorSelection widget.
The gtk.ColorScelection widget presents a colow wheel, and entry boxes for color parameters such as HSV and RGB. New color can be selected by manipulating color wheel or entering color parameters. Its get_current_color is useful for further processing.

PyGTK - File Chooser Dialog

This dialog is useful to let the user select the location and the name of file that needs to be opened or saved. It embeds FileChooserWidget and provides OK and CANCEL buttons in the action_area.
The following is a constructor of the gtk.FileChooserDialog class −
Dlg=gtk.FileChooserDialog (title = None, parent = None, 
   action = gtk.FILE_CHOOSER_ACTION_OPEN,  buttons = None, backend = None)
The parameters are −

PyGTK - Notebook Class

Notebook widget is a tabbed container. Each tab in this container holds a different page and the pages are seen in overlapped manner. Any desired page is made visible by clicking on the label of the tab. The labels can be configured to be displayed on top or bottom or to the left or right. A container widget with other widgets placed in it or a single widget is placed under each page.

PyGTK - Frame Class

Frame class is a subclass of the gtk.Bin class. It draws a decorative border around the child widget placed in it. The frame may contain a label whose position may be customized.
A gtk.Frame object is constructed with the help of the following constructor −
frame = gtk.Frame(label = None)

PyGTK - AspectFrame Class

gtk.AspectFrame class is a subclass of the Frame class. The child widget in this frame always retains its aspect ratio (of width and height) even if the main window is resized.
The ratio property of gtk.AspectFrame widget determines the widget width:height ratio. An aspect ratio of 0.5 means the width is one half the height; an aspect ratio of 2.0 means the width is twice the height. The default value for the "ratio" property is 1.0.

PyGTK - TreeView Class

The Treeview widget displays contents of a model implementing the gtk.TreeModel interface. PyGTK provides the following types of models −
  • gtk.ListStore
  • gtk.TreeStore
  • gtk.TreeModelSort

PyGTK - Paned Class

Paned class is the base class for widgets which can display two adjustable panes either horizontally (gtk.Hpaned) or vertically (gtk.Vpaned). Child widgets to panes are added by using pack1() and pack2() methods.
Paned widget draws a separator slider between two panes and provides a handle to adjust their relative width/height. If the resize property of child widget inside a pane is set to True, it will resize according to the size of the panes.

PyGTK - Statusbar Class

A notification area, usually at the bottom of a window is called the status bar. Any type of status change message can be displayed on the status bar. It also has a grip using which it can be resized.
The gtk.Statusbar widget maintains a stack of messages. Hence, new message gets displayed on top of the current message. If it is popped, earlier message will be visible again. Source of the message must be identified by context_id to identify it uniquely.

PyGTK - ProgressBar Class

Progress bars are used to give user the visual indication of a long running process. The gtk.ProgressBar widget can be used in two modes — percentage mode and activity mode.
When it is possible to accurately estimate how much of work is pending to be completed, the progress bar can be used in percentage mode, and the user sees an incremental bar showing percentage of completed job.

PyGTK - Viewport Class

If a widget has an area larger than that of the toplevel window, it is associated with a ViewPort container. A gtk.Viewport widget provides adjustment capability to be used in a ScrolledWindow. A Label widget for instance, doesn't have any adjustments. Hence it needs a Viewport. Some widgets have a native scrolling support. But a Label or a gtk.Table widget doesn't have an in-built scrolling support. Hence they must use Viewport.

PyGTK - ScrolledWindow Class

Scrolled window is created to access other widget of area larger than parent window. Some widgets like TreeView and TextView of native support for scrolling. For others such as Label or Table, a Viewport should be provided.
The following syntax is used for the constructor of the gtk.ScrolledWindow class −
sw = gtk.ScrolledWindow(hadj, vadj)
The following are the methods of the gtk.ScrolledWindow class −

PyGTK - Arrow Class

The gtk.Arrow object is used to draw simple arrow pointing towards four cardinal directions. This class is inherited from the gtk.Misc class and the object will occupy any space allocated it, for instance, a Label or Button widget.
Typically, Arrow object is created using the following constructor −
Arr = gtk.Arrow(arrow_type, shadow_type)
The predefined arrow_type constants are −

PyGTK - Image Class

This class is also inherited from the gtk.Misc class. The object of the gtk.Image class displays an image. Usually, the image is to be loaded from a file in a pixel buffer representing gtk.gdk.Pixbuf class. Instead a convenience function set_from_file() is commonly used to display image data from file in a gk.Image widget.

PyGTK - DrawingArea Class

The DrawingArea widget presents a blank canvas containing a gtk.gdk.Window on which objects such as line, rectangle, arc, etc. can be drawn.
PyGTK uses Cairo library for such drawing operations. Cairo is a popular 2D vector graphics library. It is written in C., although, it has bindings in most Languages such as C++, Java, Python, PHP etc. Cairo library can be used to draw on standard output devices in various operating systems. It can also be used to create PDF, SVG and post-script files.

PyGTK - SpinButton Class

The SpinnButton widget, often called the Spinner is a gtk.Entry widget with up and down arrows on its right. A user can type in a numeric value directly in it or increment or decrement using up and down arrows. The gtk.SpinButton class is inherited from the gtk.Entry class. It uses a gtk.Adjustment object with which the range and step of the numeric value in the spinner can be restricted.

PyGTK - Calendar Class

The Calendar widget in PyGTK toolkit displays a simple calendar with one month view at a time. The navigation controls to change month and year are displayed by default. The display options can be suitably configured.

PyGTK - Clipboard Class

A Clipboard object holds shared data between two processes or two widgets of the same application. The gtk.Clipboard is a high level interface for the gtk.SelectionData class.
The following is a prototype of the gtk.Clipboard constructor −
gtk.Clipboard(display,selction)

PyGTK - Ruler Class

This is a base class for horizontal (gtk.Hruler) and vertical (gtk.Vruler) rulers that are useful to show mouse pointer's position in window. A small triangle in the ruler indicates the location of pointer.
Ruler objects are created with their respective constructors −
hrule = gtk.Hruler()
vrule = gtk.Vruler()

PyGTK - Timeout

The gobject module of the PyGTK API has a useful function to create a timeout function that will be called periodically.
source_id = gobject.timeout_add(interval, function, …)
The second argument is the callback function you wish to have called after every millisecond which is the value of the first argument – interval. Additional arguments may be passed to the callback as function data.
The return value of this function is source_id.

PyGTK - Drag and Drop

Widgets having associated X Window are capable of drag and drop. In the program, a widget as a source and/or destination for drag-and-drop must first be designated. The widget defined as source can send out the dragged data. The destination widget accepts it when dragged data is dropped on it.
The following steps are involved in setting up a drag-and-drop enabled application −

PyGTK - Quick Guide

PyGTK - Introduction

PyGTK is a set of wrappers written in Python and C for GTK + GUI library. It is part of the GNOME project. It offers comprehensive tools for building desktop applications in Python. Python bindings for other popular GUI libraries are also available.

PyGTK - Useful Resources

The following resources contain additional information on PyGTK. Please use them to get more in-depth knowledge on this.

Useful Links on PyGTK

Discuss PyGTK

PyGTK is a set of wrappers written in Python and C for GTK + GUI library. It is part of the GNOME project. It offers comprehensive tools for building desktop applications in Python. This tutorial discusses the basic functionalities of the different widgets found in the toolkit.


Wednesday, March 29, 2017

PHP 7 - Introduction

What is PHP 7?

PHP 7 is a major release of PHP programming language and is touted to be a revolution in the way web applications can be developed and delivered for mobile to enterprises and the cloud. This release is considered to be the most important change for PHP after the release of PHP 5 in 2004.

PHP 7 - Performance

As per the Zend team, following illustrations show the performance comparison of PHP 7 vs PHP 5.6 and HHVM 3.7 on popular PHP based applications.

Magento 1.9

PHP 7 proves itself more than twice as faster, as compared to PHP 5.6 while executing Magento transactions.

PHP 7 - Environment Setup

Try it Option Online

We have set up the PHP Programming environment on-line, so that you can compile and execute all the available examples online. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it online.

PHP 7 - Scalar Type Declarations

In PHP 7, a new feature, Scalar type declarations, has been introduced. Scalar type declaration has two options −
  • coercive - coercive is default mode and need not to be specified.
  • strict - strict mode has to explicitly hinted.

PHP 7 - Return Type Declarations

In PHP 7, a new feature, Return type declarations has been introduced. Return type declaration specifies the type of value that a function should return. Following types for return types can be declared.
  • int
  • float
  • bool
  • string
  • interfaces
  • array
  • callable

PHP 7 - Null Coalescing Operator

In PHP 7, a new feature, null coalescing operator (??) has been introduced. It is used to replace the ternary operation in conjunction with isset() function. The Null coalescing operator returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

PHP 7 - Spaceship Operator

In PHP 7, a new feature, spaceship operator has been introduced. It is used to compare two expressions. It returns -1, 0 or 1 when first expression is respectively less than, equal to, or greater than second expression.

PHP 7 - Constant Arrays

Array constants can now be defined using the define() function. In PHP 5.6, they could only be defined using const keyword.

PHP 7 - Anonymous Classes

Anonymous classes can now be defined using new class. Anonymous class can be used in place of a full class definition.

Example

<?php
   interface Logger {
      public function log(string $msg);
   }

PHP 7 - Closure::call()

Closure::call() method is added as a shorthand way to temporarily bind an object scope to a closure and invoke it. It is much faster in performance as compared to bindTo of PHP 5.6.

Example - Pre PHP 7

<?php
   class A {
      private $x = 1;

PHP 7 - Filtered unserialize()

PHP 7 introduces Filtered unserialize() function to provide better security when unserializing objects on untrusted data. It prevents possible code injections and enables the developer to whitelist classes that can be unserialized.

PHP 7 - IntlChar

In PHP7, a new IntlChar class is added, which seeks to expose additional ICU functionality. This class defines a number of static methods and constants, which can be used to manipulate unicode characters. You need to have Intl extension installed prior to using this class.

PHP 7 - CSPRNG

In PHP 7, following two new functions are introduced to generate cryptographically secure integers and strings in a cross platform way.
  • random_bytes() − Generates cryptographically secure pseudo-random bytes.
  • random_int() − Generates cryptographically secure pseudo-random integers.

PHP 7 - Expectations

Expectations are a backwards compatible enhancement to the older assert() function. Expectation allows for zero-cost assertions in production code, and provides the ability to throw custom exceptions when the assertion fails. assert() is now a language construct, where the first parameter is an expression as compared to being a string or Boolean to be tested.

PHP 7 - use Statement

From PHP7 onwards, a single use statement can be used to import Classes, functions and constants from same namespace instead of multiple use statements.

PHP 7 - Error Handling

From PHP 7, error handling and reporting has been changed. Instead of reporting errors through the traditional error reporting mechanism used by PHP 5, now most errors are handled by throwing Error exceptions. Similar to exceptions, these Error exceptions bubble up until they reach the first matching catch block. If there are no matching blocks, then a default exception handler installed with

PHP 7 - Integer Division

PHP 7 introduces a new function intdiv(), which performs integer division of its operands and return the division as int.

PHP 7 - Session Options

From PHP7+, session_start() function accepts an array of options to override the session configuration directives set in php.ini. These options supports session.lazy_write, which is by default on and causes PHP to overwrite any session file if the session data has changed.

PHP 7 - Deprecated Features

Following features are deprecated and may be removed from future releases of PHP.

PHP 4 style constructors

PHP 4 style Constructors are methods having same name as the class they are defined in, are now deprecated, and will be removed in the future. PHP 7 will emit E_DEPRECATED if a PHP 4 constructor is the only constructor defined within a class. Classes implementing a __construct() method are unaffected.

PHP 7 - Removed Extensions & SAPIs

Following Extensions have been removed from PHP 7 onwards −
  • ereg
  • mssql
  • mysql
  • sybase_ct

PHP 7 - Quick Guide

PHP 7 - Introduction

What is PHP 7?

PHP 7 is a major release of PHP programming language and is touted to be a revolution in the way web applications can be developed and delivered for mobile to enterprises and the cloud. This release is considered to be the most important change for PHP after the release of PHP 5 in 2004.

PHP 7 - Useful Resources

The following resources contain additional information on PHP. Please use them to get more in-depth knowledge on this topic.

Useful Links on PHP

  • PHP Official Website − A complete resource for PHP stuff.
  • PEAR − PHP Extension and Application Repository, find a list of various useful PHP packages.
  • MySQL Homepage − Here you can download the latest MySQL release.

Discuss PHP 7

PHP 7 is the most awaited and is a major feature release of PHP programming language. PHP 7 was released on 3rd Dec 2015. This tutorial will teach you the new features of PHP 7 and their usage in a simple and intuitive way.

PHP - Introduction

PHP started out as a small open source project that evolved as more and more people found out how useful it was. Rasmus Lerdorf unleashed the first version of PHP way back in 1994.
  • PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
  • PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites.

PHP - Environment Setup

Try it Option Online

We have set up the PHP Programming environment on-line, so that you can compile and execute all the available examples on line. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it on-line.

PHP - Variable Types

The main way to store information in the middle of a PHP program is by using a variable.
Here are the most important things to know about variables in PHP.
  • All variables in PHP are denoted with a leading dollar sign ($).
  • The value of a variable is the value of its most recent assignment.
  • Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right.

PHP - Constants Types

A constant is a name or an identifier for a simple value. A constant value cannot change during the execution of the script. By default, a constant is case-sensitive. By convention, constant identifiers are always uppercase. A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. If you have defined a constant, it can never be changed or undefined.

PHP - Operator Types

What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. PHP language supports following type of operators.
  • Arithmetic Operators
  • Comparison Operators
  • Logical (or Relational) Operators
  • Assignment Operators
  • Conditional (or ternary) Operators

PHP - Decision Making

The if, elseif ...else and switch statements are used to take decision based on the different condition.
You can use conditional statements in your code to make your decisions. PHP supports following three decision making statements −

Tuesday, March 28, 2017

PHP - Loop Types

Loops in PHP are used to execute the same block of code a specified number of times. PHP supports following four loop types.
  • for − loops through a block of code a specified number of times.
  • while − loops through a block of code if and as long as a specified condition is true.
  • do...while − loops through a block of code once, and then repeats the loop as long as a special condition is true.

Sunday, March 26, 2017

PHP - Arrays

An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.
There are three different kind of arrays and each array value is accessed using an ID c which is called array index.

PHP - Introduction

PHP started out as a small open source project that evolved as more and more people found out how useful it was. Rasmus Lerdorf unleashed the first version of PHP way back in 1994.
  • PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
  • PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites.

PHP - Environment Setup

Try it Option Online

We have set up the PHP Programming environment on-line, so that you can compile and execute all the available examples on line. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it on-line.

PHP - Syntax Overview

This chapter will give you an idea of very basic syntax of PHP and very important to make your PHP foundation strong.

Escaping to PHP

The PHP parsing engine needs a way to differentiate PHP code from other elements in the page. The mechanism for doing so is known as 'escaping to PHP'. There are four ways to do this −

PHP - Variable Types

The main way to store information in the middle of a PHP program is by using a variable.
Here are the most important things to know about variables in PHP.
  • All variables in PHP are denoted with a leading dollar sign ($).
  • The value of a variable is the value of its most recent assignment.

PHP - Constants Types

A constant is a name or an identifier for a simple value. A constant value cannot change during the execution of the script. By default, a constant is case-sensitive. By convention, constant identifiers are always uppercase. A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. If you have defined a constant, it can never be changed or undefined.

PHP - Operator Types

What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. PHP language supports following type of operators.
  • Arithmetic Operators
  • Comparison Operators
  • Logical (or Relational) Operators
  • Assignment Operators
  • Conditional (or ternary) Operators

PHP - Decision Making

The if, elseif ...else and switch statements are used to take decision based on the different condition.
You can use conditional statements in your code to make your decisions. PHP supports following three decision making statements −

PHP - Loop Types

Loops in PHP are used to execute the same block of code a specified number of times. PHP supports following four loop types.
  • for − loops through a block of code a specified number of times.
  • while − loops through a block of code if and as long as a specified condition is true.
  • do...while − loops through a block of code once, and then repeats the loop as long as a special condition is true.

PHP - Strings

They are sequences of characters, like "PHP supports string operations".
NOTE − Built-in string functions is given in function reference PHP String Functions
Following are valid examples of string

PHP - Web Concepts

This session demonstrates how PHP can provide dynamic content according to browser type, randomly generated numbers or User Input. It also demonstrated how the client browser can be redirected.

Identifying Browser & Platform

PHP creates some useful environment variables that can be seen in the phpinfo.php page that was used to setup the PHP environment.

PHP - GET & POST Methods

There are two ways the browser client can send information to the web server.
  • The GET Method
  • The POST Method
Before the browser sends the information, it encodes it using a scheme called URL encoding. In this scheme, name/value pairs are joined with equal signs and different pairs are separated by the ampersand.
name1=value1&name2=value2&name3=value3

PHP - File Inclusion

You can include the content of a PHP file into another PHP file before the server executes it. There are two PHP functions which can be used to included one PHP file into another PHP file.
  • The include() Function
  • The require() Function

PHP - Files & I/O

This chapter will explain following functions related to files −
  • Opening a file
  • Reading a file
  • Writing a file
  • Closing a file

PHP - Functions

PHP functions are similar to other programming languages. A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value.
You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.

PHP - Functions

PHP functions are similar to other programming languages. A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value.
You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.

PHP - Cookies

Cookies are text files stored on the client computer and they are kept of use tracking purpose. PHP transparently supports HTTP cookies.
There are three steps involved in identifying returning users −

PHP - Sessions

An alternative way to make data accessible across the various pages of an entire website is to use a PHP Session.
A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.
The location of the temporary file is determined by a setting in the php.ini file called session.save_path. Before using any session variable make sure you have setup this path.
When a session is started following things happen −

PHP - Sending Emails using PHP

PHP must be configured correctly in the php.ini file with the details of how your system sends email. Open php.ini file available in /etc/ directory and find the section headed [mail function].
Windows users should ensure that two directives are supplied. The first is called SMTP that defines your email server address. The second is called sendmail_from which defines your own email address.
The configuration for Windows should look something like this −

PHP - File Uploading

A PHP script can be used with a HTML form to allow users to upload files to the server. Initially files are uploaded into a temporary directory and then relocated to a target destination by a PHP script.
Information in the phpinfo.php page describes the temporary directory that is used for file uploads as upload_tmp_dir and the maximum permitted size of files that can be uploaded is stated as upload_max_filesize. These parameters are set into PHP configuration file php.ini

PHP - Coding Standard

Every company follows a different coding standard based on their best practices. Coding standard is required because there may be many developers working on different modules so if they will start inventing their own standards then source will become very un-manageable and it will become difficult to maintain that source code in future.

PHP - Predefined Variables

PHP provides a large number of predefined variables to any script which it runs. PHP provides an additional set of predefined arrays containing variables from the web server the environment, and user input. These new arrays are called superglobals −
All the following variables are automatically available in every scope.

PHP - Regular Expressions

Regular expressions are nothing more than a sequence or pattern of characters itself. They provide the foundation for pattern-matching functionality.
Using regular expression you can search a particular string inside a another string, you can replace one string by another string and you can split a string into many chunks.

PHP - Error & Exception Handling

Error handling is the process of catching errors raised by your program and then taking appropriate action. If you would handle errors properly then it may lead to many unforeseen consequences.
Its very simple in PHP to handle an errors.

PHP - Bugs Debugging

Programs rarely work correctly the first time. Many things can go wrong in your program that cause the PHP interpreter to generate an error message. You have a choice about where those error messages go. The messages can be sent along with other program output to the web browser. They can also be included in the web server error log.

PHP - Date & Time

Dates are so much part of everyday life that it becomes easy to work with them without thinking. PHP also provides powerful tools for date arithmetic that make manipulating dates easy.

Getting the Time Stamp with time()

PHP's time() function gives you all the information that you need about the current date and time. It requires no arguments but returns an integer.

PHP & MySQL

PHP will work with virtually all database software, including Oracle and Sybase but most commonly used is freely available MySQL database.

What you should already have ?

  • You have gone through MySQL tutorial to understand MySQL Basics.
  • Downloaded and installed a latest version of MySQL.

PHP & MySQL

PHP will work with virtually all database software, including Oracle and Sybase but most commonly used is freely available MySQL database.

What you should already have ?

  • You have gone through MySQL tutorial to understand MySQL Basics.
  • Downloaded and installed a latest version of MySQL.

PHP & AJAX

What is AJAX ?

  • AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS and Java Script.
  • Conventional web application transmit information to and from the sever using synchronous requests. This means you fill out a form, hit submit, and get directed to a new page with new information from the server.

PHP & XML

XML is a markup language that looks a lot like HTML. An XML document is plain text and contains tags delimited by < and >.There are two big differences between XML and HTML −
  • XML doesn't define a specific set of tags you must use.
  • XML is extremely picky about document structure.

Object Oriented Programming in PHP

We can imagine our universe made of different objects like sun, earth, moon etc. Similarly we can imagine our car made of different objects like wheel, steering, gear etc. Same way there is object oriented programming concepts which assume everything as an object and implement a software using different objects.

PHP For C Developers

The simplest way to think of PHP is as interpreted C that you can embed in HTML documents. The language itself is a lot like C, except with untyped variables, a whole lot of Web-specific libraries built in, and everything hooked up directly to your favorite Web server.

PHP For PERL Developers

This chapter will list out major similarities and differences in between PHP and PERL. This will help PERL developers to understand PHP very quickly and avoid common mistakes.

PHP - Form Introduction

Dynamic Websites

The Websites provide the functionalities that can use to store, update, retrieve, and delete the data in a database.

What is the Form?

A Document that containing black fields, that the user can fill the data or user can select the data.Casually the data will store in the data base

PHP - Validation Example

Required field will check whether the field is filled or not in the proper way. Most of cases we will use the * symbol for required field.

What is Validation ?

Validation means check the input submitted by the user. There are two types of validation are available in PHP. They are as follows −

PHP - Complete Form

This page explains about time real-time form with actions. Below example will take input fields as text, radio button, drop down menu, and checked box.

Example

<html>
   
   <head>
      <style>
         .error {color: #FF0000;}
      </style>