Obtaining the HTML Title of a URL

 

Here’s a little code snippet that allows you to grab the Title tag if you have a URL in php:

$url = "http://www.folksonomy.org";
$page = file($url);
$page = implode("",$file);

if(preg_match("/<title>(.+)<\/title>/i",$page,$t))
    print "$url has the title: $t";
else
    print "No title was found";

Internet Explorer Float Clear Padding Gap Glitch

 
Container: padding: 20px;

Float
Float
Clear

If you have a container with floating elements and a clear at the bottom, Internet Explorer might include an extra gap between your elements and your clear if you assign a padding value to your container.

If you view the example to the left in Firefox or some other non-IE browser, it will look as intended, with no gap between the floats and the clear. However, in IE, the 20px padding of the container div creates a 20px gap between the floats and the clear for some reason.

Here’s the code used:

<div style="padding: 20px;">
Container: padding: 20px;
<div style="float:left; width: 50%; background: green; color: white;">
Float
</div><div style="float:right; width: 50%; background: blue; color: white;">
Float
</div>

The workaround for this bug is to create the padding using container’s padding attribute for the left and right side, and the floats’ margin attributes for the padding on the top and bottom. Doing this creates a desired look across all browsers.

Note: This workaround is assuming that the clear will be set to 1px, and that the outside container is simply a container and will not contain content.

Container: padding: 0 20px;

Float: margin: 20px 0;
Float: margin: 20px 0;
Clear

Changing Input Type from Text to Password in Internet Explorer Hack

 

signinformLet’s say you have a login form with the standard username and password input fields, but instead of labels, you want to have grayed out text inside the fields to act as labels. Since the label’s aren’t actual input, they shouldn’t be submitted as actual data if a user submits the form without entering anything, and they should disappear if the user clicks the field to enter text.

The problem is, password fields should always be type=”password”, so the text they enter isn’t displayed while they type it. One solution would be to have javascript detect when the field is selected, and to dynamically change the type attribute of the field to “password” from “text”.

However, Internet Explorer has a problem with this, and refuses to play along. Thus, we must resort to a hack. Basically, what we’ll do is have two inputs, one of which is a fake text input, and the other a real password input. Here’s one way to implement this:

<input type="text" id="mockpass" class="mock" value="Password" onFocus="document.getElementById('mockpass').style.display='none'; document.getElementById('realpass').style.display=''; document.getElementById('realpass').focus();">
<input type="password" name="password" id="realpass" class="real" style="display: none;" onBlur="if(this.value=='') {document.getElementById('mockpass').style.display=''; document.getElementById('realpass').style.display='none';}">

The real input is initially hidden due to the style=”display: none”. If the user clicks the fake input, the onFocus event handler is triggered, and the inputs are swapped. To make the transition even more seamless, we set focus onto the real input using javascript as well: document.getElementById(’realpass’).focus();

Notice that the second input is the one that has the actual name value, which is password in this case. This means that if the form is submitted without the user entering a value, the “password” value in the first field will not be submitted as the password, since there is no name attribute on that fake input.

If the user clicks away from the real password input without entering text, we want to replace the label. To do this, we simply use the onBlur event handler to check to see if the input is blank, and to swap again if it is.

This is just the bare basics, but to make it look nice and smoothly, you would need to set both inputs to have the same dimensions and attributes so that when they are swapped for one another, there is no change in the appearance of the input itself.

Using CSS, you can change the input with class mock to be grayed out, while having the other input be solid text.

From my experiences so far, this hack is pretty flawless. The only obvious problem is that it will not work for people who do not have javascript enabled (a dying breed?). The workaround would be to write this out to the page using javascript, while providing an old-school version of the input for non-javascripters using <noscript>

Here it is in action:


Debugging Apache and Mysql

 

If you’re getting too many MySQL threads or Apache connections, and you would like to debug them, here are two possible ways to get the info you need:

Apache

fullstatus - Displays a full status report from mod_status. For this to work, you need to have mod_status enabled on your server and a text-based browser such as lynx available on your system. The URL used to access the status report can be set by editing the STATUSURL variable in the script.

MySQL

SHOW PROCESSLIST shows you which threads are running. You can also get this information from the INFORMATION_SCHEMA PROCESSLIST table or the mysqladmin processlist command. If you have the PROCESS privilege, you can see all threads. Otherwise, you can see only your own threads (that is, threads associated with the MySQL account that you are using). If you do not use the FULL keyword, only the first 100 characters of each statement are shown in the Info field.


Private and Public SSH Keys for Capistrano on Windows

 

capistranosshkeysIf you’re deploying a Ruby on Rails application using Capistrano on Windows, and need SSH authentication, you might run into errors like:

connection failed for: xxx.xxx.xxx.xxx (OpenSSL::PKey::PKeyError: not a private key (C:\path\to\key))

or

connection failed for: xxx.xxx.xxx.xxx (OpenSSL::PKey::PKeyError: not a public key “C:\path\to\key.pub”)

This is because Capistrano (by default) does not like the keys generated by Putty. You can get your keys working with Capistrano by converting them to OpenSSH keys using the following steps:

  1. Load your existing private.ppk private key file into PuTTy Key Generator by clicking the Load button.
  2. In the Conversions menu, select “Export OpenSSH key”. This will give you an OpenSSH private key that Capistrano accepts.
  3. Copy and paste the public key contents provided for you in the box under “Public-key for pasting into OpenSSH authorized_keys file:”. Save this in a file of the same name with .pub appended to the end.

Once you do this, you should have OpenSSH public and private keys that Capistrano will accept, and you can still use the old key files for PuTTy.


Formatting Strings for URLs

 

Here’s a quick Ruby snippet you can use to format a string to be used in a URL:

string.downcase.gsub(/[^a-z0-9]+/i, '_').chomp('_')

This turns something like

This is a Post URL!

into

this_is_a_post_url

which you can use in your archive URLs (like http://www.website.com/article/this_is_a_post_url)

The string is first converted to all lowercase letters with the downcase method of the String class.

Next, we use gsub to strip out everything that isn’t a letter or a number (including spaces) using regular expressions. We replace each of the gaps with a URL friendly separator, the ‘_‘ underscore character. You could also use some other character, like a hyphen, if you prefer.

Finally, since our formatted string could end with a separator character, we chomp that off the end.


Future-proofing Blog URLs

 

This entry is about five years too late, but if you’re starting a new blog, be sure to first read Már Örlygsson’s article about futureproofing blog URLs. Though the article is written specifically for Movable Type users, many of the points are valid no matter what blogging service or software you use.

To make your weblog URLs really future-proof you have to make sure they don’t contain either of the following:

a. File-extensions (.html, .php, .asp, etc.) as you might wish to switch between different server-side solutions at some point in the future. Showing your programming environment in your URLs is bad.
b. Any reference to some internal ID schema unique to your current weblog tool. Cryptic IDs are bad.

I would also recommend following these guidelines for both reasons mentioned in the article and additional reasons as well. Two incentives for choosing good naming conventions that are not mentioned in the article are search engine optimization (SEO) and contextual advertising (like Google Adsense).

If you’ve already launched your blog and it’s too late to conform to the guidelines mentioned in the article, there’s still some hope left. It’s entirely possible to have files of one extension parsed as a language of another extension. To look into this, just search for something like “parse .html as php“.


Rails Auto-Clearing Input Field

 

inputfieldAt certain times you might want to have a form input field have a description or default value that automatically clears when the user clicks the field to enter text.

An example of this is Digg’s search box. By default, it reads, “Search Digg…”, but when you click it, the default text disappears and makes room for your search terms.

To do this, we need to set the default value of the field using the value attribute, then set it to automatically clear when a user clicks it by using the onFocus event handler.

When a user clicks away from the field and the field is empty, we want to restore the default text. We can accomplish this with the onBlur event handler by checking whether the value is empty when the field loses focus. If it is, restore the default text.

Here is how you can implement this in HTML:

<input onFocus="if(this.value==this.defaultValue) this.value='';" onBlur="if(this.value=='') this.value=this.defaultValue;" type="text" value="Search..." />

Implementing this in Rails is just as easy. In your form code, use:

<%= text_field_tag(:s, "Search...", :onFocus => "if(this.value==this.defaultValue) this.value='';", :onBlur => "if(this.value=='') this.value=this.defaultValue;") %>

This is an example of such an input field:


Basic Search Form in Rails

 

railssearchIf you want to add a simple search page to your rails application, you’ll probably want a form that uses GET rather than POST, since GET will allow your visitors to bookmark the results page, and won’t complain if the user decides to refresh the results page.

Also, you’ll want the form to simply update the URL of the page itself, rather than have a controller parse the submitted data directly. This will allow you to grab the search parameters from the data in the URL and figure out what the return accordingly.

This is the code snippet you’re looking for:

<% form_tag(search_path, :method => "get") do %>
  <%= text_field_tag(:s) %>
  <%= submit_tag("Search", :name => nil) %>
<% end %>

In the form_tag, search_path is the named route you define in your config/routes.rb file.

text_field_tag(:s) will generate the following input field HTML:

<input id="s" name="s" type="text" />

When submitted, whatever the user enters into this field will be appended to the url in the form ?s=SEARCHTERM.

Also, notice that :name => nil is added to the submit_tag. If it were omitted, then the resulting URL would be search?s=searchterm&commit=Search


Dynamic Digg-Like Javascript Countdown

 

Digg comment screenshotWhen you save a comment on Digg, you have five minutes to edit it. Digg informs you of the time remaining with a real-time javascript countdown.

These “live” countdowns are definitely the way to go if you need to inform your user of time deadlines in the near future, since static HTML “time remaining” numbers would leave the user in a dilemma of not being able to see how much time they have left without refreshing and losing their data.

Here’s one possible way to implement this type of counter for your web service:

<script type="text/javascript">
// time is the number of seconds left
// name is the text part of the container to insert countdown in
// num is the unique id of the container. Allows for more than 1 per page
function countdown(time, name, num)
{
   // grab the element object of the countdown container
   countdownDiv = document.getElementById(name + num); 

   // calculate number of minutes from the seconds
   minutes = Math.floor(time / 60); 

   // remainder is number of seconds
   seconds = time % 60; 

   // add the current countdown display to the container specified
   countdownDiv.innerHTML = minutes + 'm ' + seconds + 's remaining';

   // if time is up remove the edit div, otherwise repeat every second
   if(time <= 0)
      countdownDiv.parentNode.removeChild( countdownDiv );
   else
      setTimeout('countdown(' + --time + ',"' + name + '","' + num + '");', 1000);
} 

</script>

This function takes two arguments: time is the duration of the countdown in seconds, and id is the id of the DOM that contains the countdown and should be updated every second.

To insert a counter into a page, the code should look like this:

<!-- In this case name is div_name and num is 1 -->
<div id=”div_name1″></div>

<script type=”text/javascript”>
   countdown(300, "div_name", 1)
</script>

Here’s a demo of the result:

example div