The Original Jelani Harris The one and only

11Jun/120

How to check if a jquery plugin is installed or available

Most Jquery plugins act a lot like functions. They are attached to the main Jquery object, so essentially all we have to do is check that the function exists and is defined.

if ($.pluginFunction) {
  // Function exists, do your plugin stuff here.
} else {
  // Plugin does not exist, use alternatives or do nothing in here.
}
Tagged as: , No Comments
4Jun/120

Strip Whitespace on save with Aptana

So recently I had a coworker get slightly annoyed with me and my trailing whitespaces at the end of lines. I'm using Aptana and not anything crazy like vim to do my programming work, I don't actually see the whitespace I'm leaving around.

However, they do show up in the git commits.

Because I don't want to turn on those annoying characters that show my line breaks and whitespace I tried to find an automated solution. My first thought was that maybe Aptana would have an option to remove all of the whitespace before I save. Alas, no option exists (at least with Aptana 3).

Then I found an Eclipse plugin called AnyEdit that solved my problem. AnyEdit can be found at http://andrei.gmxhome.de/anyedit/ .

Installing AnyEdit

So the first thing you'll want to do is to load up Aptana, go to Help -> Install New Software. You'll want to use http://andrei.gmxhome.de/eclipse/ as the "Work With:" URL.

Explore the drop downs and check the AnyEditTools plugin and then hit next. Go through the license agreement pages and Aptana will install the plugin. You'll be prompted to restart Aptana, which I always recommend.

The best part, is that the strip whitespace feature is turned on by default across all of your projects. In the case where you don't want to have that functionality, you can go to the properties of a project, and go to the AnyEdit Tools section and turn on Enable Project Specific Settings and then Remove Trailing Whitespace.

And .. it's that easy. Enjoy having cleaner code and even cleaner git commits.

Tagged as: , No Comments
24Sep/115

How to install Paperclip in Rails 3

The thoughtbot logo

Paperclip is a plugin/gem created by the talented folks at ThoughtBot. It will make using attachments and uploads in your rails application ridiculously easy to implement. Let's get started!

Things you'll need installed 

Before we start there is only one thing that you will need to have installed on your system before we can proceed.

ImageMagik
ImageMagik is a software suite that is used to edit and create images. Paperclip uses it to resize and modify images. The easiest way to install this is to first make sure that you have MacPorts installed, and then running:

sudo port install ImageMagick

This is a massive library and it will take a little while to install.

Installing Paperclip

So you can install Paperclip as a plugin, or you can install it as a gem.

Install as a Gem
This is the recommended way of installing Paperclip. All you need to do is to add to your config/environment.rb

config.gem 'paperclip', :source => 'http://rubygems.org'

Then run:

rake gems:install
rake gems:unpack

Or you can add it directly to your Gemfile if you have Bundler:

source 'http://rubygems.org'
gem 'paperclip'

Install as a Plugin
To install it as a plugin you use:

ruby script/plugin install git://github.com/thoughtbot/paperclip.git

Using Paperclip in Your Application

Lets add the 'has_attached_file' attributes to the model we want to be able to attach files to:

class Author > ActiveRecord::Base
  has_attached_file :avatar,
    :styles => {
      :thumb => "75x75#",
      :small => "100x100#",
      :medium => "150x150>"
    }
end

Thankfully attached files do not need to have a separate model. Your attachments are essentially treated like another attribute. The image is not saved until your model is saved (if you desire, there are ways of forcing attachment creation/updates without model involvement - but that's another tutorial)

Now that we have our model paperclip enabled we need to add some database columns to provide full support for it.

class AddAvatarToAuthor > ActiveRecord::Migration
  def self.up
    add_column :author, :avatar_file_name, :string
    add_column :author, :avatar_content_type, :string
    add_column :author, :avatar_file_size, :integer
  end
  def self.down
    remove_column :author, :avatar_file_name
    remove_column :author, :avatar_content_type
    remove_column :author, :avatar_file_size
  end
end

So the first part of the column name is the same as what we called our attachment attribute in our model. In this case that's photo. Now to update our database we use:

rake db:migrate

Now that we have our database and our model taken care of, we can start working on our content. So in our view we can add a file field:

<% form_for :author, :html => {:multipart => true} do |f| %>
  <%= f.label :avatar %><br />
  <%= f.file_field :avatar %>
  <%= f.submit %>
<% end %>

Displaying Attachments
Now when you want to display your model's attachments all you need to do is use:

<%= image_tag @author.avatar.url %>
<%= image_tag @author.avatar.url(:thumb) %>
Tagged as: , 5 Comments
21Aug/111

Fixing the error 0xe800400c or (-48) when syncing to Itunes

Imagine how disappointed I was when I had plugged in my brand new iPad 2 and only to realize that it simply cannot sync with my iTunes.

If you're getting an error messages or weird stuff like:

  • Device Timed Out error message
  • Internal device error
  • An unknown error has occurred 0xe800400c or -48
  • Failing on particularly the song synchronization part - and claims that the songs cannot be found.
  • An unusual long time to sync  - compared to other apple products - and then just to fail right at the end.
  • Occasionally after an error message, my 16GB iPad would show that it was only 4GB large. If you reconnect it, it goes back to normal.

I might have figured out how to fix this problem - at least for me. Your solution may be different of course. Here's what I did on my Windows PC.

  1. Install/upgrade iTunes to the latest version
  2. Restore factory settings on the iPad
  3. Disable firewall (so iTunes can talk to apple) and also disable your anti-virus software. Yes, Microsoft Security Essentials counts. You want to disable anything that can get between iTunes and the iPad.
  4. Check to make sure that your BIOS is updated. My gigabyte P55 board was 7 versions out of date. This is at your own risk of course.
  5. Reconnected the iPad to a different USB spot that is not the front ports, or a USB hub, or USB on a monitor. Use the back ones - the ones directly attached to the motherboard.

My guess  is that the USB isn't providing enough power to charge  or perform syncs with the iPad. My motherboard had a bios update that actually resolves the underpowered USB issue. After praying for a successful patch and a reboot later my ipad was finally syncing.

I really, really hopes this helps and saves some people some time out there.

Filed under: Troubleshooting 1 Comment
29May/113

Installing Ruby on Rails 3 in Windows

Ruby-In-Windows

So last week I got a little tired of having to reboot my computer to dual-boot in a linux environment so that I could work on Rails stuff. Then I decided to try using Rails in Windows. Here's a step by step guide on how to install rails in Windows.

Install Ruby 1.9

To install ruby on our windows machine we will be using RubyInstaller. RubyInstaller is the easiest way to install ruby in windows. It includes the Ruby execution environment and documentation.

First download and install The RubyInstaller.  Installing it to C:\Ruby192 is perfectly fine. I would not recommend installing Ruby to a place that has spaces in it, like the Program Files folder.

From here you can also download the DevKit as well. It allows you to have RubyGems build C-based gems. If you decide to get the DevKit, just install it to the C:\Ruby192\devkit folder for now.

So as you're installing the RubyInstaller, Be sure to select, "Add Ruby Executables to your Path"

Now let's verify that Ruby has been correctly installed. Get to your command prompt (Via Start -> Run -> type in cmd). Then type in:

ruby -v

Then it should reply with something similar to:

ruby 1.9.2p180 (2011-02-18) [i386-mingw32]

Now with your command prompt still open, let's check to see that RubyGems was installed as well:

gem -v

Hey that wasn't so difficult was it? I told you that RubyInstaller was easy :)

Install SqlLite3

So when running rails we would like to have a database to start off with without having to set up a local database connection. And of course, Windows does not support SqlLite right out of the box. Thus we will have to get it ourselves.

Go to the SQLite download page and find the precompiled binaries for windows section and download the sqlite-dll-win32-x86-3070603.zip

After unzipping that file, you should end up with the files sqlite3.dll and sqlite3.def. Copy both of those files into the C:\Ruby192\bin directory.

Also, while you're still at the SqlLite download page you should pick up the shell file (sqlite-shell-win32-x86-3070603.zip) as well. The command line shell is useful for looking around in your sqlite3 databases. Copy the executable in the zip also to the C:\Ruby192\bin directory. You can verify that this is installed by typing:

sqllite3 -version

Now we should install the ruby bindings to SQLite3

gem install sqlite3

 

Install Rails 3

Rails is distributed by RubyGems. When you install Ruby, the RubyGems system is also installed. This makes it really easy to install Rails.

Install Rails by typing:

gem install rails

This should take a few minutes because it is installing several of the Rails dependencies (ActiveRecord, ActionPack, ActiveSupport, etc).

When that is done installing, verify that the correct version of Rails was installed by typing

rails -v

And it should respond with 3.0.7 or higher

 

Creating a Rails application

Go into your development directory and type in:

rails new project_name

Replace the project_name with the name of your new application. You should see it create a bunch of new directories and files

Now we need to install the gems we are going to use with this project. You can install the gems using:

bundle install

Once those gems are installed, we need to create the sqlite3 database in your project directory by typing in:

rake db:migrate

Once that is done, start your rails server by using the commands

rails server

And then navigate to http://localhost:3000/ to view your application. It should look something similar to this:

 

Now get out there and start working on your web projects!

Filed under: Uncategorized 3 Comments
8Dec/100

How to read remote files using PHP

When I was implementing pingback functionality in my custom blogging software, I needed to read files from a remote server.

As long as allow_url_fopen is enabled in your php.ini configuration you can use HTTP and FTP urls with a majority of the functions that use a filename as a parameter.

I found that there are 3 ways to read remote files using PHP.

Fopen

if ($filepointer = fopen("http://banditrevolvers.com", "r")) {
     $site_content = "";
 
     //While we still have content to read, append it
     //1k at a time
     while ($line = fread($filepointer, 1024) {
          $site_content .= $line;
     }
 
} else {
     //Error occured while trying to read the url
}
 
fclose($filepointer);

Another example using fgets instead of fread

if ($filehandle = fopen("http://banditrevolvers.com", 'r') {
 
     while(!feof($filehandle)) {
          $readline = fgets($filehandle, 1024);
          if (eregi("&lt;title&gt;(.*)&lt;/title&gt;", $readline, $output) {
               $title = $output[1];
               break;
          }
     }
} else {
     //Error occured while trying to read the url
}
 
echo "Title of the page is: " . $title;
 
fclose($filehandle);

Wait what's the difference between fgets and fread?

Glad you noticed that. The truth is that fread is the more preferable function to use when reading (or in this case streaming) data from a remote file. The reason is because the fgets function reads a line at a time. For example, if you had a 2000 line file that was only 35k in size, it would loop 2000 times with fgets. However it would only loop 35 times with fread (assuming a 1k buffer).

Then again, if you need to read a file one line at a time fgets is the function you'll need.

File_get_contents

This function will return the contents of a file in a string. To use it just specify a URL as a parameter. Be sure to check the return value to see if it was successful or not.

$content = file_get_contents("http://banditrevolvers.com");
 
if ($content !== false) {
     //Do something with the content
} else {
     //An error occurred
}

CURL

Not all web hosts have the CURL library in their installation. Thus we have to check to see if the function exists before we attempt to use it.

if (function_exists('curl_init')) {
     //Initialize a new resource for curl
     $ch = curl_init();
 
     //Set the url the retrieve
     curl_setopt($ch, CURLOPT_URL, 'http://banditrevolvers.com');
 
     //Return the value instead of outputting to the browser
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 
     $contents = curl_exec($ch);
     curl_close($ch);
 
     if ($contents) {
          //Do stuff with the contents
     } else {
          //Show error message
     }
 
}
Filed under: Code Gems No Comments
1Dec/101

Changing the pointer into the hand cursor in AS3

One of the problems that I ran into while migrating from Actionscript 2 (AS2) to ActionScript 3 (AS3) was the fact that not only was setting a mouse event of a MovieClip different, so does how the mouse cursor acts.

In AS2, setting the onPress event for a MovieClip would automatically cause the cursor to switch the hand whenever you hovered over the element. However in AS3 I discovered that in order to get the same functionality it has to be done manually to get the same effect:

//These are properties of the MovieClip class
targetMc.buttonMode = true;
targetMc.useHandCursor = true;

Upon discovering this bit of code, I noticed that I had already created more than a dozen of clickable instances that could use this code and not all of them had classes for them. I had searched for some kind of global variable that I could set to see if I could get this working with all of them the easy way. Alas, I came up with nothing. So instead I decided to create a base class to implement this functionality for me.

import flash.display.MovieClip
 
package com.jelaniharris {
     class ButtonMovieClip extends MovieClip {
          //Override the default constructor and make this movieclip indicate it's a button to the user
          public function ButtonMovieClip (): void {
               this.buttonMode = true;
               this.useHandCursor = true;
          }
     }
}

Then all I needed to do was to go to my library and set the Base Class of all of my button-like elements to the ButtonMovieClip class.

I hoped this helped someone out there.

Tagged as: , 1 Comment
16Jul/1011

Using Jquery to disable the enter key

There are times that you do not want a form to automatically submit when a user hits the enter key. Or if you want to do some validation via javascript before you allow the submit to go through.

//Bind this keypress function to all of the input tags
$("input").keypress(function (evt) {
//Deterime where our character code is coming from within the event
var charCode = evt.charCode || evt.keyCode;
if (charCode  == 13) { //Enter key's keycode
return false;
}
});

By returning false in the keypress function it tells the browser not to allow the enter key event.

4May/101

Removing empty elements from an array

When dealing with tag inputs from users, I find myself having to make sure they they don't enter in any blank or empty tags. Then I realized that I needed to find out how to remove undesirable elements not only from the Php side, but also from the Javascript side as well. Thus, here are some functions that may help some other people out if they're searching for similar functionality.

In PHP

    foreach ($my_array as $key =&gt; $value) {
      //We check to make sure that the value is either null or just an empty string
      if (is_null($value) || $value=="") {
        unset($my_array[$key]);
      }
    }

An easier way to clean arrays is to use php's array_filter function without a callback parameter. By default that function is set to remove elements that contain a false (or a 0), null or a "". I mean seriously, look at how much cleaner it is:

   //This prunes out 'false', '0', 'null' or ''
   $my_array = array_filter($my_array);

In JavaScript

We can mimic the functionality of Php's array_filter in Javascript by using the Array.filter function.

   var my_array = [1,2,3,'4','', 0, null, 'false'];
   function emptyElement(element) {
	//Removes nulls, zeros (also falses), text version of false, and blank element
	if (element == null || element == 0 || element.toString().toLowerCase() == 'false' || element == '')
		return false;
		else return true;
	}
 
	var my_array = [0,'false',1,null, 2,'',3,'4',false];
	my_array = my_array.filter(emptyElement);
   }

Then my_array will include 1,2,3,4.

I hope this was somewhat useful.

Tagged as: , 1 Comment
16Sep/090

Increasing performance of Adobe CS3 Flash in Vista

When I first started to use Flash CS3 in Vista I noticed that all of my flash movies were performing very very slowly.

Honestly .. I'm not sure why. But, here's how you can make it perform better.

Here's how to speed up flash CS3 for vista

Here's how to speed up flash CS3 for vista

  1. Navigate to your Program Files -> Adobe folder(s) -> Adobe Flash CS3 and find the Flash.exe.
  2. Right click on that file and goto the Compatibility tab.
  3. Check "run this program in compatibility mode", and voila, suddenly it's running as fast as it did on XP. Happy coding!
Tagged as: , , , No Comments