Monday, June 16, 2008

Linux: Some configuration

* Name your workstation : For setting the name virus, edit /etc/hostname and put virus only in a line.

* Mount NTFS in Ubantu :
mounting ntfs in ubantu :
sudo su-
cd /media/;
mkdir win;
vi /etc/fstab;
type (assuming sda1 is win partition) : /dev/sda1 /media/win ntfs ro,dmask=0222,fmask=0333 0 0
mount /dev/sda1;
ls win;

Done !!!

* Error (Ubantu): Checking for C compiler default output file name... configure: error: C compiler cannot create executables
sudo apt-get install build-essential

* Setting host time in the shell prompt (virus 15:40:27 /etc $):
if [ "$PS1" != "" ]
then
PS1="\h \t \w \$ "
setenv () { export $1="$2"; }
unsetenv () { unset $*; }
fi

Linux: VI Editor

Since the 70’s, Vi is one of the programmer’s best friend. Nevermind you’re new to Vi or not, here’s a big list of more than 100 useful commands, organized by topic, which will make your coder life better :

Search
/word Search “word” from top to bottom
?word Search “word” from bottom to top
/jo[ha]n Search “john” or “joan”
/\< the Search “the”, “theatre” or “then”
/the\> Search “the” or “breathe”
/\<> Search “the”
/\< ….\> Search all words of 4 letters
/\/ Search “fred” but not “alfred” or “frederick”
/fred\|joe Search “fred” or “joe”
/\<\d\d\d\d\> Search exactly 4 digits
/^\n\{3} Find 3 empty lines
:bufdo /searchstr/ Search in all open files

Replace
:%s/old/new/g Replace all occurences of “old” by “new” in file
:%s/old/new/gw Replace all occurences with confirmation
:2,35s/old/new/g Replace all occurences between lines 2 and 35
:5,$s/old/new/g Replace all occurences from line 5 to EOF
:%s/^/hello/g Replace the begining of each line by “hello”
:%s/$/Harry/g Replace the end of each line by “Harry”
:%s/onward/forward/gi Replace “onward” by “forward” , case unsensitive
:%s/ *$//g Delete all white spaces
:g/string/d Delete all lines containing “string”
:v/string/d Delete all lines containing which didn’t contain “string”
:s/Bill/Steve/ Replace the first occurence of “Bill” by “Steve” in current line
:s/Bill/Steve/g Replace “Bill” by “Steve” in current line
:%s/Bill/Steve/g Replace “Bill” by “Steve” in all the file
:%s/\r//g Delete DOS carriage returns (^M)
:%s/\r/\r/g Transform DOS carriage returns in returns
:%s#<[^>]\+>##g Delete HTML tags but keeps text
:%s/^\(.*\)\n\1$/\1/ Delete lines which appears twice
Ctrl+a Increment number under the cursor
Ctrl+x Decrement number under cursor
ggVGg? Change text to Rot13

Case
Vu Lowercase line
VU Uppercase line
g~~ Invert case
vEU Switch word to uppercase
vE~ Modify word case
ggguG Set all text to lowercase
:set ignorecase Ignore case in searches
:set smartcase Ignore case in searches excepted if an uppercase letter is used
:%s/\<./\u&/g Sets first letter of each word to uppercase
:%s/\<./\l&/g Sets first letter of each word to lowercase
:%s/.*/\u& Sets first letter of each line to uppercase
:%s/.*/\l& Sets first letter of each line to lowercase

Read/Write files
:1,10 w outfile Saves lines 1 to 10 in outfile
:1,10 w >> outfile Appends lines 1 to 10 to outfile
:r infile Insert the content of infile
:23r infile Insert the content of infile under line 23

File explorer
:e . Open integrated file explorer
:Sex Split window and open integrated file explorer
:browse e Graphical file explorer
:ls List buffers
:cd .. Move to parent directory
:args List files
:args *.php Open file list
:grep expression *.php Returns a list of .php files contening expression
gf Open file name under cursor

Interact with Unix
:!pwd Execute the “pwd” unix command, then returns to Vi
!!pwd Execute the “pwd” unix command and insert output in file
:sh Temporary returns to Unix
$exit Retourns to Vi

Alignment
:%!fmt Align all lines
!}fmt Align all lines at the current position
5!!fmt Align the next 5 lines

Tabs
:tabnew Creates a new tab
gt Show next tab
:tabfirst Show first tab
:tablast Show last tab
:tabm n(position) Rearrange tabs
:tabdo %s/foo/bar/g Execute a command in all tabs
:tab ball Puts all open files in tabs

Window spliting
:e filename Edit filename in current window
:split filename Split the window and open filename
ctrl-w up arrow Puts cursor in top window
ctrl-w ctrl-w Puts cursor in next window
ctrl-w_ Maximise current window
ctrl-w= Gives the same size to all windows
10 ctrl-w+ Add 10 lines to current window
:vsplit file Split window vertically
:sview file Same as :split in readonly mode
:hide Close current window
:only Close all windows, excepted current
:b 2 Open #2 in this window

Auto-completion
Ctrl+n Ctrl+p (in insert mode) Complete word
Ctrl+x Ctrl+l Complete line
:set dictionary=dict Define dict as a dictionnary
Ctrl+x Ctrl+k Complete with dictionnary

Marks
mk Marks current position as k
‘k Moves cursor to mark k
d’k Delete all until mark k

Abbreviations
:ab mail mail@provider.org Define mail as abbreviation of mail@provider.org

Text indent
:set autoindent Turn on auto-indent
:set smartindent Turn on intelligent auto-indent
:set shiftwidth=4 Defines 4 spaces as indent size
ctrl-t, ctrl-d Indent/un-indent in insert mode
>> Indent
<< Un-indent

Syntax highlighting
:syntax on Turn on syntax highlighting
:syntax off Turn off syntax highlighting
:set syntax=perl Force syntax highlighting

% - jump to matching parenthesis
=% - indent the code between parenthesis
[[ - jump to function start
[{ - jump to block start
* - search the word under cursor
:new abc.txt - edit abc.txt in new window

:Sex Split window and open integrated file explorer

Some configuration :
/etc/vimrc
:set all # Display all Set options
:set autoindent # Indent following lines to the indentation of previous line.
:set ts=4 # set tab stop to 4 char
:set ignorecase # gnore case during pattern matching.
:set list # Show special characters in the file.
:set number # Display line numbers.
:set shiftwidth=n # Width for shifting operators <<>>
:set showmode # Display when in Insert, Append, or Replace mode.
:set wrapmargin=n # Set right margin 80-n for autowrapping lines (inserting newlines). 0 turns it off.

Linux: SSH Keys b/w two servers

Say, we have to setup SSH Keys b/w Reqester & Responser machines.
Steps :
* Install OpenSSH on two Linux/ Unix machines.
* To create the base .ssh directory at each machine, make a ssh connection for some other machine from the two machine.
* At machine Reqester type ssh-keygen -t dsa. If this works right you will get two files called id_dsa and id_dsa.pub in your .ssh dir. You can use a passphrase.
* Put the keys from Requester,
scp ~/.ssh/id_dsa.pub Responser:.ssh/authorized_keys
* Now Responser is ready to accept your ssh key. How to tell it which keys to use? The ssh-add command will do it :
ssh-agent sh -c 'ssh-add < /dev/null && bash'

PHP: Code Snippets ..

/** 1. returns count of the processes currently running
* Input : name of the process like garbageCollector
* Output : count of the processes running.
*
Use eg.: echo checkProcess("java");
*/
function checkProcess($processName = "garbageCollector") {
return $processCount = shell_exec("ps ax | grep $processName | grep -v grep | wc -l");
}

/** 2. returns name of the tables which suffix is in Date format Ymd
* Input : table count, table name, suffix date format
* Output : count of the processes running.
* Use eg. : echo findNames(10, "TABLE");
*/
function findNames($countTables, $str, $format = "Ymd") {
$retStr = "";
for($i = 0; $i < $countTables; $i++) $retStr .= $str.date($format, mktime(0, 0, 0, 01, 01 + $i, 2008)).","; return $retStr = substr($retStr, 0, strlen($retStr) - 1); }


/*** 4. ***/

for($i = -19; $i < 0; $i++) {
echo $date = date("Y-m-d", strtotime("$i day"));
}

/*** 3. **
* Polymorphism Example
*/

class Car{

 private $name;
function __construct($n) {
$this->set_name($n);
}
function set_name($n) {
$this->name = $n;
}
function get_name() {
return $this->name;
}
function accelerate() {
echo "Now I'm running 10 mile faster\n";
}
}

class SportsCar extends Car
{
function __construct($n) {
parent::__construct($n);
}
function accelerate() {
echo "Now I'm running 20 mile faster\n";
}
}

// an array of cars of different types
$cars = array(new Car("Ford"), new SportsCar("Porche"));
foreach ($cars as $c) {
$c->accelerate(); // polymorphic behaviors
}

PHP: Concepts, FAQs

Q. Explain Cookies in PHP.

bool setcookie ( string $name [, string $value [, int $expire [, string $path [, string $domain [, bool $secure [, bool $httponly ]]]]]] ) : A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too with the http headers before any output. It is a simple way to maintain data between the different pages in a web application. Cookies are sent by PHP through the web server with the setcookie() function and are stored in the browser. Official maximum size for a HTTP cookie header is 4K. So the actual cookie will be slightly smaller. Some browsers will work with bigger cookies, others won't. The maximum number of cookies from a host that can be stored by a browser is 20.


Q. Explain Sessions in PHP.
A PHP session allows an application to store information for the current session, which can be defined as one user being logged in to your application. A session is identified by a unique session ID. PHP creates a session ID that is an MD5 hash of the remote IP address, the current time, and some extra randomness represented in a hexadecimal string. This session ID can be passed in a cookie or added to all URLs to navigate your application. For security reasons, it’s better to force the user to have cookies enabled than to pass the session ID on the URL where it might end up in web server’s logs as a HTTP_REFERER or be found by some evil person monitoring your traffic. That evil person can still see the session cookie data, of course, so you might want to use an SSL-enabled server to be really safe. When a visitor accesses your site, PHP will check automatically (if session.auto_start is set to 1) or on your request (explicitly through session_start() or implicitly through session_register()) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated. If you do turn on session.auto_start then you cannot put objects into your sessions since the class definition has to be loaded before starting the session in order to recreate the objects in your session. All registered variables are serialized after the request finishes.

* Security : The session module cannot guarantee that the information you store in a session is only viewed by the user who created the session. If you want to protect users from simple social engineering tactics (eg. copying the url), you need to enable session.use_only_cookies. In that case, cookies must be enabled unconditionally on the user side, or sessions will not work.

Q. Compare Sessions & Cookies ?
Sessions & Cookies serve somewhat the same purpose, and are, to a certain extent, usable interchangeably. Cookies can be used to track information even from one session to another by setting it's time() parameter, Differences :

* Cookies are stored on the client, while the session data is stored on the server. As a result, sessions are more secure than cookies (no information is being sent back and forth between the client and the server).

* Cookies, having their data stored on the client, work smoothly when you have a cluster of web servers, whereas sessions are stored on the server, meaning in one of your web servers handles the first request, the other web servers in your cluster will not have the stored information.

* Cookies can be stooped woking as it can be disabled at client end, but session cann't be as they stored on the server.

* A cookie can store only single value, a session can hold multiple variables.

* Cookies can be set to a long lifespan as stored at client's machine.


Q. How can you get round the stateless nature of HTTP using PHP?
The top two options that are used are sessions and cookies. To access a session, you will need to have session_start() at the top of each page, and then you will use the $_SESSION hash to access and store your session variables. For cookies, you only have to remember one rule. You must use the set_cookie function before any output is started in your PHP script. From then on you can use the $_COOKIE has to access your cookie variables and values.
There are other methods, but they are not as fool proof and most often than not depend on the IP address of the visitor, which is a very dangerous thing to do.

Q. What is meant by PEAR in php?
PEAR -
PHP Extension and Application Repository is the next revolution in PHP. This repository is bringing higher level programming to PHP. PEAR is a framework and distribution system for reusable PHP components. It eases installation by bringing an automated wizard, and packing the strength and experience of PHP users into a nicely organised OOP library. PEAR also provides a command-line interface that can be used to automatically install "packages"

Q. Explain different sort functions in php.
bool
sort ( array &$array [, int $sort_flags ] ) : Sorts an array in alphabetical order based on the value of each element. This function assigns new keys for the elements in array . It will remove any existing keys you may have assigned, rather than just reordering the keys. Sorting type flags: SORT_REGULAR, SORT_NUMERIC, SORT_STRING, SORT_LOCALE_STRING. Reverse is rsort.
bool
asort ( array &$array [, int $sort_flags ] ) : This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant. Reverse is arsort.
bool
ksort ( array &$array [, int $sort_flags ] ) : Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays. Reverse is krsort.

bool uksort ( array &$array , callback $cmp_function ) : will sort the keys of an array using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.

bool natsort ( array &$array ) : Sort an array using a "natural order" algorithm.

bool usort ( array &$array , callback $cmp_function ) : Sort an array by values using a user-defined comparison function.

Q. What's the difference between mysql_fetch_row() and mysql_fetch_array()?
mysql_fetch_object() collects first single matching record
mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
mysql_fetch_assoc() returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array.
mysql_fetch_array() returns an array that corresponds to the fetched row and moves the internal data pointer ahead.

Q. What are magic methods in PHP?
Functionalities like serializing, converting objects to string, getting setting values without explicit get and set methods for the variables etc, are magic functionality. PHP defines methods with names starting with __(double underscore).
Eg. __get, __set, __construct, __destruct, __set, __isset, __unset, __sleep, __wakeup, __toString, __clone, __autoload, __set_state
http://in.php.net/manual/en/language.oop5.magic.php

Q. What are predefined variables, predifined classes in php ?
PHP provides an additional set of predefined arrays containing variables from the web server (if applicable), the environment, and user input. These new arrays are rather special in that they are automatically global
http://in.php.net/manual/en/language.variables.predefined.php
e.g., $_SERVER, $_REQUEST, $_POST, $_GET, $_ENV, $_COOKIE, $_FILES, $_SESSION, $GLOBALS, $php_errormsg, $http_response_header
Predefined classes : stdClass, Exception,_PHP_Incomplete_Class, php_user_filter, Directory
Exception : for exception handling
Directory: dir class
eg. public/private/protected [static] class extends {
{
public $x;

public function method_a() {

}
}

Q. What functions can you use to add library code to the currently running script?
This is another question where the interpretation could completely hit or miss the question. For class libraries written in PHP, so
include(), include_once(), require(), and require_once() came to mind. However, you can also include COM objects and .NET libraries. By utilizing the com_load and the dotnet_load respectively you can incorporate COM objects and .NET libraries into your PHP code.

Q. How do you debug a PHP application?
PHP - Advanced PHP Debugger or PHP-APD. First you have to install it by running: pear install apd
Once installed, start the trace by placing the following code at the beginning of your script: apd_set_pprof_trace();
Then once you have executed your script, look at the log in apd.dumpdir.You can even use the pprofp command to format the data as in: pprofp -R /tmp/pprof.22141.0
For more information see http://us.php.net/manual/en/ref.apd.php

Q. What does === do? What’s an example of something that will give true for ‘==’, but not ‘===’?
The === operator is used for functions that can return a Boolean false and that may also return a non-Boolean value which evaluates to false. Such functions would be strpos and strrpos.
I am having a hard time with the second portion, as I am able to come up with scenarios where '==' will be false and '===' would come out true, but it's hard to think of the opposite. So here is the example I came up with:
PHP:
if (strpos("abc", "a") == true)
{
// this does not get hit, since "a" is in the 0 index position, it returns false.
}
if (strpos("abc", "a") === true)
{
// this does get hit as the === ensures this is treated as non-boolean.
}

Q. What is the difference between include, include_once, require and require_once?
All three allow the script to include another file, be it internal or external depending on if allow_url_fopen is enabled. However, they do have slight differences, which are denoted below.
1. include()
The include() function allows you to include a file multiple times within your application and if the file does not exist it will throw a Warning and continue on with your PHP script.
2. include_once()
include_once() is like include() except as the name suggests, it will only include the file once during the script execution.
3. require()
Like include(), you can request to require a file multiple times, however, if the file does not exist it will throw a Warning that will result in a Fatal Error stopping the PHP script execution.

Q. string ereg_replace (string $pattern, string $replacement, string $string)
1. Convert mm/dd/yyyy => dd/mm/yyyy format
print ereg_replace("([0-9]+)/([0-9]+)/([0-9]+)","\\2/\\1/\\3",'08/26/2003');
2. Replace URLs with links
$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "\\0", "http://php-question.blogspot.com");
3. Strip all the HTML tags
echo preg_replace("/<(.*?)>(.*?)<\/(.*?)>/", "\\2", "testing hereha ha ha");
echo ereg_replace("(<.*>)(.*)", "\\2", "testing hereha ha ha");
echo preg_replace("/(<[^>]*>)/", "", "testing hereha ha ha");
4. Email check :
5."div
\b(?:(?=(\s+(?:id="([^"]*)"|class="([^"]*)")|[^\s>]+|\s+))\1)*>"
6. "img\s+(?:alt="([^"]*)"|class="([^"]*)"|style="([^"]*)"|src="([^"]*)"|height="([^"]*)"|width="([^"]*)")|[^\s>]+|\s+)*>"
7. "img\s+(?:alt="([^"]*)"()|class="([^"]*)"())|[^\s>]+|\s+)*\2\4>"

Q. What's the difference between the way PHP and Perl distinguish between arrays and hashes?
In Perl, you are required to use the @ sign to start all array variable names, for example, @myArray. In PHP, you just continue to use the $ (dollar sign), for example, $myArray.
Now for hashes in Perl you must start the variable name with the % (percent sign), as in, %myHash. Whereas, in PHP you still use the $ (dollar sign), as in, $myHash.

Q. What does the GD library do?
This is probably one of my favorite libraries, as it is built into PHP as of version 4.3.0 (I am very happy with myself, I didn't have to look up the version of PHP this was introduced on php.net). This library allows you to manipulate and display images of various extensions. More often than not, it is used to create thumbnail images. An alternative to GD is ImageMagick, however, unlike GD, this does not come built in to PHP and must be installed on the server by an Administrator.

Q. Is PHP better than Perl? - Discuss.
"Pick the language for the job, do not fit the job into a particular language."
Perl in my opinion is great for command line utilities, yes it can be used for the web as well, but its' real power can be really demonstrated through the command line. Likewise, PHP can be used on the command line too, but I personally feel it's more powerful on the web. It has a lot more functions built with the web in mind, whereas, Perl seems to have the console in mind.
Pick the language for the job. If I needed a console application that was meant to show off the performance differences between a quick sort, bubble sort, and a merge sort, give me C/C++! If you want a Photo Gallery, give me PHP or C# (though I personally find .NET languages better for quick GUI applications than web).

Q. What is the difference between a reference and a regular variable? How do you pass by reference and why would you want to?
Reference variables pass the address location of the variable instead of the value. So when the variable is changed in the function, it is also changed in the whole application, as now the address points to the new value.
Now a regular variable passes by value, so when the value is changed in the function, it has no affect outside the function.
PHP:
$myVariable = "its' value";
Myfunction(&$myVariable); // Pass by Reference Example
So why would you want to pass by reference? The simple reason, is you want the function to update the value of your variable so even after you are done with the function, the value has been updated accordingly.

Q. What is the difference between foo() & @foo()?
foo() executes the function and any parse/syntax/thrown errors will be displayed on the page.
@foo() will mask any parse/syntax/thrown errors as it executes. eg. @mysql_connect()
However, I feel that approach is significantly flawed as you should never hide errors, rather you should manage them accordingly and if you can, fix them.

Q. Can we write windows like applications in PHP?
Yes, using PHP-GTK on linux and WinBinder on windows.

Q. What are the ways to find out if a variable has been declared?
isset or empty language constructs.

Q. What is the difference between echo and print ?
1. echo can take more than one parameter for displaying, while print cannot take more than one (parse error : unexpected ',')
2. echo cannot be used to return anything (parse error : unexpected T_ECHO), while print returns 1 always.

Q. What is eval in php?
Evaluates the string given in code_str as PHP code. Among other things, this can be useful for storing code in a database text field for later execution.

Apache: httpd.conf Configuration

ServerRoot: The top of the directory tree under which the server's configuration, error, and log files are kept.

ServerType: This directive is determines whether the server is spawned by the inetd process on a per query basis, or runs as a standalone process. For performance reasons, it is preferred to run it as a standalone process. It is only possible to run the server under inetd if it is started by the root account. (default standalone)

ServerAdmin: Your address, where problems with the server should be e-mailed. This address appears on some server-generated pages, such as error documents (default: you@example.com)

ServerName: gives the name and port that the server uses to identify itself. This can often be determined automatically, but we recommend you specify it explicitly to prevent problems during startup. If your host doesn't have a registered DNS name, enter its IP address here.

DocumentRoot: The directory out of which you will serve your documents. By default, all requests are taken from this directory, but symbolic links and aliases may be used to point to other locations.

TimeOut: This directive sets the maximum amount of time the server will allow a connection to remain open (default 1200)

Listen: Allows you to bind Apache to specific IP addresses and/or ports(0 - 65536), instead of the default (port 80).

LoadModule: To be able to use the functionality of a module which was built as a Dynamic Shared Object (DSO) you have to place corresponding `LoadModule' lines at this location so the directives contained in it are actually available _before_ they are used. Statically compiled modules (those listed by `httpd -l') do not need to be loaded here.

User/Group: The name (or #number) of the user/group to run httpd as. It is usually good practice to create a dedicated user and group for running httpd, as with most system services (default user/daemon)

: Each directory to which Apache has access can be configured with respect to which services and features are allowed and/or disabled in that directory (and its subdirectories). First, we configure the "default" to be a very restrictive set of features.

ErrorLog: The location of the error log file. If you do not specify an ErrorLog directive within a container, error messages relating to that virtual host will be logged here. If you *do* define an error logfile for a container, that host's errors will be logged there and not here (default: logs/error_log)

TransferLog: This directive sets the location of the access log file (default logs/access_log)

PidFile: This directive sets the location of the process id log file (default logs/httpd.pid)

LogLevel: Control the number of messages logged to the error_log. Possible values include: debug, info, notice, warn, error, crit, alert, emerg (default: warn)

DefaultType: the default MIME type the server will use for a document if it cannot otherwise determine one, such as from filename extensions. If your server contains mostly text or HTML documents, "text/plain" is a good value. If most of your content is binary, such as applications or images, you may want to use "application/octet-stream" instead to keep browsers from trying to display binary files as though they are text(default text/plain)

mod_mime_magic: module allows the server to use various hints from the contents of the file itself to determine its type. The MIMEMagicFile directive tells the module where the hint definitions are located.

Customizable error responses: come in three flavors: 1) plain text 2) local redirects 3) external redirects. (eg. ErrorDocument 404 /missing.html)

EnableMMAP and EnableSendfile: On systems that support it, memory-mapping or the sendfile syscall is used to deliver files. This usually improves server performance, but must be turned off when serving from networked-mounted filesystems or if support for these functions is otherwise broken on your system.

IdentityCheck: With this directive set to on, the server will attempt to record the userid of each query to the server. Keep this directive set to off unless you are willing to devote a significant amount of network bandwidth to this function.