December 2011
1 post
3 tags
Du sort by size and human readable
Quick example to improve the du command output by displaying the biggest 10 subfolder of the current folder, each with its human redable size.
du -k * | sort -nr | cut -f2 | xargs -d '\n' du -sh | head -n 10
Found on ubuntu forums
July 2011
1 post
2 tags
Simple PHP updating counter on a Bash shell
If you’re running a php script on a shell and want to know what it’s doing, at which point of the script it is you can simply use the chr function to print a backspace and updating a counter while running.
Below is a quick example
<?php
$howmany = 20;
echo "I have to do $howmany cycles\n";
for($a=0;$a<$howmany;$a++) {
$bkspacestring =...
February 2010
1 post
tw2buzz →
Find your twitter followers using buzz too and connect with them!
January 2010
4 posts
[Browser] My favourite Chrome extensions
codepuzzling:
The development release of Chrome allow to install extension as for Firefox, but the process of installation (and even of creation as I heard from some developers) is faster. Here it is my list:
AdThwart: Block ads on websites. Supports EasyList and many other ad blocker filter lists.
RSS Subscription Extension: Adds one-click subscription to your toolbar.
Chrome Gestures:...
Responding to the Haiti Earthquake →
marco:
There aren’t a lot of natural disasters worse than the earthquake that just struck Haiti. The earthquake is such a disaster that the people who are normally in charge of telling you what a disaster it is are mostly dead or missing.
Earlier, I posted a list of charities that are set up to quickly get relief to those who need it. All of these charities are legitimate and regardless of...
Tornado Web Server →
(via manfrys)
1 tag
formspring.me
Ask me anything http://formspring.me/andreaolivato
December 2009
2 posts
3 tags
Recursively download a #Ftp tree via #Wget
This shows how to download recursively a complete ftp tree using wget command line tool
wget -r 'ftp://USER:PASS@HOST/PATH'
Going Mobile - Twhois Android App
twhois:
We are very proud to present you our new Android application featuring the Twhois service.
The App was realized as experiment and is still an Alpha version. It’s compatible with Android 1.5+ (tested until 2.1) and is very rough as layout.
From the main window you can type the username of a tweep you’re interested on, and then press the Twhois this button.
After a bit of...
November 2009
3 posts
Remove unwanted profiles - part 1
twhois:
We continue working on the editing part of twhois and today we’re releasing the first part of the remove feature we were asked to implement.
Logging in via Twitter API you are now able to delete previously added profiles. This means that the red cross shown above will only be present for links you added manually from the ‘Add profiles’ button.
We’re working hard to release the second...
Add more links to your profile page!
twhois:
Our crawling system can not be perfect of course and many of you recently complained about missing important links in your own home pages on Twhois.
During last days we managed to improve our editing script, increasing the personalization possibilities by enabling the ‘Add profiles’ button.
After you logged in via twitter and pressed the button, it would open a nice popup...
October 2009
4 posts
2 tags
Target #CSS to browser [ #IE fixes ]
How to target a single CSS instruction to IE and also to a single version of IE.
element {
/* All Browsers */
property: value;
/* IE 7 and below */
*property: value;
/* IE 6 and below */
_property: value;
/* IE 6 only */
_pr\operty: value;
}
3 tags
Regex to change any BR in space in #PHP
This is a simple example showing how to change any <br> contained in an HTML string into a space, avoiding double spaces.
<?php
$string = 'Lorem <br>ipsum<br style="border:1px solid #CCC" />dolor<br /> sit<br style="height:1000px;">amet';
/* Stripping all other tags
* [optional, depends on what you want to do
*/
$string = strip_tags($string,'<br>');
/*...
2 tags
#Apache Error : No space left on device
Here’s how I get rid of annoying error ‘no space left on device’ while restarting apache webserver on Debian Lenny
fuser -k -n tcp 80
2 tags
Show tables in #Postgres ( #SQL )
This is a quick replacement for the ‘show tables’ #mysql command when using #postgres. If you’re on a psql shell you can just do ‘\d’ the following scripts refers to the case you need to show tables from an external script.
select tablename from pg_tables where tableowner='yourname';
September 2009
1 post
3 tags
August 2009
3 posts
2 tags
Be sure that Ajax calls came from your domain in...
Useful for be sure nobody steals your resources (cpu ecc) this script checks if the ajax call started from your domain. If not… dies.
$ref_domain = parse_url($_SERVER['HTTP_REFERER']);
if ( $_SERVER['SERVER_NAME'] != $ref_domain['host'])
die;
1 tag
Randomize an Array in #php using shuffle
Simple way to re-order an array by random in php.
<?php
/* First of all I create an array */
$array = Array(1,2,3,4);
/* Now I shuffle it */
shuffle($array);
/* Here's the disordered result */
echo implode(', ',$array);
?>
1 tag
Bash tricks & tips
The following examples are not difficult coding examples, but just quick reminders to make working with bash easier and quicker.
# Use last argument of previous command
touch somefile
vim !$
# Monitor code execution
/bin/bash -x command
# or declare it at the top of the script
#!/bin/bash -x
# Repeat previous command changing a world with an other
for i in $(seq 0 10); do mv somefile.somext...
July 2009
23 posts
1 tag
Max ID from Mysql - Speed tests
I know three methods able to retrieve the max ID (primary key with autoincrement) of a table and I wanted to know which was faster so I run some tests.
SELECT Auto_increment FROM information_schema.tables WHERE table_name="MYDB" AND table_schema="MYTABLE" LIMIT 1;
SELECT MAX(id) From MYDB.MYTABLE LIMIT 1;
SELECT id FROM MYDB.MYTABLE ORDER BY id DESC LIMIT 1
Before giving you the results...
1 tag
Htaccess rewrite : forward query string and add...
This shows a simple solution to make some redirs adding parameters to querystring. I used this to implement an API service.
Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REQUEST_URI} !/index.php* [NC]
RewriteCond %{QUERY_STRING} ^(.+)$
RewriteRule ^([^.]+).([^?]+)$ index.php?method=$1&format=$2&%1
Example request:
/create.json?param=something&foo=smelse
Redirects to...
2 tags
Brace expansions examples in bash
A bunch of self-explaining examples using brace
# Just echo
echo {John,Jane,Baby,Precious}
#John Jane Baby Precious
# Combine
echo {John,Jane,Baby,Precious}Doe
#JohnDoe JaneDoe BabyDoe PreciousDoe
# Combine with with spaces
echo {"John ","Jane ","Baby ","Precious "}Doe
#John Doe Jane Doe Baby Doe Precious Doe
# Combine with with spaces and commas
echo {"John ","Jane ","Baby ","Precious...
2 tags
Send a message to all active users on system with...
Wall is a great utility for sysadm which allows them to send a message to all currently opened shells. Here’s a common use :
wall Rebooting server in 5 mins, please save works and get the hell out of here
Any currently connected user will receive a message like
Broadcast message from sysadm (pts/5) (Wed Jul 29 11:50:59 2009):
Rebooting server in 5 mins, please save works and get...
2 tags
Split big files in bash with ... split
Example on how to use split to phisically split large files in smaller ones.
ls -lh bigfile
# This is our initial situation: a large file we want to split
#-rw-r--r-- 1 foo foo 10M Jul 29 11:30 bigfile
# This will do the dirty job
# we're going to split the big file in many little ones, each of 2mb
split -b 2m bigfile part_
# Let's check what we got
ls -lh part_*
# Will output the list of new...
2 tags
Count multiple files lines with wc
Ok this is probably granted, but I didn’t know wc was able to read and count from multiple files at once.
# From standard input
cat *.pl | wc -l
# From list
wc -l file1.pl file2.pl
1 tag
Foreach key => val in Javascript
Simple example on how to obtain a key => val cycle for a Javascript Object
var object = { foo: 1, bar: 2, baz: 3 };
[ alert ( key + "=" + obj[val] ) for ( val in obj ) ];
3 tags
Reinstall all currently installed packages from...
This script, found on ubuntu forums, might help if you rm -rf some important dir and want to repair everything. Obviously it never happened to me.
for pkg in `dpkg --get-selections | awk '{print $1}' | egrep -v '(dpkg|apt|mysql|mythtv)'` ; do apt-get -y --force-yes install --reinstall $pkg ; done
2 tags
2 tags
Folder size in shell using du
Simple way to retrieve a folder size in human readable format using du utility.
du -sh folder_name
3 tags
Delete .svn folders from trunk with find
Quick code to remove all .svn files and folder from a trunk.
find . -name "*svn*" -exec rm -rf '{}' \;
2 tags
Update DynDns host with current IP with Perl
Updates any DynDns host with current IP address. Useful if put in crontab and executed every 15mins.
#!/usr/bin/perl
# Load Needed Modules
use strict;
use XML::Simple;
use LWP::UserAgent;
# Get login data
my $username="DynDns_user";
my $password="DynDns_user";
my $hostname="yourhost.example.com";
# Create a new useragent
my $ua = new LWP::UserAgent;
$ua->agent('Mozilla/5.0 (X11; ; Linux...
4 tags
Create a Zenity progress bar using wget output
I found this simple script to redirect wget progress bar to a nicer zenity window.
Sed is used to parse the output and send to Zenity only the correct progress. An infinite bash cycle is used to check that zenity is still running (if the user closes the window probably you want wget to be killed)
# Start wget | zenity
# Note the & at the end of the pipe, this allows the script to continue...
1 tag
[PHP] How much memory does your app consume?
Reblogged codepuzzling:
Here it is a simple function to display how much memory your PHP script is consuming.
// debug function with time, memory consumption (MB) and optional custom message
public function getMemoryUsage($message="", $echo=1)
{
$mem_used = memory_get_usage(true)/ 1024 / 1024;
$mem_peak = memory_get_peak_usage(true) / 1024 / 1024;
...
1 tag
1 tag
3 tags
Use Zenity calendar to get dates in different...
Quick example on how to open a calendar with Zenity, get the selected date from a Bash script, and change the returned date format (timestamp f.e.).
#!/bin/bash
# Creates a Zenity calendar obj,
# Put the selected date on a variable.
DATE=`$(zenity --calendar --text "When to leave?" --title "Holidays"); echo $szDate`;
# If you want to return the date in a different format you can play with
#...
2 tags
Zenity dialog. Get the answer from Bash.
This shows how to create a Zenity dialog window and how to get the answer given by user into a Bash variable.
#!/bin/bash
# Creates a Zenity question dialog,
# similar to JS confirm().
# Put the answer code on a variable.
ANSWER=$(zenity --entry --text "What's your name?" ); echo $szAnswer
# Creates a Zenity popup (information dialog)
# and put there user previous answer
zenity --info --text...
2 tags
Zenity questions
Quick examples on how to launch Zenity questions from Bash and use the returned values.
#!/bin/bash
# Creates a Zenity question dialog,
# similar to JS confirm().
# Put the answer code on a variable.
ANSWER=`zenity --question --text "Do you like me?"; echo $?`;
# Check what the user pressed
if [[ $ANSWER -eq 1 ]]
then
# 1 => pressed cancel
echo "No, you don't";
else
# 0 => pressed...
2 tags
Cycle all folder's file and get each name in #bash
This is pretty useful if you need to do some operations on certain files in a folder. In the example I’m cycling all files in the apache log folder, selecting only the .log files and then get the basename (no path) of the log.
DIR="/var/log/apache2";
for FILE in ${DIR}/*.log
do
FILE=`basename $FILE`;
echo "Let's do some op on $FILE";
done
1 tag
[JS] How to test if a variable is defined
codepuzzling:
// returns 1 if defined, 0 otherwise.
function isDefined(anObj) {
switch(typeof(anObj)) {
case "string": if(anObj != "") return 1; else return 0;
case "undefined": return 0;
case "object": if(anObj != null) return 1; else return 0;
default: return 0;
}
}
2 tags
Using Sqlite3 in Bash
After my previous post about working with sqlite3 on #perl, here’s an other quick script to explore how to use this simple DB in #bash.
#!/bin/bash
# Defining my databse first table
STRUCTURE="CREATE TABLE data (id INTEGER PRIMARY KEY,name TEXT,value TEXT);";
# Creating an Empty db file and filling it with my structure
cat /dev/null > dbname.db
echo $STRUCTURE >...
June 2009
15 posts
2 tags
String to upper or lower in #Bash
This shows how to convert a string to lower or upper using bash and tr utility.
STRING="myFAncyString";
# String to lower
echo $STRING | tr "[:upper:]" "[:lower:]";
# String to upper
echo $STRING | tr "[:lower:]" "[:upper:]";
Via spikesource
2 tags
Urlencode a string in #perl
Quick script able to urlencode a string without the needing of importing modules
$mystring = "String to encode";
$mystring =~ s/([\W])/"%" . uc(sprintf("%2.2x",ord($1)))/eg;
print $mystring;
# Returns String%20to%20encode
3 tags
Check if variable is an array in #perl
This is quite useful when parsing xml code and you don’t know if an object contains an array of tags or a single value.
eval {
$#{$isthisanarray}
};
if ($@){
print "Nuuu! It's not";
} else {
print "Yes it is";
}
3 tags
Get your system load
How to get the system load only using uptime ouptut, filtered using awk.
uptime | awk -F'load average:' '{ print "Load: "$2 }'
On twitter @markkolich suggested me a quicker way to obtain the same result
cat /proc/loadavg
3 tags
memtop: order top by %Mem using expect
Top is one of the commands I use the most while working on linux servers. It’s terribly useful and configurable, got a clean interface and is simple to modify its output using shortcuts.
A lot of times I need to order top by memory percentage instead of cpu percentage. This can be easily achieved by pressing ‘M’ while looking at top.
As I’m really (terribly) lazy and I...
2 tags
How to check if a string contains an other in...
Quick trick using #grep in #bash for checking if a string is contained in an other one
STRING="someUnknownString";
NAIL="know";
res=`echo $STRING | grep $NAIL`;
if [[ ${#res} > 0 ]];
then
echo "Yes I found it.";
else
echo "No way, there isn't."
fi
If you want you can make the whole thing case insensitive just using grep -i
STRING="someUnknownString";
NAIL="Unkn";
res=`echo $STRING | grep...
How to export to an array a MySQL query with 3...
codepuzzling:
By reading a good contribution on PHP site, I discovered this method for exporting to an array a query submitted to MySQL:
$result = mysql_query("SELECT * FROM table"); for($i = 0; $array[$i] = mysql_fetch_assoc($result); $i++) ; array_pop($array); // removes last empty array
It produces:
Array ( [0] => Array ( [id] => 1 [user] => myuser ...