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


7 Ways to Optimize Your Blog

 

optimize blog

Every half second, a new blog appears on the Internet. With 175,000 being created every day and the blogosphere doubling in size every six months, the standards for a quality weblog have become much higher. Here are 7 ways to optimize yours:

1. Spend Time on Appearance

If you study Technorati’s list of most popular blogs, you’ll see that each has a unique and trademark design. None of them use the default template that ships with Wordpress or MovableType. The appearance of your blog says a lot about it, so either spend time developing the design yourself or have a talented designer craft a distinct look for it. Good content and good design should always go hand in hand. Additionally, different browsers behave differently, so make sure your design has cross-browser compatibility. An easy way to ensure this is to validate your website using the Markup Validation Service provided by W3C.

2. Focus on Information Design

Quality content is not always effective content. Teachers and professors are not the only people who appreciate clear organization and orderly formatting. Make it as easy as possible for your readers to absorb the material you’re providing, and they’ll be thankful that you took the time to organize your words and thoughts. Long entries are always easier to follow when they are broken into smaller paragraphs and sections with proper formatting. Images go well with words. Neatness counts.

3. Keep Things Futureproof and Scalable

Scalability is not mentioned much in blogging, but it is important to keep in mind. Develop and design everything as if your blog already has years of content and millions of readers. Minimize the size of your entries. This might not make much of a difference under normal conditions, but if you ever experience a sudden explosion in traffic, your server will be more likely to hold up under the strain. For futureproofing, use CSS whenever you can instead of hardcoding formatting directly into your entry HTML. This allows you to make formatting changes globally across all your blog’s entries. By planning carefully for the future, you can avoid making irreversible mistakes in the present.

4. Standardize Everything Possible

Develop your own standards for everything on your blog, and stick to them. An entry you publish years later should be very similar in design, topic, and formatting to what you post today. Therefore, think and plan carefully about everything you choose to do. Be consistent in how often you post, how you format your entry titles, and what you post about. Everyone loves and appreciates neatness, so be systematic and standardize every aspect of your blog.

5. Streamline the Posting Process

The amount of time it takes you to write and publish entries might not seem significant when you start out, but it accumulates as the days, months, and years go by. Making the posting process as simple and efficient as possible helps you in post consistently while letting you focus your time, energy, and brainpower on the content itself. If you have programming knowledge, write software modifications and custom scripts that help you shrink repetitive chores into the fewest number of clicks and keystrokes. Look for any tedious, recurring tasks, and find ways to minimize the time it takes to accomplish them. If you don’t have the programming knowledge necessary to write custom scripts, standardize your entries with a minimalistic mindset.

6. Keep Things Simple

Follow the example Google set in designing their homepage by thinking of each pixel on your blog as prime real estate. If there isn’t a good reason that something should be added to your page, there’s probably many reasons to leave it off. Thinking carefully about what you add to your blog helps you ensure fast load times and uncluttered pages.

7. Put Your Readers Above Yourself

While everyone seems to be preaching tips on how to maximize advertising income from your blog, it’s easy to forget the fact that people visit your blog to read it. Sure, placing contextual advertising directly into your content could drastically improve your daily clickthrough rate, but content is best when read by the readers, not milked by the owners. Blogging is a mutual, symbiotic relationship between bloggers and readers, so don’t sacrifice long term results for short term gain.


7 Tips for Naming Your Web 2.0 Startup

 

name startup

One of the first important things to consider when building a startup is the name. With Internet companies being so cheap and easy to start, it seems like a new one is born every few seconds. Here are 7tips for choosing the right name for yours:

1. Keep Length at a Minimum

What’s easier to type in multiple a times for day for a simple web search, Google.com or AskJeeves.com? It’s clear why AskJeeves shortened their name to Ask. If you can’t beat competition on quality and functionality, you’d better be aiming to make it as easy as possible for users to access your service. How easily a domain name is typed can make a big difference in whether or not a visitor will want to visit often. Part of the reason I read CNN.com for news is how easily the three letters can be typed into the address bar. A good length for one word names is five to six letters. Names should typically also never exceed two words.

2. Be Generic or Be Original

When Flickr exploded in popularity, quite a few entrepreneurs seemed to think that it set some sort of de facto standard for Web 2.0 naming conventions. It didn’t. Naming your service Locatr, Bookmarkr, Zooomr, Preloadr, or Frappr doesn’t put you next in line on the Yahoo acquisition queue. Either go for an expensive generic name that accurately describes what you’re about, or be creative by choosing an effective and unique name that stands out.

3. Encourage Word of Mouth

Company names should not be difficult to pronounce or spell. If a name doesn’t roll of the tongue, then choose something simpler. Can you imagine people around the world asking each other, “Have you heard of the web service PriceWaterhouseCoopers?” Well, neither can I. Once a name has gone from one person’s mouth to another person’s ear, there shouldn’t be any confusion as to how its spelled when typed into a browser.

4. Capture the .com

When Nintendo revealed that their seventh-generation console would be named “Wii”, the domain name Wii.com was already registered by someone else. Luckily for them, they had the money it took to acquire the domain from the existing owner. If your pockets aren’t as deep as Nintendo’s, think about working your name around to fit a .com instead of working domain extensions around to fit your name. Even if a domain is unavailable, look up the whois information on the domain and attempt to negotiate for it directly from the existing owner. Ever wonder how many extra hits Disney’s dig.com gets because of the popularity of Digg? It would greatly benefit Digg if they got their hands on Dig.com, but I doubt Disney would sell now. This is also why thefacebook.com quickly purchased facebook.comfrom the existing owner when they had the money to do so.

5. Avoid Using Hyphens

Only in special circumstances do hyphens benefit a website (e.g. experts-exchange.com instead of expertsexchange.com), but in most cases they don’t. Don’t burden your startup with a hyphen in the domain name just because the hyphen-less domain was already registered. How do you tell some to go to a website if there’s a hyphen in the name? If Myspace used the domain name my-space.com, how many people a day would erroneously type in myspace.com? There’s a whole industry of people who specialize in profiting off typo domains. Don’t feed them with your ignorance.

6. Avoid Domain Hacks

Yes, there was a time when it was creative and unique to name your service something like Del.icio.us, but now domain hacks have gone from being special to being inconvenient. That’s probably why Yahoo acquired the domain name delicious.com as an alternative (and easier) way to access the service through the address bar. Words in the English language don’t usually have multiple periods within them, therefore it takes more brainpower and time to type them in (both of which are a limited resource these days). If for some reason you just have to use a domain hack, register the .com version and forward it to your domain hack, like competitious.com.

7. Keep it Meaningful

We all know generic domain names are hard to come by these days. That, however, does not mean it’s hard to come up with a quality name for your company. An easy trick to an effective name is to combine a descriptive word with a meaningful, generic word. Examples include Feed/Burner, You/Tube, Hot/Mail, Tech/Crunch, etc… Make sure the descriptive word gives people a clear idea of what exactly your company does. The meaningful word should make sense and suggest something positive. Naming your startup something like FeedPorcupine or PictureSloth wouldn’t fit this rule. Don’t do it.