<?php
$mail_to_array = array("sysadmin@sample.net","admin@sample.net");
$mail_log_path = "/var/log/maillog";
echo "Producing filtered maillog..";
$generated_date_month = date("M");
$generated_date_day = date("j");
if(strlen($generated_date_day) == 1) {
$gen_date = "$generated_date_month $generated_date_day";
}else {
$gen_date = "$generated_date_month $generated_date_day";
}
$execution_string = "grep unknown $mail_log_path | grep '$gen_date' > /tmp/.unknownhack";
exec($execution_string);
$command = "mail -s '[Unknown_user_hack potato] $HOSTNAME - date()' sysadmin@sample.net < /tmp/.unknownhack";
exec($command);
?>
Tuesday, August 30, 2011
php script date and grep
FPDF – Creating PDF files using PHP
Category:
PHP
— SkyHi @ Tuesday, August 30, 2011
What is FPDF?
I came across thsi little gem while searching for a PHP class that allowed me to create PDFs on the fly using PHP. Basically, FPDF is a PHP class which generates PDF files using PHP. It is a free class and full documentation of its use and hw to use it can be found here.
With FPDF you can format a PDF in the same way that you would any PDF. There is support for header and footers, page breaks, images, colors and font-styling and page compression amongst other things.
FPDF works with PHP4 and PHP5.
The class is available for download from the FPDF site.
Once downloaded, put the class into site wherever you fancy and creating a PDF can be as simple as using the following code:
REFERENCES
http://nick.boldison.com/websites/php/fpdf-creating-pdf-files-using-php/
I came across thsi little gem while searching for a PHP class that allowed me to create PDFs on the fly using PHP. Basically, FPDF is a PHP class which generates PDF files using PHP. It is a free class and full documentation of its use and hw to use it can be found here.
With FPDF you can format a PDF in the same way that you would any PDF. There is support for header and footers, page breaks, images, colors and font-styling and page compression amongst other things.
FPDF works with PHP4 and PHP5.
The class is available for download from the FPDF site.
Once downloaded, put the class into site wherever you fancy and creating a PDF can be as simple as using the following code:
<?php
define('FPDF_FONTPATH','fpdf16/font/');
require('fpdf16/fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
REFERENCES
http://nick.boldison.com/websites/php/fpdf-creating-pdf-files-using-php/
mysql last update file
#find . -iname "*.MYD" -mtime -720
Find Files By Access, Modification Date / Time Under Linux or UNIX do not remember where I saved pdf and text files under Linux. I have downloaded files from the Internet a few months ago. How do I find my pdf or text files?
You need to use the find command. Each file has three time stamps, which record the last time that certain operations were performed on the file:
[a] access (read the file's contents) - atime
[b] change the status (modify the file or its attributes) - ctime
[c] modify (change the file's contents) - mtime
You can search for files whose time stamps are within a certain age range, or compare them to other time stamps.
You can use -mtime option. It returns list of file if the file was last accessed N*24 hours ago. For example to find file in last 2 months (60 days) you need to use -mtime +60 option.
Display content of file on screen that were last modified 60 days ago, use
Count total number of files using wc command
You can also use access time to find out pdf files. Following command will print the list of all pdf file that were accessed in last 60 days:
List all mp3s that were accessed exactly 10 days ago:
There is also an option called -daystart. It measure times from the beginning of today rather than from 24 hours ago. So, to list the all mp3s in your home directory that were accessed yesterday, type the command
Where,
To list all of the files in your home directory tree that were modified from two to four days ago, type:
REFERENCES
http://www.cyberciti.biz/faq/howto-finding-files-by-date/
Find Files By Access, Modification Date / Time Under Linux or UNIX do not remember where I saved pdf and text files under Linux. I have downloaded files from the Internet a few months ago. How do I find my pdf or text files?
You need to use the find command. Each file has three time stamps, which record the last time that certain operations were performed on the file:
[a] access (read the file's contents) - atime
[b] change the status (modify the file or its attributes) - ctime
[c] modify (change the file's contents) - mtime
You can search for files whose time stamps are within a certain age range, or compare them to other time stamps.
You can use -mtime option. It returns list of file if the file was last accessed N*24 hours ago. For example to find file in last 2 months (60 days) you need to use -mtime +60 option.
- -mtime +60 means you are looking for a file modified 60 days ago.
- -mtime -60 means less than 60 days.
- -mtime 60 If you skip + or - it means exactly 60 days.
$ find /home/you -iname "*.txt" -mtime -60 -printDisplay content of file on screen that were last modified 60 days ago, use
$ find /home/you -iname "*.txt" -mtime -60 -exec cat {} \; Count total number of files using wc command
$ find /home/you -iname "*.txt" -mtime -60 | wc -lYou can also use access time to find out pdf files. Following command will print the list of all pdf file that were accessed in last 60 days:
$ find /home/you -iname "*.pdf" -atime -60 -type -fList all mp3s that were accessed exactly 10 days ago:
$ find /home/you -iname "*.mp3" -atime 10 -type -fThere is also an option called -daystart. It measure times from the beginning of today rather than from 24 hours ago. So, to list the all mp3s in your home directory that were accessed yesterday, type the command
$ find /home/you -iname "*.mp3" -daystart -type f -mtime 1 Where,
- -type f - Only search for files and not directories
-daystart option
The -daystart option is used to measure time from the beginning of the current day instead of 24 hours ago. Find out all perl (*.pl) file modified yesterday, enter:find /nas/projects/mgmt/scripts/perl -mtime 1 -daystart -iname "*.pl"
You can also list perl files that were modified 8-10 days ago, enter:To list all of the files in your home directory tree that were modified from two to four days ago, type:
find /nas/projects/mgmt/scripts/perl -mtime 8 -mtime -10 -daystart -iname "*.pl"
-newer option
To find files in the /nas/images directory tree that are newer than the file /tmp/foo file, enter:find /etc -newer /tmp/fooYou can use the touch command to set date timestamp you would like to search for, and then use -newer option as follows
touch --date "2010-01-05" /tmp/foo
# Find files newer than 2010/Jan/05, in /data/images find /data/images -newer /tmp/fooRead the man page of find command for more information:
man findREFERENCES
http://www.cyberciti.biz/faq/howto-finding-files-by-date/
Monday, August 29, 2011
Why you should learn just a little Awk - A Tutorial by Example
Category:
awk
— SkyHi @ Monday, August 29, 2011
In grad school, I once saw a prof I was working with grab a text file and in seconds manipulate it into little pieces so deftly it blew my mind. I immediately decided it was time for me to learn awk, which he had so clearly mastered.
To this day, 90% of the programmers I talk to have never used awk. Knowing 10% of awk's already small syntax, which you can pick up in just a few minutes, will dramatically increase your ability to quickly manipulate data in text files. Below I'll teach you the most useful stuff - not the "fundamentals", but the 5 minutes worth of practical stuff that will get you most of what I think is interesting in this little language.
Awk is a fun little programming language. It is designed for processing input strings. A (different) prof once asked my networking class to implement code that would take a spec for an RPC service and generate stubs for the client and the server. This professor made the mistake of telling us we could implement this in any language. I decided to write the generator in Awk, mostly as an excuse to learn more Awk. Surprisingly to me, the code ended up much shorter and much simpler than it would have been in any other language I've ever used (Python, C++, Java, ...). There is enough to learn about Awk to fill half a book, and I've read that book, but you're unlikely to be writing a full-fledged spec parser in Awk. Instead, you just want to do things like find all of your log lines that come from ip addresses whose components sum up to 666, for kicks and grins. Read on!
For our examples, assume we have a little file (logs.txt) that looks like the one below. If it wraps in your browser, this is just 2 lines of logs each staring with an ip address.
07.46.199.184 [28/Sep/2010:04:08:20] "GET /robots.txt HTTP/1.1" 200 0 "msnbot"
123.125.71.19 [28/Sep/2010:04:20:11] "GET / HTTP/1.1" 304 - "Baiduspider"
These are just two log records generated by Apache, slightly simplified, showing Bing and Baidu wandering around on my site yesterday.
Awk works like anything else (ie: grep) on the command line. It reads from stdin and writes to stdout. It's easy to pipe stuff in and out of it. The command line syntax you care about is just the command awk followed by a string that contains your program.
awk '{print $0}'
Most Awk programs will start with a "{" and end with a "}". Everything in between there gets run once on each line of input. Most awk programs will print something. The program above will print the entire line that it just read, print appends a newline for free. $0 is the entire line. So this program is an identity operation - it copies the input to the output without changing it.
Awk parses the line in to fields for you automatically, using any whitespace (space, tab) as a delimiter, merging consecutive delimiters. Those fields are available to you as the variables $1, $2, $3, etc.
echo 'this is a test' | awk '{print $3}' // prints 'a'
awk '{print $1}' logs.txt
Output:
07.46.199.184
123.125.71.19
Easy so far, and already useful. Sometimes I need to print from the end of the string though instead. The special variable, NF, contains the number of fields in the current line. I can print the last field by printing the field $NF or I can just manipulate that value to identify a field based on it's position from the last. I can also print multiple values simultaneously in the same print statement.
echo 'this is a test' | awk '{print $NF}' // prints "test"
awk '{print $1, $(NF-2) }' logs.txt
Output:
07.46.199.184 200
123.125.71.19 304
More progress - you can see how, in moments, you could strip this log file to just the fields you are interested in. Another cool variable is NR, which is the row number being currently processed. While demonstrating NR, let me also show you how to format a little bit of output using print. Commas between arguments in a print statement put spaces between them, but I can leave out the comma and no spaces are inserted.
awk '{print NR ") " $1 " -> " $(NF-2)}' logs.txt
Output:
1) 07.46.199.184 -> 200
2) 123.125.71.19 -> 304
Powerful, but nothing hard yet, I hope. By the way, there is also a printf function that works much the way you'd expect if you prefer that form of formatting. Now, not all files have fields that are separated with whitespace. Let's look at the date field:
$ awk '{print $2}' logs.txt
Output:
[28/Sep/2010:04:08:20]
[28/Sep/2010:04:20:11]
The date field is separated by "/" and ":" characters. I can do the following within one awk program, but I want to teach you simple things that you can string together using more familiar unix piping because it's quicker to pick up a small syntax. What I'm going to do is pipe the output of the above command through another awk program that splits on the colon. To do this, my second program needs two {} components. I don't want to go into what these mean, just to show you how to use them for splitting on a different delimiter.
$ awk '{print $2}' logs.txt | awk 'BEGIN{FS=":"}{print $1}'
Output:
[28/Sep/2010
[28/Sep/2010
I just specified that I wanted a different FS (field separator) of ":" and that I wanted to then print the first field. No more time, just dates! The simplest way to get rid of that prefix [ character is with sed, which you are likely already familiar with:
$ awk '{print $2}' logs.txt | awk 'BEGIN{FS=":"}{print $1}' | sed 's/\[//'
Output:
28/Sep/2010
28/Sep/2010
I can further split this on the "/" character if I want using the exact same trick, but I think you get the point. Next, lets learn just a tiny bit of logic. If I want to return only the 200 status lines, I could use grep, but I might end up with an ip address that contains 200, or a date from year 2000. I could first grab the 200 field with Awk and then grep, but then I lose the whole line's context. Awk supports basic if statements. Lets see how I might use one:
$ awk '{if ($(NF-2) == "200") {print $0}}' logs.txt
Output:
07.46.199.184 [28/Sep/2010:04:08:20] "GET /robots.txt HTTP/1.1" 200 0 "msnbot"
There we go, returning only the lines (in this case only one) with a 200 status. The if syntax should be very familiar and require no explanation. Let me finish up by showing you one stupid example of awk code that maintains state across multiple lines. Lets say I want to sum up all of the status fields in this file. I can't think of a reason I'd want to do this for statuses in a log file, but it makes a lot of sense in other cases like summing up the total bytes returned across all of the logs in a day or something. To do this, I just create a variable which automatically will persist across multiple lines:
$ awk '{a+=$(NF-2); print "Total so far:", a}' logs.txt
Output:
Total so far: 200
Total so far: 504
Nothing doing. Obviously in most cases, I'm not interested in cumulative values but only the final value. I can of course just use tail -n1, but I can also print stuff after processing the final line using an END clause:
$ awk '{a+=$(NF-2)}END{print "Total:", a}' logs.txt
Output:
Total: 504
If you want to read more about awk, there are several good books and plenty of online references. You can learn just about everything there is to know about awk in a day with some time to spare. Getting used to it is a bit more of a challenge as it really is a little bit different of a way to code - you are essentially writing only the inner part of a for loop. Come to think of it, this is a lot like how MapReduce feels, which is also initially disorienting.
I hope some of that was useful. If you found it to be so, leave a comment to let me know, I enjoy the feedback if nothing else.
Update Sep 30, 2010: There are some great comments elsewhere in addition to here. I wish they would end up in one place, but the best I can do currently is to link to them:
To this day, 90% of the programmers I talk to have never used awk. Knowing 10% of awk's already small syntax, which you can pick up in just a few minutes, will dramatically increase your ability to quickly manipulate data in text files. Below I'll teach you the most useful stuff - not the "fundamentals", but the 5 minutes worth of practical stuff that will get you most of what I think is interesting in this little language.
Awk is a fun little programming language. It is designed for processing input strings. A (different) prof once asked my networking class to implement code that would take a spec for an RPC service and generate stubs for the client and the server. This professor made the mistake of telling us we could implement this in any language. I decided to write the generator in Awk, mostly as an excuse to learn more Awk. Surprisingly to me, the code ended up much shorter and much simpler than it would have been in any other language I've ever used (Python, C++, Java, ...). There is enough to learn about Awk to fill half a book, and I've read that book, but you're unlikely to be writing a full-fledged spec parser in Awk. Instead, you just want to do things like find all of your log lines that come from ip addresses whose components sum up to 666, for kicks and grins. Read on!
For our examples, assume we have a little file (logs.txt) that looks like the one below. If it wraps in your browser, this is just 2 lines of logs each staring with an ip address.
07.46.199.184 [28/Sep/2010:04:08:20] "GET /robots.txt HTTP/1.1" 200 0 "msnbot"
123.125.71.19 [28/Sep/2010:04:20:11] "GET / HTTP/1.1" 304 - "Baiduspider"
These are just two log records generated by Apache, slightly simplified, showing Bing and Baidu wandering around on my site yesterday.
Awk works like anything else (ie: grep) on the command line. It reads from stdin and writes to stdout. It's easy to pipe stuff in and out of it. The command line syntax you care about is just the command awk followed by a string that contains your program.
awk '{print $0}'
Most Awk programs will start with a "{" and end with a "}". Everything in between there gets run once on each line of input. Most awk programs will print something. The program above will print the entire line that it just read, print appends a newline for free. $0 is the entire line. So this program is an identity operation - it copies the input to the output without changing it.
Awk parses the line in to fields for you automatically, using any whitespace (space, tab) as a delimiter, merging consecutive delimiters. Those fields are available to you as the variables $1, $2, $3, etc.
echo 'this is a test' | awk '{print $3}' // prints 'a'
awk '{print $1}' logs.txt
Output:
07.46.199.184
123.125.71.19
Easy so far, and already useful. Sometimes I need to print from the end of the string though instead. The special variable, NF, contains the number of fields in the current line. I can print the last field by printing the field $NF or I can just manipulate that value to identify a field based on it's position from the last. I can also print multiple values simultaneously in the same print statement.
echo 'this is a test' | awk '{print $NF}' // prints "test"
awk '{print $1, $(NF-2) }' logs.txt
Output:
07.46.199.184 200
123.125.71.19 304
More progress - you can see how, in moments, you could strip this log file to just the fields you are interested in. Another cool variable is NR, which is the row number being currently processed. While demonstrating NR, let me also show you how to format a little bit of output using print. Commas between arguments in a print statement put spaces between them, but I can leave out the comma and no spaces are inserted.
awk '{print NR ") " $1 " -> " $(NF-2)}' logs.txt
Output:
1) 07.46.199.184 -> 200
2) 123.125.71.19 -> 304
Powerful, but nothing hard yet, I hope. By the way, there is also a printf function that works much the way you'd expect if you prefer that form of formatting. Now, not all files have fields that are separated with whitespace. Let's look at the date field:
$ awk '{print $2}' logs.txt
Output:
[28/Sep/2010:04:08:20]
[28/Sep/2010:04:20:11]
The date field is separated by "/" and ":" characters. I can do the following within one awk program, but I want to teach you simple things that you can string together using more familiar unix piping because it's quicker to pick up a small syntax. What I'm going to do is pipe the output of the above command through another awk program that splits on the colon. To do this, my second program needs two {} components. I don't want to go into what these mean, just to show you how to use them for splitting on a different delimiter.
$ awk '{print $2}' logs.txt | awk 'BEGIN{FS=":"}{print $1}'
Output:
[28/Sep/2010
[28/Sep/2010
I just specified that I wanted a different FS (field separator) of ":" and that I wanted to then print the first field. No more time, just dates! The simplest way to get rid of that prefix [ character is with sed, which you are likely already familiar with:
$ awk '{print $2}' logs.txt | awk 'BEGIN{FS=":"}{print $1}' | sed 's/\[//'
Output:
28/Sep/2010
28/Sep/2010
I can further split this on the "/" character if I want using the exact same trick, but I think you get the point. Next, lets learn just a tiny bit of logic. If I want to return only the 200 status lines, I could use grep, but I might end up with an ip address that contains 200, or a date from year 2000. I could first grab the 200 field with Awk and then grep, but then I lose the whole line's context. Awk supports basic if statements. Lets see how I might use one:
$ awk '{if ($(NF-2) == "200") {print $0}}' logs.txt
Output:
07.46.199.184 [28/Sep/2010:04:08:20] "GET /robots.txt HTTP/1.1" 200 0 "msnbot"
There we go, returning only the lines (in this case only one) with a 200 status. The if syntax should be very familiar and require no explanation. Let me finish up by showing you one stupid example of awk code that maintains state across multiple lines. Lets say I want to sum up all of the status fields in this file. I can't think of a reason I'd want to do this for statuses in a log file, but it makes a lot of sense in other cases like summing up the total bytes returned across all of the logs in a day or something. To do this, I just create a variable which automatically will persist across multiple lines:
$ awk '{a+=$(NF-2); print "Total so far:", a}' logs.txt
Output:
Total so far: 200
Total so far: 504
Nothing doing. Obviously in most cases, I'm not interested in cumulative values but only the final value. I can of course just use tail -n1, but I can also print stuff after processing the final line using an END clause:
$ awk '{a+=$(NF-2)}END{print "Total:", a}' logs.txt
Output:
Total: 504
If you want to read more about awk, there are several good books and plenty of online references. You can learn just about everything there is to know about awk in a day with some time to spare. Getting used to it is a bit more of a challenge as it really is a little bit different of a way to code - you are essentially writing only the inner part of a for loop. Come to think of it, this is a lot like how MapReduce feels, which is also initially disorienting.
I hope some of that was useful. If you found it to be so, leave a comment to let me know, I enjoy the feedback if nothing else.
Update Sep 30, 2010: There are some great comments elsewhere in addition to here. I wish they would end up in one place, but the best I can do currently is to link to them:
Update Jan 2, 2011: This post caught the interest of Hacker Monthly who republished it in issue #8. You can grab the pdf version of this article courtesy of Lim Cheng Soon, Hacker News' Founder.
REFERENCES
A crash course in PostgreSQL, Part 1
Category:
PostgreSQL
— SkyHi @ Monday, August 29, 2011
PostgreSQL is a first-rate, enterprise-worthy open source RDBMS (relational database management system) that compares very favorably to high-priced closed-source commercial databases. Databases are complex, tricksy beasts full of pitfalls. In this two-part crash course, we'll get a new PostgreSQL database up and running with elegant ease, and learn important fundamentals.
['NewSQL' could combine the best of SQL and NoSQL and NoSQL offers users scalability, flexibility, speed]
If you're a database novice, then give yourself plenty of time to learn your way around. PostgreSQL is a great database for beginners because it's well documented and aims to adhere to standards. Even better, everything is discoverable -- nothing is hidden, not even the source code, so you can develop as complete an understanding of it as you want.
Linux and FreeBSD split PostgreSQL into multiple packages. You want both the server and client. For example, on Debian the metapackage
The downloads page also includes some live CDs which make it dead easy to set up a test server; simply boot the CD and go to work. For this article, I used a Debian Wheezy (Testing) system running PostgreSQL 9.0.4, the current stable release.
Now, let's list all of our databases. (The last column of the table has been separated out so it'll all fit on the page, but this will be one table on your screen.)
Postgres is more than a RDBMS; it calls itself an an object-relational database management system, or ORDBMS. This is not the same as a object-oriented database management system (OODBMS), but something of a hybrid, a traditional relational database with an object-oriented database model; it supports objects, classes and inheritance.
That's all for today. Come back for Part 2 to find out how to populate tables with data, to learn about schema, keys, normalization, views, and tuples, and to discover how to use pgAdmin3.
REFERENCES
http://www.itworld.com/data-centerservers/196745/crash-course-postgressql-part-1
['NewSQL' could combine the best of SQL and NoSQL and NoSQL offers users scalability, flexibility, speed]
If you're a database novice, then give yourself plenty of time to learn your way around. PostgreSQL is a great database for beginners because it's well documented and aims to adhere to standards. Even better, everything is discoverable -- nothing is hidden, not even the source code, so you can develop as complete an understanding of it as you want.
Planning
The most important part of administering any database is preparation, in planning and design, and in learning best practices. A good requirements analysis will help you decide what data to store, how to organize it, and what business rules to incorporate. You'll need to figure out where your business logic goes -- in the database, in middleware, or applications? You may not have the luxury of a clean, fresh new installation, but must instead grapple with a migration from a different database. These are giant topics for another day; fortunately there are plenty of good resources online, starting with the excellent PostgreSQL manuals and Wiki.Installation
We'll use three things in this crash course: PostgreSQL, its built-in interactive command shellpsql, and the excellent pgAdmin3 graphical administration and development tool. Linux users will find PostgreSQL and pgAdmin3 in the repositories of their favorite Linux distributions, and there are downloads on PostgreSQL.org for Linux, FreeBSD, Mac OS X, Solaris, and Windows. There are one-click installers for OS X and Windows, and they include pgAdmin3. Any of these operating systems are fine for testing and learning. For production use, I recommend a Linux or Unix server, because they're reliable, efficient, and secure.Linux and FreeBSD split PostgreSQL into multiple packages. You want both the server and client. For example, on Debian the metapackage
postgresql installs all of these packages:# apt-get install postgresql
postgresql postgresql-9.0 postgresql-client-9.0
postgresql-client-common postgresql-common
See the detailed installation guides on the PostgresSQL wiki for more information for all platforms.The downloads page also includes some live CDs which make it dead easy to set up a test server; simply boot the CD and go to work. For this article, I used a Debian Wheezy (Testing) system running PostgreSQL 9.0.4, the current stable release.
Creating and destroying a new PostgreSQL database
You'll have to jump through a number of startup and user account hurdles to get started. First, verify that your PostgreSQL server has started by openingpsql, its interactive command shell:$ psql psql: could not connect to server: No such file or directoryOops, PostgreSQL is not running. Go back to the appropriate installation guide to see how to start it on your system. On Debian, it starts automatically after installation, so the above command produces the following result:
carla@xena:~$ psql psql: FATAL: role "carla" does not existWell, excuse me all to heck! But this really isn't a big deal, because PostgreSQL creates a default
postgres superuser with no password. So you have to change to this user, and then create a new user account that you will use to administer the database. On Linux and Unix you need to gain rootly powers, like this:carla@xena:~$ su root@xena:/home/carla# su postgres postgres@xena:/home/carla$There, now we can get some real work done! Let's create a
carla superuser for PostgreSQL:postgres@xena:/home/carla$ createuser carla could not change directory to "/home/carla" Shall the new role be a superuser? (y/n) yThese PostgreSQL roles,
postgres and carla, are PostgreSQL user accounts that are independent of system accounts. A role can be a single user or a group of users. Roles can own database objects, such as tables, and can assign privileges to access those tables to other roles. Use the dropuser command to delete a role:$ dropuser carlaNow, let's create a brand-new database:
$ createdb testdbNo news is good news; if this is successful there will be no feedback. You'll see a message only if something went wrong. Now let's destroy our new database:
$ dropdb testdbAgain, silence equals success.
Exploring PostgreSQL
Start by creating a new database so you have something to work with. There won't be any data in it yet, but that's all right. Once you've created to it, connect to it using thepsql command:$ psql testdb psql (9.0.4) Type "help" for help. testdb=#Excellent! We are now sitting at the command prompt of our new database. The hash mark indicates that a superuser is logged in. (An angle brace would indicate a less-privileged user.) You would use
\q to quit (i.e., testdb=# \q). man psql lists all of the PostgresSQL commands. All commands that begin with a backslash are internal psql commands. They are not operating system shell commands, and they are not SQL commands.Now, let's list all of our databases. (The last column of the table has been separated out so it'll all fit on the page, but this will be one table on your screen.)
$ testdb=# \list
List of databases
Name | Owner | Encoding | Collation | Ctype
-----------+----------+----------+-------------+-------------
postgres | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8
template0 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8
| | | |
template1 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8
| | | |
testdb | carla | UTF8 | en_US.UTF-8 | en_US.UTF-8
| Access privileges
+-----------------------
|
| =c/postgres +
| postgres=CTc/postgres
| =c/postgres +
| postgres=CTc/postgres
|
There's our little testdb down at the bottom. The postgres database holds system data. template0 and template1 are templates for new databases, and template1 is the default. (You can use any Postgres database as a template.) template0 cannot be changed, but template0 can. Let's take a look inside postgres.$ psql postgres psql (9.0.4) Type "help" for help. postgres=#Who are the postgres DB users?
postgres=# \du
List of roles
Role name | Attributes | Member of
-----------+-----------------------------------+-----------
carla | Superuser, Create role, Create DB | {}
postgres | Superuser, Create role, Create DB | {}
What tablespaces do we have?postgres=# \db
List of tablespaces
Name | Owner | Location
------------+----------+----------
pg_default | postgres |
pg_global | postgres |
(2 rows)
Wait, back up: What are tablespaces? That's PostgreSQL's name for the physical storage locations of your database objects on disk. In other words, they're plain old directories on your filesystem. So you can control your disk layout and put your database objects wherever you like; for example, you could put a heavily-used index on a fast disk, or move objects to another partition or disk if you run out of space. Postgres has a squillion built-in objects, such as tables, functions, data types, aggregates, operators, and views. It also supports user-created objects. You can see the objects in the postgres DB, as this abbreviated example shows:postgres=# \ddS
Object descriptions
Schema | Name | Object | Description
------------+------------+-----------+----------------------------------
pg_catalog | abbrev | function | abbreviated display of inet value
pg_catalog | abs | function | absolute value
pg_catalog | abstime | data type | absolute, limited-range date and time
pg_catalog | aclitem | data type | access control list
pg_catalog | bit_and | aggregate | bitwise-and bigint aggregate
Press the Q key to exit the object descriptions. \dd means "show descriptions of all objects that have descriptions." By default system objects are not shown, so to see these add S.Postgres is more than a RDBMS; it calls itself an an object-relational database management system, or ORDBMS. This is not the same as a object-oriented database management system (OODBMS), but something of a hybrid, a traditional relational database with an object-oriented database model; it supports objects, classes and inheritance.
Viewing Tables
Let's look at some tables while we're in thepostgres DB. First, list its system tables:postgres=# \dtS
List of relations
Schema | Name | Type | Owner
------------+-----------------+-------+----------
pg_catalog | pg_aggregate | table | postgres
pg_catalog | pg_am | table | postgres
pg_catalog | pg_amop | table | postgres
What's inside the pg_am table?postgres=# \d pg_am
Table "pg_catalog.pg_am"
Column | Type | Modifiers
-----------------+----------+-----------
amname | name | not null
amstrategies | smallint | not null
amsupport | smallint | not null
amcanorder | boolean | not null
[...]
amcostestimate | regproc | not null
amoptions | regproc | not null
Indexes:
"pg_am_name_index" UNIQUE, btree (amname)
"pg_am_oid_index" UNIQUE, btree (oid)
This is just the table structure without data. It shows the column names, the data type for each column, and any optional modifiers. Try creating your own table in your test database. For instance, this simple table tracks my underground comics collection:CREATE TABLE comics (
name varchar(80),
publisher varchar(80),
date_published date
);
You can copy and paste this right into your own psql prompt:testdb=# CREATE TABLE comics ( testdb(# name varchar(80), testdb(# publisher varchar(80), testdb(# date_published date testdb(# ); CREATE TABLE testdb=#The commas tell
psql where your columns end, and the semi-colon tells where your command ends. Try running the commands you've already learned on your test database and new table to see how they look. Use DROP TABLE tablename;That's all for today. Come back for Part 2 to find out how to populate tables with data, to learn about schema, keys, normalization, views, and tuples, and to discover how to use pgAdmin3.
REFERENCES
http://www.itworld.com/data-centerservers/196745/crash-course-postgressql-part-1
Learn Vim Progressively
Category:
Vim
— SkyHi @ Monday, August 29, 2011
Vim the Six Billion Dollar editor
I suggest you to learn it in 4 steps:
But before we start, just a warning. Learning vim will be painful at first. It will take time. It will be a lot like playing a music instrument. Don’t expect to be more efficient with vim than with another editor in less than 3 days. In fact it will certainly take 2 weeks instead of 3 days.
You should feel a bit better. You can type letters like in a standard notepad. To get back in Normal mode just tap the
You know how to switch between Insert and Normal mode. And now, the list of command you can use in Normal mode to survive:
REFERENCES
http://yannesposito.com/Scratch/en/blog/Learn-Vim-Progressively/
Better, Stronger, Faster.Learn vim and it will be your last text editor. There isn’t any better text editor I know. Hard to learn, but incredible to use.
I suggest you to learn it in 4 steps:
- Survive
- Feel comfortable
- Feel Better, Stronger, Faster
- Use vim superpowers
But before we start, just a warning. Learning vim will be painful at first. It will take time. It will be a lot like playing a music instrument. Don’t expect to be more efficient with vim than with another editor in less than 3 days. In fact it will certainly take 2 weeks instead of 3 days.
1st Level – Survive
- Install vim
- Launch vim
- DO NOTHING! Read.
i.You should feel a bit better. You can type letters like in a standard notepad. To get back in Normal mode just tap the
ESC key.You know how to switch between Insert and Normal mode. And now, the list of command you can use in Normal mode to survive:
Recommended:
i: Insert mode. TypeESCto return to Normal mode.x: Delete the char under the cursor:wq: Save and Quit (:wsave,:qquit)dd: Delete (and copy) current linep: Paste
Only 5 commands. This is very few to start. Once these command start to become natural (may be after a complete day), you should go on level 2.
hjkl(recommended but not mandatory): basic cursor move (←↓↑→). Hint:jlook like a down arrow.:help: Show help about, you can start using :helpwithout anything else.
But before, just a little remark on Normal mode. In standard editors, to copy you have to use theCtrlkey (Ctrl-cgenerally). In fact, when you pressCtrl, it is a bit like if all your key change meaning. With vim in Normal mode, it is a bit like if yourCtrlkey is always pushed down.
A last word about notation: instead of writingCtrl-λ, I’ll write.
2nd Level – Feel comfortable
You know the commands required for survival. It’s time to learn a few more commands. I suggest:
Take the time to integrate all of these command. Once done, you should be able to do every thing you are able to do on other editors. But until now, it is a bit awkward. But follow me to the next level and you’ll see why.
- Insert mode variations:
a→ insert after the cursoro→ insert a new line after the current oneO→ insert a new line before the current onecw→ replace from the cursor to the end the word- Basic moves
0→ go to first column^→ go to first non-blank character of the line$→ go to the end of lineg_→ go to the last non-blank character of line/pattern→ search forpattern- Copy/Paste
P→ paste before, rememberpis paste after current position.yy→ copy current line, easier but equivalent toddP- Undo/Redo
u→ undo→ redo- Load/Save/Quit/Change File (Buffer)
:e→ open:w→ save:saveas→ save toZZor:wq→ save and quit:q!→ quit without saving, also:qa!to even if there are some modified hidden buffers.:bn(resp.:bp) → show next (resp. previous) file (buffer)
3rd Level – Better. Stronger. Faster.
Congratulation reaching this far! We can start the interesting stuff. At level 3, we’ll only talk about command which are compatible with the old vi.
Better
Lets look at how vim could help you to repeat yourself:
Some examples, open a file and type:
.→ (dot) will repeat the last command,- N
→ will do the command N times.
2dd→ will delete 2 lines3p→ will paste the text 3 times100idesu [ESC]→ will write “desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu desu “.→ Just after the last command will write again the 100 “desu “.3.→ Will write 3 “desu” (and not 300, how clever).Stronger
Knowing how to move efficiently with vim is very important. Don’t skip this section.
Now let’s talk about very efficient moves:
- N
G→ Go to line Ngg→ shortcut for1G, go to the start of the fileG→ Go to last line- Word moves:
By default, word are composed of letter and the underscore character. If you want to use word in the meaning of group of letter separated by spaces, just use uppercases:
w→ go to the start of the following word,e→ go to the end of this word.
W→ go to the start of the following “extended” word,E→ go to the end of this “extended” word.
Believe me, the last three commands are gold.
%: Go to corresponding(,{,[.*(resp.#) : go to next (resp. previous) occurrence of the word under the cursor
Faster
Remember about the importance of vi moves? Here is the reason. Most commands can be used using the following general format:
For example :0y$means
We also can do things like
0→ go to the beginning of this liney→ yank from here$→ up to the end of this lineye, yank from here to the end of the word. But alsoy2/fooyank up to the second occurrence of “foo”.
But what was true fory(yank), is also true ford(delete),v(visual select),gU(uppercase),gu(lowercase), etc…
4th Level – Vim Superpowers
With all preceding commands you should be comfortable to use vim. But now, here are the killer features. Some of these features were the reason I started to use vim.
Move on current line:
0^$fFtT,;Some Useful Tips
0→ go to column 0^→ go to first character on the line$→ go to the last character on the linefa→ go to next occurrence of the letteraon the line.,(resp.;) will seek for the next (resp. previous) occurrence.t,→ go just before the character,.3fa→ search the 3rd occurrence ofaon this line.FandT→ likefandtbut backward.
dt"→ remove everything until the".vi"→ select everything inside two".Select rectangular blocks:
Rectangular blocks are very useful to comment many lines of code. Typically:.0I-- [ESC]
^→ go to start of the line→ Start block selection→ move down (could also bejjjor%, etc…)I-- [ESC]→ write--to comment each line
Not on windows you might have to useinstead ofif your clipboard is not empty.
Completion:
In Insert mode, just type the start of a word, then typeand., magic…![]()
Macros :
qado somethingq,@a,@@qarecord your actions in the registera. Then@awill replay the macro saved into the registeraas if you typed it.@@is a shortcut to replay the last executed macro.
Example
On a line containing only the number 1, type this:
qaYp→q
qastart recording.Ypduplicate this line.increment the number.qstop recording.@a→ write 2 under the 1@@→ write 3 under the 2- Now do
100@@will create a list of increasing numbers until 103.
Visual selection:
We saw an example withv,V,. There is alsovandV. Once the selection made, you can:
J→ join all lines together.<(resp.>) → indent to the left (resp. to the right).=→ auto indent
Add something at the end of all visually selected lines:
- go to desired line (
jjjoror/patternor%etc…)$go to the end of lineA, write text,ESC.
Splits:
Here are the main commands, but you should look at:splitandvsplit.:help split.
:split→ create a split (:vsplitcreate a vertical split): where dir is any ofhjklor ←↓↑→ to change split.(resp._ ) : maximise size of split (resp. vertical split)| (resp.+ ) : Grow (resp. shrink) split-
Conclusion
That was 90% of commands I use every day. I suggest you to learn no more than one or two new command per day. After two to three weeks you’ll start to feel the power of vim in your hands.
Then, you will learn about!, folds, registers, the plugins and many other features. Learn vim like you’d learn piano and all should be fine.
REFERENCES
http://yannesposito.com/Scratch/en/blog/Learn-Vim-Progressively/
Thursday, August 25, 2011
MySQL configuration file variables Explained
Category:
MySQL
— SkyHi @ Thursday, August 25, 2011
This MySQL server has been running for 0 days, 2 hours, 9 minutes and 22 seconds. It started up on Aug 25, 2011 at 09:34 AM.
1 On a busy server, the byte counters may overrun, so those statistics as reported by the MySQL server may be incorrect.
SQL query SSL Handler Query cache Threads Binary log Temporary data Delayed inserts Key cache Joins Replication Sorting Tables Transaction coordinator
Server traffic: These tables show the network traffic statistics of this MySQL server since its startup.
| Traffic 1 | ø per hour | |
|---|---|---|
| Received | 15 KiB | 7,284 B |
| Sent | 43 KiB | 20 KiB |
| Total | 59 KiB | 27 KiB |
| Connections | ø per hour | % | |
|---|---|---|---|
| max. concurrent connections | 2 | --- | --- |
| Failed attempts | 0 | 0.00 | 0.00% |
| Aborted | 0 | 0.00 | 0.00% |
| Total | 87 | 40.35 | 100.00% |
Query statistics: Since its startup, 284 queries have been sent to the server.
| Total | ø per hour | ø per minute | ø per second |
|---|---|---|---|
| 284 | 131.72 | 2.20 | 0.04 |
| Query type | ø per hour | % | |
|---|---|---|---|
| select | 158 | 73.280 | 80.20% |
| set option | 15 | 6.957 | 7.61% |
| show tables | 8 | 3.710 | 4.06% |
| show binlogs | 3 | 1.391 | 1.52% |
| change db | 3 | 1.391 | 1.52% |
| show variables | 3 | 1.391 | 1.52% |
| Query type | ø per hour | % | |
|---|---|---|---|
| admin commands | 2 | 0.928 | 1.02% |
| show slave status | 1 | 0.464 | 0.51% |
| show master status | 1 | 0.464 | 0.51% |
| show databases | 1 | 0.464 | 0.51% |
| flush | 1 | 0.464 | 0.51% |
| show status | 1 | 0.464 | 0.51% |
| Query type | ø per hour | % | |
|---|---|---|---|
| show charsets | 1 | 0.464 | 0.51% |
| show collations | 1 | 0.464 | 0.51% |
| show grants | 1 | 0.464 | 0.51% |
| show plugins | 1 | 0.464 | 0.51% |
| Variable | Value | Description |
|---|---|---|
| Ssl_accept_renegotiates | 0 | |
| Ssl_accepts | 0 | |
| Ssl_callback_cache_hits | 0 | |
| Ssl_cipher | ||
| Ssl_cipher_list | ||
| Ssl_client_connects | 0 | |
| Ssl_connect_renegotiates | 0 | |
| Ssl_ctx_verify_depth | 0 | |
| Ssl_ctx_verify_mode | 0 | |
| Ssl_default_timeout | 0 | |
| Ssl_finished_accepts | 0 | |
| Ssl_finished_connects | 0 | |
| Ssl_session_cache_hits | 0 | |
| Ssl_session_cache_misses | 0 | |
| Ssl_session_cache_mode | NONE | |
| Ssl_session_cache_overflows | 0 | |
| Ssl_session_cache_size | 0 | |
| Ssl_session_cache_timeouts | 0 | |
| Ssl_sessions_reused | 0 | |
| Ssl_used_session_cache_entries | 0 | |
| Ssl_verify_depth | 0 | |
| Ssl_verify_mode | 0 | |
| Ssl_version |
| Variable | Value | Description |
|---|---|---|
| Handler_commit | 0 | The number of internal COMMIT statements. |
| Handler_delete | 0 | The number of times a row was deleted from a table. |
| Handler_discover | 0 | The MySQL server can ask the NDB Cluster storage engine if it knows about a table with a given name. This is called discovery. Handler_discover indicates the number of time tables have been discovered. |
| Handler_prepare | 0 | |
| Handler_read_first | 4 | The number of times the first entry was read from an index. If this is high, it suggests that the server is doing a lot of full index scans; for example, SELECT col1 FROM foo, assuming that col1 is indexed. |
| Handler_read_key | 0 | The number of requests to read a row based on a key. If this is high, it is a good indication that your queries and tables are properly indexed. |
| Handler_read_next | 0 | The number of requests to read the next row in key order. This is incremented if you are querying an index column with a range constraint or if you are doing an index scan. |
| Handler_read_prev | 0 | The number of requests to read the previous row in key order. This read method is mainly used to optimize ORDER BY ... DESC. |
| Handler_read_rnd | 0 | The number of requests to read a row based on a fixed position. This is high if you are doing a lot of queries that require sorting of the result. You probably have a lot of queries that require MySQL to scan whole tables or you have joins that don't use keys properly. |
| Handler_read_rnd_next | 1,878 | The number of requests to read the next row in the data file. This is high if you are doing a lot of table scans. Generally this suggests that your tables are not properly indexed or that your queries are not written to take advantage of the indexes you have. |
| Handler_rollback | 0 | The number of internal ROLLBACK statements. |
| Handler_savepoint | 0 | |
| Handler_savepoint_rollback | 0 | |
| Handler_update | 0 | The number of requests to update a row in a table. |
| Handler_write | 1,819 | The number of requests to insert a row in a table. |
| Variable | Value | Description |
|---|---|---|
| Delayed_errors | 0 | The number of rows written with INSERT DELAYED for which some error occurred (probably duplicate key). |
| Delayed_insert_threads | 0 | The number of INSERT DELAYED handler threads in use. Every different table on which one uses INSERT DELAYED gets its own thread. |
| Delayed_writes | 0 | The number of INSERT DELAYED rows written. |
| Not_flushed_delayed_rows | 0 | The number of rows waiting to be written in INSERT DELAYED queues. |
| Variable | Value | Description |
|---|---|---|
| Key_blocks_not_flushed | 0 | The number of key blocks in the key cache that have changed but haven't yet been flushed to disk. It used to be known as Not_flushed_key_blocks. |
| Key_blocks_unused | 13 k | The number of unused blocks in the key cache. You can use this value to determine how much of the key cache is in use. |
| Key_blocks_used | 0 | The number of used blocks in the key cache. This value is a high-water mark that indicates the maximum number of blocks that have ever been in use at one time. |
| Key_read_requests | 0 | The number of requests to read a key block from the cache. |
| Key_reads | 0 | The number of physical reads of a key block from disk. If Key_reads is big, then your key_buffer_size value is probably too small. The cache miss rate can be calculated as Key_reads/Key_read_requests. |
| Key_write_requests | 0 | The number of requests to write a key block to the cache. |
| Key_writes | 0 | The number of physical writes of a key block to disk. |
| Key_buffer_fraction_% | 18.24 % | |
| Variable | Value | Description |
|---|---|---|
| Select_full_join | 0 | The number of joins that do not use indexes. If this value is not 0, you should carefully check the indexes of your tables. |
| Select_full_range_join | 0 | The number of joins that used a range search on a reference table. |
| Select_range | 0 | The number of joins that used ranges on the first table. (It's normally not critical even if this is big.) |
| Select_range_check | 0 | The number of joins without keys that check for key usage after each row. (If this is not 0, you should carefully check the indexes of your tables.) |
| Select_scan | 26 | The number of joins that did a full scan of the first table. |
| Variable | Value | Description |
|---|---|---|
| Sort_merge_passes | 0 | The number of merge passes the sort algorithm has had to do. If this value is large, you should consider increasing the value of the sort_buffer_size system variable. |
| Sort_range | 0 | The number of sorts that were done with ranges. |
| Sort_rows | 0 | The number of sorted rows. |
| Sort_scan | 0 | The number of sorts that were done by scanning the table. |
| Variable | Value | Description |
|---|---|---|
| Flush (close) all tables Show open tables | ||
| Open_tables | 64 | The number of tables that are open. |
| Opened_tables | 418 | The number of tables that have been opened. If opened tables is big, your table cache value is probably too small. |
| Table_locks_immediate | 89 | The number of times that a table lock was acquired immediately. |
| Table_locks_waited | 0 | The number of times that a table lock could not be acquired immediately and a wait was needed. If this is high, and you have performance problems, you should first optimize your queries, and then either split your table or tables or use replication. |
| Variable | Value | Description |
|---|---|---|
| Tc_log_max_pages_used | 0 | |
| Tc_log_page_size | 0 | |
| Tc_log_page_waits | 0 |
Subscribe to:
Posts (Atom)
