December 2011
1 post
OS X: replace tabs with spaces in all files using...
We use four spaces (a.k.a. soft tabs) to indent our PHP files. If an errant developer has unknowingly used tabs, you can use expand to replace tabs with spaces across an entire project.
https://gist.github.com/1468061
April 2011
2 posts
2 tags
PHP: removing zero values from an array
If you call array_filter without a callback function, it’ll remove all array elements that evaluate to false (including zeroes).
$numbers = array(0, 1, 2, 0);
echo array_filter($numbers);
Produces:
array(1,2);
2 tags
PHP: returning an array of single attributes from...
I miss Ruby’s shorthand collect method to return an array of single attributes:
animals.collect(&:name)
…so I’ve created a (less elegant) equivalent for PHP.
class ArrayExtensions
{
/**
* From an array of objects, create a new array containing only
* a single attribute of each object
*
* Similar to array.collect(&:attribute) in Ruby
*/
...
March 2011
1 post
2 tags
PHP: check if a PEAR class is installed
You can’t use file_exists because it doesn’t search the include path.
fopen has a third argument that will check the include path, though:
if (@fopen('Log.php', 'r', true))
{
echo 'It exists!';
}
August 2010
2 posts
4 tags
Redirect the output of a command to a file when...
Rather than > or », use tee.
Redirecting the output of commands run with sudo requires a different approach. For instance consider sudo ls > /root/somefile will not work since it is the shell that tries to write to that file. You can use ls | sudo tee -a /root/somefile to append, or ls | sudo tee /root/somefile to overwrite contents.
From...
1 tag
Subversion branching best practice
Most new code is checked into the trunk. In general, our developers try to never “break the tree”. Anyone who checks in code which causes the trunk builds to fail will be the recipient of heaping helpings of trash talk and teasing until he gets it fixed. The trunk should always build, and as much as possible, the resulting build should always work.
Most new code is checked into the...
May 2010
2 posts
2 tags
List your Apache virtual hosts
apache2ctl -t -D DUMP_VHOSTS
Copy a large directory of files using ls and xargs
ls . | xargs -i -t cp ./{} /path/to/new/directory
See example 12-6 at http://www.homepage.montana.edu/~unixuser/051905/abs-guide/moreadv.html
April 2010
1 post
4 tags
Rails migrations: creating a MySQL BIGINT
add_column :facebook_user_id, :integer, :limit => 8 # BIGINT
February 2010
2 posts
3 tags
Basic use of 'screen'
Using screen is a great way to leave long-running processes churning away when you’re not logged into the machine.
Open a new screen
screen
Detach from the screen
This does not interrupt whatever is running in the screen.
Press Ctrl-A then D.
Reattach to a screen you’ve already opened
screen -r
If you’ve opened multiple screens, a list will be displayed:
There are...
1 tag
Change your default SSH username
If you’ve not had your own choice of username on your machine (for example, if your company imposes a username policy), you can set up a different default username for SSH in ~/.ssh/config:
Host *
User chris
January 2010
1 post
3 tags
Readable, colourful Terminal in Snow Leopard
Install SIMBL: http://www.culater.net/software/SIMBL/SIMBL.php
Install the Snow-Leopard-friendly version of the TerminalColors plugin for SIMBL: http://github.com/timmfin/terminalcolours
Install the IR_Black theme and set it as default in Terminal.app preferences: http://blog.infinitered.com/entries/show/6
Turn on CLI color in your .bash_profile:
export CLICOLOR=1;
Bonus round: set yourself...
December 2009
1 post
4 tags
Border radius in Chrome, Firefox and Safari
Chrome 4 currently appears to be the only browser to implement the W3C’s border-radius property:
http://www.w3.org/TR/2002/WD-css3-border-20021107/#the-border-radius
border-top-left-radius: 1em;
border-top-right-radius: 1em;
You can produce the same result using proprietary attributes in Firefox 3.5 and Safari 4:
/* Firefox */
-moz-border-radius-topleft:...
October 2009
2 posts
1 tag
Using find with -exec to copy large directories
To copy files from one directory, you might usually do:
cp dir/* anotherdir/
If you try to do this with a particular large number of files, you may encounter the ‘argument list too long’ error. In this case you can use:
find . -exec cp {} /path/to/anotherdir/ \;
More approaches at: http://www.linuxjournal.com/article/6060
2 tags
FOWA 2009: The Future of HTML5
“The web is too important for society to be in the hands of any one vendor” - Bruce Lawson, Opera
HTML5 is more a collection of new technologies than a single new standard - we can start using parts of it today.
You can use Moderizr to check what HTML5/CSS3 features are available in your browser. You can see it in action at FindMeByIP.
Canvas/SVG
Cross-browser canvas support &...
September 2009
2 posts
1 tag
Linux: email alert when disk is nearly full
#!/bin/bash
# Send an email when disk space used reaches a certain threshold
FS="/"
SERVER_NAME="linux02"
EMAIL="user@example.com"
THRESHOLD=95
OUTPUT=($(LC_ALL=C df -P ${FS}))
CURRENT=$(echo ${OUTPUT[11]} | sed 's/%//')
[ $CURRENT -gt $THRESHOLD ] && df -h | mail -s "$SERVER_NAME disk space alert: $CURRENT% full" $EMAIL
I’ve set this up as a cron job run at 3am daily:
0 3 * * *...
3 tags
Is IE rendering in quirks mode?
To find out, load the page in question and then paste this into your address bar:
javascript:alert(document.compatMode);
‘backCompat’ is quirks mode; ‘css1Compat’ is standards mode.
More info on quirks mode: http://www.quirksmode.org/css/quirksmode.html
August 2009
2 posts
2 tags
Configuring the viewport on iPhone and iPod Touch
By default, Mobile Safari assumes that the page is 980px wide and sizes the viewport accordingly. If your page is significantly smaller, you can use the viewport meta tag to configure the viewport dimensions. For example:
Detailed documentation is available at developer.apple.com.
In portrait mode, the viewport is 320px wide; in landscape mode, it’s 480px wide.
3 tags
Apache: rewriting requests for iPhone and iPod...
This snippet will rewrite all requests to the page iphone.html when viewed on iPhone or iPod Touch. Requests for .gif and .css files are not rewritten, so you can include stylesheets and images in your iPhone-specific page.
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} .*Mobile.*Safari
RewriteRule !\.(gif|css)$ /iphone.html [L]
Source:...
July 2009
3 posts
1 tag
Find files created in the last x minutes
To find files created in the last 30 minutes:
find -cmin +30
2 tags
httperf
Get latest version from
ftp://ftp.hpl.hp.com/pub/httperf/
Usage
httperf --server staging.myserver.com
--uri /test/report_generation --num-conns 1000 --rate 10
(1000 connections at a rate of 10 per second)
There’s an excellent Peepcode screencast on the subject:
http://peepcode.com/products/benchmarking-with-httperf
2 tags
Dealing with Outlook 2007
You can use conditional comments to target Outlook 2007.
A common problem is that unordered lists do not appear with bullets. This can be fixed using:
More details at: http://www.campaignmonitor.com/blog/post/1774/using-conditional-comments-to-1/
May 2009
1 post
2 tags
Why getting good quality user feedback is hard
Ask a person why they bought a “blue Acura RX”, and the answer you’re likely to get is one that the person has created in their mind, a sort of cover for instinctive decisions made following intrinsic rules of fundamental human desires.
It is sort of like that old saying - “the heart has reasons that reason doesn’t know about”.
There is actually a proven psychological principle that sort of...
April 2009
2 posts
3 tags
Bash: replacing a string in files using sed
sed -i 's/old-word/new-word/g' *.txt
More: http://www.cyberciti.biz/faq/unix-linux-replace-string-words-in-many-files/
3 tags
Bash: clean up temporary files with find and xargs
find . -name ._* | xargs rm
February 2009
4 posts
Bash: the last word you typed with !$
Another terminal command that is as indispensable as the !! command is the !$ command. This command uses the last word you typed, and is particularly useful when you’re doing several things to the same file or directory, or when the last thing you typed is long and complicated. For example:
mkdir /usr/share/lib/foobar
chmod 755 !$
cd !$
Eventually your brain will type these...
4 tags
Rails integration test: setting the host
def test_something_else
sess = open_session
sess.host = "foo.bar.com"
end
3 tags
Running individual tests with rake
rake TEST=test/units/foo_test.rb
Source: http://rails.lighthouseapp.com/projects/8994/tickets/168-patch-generators-create-tests-with-require-test_helper-which-doesn-t-work
4 tags
Installing the mysql gem on OS X Leopard
First make sure you have the MySQL client libraries installed, then:
sudo env ARCHFLAGS="-arch i386" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config
Source: http://weblog.rubyonrails.com/2007/10/26/today-is-leopard-day
December 2008
1 post
3 tags
Update time on Ubuntu using NTP
ntpdate ntp.ubuntu.com
October 2008
2 posts
3 tags
Bash: loop through directory of files and act on...
In this example, we svn revert every file in the directory:
for each in `ls .`; do svn revert $each; done
3 tags
Ruby: returning an array of single attributes from...
You can do this:
animals.collect(&:name)
…to return an array of animal names. This is essentially a shorthand version of:
animals.collect { |animal| animal.name }
Source
August 2008
2 posts
2 tags
Flush DNS cache on OS X
dscacheutil -flushcache
4 tags
Apache: force all http requests to redirect to...
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
July 2008
3 posts
4 tags
Ruby: convert Unix timestamp to date
t = Time.at(1215163257)
puts t.to_date
>> 2008-07-04
2 tags
Ignore columns in a legacy database with...
Add this to the model:
# prevent ActiveRecord stumbling on the column named 'hash'
# by removing it from the column list
class << self # Class methods
alias :all_columns :columns
def columns
all_columns.reject {|c| c.name == 'hash'}
end
end
Solution half-inched from: http://groups.google.com/group/compositekeys/msg/202d04713ecbd6ee
2 tags
Multi-line strings in Ruby
numbers = %{
one
two
three
}
June 2008
4 posts
3 tags
Mongrel init script
#!/usr/bin/env ruby
app_dir = '/srv/www'
apps = {
'ladybird' => 8001
}
if ['stop', 'restart'].include? ARGV.first
apps.each do |path, port|
path = File.join app_dir, path
puts "Stopping #{path}..."
`mongrel_rails stop -c #{path}/current -P log/mongrel.pid`
end
end
if ['start', 'restart'].include? ARGV.first
apps.each do |path, port|
path = File.join app_dir, path
...
1 tag
Count array items in Perl
$#data
…where @data is an array
3 tags
ActiveRecord: has the object been saved to the...
Cleaner than checking if the value of fruit.id is nil:
fruit.new_record?
3 tags
Rails controller: logic for a specific request...
if request.format.html?
# do stuff
end
Works for any valid MIME type…
if request.format.xml?
More details at http://ryandaigle.com/articles/2007/2/15/what-s-new-in-edge-rails-mime-type-convenience-methods
May 2008
4 posts
sudo the previous command
You run a command, but it requires superuser privileges. Don’t retype it! Use:
sudo !!
3 tags
Removing pesky ._ files created by Textmate
find . -name ._* | grep -v .svn | xargs rm
The grep -v switch will negate (or reverse) the result set. In this case, it will find paths that do not include ‘.svn’.
2 tags
Rails: access the controller name in the view
@controller.controller_name
4 tags
Coloured bash prompt in OS X
Pop this into /etc/bashrc for a green and blue one…
export PS1="\[\e[32;1m\]\u@\h:\[\e[34;1m\]\w\[\e[0m\]$ "
More colour codes here: http://blog.infinitered.com/entries/show/6
April 2008
4 posts
2 tags
Writing to the Rails log
RAILS_DEFAULT_LOGGER.error('log message')
…will write to the log file of the current environment.
Ruby: make gems available to your command-line .rb...
If you add a require line to a command line Ruby script, like this:
require 'tzinfo'
…it will fail to find the library unless you’ve done one of the steps below.
Include rubygems at runtime
When running your script, use:
ruby -rubygems my_program_that_uses_gems
Easier: set the RUBYOPT environment variable to always include gems
Edit .bash_profile and add:
export...
Ruby equivalent of in_array
animals = %w(monkey goat octopus)
print animals.include?('monkey')
is the equivalent to
$animals = array('monkey', 'goat', 'octopus');
print in_array('monkey', $animals);
3 tags
Rails console reload
When you make changes to your model objects, you can reload them in the console using:
reload!
March 2008
4 posts
1 tag
Finishing a message in Unix mail
To finish a message when using the mail command, type a period (.) in the first column and hit Enter.