Just another idiot with a blog

Kohana 3 Name Spacing with Underscores in Controller Classes

So, I’ve been working with Kohana 2.3.4 lately and its absolutely beautiful. A much improved version of what Codeigniter should have been. Now they released Kohana 3 which is similar, yet very different. One of the “gotchas” I noticed in KO3 (Kohana 3) is the auto loading of controller classes and the name spacing with underscores. Here is an example of what I’m talking about.

All underscores are converted to slashes

In Kohana 2 you could name a class with underscores and there would be no problem

now the underscores are converted to slashes

notice the Controller_ is in the front now which translates to controller/

Within the classes folder in application you notice there is classes/controllers to keep for instance a file extending off template.

So a template in controllers would need to be named defaulttemplate.php which would become Controller_DefaultTemplate, BUT if you wanted it to be Controller_Default_Template it would have to be in a sub folder called Default in controllers then template.php

Its a bit confusing in the beginning but you’ll get used to it. The entire system is a helluva improvement. Look forward to a few articles i’ll be writing on using the ORM.

Cheers,
-Wes

Calculate Kaprekar’s Constant in PHP with Math

This is just a bullshit post, not practical at all, but math is good shit and I decided to make this for fun in 30 minutes… If you are unfamiliar with Kaprekar’s Constant.. well the breakdown is as follows..

Take any four digit number (whose digits are not all identical), and follow the steps:

  1. Arrange the string of digits to form the largest and smallest 4 digit numbers possible that are not identical.
  2. Arrange them ascending and descending.. so if your number is 3758, you get 8753 and 3578
  3. Take these two numbers and subtract the smaller number from the larger. (8753-3578)
  4. Repeat the process until you get 6174..from 6174 it will stay 6174..fucking neat.

Tip:If there is a 0, 5032 for example its not 532-235, its 5320 – 0235.

DEMO:

HTML

<h1>Kaprekar's Constant</h1>
<h2>Directions:</h2>
<p>Enter a 4-digit number that are not all the same digits and watch Kaprekar's Constant turn into 6174.</p>
<form method="POST" >
<input type="text" size="30" name="number" />
<input type="submit" value="Calculate" />
</form>

PHP


//Check if the number is there and Trim whitespace
if (isset($_POST['number'])) {
	$number = trim($_POST['number']);

	//Run the function
	kaprekars($number);
}

function kaprekars($number) {

	//Not set? Let them know.
	if ((empty($number)) &&  (isset($number)))  {
		$errors[] = 'Make sure you enter something.';
	}

	//Not numeric? Let them know.
	if (!is_numeric($number)) {
		$errors[] = 'Make sure its a number.';
	}
	//Not 4 digits? Let them know.
	if ((strlen($number) < 4) || (strlen($number) > 4)) {
		$errors[] = 'Make sure its 4 digits.';

	}
	//If its 4 digits it cant be 1111 or 8888, let them know.

	//Define the arrays, because if you loop and its empty.. the variable doesnt get set, just an error
	$forwards 	= array();
	$backwards 	= array();

	//loopz
	for ($i=0; $i<strlen($number); $i++) {

		//Make an array of the numbers
		$forwards[$i] = substr($number,$i, 1);
	}
	//Reverse it
	$backwards = array_reverse($forwards);

	//Comepare...are they the same? YES, fucking error bitch.
	if ($forwards == $backwards) {
		$errors[] = 'The value must not be four of the same digit.';
	}

	//Errors array set?
	if (isset($errors)) {

		//YES, so loop through and output them.
		echo '<ul id="errors">';

		foreach ($errors as $k => $v) {
			echo '<li class="errors_text">' . $v . '</li>';
		}

		echo '</li>';

		die();

	} else {

		//make sure the number is not 6174
		while ($number != "6174") {

			//IF its 3 digits like 333 append a 0 in front of it
			if (strlen($number) == 3) {
				$number = '0' . $number;
			}

			//loop through the length of the sum which is always 4
			for ($i=0; $i<strlen($number); $i++) {

				//Create an array called combined based on $i which is 0 to 3 aka 4 by 1
				// e.g. $combined = array(6,1,7,4);
				$combined[$i] = substr($number,$i, 1);
			}

			//sort the array ascending 1467
			sort($combined);
			$asc = implode("",$combined);

			//now descending 7641<br>

			rsort($combined);
			$desc = implode("",$combined);

			//subtract it to get the next number until you hit Kaprekars constant 6174
			$number = $desc - $asc;

			//Output it.
			echo $desc . ' - ' . $asc . ' = ' . $number . '<br />';
		}
	}
}

Wufoo Style jQuery form Tutorial with focus / active state

So you like how Wufoo looks do you? Well you can make your form look just like their’s. I have a DEMO you can check out to test the functionality of what the hell I’m talking about in this tutorial. But I would much rather show you in code than ramble about something that doesn’t need much explaining. SO, here is the breakdown of this tutorial on how to focus a form field state with jQuery . GO!

jQuery

This is the jQuery, which is a javascript framework that makes coding this crap SO much easier. and it must be included on the page for this to work. You can view the source of the DEMO and get an idea about exactly what is going on. Its commented for your understanding.

	//Wesified.
		$(document).ready(function() {
	//On input focus (tabbed or clicked)..it will..
			$("input,textarea,select").focus(function () {
	//grab the parent nested LI of that input and add the bg color
		        	$(this).parents('li').css('background-color','#FFFFDD');
				}).blur(function() {
	//Then get rid of it
			$(this).parents('li').css('background-color','#FFFFFF');
	});
});

HTML

So this is the structure of the form. nuff’ said

<form id="contact_form" class="contact_form">
  <div>
    <ul>
      <li> <span class="left_half">
        <label for="first_name">First Name <span class="required"> *</span></label>
        <input class="required" type='text' name='first_name' value=''>
        </span> <span class="right_half">
        <label for="last_name">Last Name <span class="required"> *</span></label>
        <input class="required" type='text' name='last_name' value=''>
        </span> </li>
      <li> <span class="left_half">
        <label for="other_stuff">Other Stuff<span class="required"> *</span></label>
        <input class="required" type='text' name='other_stuff' value=''>
        </span> <span class="right_half">
        <label for="expand_more">Expand More <span class="required"> *</span></label>
        <input class="required" type='text' name='expand_mores' value=''>
        </span> </li>
      <li> <span class="full">
        <label for="company">Company <span class="required"> *</span></label>
        <input class="required" type='text' name='company' value=''>
        </span> </li>
      <li class="button">
        <button type="submit">Submit Form</button>
      </li>
    </ul>
  </div>
</form>

CSS

This is what makes it look badass.

form ul {
	list-style-type:none;
	width: 450px;
}
form li {
	clear:both;
	display:block;
	margin:0;
	padding:6px 9px 9px 9px;
	font-size: small;
	width:500px;
	overflow: hidden;
}
form li input, textarea {
	border-color:#7C7C7C #C3C3C3 #DDDDDD;
	border-style:solid;
	border-width:1px;
	color:#333333;
	margin:0;
	padding:2px 0;
	font-family:Tahoma, Arial, sans-serif;
	width:100%;
}
form li label {
	border:medium none;
	color:#222222;
	display:block;
	font-size:95%;
	font-weight:bold;
	line-height:150%;
	margin:0;
	padding:0 0 3px;
	font-family:Tahoma, Arial, sans-serif;
}
form li span label.sub {
	padding-bottom:0px;
	font-weight:normal;
}
form li label, form li span label {
	clear:both;
	color:#444444;
	display:block;
	font-size:85%;
	margin:0;
	padding-top:6px;
}
.left_half {
	float:left;
	width:250px;
}
.right_half {
	float:right;
	width:230px;
}
.full {
	width:460px;
}
li.left_half {
	clear:left !important;
	float:left;
}
form li:hover {
	background-color:#FFFFDD;
}
form li.section {
	border-top:1px dotted #CCCCCC;
}
form li.button:hover {
	background-color:#FFFFFF;
}
label.error, span.required {
	color:#DF0000;
}
h2.form_title {
	border-bottom:1px dotted #CCCCCC;
	width:460px;
	margin-bottom:10px;
}

All in all, this is a pretty easy concept and I hope it helps a few of you out there. If you have any questions just leave a comment and I’ll do my best to help you out.

Cheers,

Wes

Google Analytics Asynchronous Tracking, Finally!

Unlike the regular tracking code google analytics has, this snippet directly from google, this optimizes the way the page loads…SO if some of you have noticed on sites they get hung up and won’t load because its waiting on analytics loading in the header..Well fuck that.

here is the snipper


<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXX-X']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
  })();

</script>

It inserts the ga.js into the page, it specified the page’s web property ID and then calls _trackPageview to send the data back. Just Replace the UA-XXXXX-X with your web property ID. Visit this page from google for more details!

Remove Non Ascii Characters using PHP and Regular Expressions

So there I was taking forever to fix content from a Word Perfect document converted to Word then pasted as HTML. I was spending a while removing all the bullshit non Ascii Characters and I thought to myself and said…Wes, you idiot, you are a programmer, do this the right way and filter it out. So I did and here is a simple way of doing it through regular expressions and php.


<?php
//Your nasty string of word and non ascii chars
$Contentz = "These are shitty chars „ and we dont like them nor want them.";

//Array of content I want to make a space
$badContent = array("&nbsp;");

//Replace the bad arrays with a space
$Contentz = trim(str_replace($badContent," ",$Contentz));

//Specific string replaces for ellipsis, etc that you dont want removed but replaced
$theBad = 	array("“","”","‘","’","…","—","–");
$theGood = array("\"","\"","'","'","...","-","-");
$Contentz = str_replace($theBad,$theGood,$Contentz);

//Whatever might be left over...
//Remove all non ascii chars (aka: bad Microsoft Word and Word Perfect Shit shit)
$Contentz = preg_replace('/[^(\x20-\x7F)\x0A]*/','', $Contentz);

echo $Contentz;
?>

$Contentz will show up removing the characters.

Cheers,
Wes S .Ray

Configuring PHP Web server on Fedora 11

This is going to be a quick and simple tutorial on how to setup a Fedora 11 Linux Server with PHP, MySQL, Apache and phpmyadmin. Now I’m assuming you already have the OS installed on your machine. Most of you will be using cloud servers, mine is from Linode.com. You will need to have shell access to your server. If you have very little experience with linux I suggest you brush up and learn a little syntax so you aren’t shooting in the dark.

Ok, so lets get started with the actual configuration of the server. At this point I AM ASSUMING you have the operating system installed and its just a bare canvas.

Here we go, hold on kids.

The first step that is needed to taken is open up your terminal, I personally use PuTTY, a free telnet/ssh client. One you are logged in make sure you have full access to the system, whether it be root or sudo.

Now lets install PHP and MySQL. These will be commands you type in the terminal.  We will be installing the apache, mysql and php and configuring them.

  • yum -y install httpd php mysql mysql-server php-mysql

We set chkconfig so that when rebooted the servers will start automatically, and we do this like so.

  • chkconfig httpd on
  • chkconfig mysqld on

Now that Apache and MySQL are starting with the server, we can configure MySQL

  • mysqladmin -u root ‘root_pw_of_your_choice’

Now lets install phpMyAdmin, a mysql database management tool.

  • yum install phpMyAdmin.noarch

Since that has been taken care of let, lets open up the phpmyadmin config.

  • nano /etc/httpd/conf.d/phpMyAdmin.conf

At this point what we need to do is comment out a certain section. Notice that I have a # which denotes comment out

#<Directory /usr/share/phpMyAdmin/>
#   order deny,allow
#   deny from all
#   allow from 127.0.0.1
#</Directory>

Next we are going to jump into the httpd.conf, otherwise known as the Apache Config File

  • nano /etc/httpd/conf/httpd.conf

Once in there you are going to want to change a section

<Directory />
Options FollowSymLinks
AllowOverride All
</Directory>

You will want to set it to AllowOverride All, by default it should be set to none, but we dont want that.

Now at the end of the file add these to make your IP address directly or URL go directly to phpMyAdmin unless you set a virtualhost otherwise.  You need to put all of this at the bottom of your httpd.conf file

<VirtualHost your.ip:80>
ServerAdmin youremail@server.com
DocumentRoot /usr/share/phpMyAdmin/

ServerName yourIP
ServerAlias yourIP

ErrorLog logs/home-error_log
CustomLog logs/home-access_log common
</VirtualHost>

Include /etc/httpd/conf/sites-production/*
Include /etc/httpd/conf/sites-development/*

Save and close the conf file and finally create your folders than you included, e.g

  • mkdir /etc/httpd/conf/sites-production
  • mkdir /etc/httpd/conf/sites-development

Now that the config file directories are made, lets make the place holders for the actual website content

  • /var/www/sites-production
  • /var/www/sites-development

That about sums it up for the base server setup on fedora 11 for a linode VPS.  If you want more PHP Packages just run this command and you should have everything you need.

yum install php php-devel php-gd php-imap php-ldap php-mysql php-odbc php-pear php-xml php-xmlrpc php-eaccelerator php-magickwand php-magpierss php-mapserver php-mbstring php-mcrypt php-mhash php-mssql php-shout php-snmp php-soap php-tidy curl curl-devel perl-libwww-perl ImageMagick libxml2 libxml2-devel

If you need any MySQL help for setting up users, I reccomend this site

http://www.databasef1.com/tutorial/mysql-create-user.html

If any help is needed feel free to leave comments and I will respond.  Good luck!

Feeling Generous??

Sign up for a linode VPS, I pay $20 a month and it fucking rocks

My Linode.com Referral Code 2bf9ae77ecd8e759a2b79bf1011e1c3147d93525

-Wes

jQuery Accordion for Wordpress

So I was working on a site with a vertical navigation today and the previous developer working on it made the entire navigation static….Well thats pretty much worthless for a CMS like Wordpress. So I took it upon myself to create an accordion script for Wordpress (it can be used wtihout Wordpress just as easily). I commented the code nicely and you can essentially paste this directly into wordpress and it will work.

The File Structure is as follows

<ul>
   <li><a href="http://link"></a>
        <ul>
            <li><a href="http://subnavlink">LINK</a></li>
        </ul>
   </li>
</ul>

The CSS You will need

#navigation ul li ul { display:none; }
#navigation .displayMe { display:block; }

Now for the Javascript. This one is for all your Wordpress Developers who need a custom jQuery Accordion

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">

$(document).ready(function() {	

//If its a page parent (based off wordpress), add the class "displayMe"
//This way the accordion will be opened up on the page you are on.
if ($('#navigation ul li').hasClass("current_page_parent")) {
	$('#navigation .current_page_parent ul').addClass("displayMe"); }

//Hide the submenus
$('#navigation ul li ul').hide();

//Add a class to the parent li IF it has sub UL's
$("#navigation ul li:has(ul)").addClass("theDon");

//Da henchman
$("#navigation ul li ul li:has(a)").addClass("henchmen");

//Remove the link if it has a submenu
$('#navigation .theDon > a').attr('href', '#');

//When you click it, toggle bitch.
$('#navigation ul li a').click(
function() {

//Onclick Remove the class dipslay me which is only display:block;
//This way they can close it if they click it or it will glitch
$(this).next().slideToggle('slow').removeClass("displayMe");

//return false so the # doenst move view to the top of the page
if ($(this).attr('href') == '#') { return false; }

//Close it all out
	});
 });

</script>

<div id="navigation">
<ul>
<?php wp_list_pages('title_li='); ?>
</ul>
</div>

Hope this jQuery Accordion with an emphasis for Wordpress helps!

Cheers,
-Wes

Dell Inspiron 1501 Sound Issue Fix

So if you have a Dell Inspiron 1501 its safe to say you fucking hate Dell and this computer.  SO here’s the underlying issue with this machine….  The sound card is not shielded correctly from the high frequency of the wireless-N (5GHz).  As an example, have you ever been in a car or near computer speakers when someones cell phone goes off.  It makes a weird noise, something similar to a damn 9600 baud modem trying to make its way to the internet.  SO, lets give you guys a taste of how to fix this computer ruining issue that Dell has never fucking acknowledged (hate those bastards).

(I’m not going to spoon feed you, if you can’t get to places like “my computer” you should just leave my site and never return.  :D )

  • First, right click on my computer go to system properties.
  • Next, click the hardware tab and go to device manager.
  • Find network adapters and click on the “Dell Wireless 1501 Draft…etc” and go to properties.
  • Now that the card properties are up click on the advanced tab.
  • Go to the “Disable Bands” property and disable the 802.11a band.
  • DONE.

From here on out, your issues with a “crackling” or “popping” noise with your Dell Inspiron 1501 will cease.  Sometimes it will tend to revert itself because..well, Windows sucks.   Hope this saves you people from wanting to rip your eyes out.  Probably one of the most annoying issues I’ve ever dealt with.

-Wes

Finally Up!

I finally have my server up thanks to linode.com.  Their VPS are great and provide me with just what I need.  My first tutorial I plan to setup  will definitely be  configuring basic Fedora 11 web server dedicated to the LAMP Stack.   I took extensive notes upon the installation and will be a great reference for this tutorial.  Soon enough small PHP and jQuery scripts with a pinch of MySQL to flare it up.  This is going to be my playground and should be a pretty interesting ride.

-Wes

Copyright ©2010 wessray.com
Protected by Copyscape Unique Content Validation