<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Programming Tips That Help You Become a Better Programmer</title>
	
	<link>http://www.codercaste.com</link>
	<description>Programming Tips That Help You Become a Better Programmer</description>
	<lastBuildDate>Wed, 08 Sep 2010 02:37:52 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/Codercastecom" /><feedburner:info uri="codercastecom" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId>Codercastecom</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><item>
		<title>Ruby On Rails Programming : Introduction and the Model View Controller Model Explained</title>
		<link>http://feedproxy.google.com/~r/Codercastecom/~3/20BSwi7R3vc/</link>
		<comments>http://www.codercaste.com/2010/09/07/ruby-on-rails-programming-introduction-and-the-model-view-controller-model-explained/#comments</comments>
		<pubDate>Wed, 08 Sep 2010 02:37:52 +0000</pubDate>
		<dc:creator>Spyros Panagiotopoulos</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[introduction to ruby programming]]></category>
		<category><![CDATA[learn ruby]]></category>
		<category><![CDATA[model view controller]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[ruby on rales]]></category>
		<category><![CDATA[ruby programming]]></category>

		<guid isPermaLink="false">http://www.codercaste.com/?p=789</guid>
		<description><![CDATA[Lately, i&#8217;ve been quite interested in learn more things abour Ruby Programming. To be sincere, i always wanted to learn a bit more about the language, but I&#8217;ve been into some WordPress Theme programming the past 2-3 months. Hopefully, i will write some posts about this subject as well, in the future. What is Ruby [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.codercaste.com/wp-content/uploads/2010/09/ruby.jpg"><img class="alignleft size-thumbnail wp-image-792" title="ruby" src="http://www.codercaste.com/wp-content/uploads/2010/09/ruby-150x150.jpg" alt="ruby 150x150 Ruby On Rails Programming : Introduction and the Model View Controller Model Explained" width="150" height="150" /></a>Lately, i&#8217;ve been quite interested in learn more things abour Ruby Programming. To be sincere, i always wanted to learn a bit more about the language, but I&#8217;ve been into some WordPress Theme programming the past 2-3 months. Hopefully, i will write some posts about this subject as well, in the future.</p>
<p><span id="more-789"></span></p>
<p><strong>What is Ruby on Rails ?</strong></p>
<p>Ruby, as you may know, is a very well known scripting language, with an exceptional and clean syntax. I&#8217;ve always been a fan of Python and i must say that moving to Ruby is a totally different programming style. Luckily, learning Ruby is quite easy. It indeed offers some very good techniques, like code blocks etc, but overall, it resembles interpreted language, like Python and Perl also are.</p>
<p>On the other side, Ruby on Rails is something completely different and harder to learn. RoR (widely used for Ruby on Rails), is actually a framework for creating web applications. As simple as that. You may already know the Django alternative for Python. Sounds &#8230; ok, but is it just that ?</p>
<p><strong>Why Ruby on Rails is Really Really Good</strong></p>
<p>RoR is really great because it makes the life of the programmer a WHOLE lot easier. Imagine that you wanted to write a php function that checks whether  passwords match in a simple registration routine. Using php, you would need to get the input, compare it and write an html page that presents the error to the user. Lots of work for doing a simple thing. But with ruby :</p>
<pre class="brush: plain;">validates_confirmation_of :password</pre>
</pre>
<p>is just enough !</p>
<p><strong>Installation of RoR</strong></p>
<p>Installing RoR is a pretty easy procedure for the well known operating systems. There is an installer for Windows, you can use a package manager for Linux and macports for mac OS (as i currently use). For more information on the whole process, please take a look at the <a href="http://rubyonrails.org/">official ruby programming website</a>.</p>
<p><strong>The MVC (Model - View - Controller) Model.</strong></p>
<p>MVC is the programming model that RoR utilizes. If you have used a <a href="http://www.codercaste.com/2009/09/29/using-smarty-as-a-template-engine-for-your-php-websites/">templating system like smarty</a> in the past, you have most probably already used the model. This model simply identifies that our web program has 3 different entities that we need to look after. The model, the view and the controller. But, what is the difference ? Now, i could describe that in words, but i prefer providing an example as well :</p>
<p>The View is the easy entity. It is what our program prints out to the browser of a user.</p>
<p>The Controller closely relates to data. It is the part where data is initialized, to be then provided to the View and shown to the user.</p>
<p>The Model is the auxiliary entity where we write our large functions that operate on data.</p>
<p>Now, think of this situation. You have a page that presents some products for people to buy. The Controller is the first thing that gets utilized. Once the browser requests the page, the controller takes action. Therefore, when the products page is requested, the Controller understands that this page was called and provides the gateway between your large functions and your view. Now, the Model contains functions such as getAllProducts(). This function is called by the controller, to provide an instance of all the products. This variable, most times a class variable like @products, is going to be used in the view.</p>
<p>Hope this starts to make sense, i've tried to describe it to the best of my knowledge. I do not want to take this post any further. In my next one about RoR, i will describe how to create a test project, use migrations and more. Have fun with Ruby, play a little bit with it, it is really worth it, you have my word !</p>
<img src="http://www.codercaste.com/wp-content/plugins/pixelstats/trackingpixel.php?post_id=789&amp;ts=1283913487" style="display:none;" alt="pixelstats trackingpixel" title="Ruby On Rails Programming : Introduction and the Model View Controller Model Explained" /><img src="http://feeds.feedburner.com/~r/Codercastecom/~4/20BSwi7R3vc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.codercaste.com/2010/09/07/ruby-on-rails-programming-introduction-and-the-model-view-controller-model-explained/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.codercaste.com/2010/09/07/ruby-on-rails-programming-introduction-and-the-model-view-controller-model-explained/</feedburner:origLink></item>
		<item>
		<title>Let’s Do Some Python Programming Together !</title>
		<link>http://feedproxy.google.com/~r/Codercastecom/~3/6OoA8iV5Wno/</link>
		<comments>http://www.codercaste.com/2010/03/30/lets-do-some-python-programming-together/#comments</comments>
		<pubDate>Wed, 31 Mar 2010 02:50:40 +0000</pubDate>
		<dc:creator>Spyros Panagiotopoulos</dc:creator>
				<category><![CDATA[Python Programming]]></category>
		<category><![CDATA[python challenge]]></category>
		<category><![CDATA[python team]]></category>

		<guid isPermaLink="false">http://www.codercaste.com/?p=781</guid>
		<description><![CDATA[As a result of this very interesting post by Kr0w, i was thinking of creating something which i feel that it would be very interesting for everybody to work on their Python Programming skills and associate with other people who also like Python. Have you by any chance taken a look at the python online [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.codercaste.com/wp-content/uploads/2010/03/snake.jpg"><img class="alignleft size-thumbnail wp-image-782" title="snake" src="http://www.codercaste.com/wp-content/uploads/2010/03/snake-150x150.jpg" alt="snake 150x150 Lets Do Some Python Programming Together !" width="150" height="150" /></a>As a result of this <a href="http://www.codercaste.com/forum/general-off-topic-discussion/23-technology-acronym-quiz.html#post51">very interesting post</a> by Kr0w, i was thinking of creating something which i feel that it would be very interesting for everybody to work on their Python Programming skills and associate with other people who also like Python.</p>
<p><span id="more-781"></span></p>
<p>Have you by any chance taken a look at the <a href="http://www.pythonchallenge.com/">python online challenge</a> ? This is a great series of 33 Python Programming levels that require great Python knowledge in order to be solved. In the past i&#8217;ve solved a bunch of them, but never really went as far as completing the whole nine yards.</p>
<p>Therefore, i was thinking that it would be a quite good idea to create a section at the <a href="http://www.codercaste.com/forum/">codercaste.com forum</a>, where we would not only talk about those challenges, but more importantly solve them together. This way, we would learn more about Python and not alone. I&#8217;ve noticed that some of the levels can also be done easier using some unix tools or so. We will discuss that as well.</p>
<p>What do you think about that ? Would you participate ? I think that i will create this section pretty soon, so if you want to do so, please take a moment to join the <a href="../forum/">codercaste.com forum.</a></p>
<p>And let&#8217;s have fun ! <img src='http://www.codercaste.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' title="Lets Do Some Python Programming Together !" /> </p>
<img src="http://www.codercaste.com/wp-content/plugins/pixelstats/trackingpixel.php?post_id=781&amp;ts=1283913487" style="display:none;" alt="pixelstats trackingpixel" title="Lets Do Some Python Programming Together !" /><img src="http://feeds.feedburner.com/~r/Codercastecom/~4/6OoA8iV5Wno" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.codercaste.com/2010/03/30/lets-do-some-python-programming-together/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.codercaste.com/2010/03/30/lets-do-some-python-programming-together/</feedburner:origLink></item>
		<item>
		<title>How to Set Up a Virtual Private Network (VPN) Using OpenVPN</title>
		<link>http://feedproxy.google.com/~r/Codercastecom/~3/39O2w-FELGE/</link>
		<comments>http://www.codercaste.com/2010/03/29/how-to-set-up-a-virtual-private-network-vpn-using-openvpn/#comments</comments>
		<pubDate>Tue, 30 Mar 2010 00:43:48 +0000</pubDate>
		<dc:creator>Spyros Panagiotopoulos</dc:creator>
				<category><![CDATA[General Tips & Tricks]]></category>
		<category><![CDATA[Linux Tips]]></category>
		<category><![CDATA[configure openvpn]]></category>
		<category><![CDATA[create openvpn]]></category>
		<category><![CDATA[openvpn client]]></category>
		<category><![CDATA[openvpn linux]]></category>
		<category><![CDATA[openvpn server]]></category>
		<category><![CDATA[openvpn unix]]></category>
		<category><![CDATA[virtual private network create]]></category>
		<category><![CDATA[vpn set up]]></category>

		<guid isPermaLink="false">http://www.codercaste.com/?p=777</guid>
		<description><![CDATA[Imagine that in your office&#8217;s computer, there are lots of interesting files that you have saved. As long as you are in your office, you have access to all of them, but when you go home, you can&#8217;t access it. The reason is that although your office computer has internet, it&#8217;s behind NAT and therefore [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.codercaste.com/wp-content/uploads/2010/03/idsvlan.jpg"><img class="alignleft size-thumbnail wp-image-778" title="idsvlan" src="http://www.codercaste.com/wp-content/uploads/2010/03/idsvlan-150x150.jpg" alt="idsvlan 150x150 How to Set Up a Virtual Private Network (VPN) Using OpenVPN" width="150" height="150" /></a>Imagine that in your office&#8217;s computer, there are lots of interesting files that you have saved. As long as you are in your office, you have access to all of them, but when you go home, you can&#8217;t access it. The reason is that although your office computer has internet, it&#8217;s behind NAT and therefore you cannot access it directly. This is where a VPN can really be helpful.</p>
<p><span id="more-777"></span></p>
<p>A Virtual Private Network is a way to access a private network (your office lan in this occasion) through a larger network (the internet in this and actually most cases). What you would do in this occasion is install openvpn in both your computers and set your office computer to be the server and your home computer to be the client. Let&#8217;s take a look on the steps that you need to take in order to create the vpn.</p>
<p><strong>Generate The Master CA certificate, the Server Certificate and The Clients Certificates</strong></p>
<p>After you install openVPN on your machines (installation is trivial, there are packages available or you can even compile from sources), go to your server and locate the openVPN configuration files. It should be under /etc/openvpn/. Inside the easy-keys/2.0/ directory, execute these commands to initialize the Public Key Infrastructure :</p>
<pre class="brush: bash;">

./vars
./clean-all
./build-ca
</pre>
<p>After executing build-ca, you will be asked for some information. Changing the Common Name is a good idea if you like to. You can leave the rest as they are. After completion, the Master CA Certificate is now generated.</p>
<p>Let&#8217;s now generate the certificate and private keys for our server, using the command :</p>
<pre class="brush: bash;">

./build-key-server server
</pre>
<p>Sign and commit the certificate, while also provide a meaningfull Common Name, like &#8220;officeServer&#8221;. Our server is set and we just need to configure our client(s).  Again, this is almost the same as the server key and certificate generation :</p>
<pre class="brush: bash;">

build-key homeClient
</pre>
<p>You could create more clients if you like, but in this case we just need one for our home. In the end, you also need to generate the Diffie-Hellman public key scheme parameters using :</p>
<pre class="brush: bash;">

build-dh
</pre>
<p>This will create a *.pem file that we need for our server. In the end of the process, you will have a bunch of different files in easy-keys/2.0/ . The ca.crt file is needed by both the server and the client(s), it is the master certificate. The server has 3 more files. The *.pem file, the server.crt and server.key file (or however you named them). A client has 2 files, the client.crt and client.key file.</p>
<p>The next thing that you would need to do is create a tarball with the client files, client.crt, client.key AND the ca.crt, which is needed by every computer.</p>
<p><strong>Sample Configuration Files For OpenVPN Clients and Server</strong></p>
<p>Now, both your server and client(s) need to have config files in /etc/openvpn/ . This is actually pretty easy to do and you can follow the <a href="http://www.openvpn.net/index.php/open-source/documentation/howto.html#examples">official openvpn sample files</a> to do so. Once you&#8217;re done, just restart both openvpns using &#8220;/etc/init.d/openvpn restart&#8221; and your virtual private network is now working !</p>
<img src="http://www.codercaste.com/wp-content/plugins/pixelstats/trackingpixel.php?post_id=777&amp;ts=1283913487" style="display:none;" alt="pixelstats trackingpixel" title="How to Set Up a Virtual Private Network (VPN) Using OpenVPN" /><img src="http://feeds.feedburner.com/~r/Codercastecom/~4/39O2w-FELGE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.codercaste.com/2010/03/29/how-to-set-up-a-virtual-private-network-vpn-using-openvpn/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.codercaste.com/2010/03/29/how-to-set-up-a-virtual-private-network-vpn-using-openvpn/</feedburner:origLink></item>
		<item>
		<title>How to Create And Use Lambda Anonymous Functions in Python</title>
		<link>http://feedproxy.google.com/~r/Codercastecom/~3/2O3vVqTJ9rw/</link>
		<comments>http://www.codercaste.com/2010/03/29/how-to-create-and-use-lambda-anonymous-functions-in-python/#comments</comments>
		<pubDate>Mon, 29 Mar 2010 06:03:12 +0000</pubDate>
		<dc:creator>Spyros Panagiotopoulos</dc:creator>
				<category><![CDATA[Python Programming]]></category>
		<category><![CDATA[anonymous functions in python]]></category>
		<category><![CDATA[filter python]]></category>
		<category><![CDATA[map python]]></category>
		<category><![CDATA[python lambda function]]></category>

		<guid isPermaLink="false">http://www.codercaste.com/?p=765</guid>
		<description><![CDATA[Lambda functions are an interesting and quite useful Python feature, that you have most certainly witnessed in other programming languages as well, probably as anonymous. A lambda function is really a way to create an &#8220;on the fly&#8221; function that can be used in Python expressions. Let&#8217;s take a look at a short example of [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.codercaste.com/wp-content/uploads/2010/03/Lambda.png"><img class="alignleft size-thumbnail wp-image-769" title="Lambda" src="http://www.codercaste.com/wp-content/uploads/2010/03/Lambda-150x150.png" alt="Lambda 150x150 How to Create And Use Lambda Anonymous Functions in Python" width="150" height="150" /></a>Lambda functions are an interesting and quite useful Python feature, that you have most certainly witnessed in other programming languages as well, probably as anonymous. A lambda function is really a way to create an &#8220;on the fly&#8221; function that can be used in Python expressions. Let&#8217;s take a look at a short example of a simple lambda function :</p>
<p><span id="more-765"></span></p>
<pre class="brush: python;">
func = lambda x: x + 2
print func(4)
</pre>
<p>Upon execution, this prints the number 6 on your screen. Quite simply, we create a lambda function that gets a parameter and returns this integer parameter after adding 2 to it. Notice the syntax here. &#8220;lambda x: x + 2&#8243;. If this was a standard Python function, the code would be like :</p>
<pre class="brush: python;">

def myfunc(x):
  return x + 2
</pre>
<p>Notice the differences ? As you see, a lambda function is a way to create a simple function quickly, without having to define it as usual. You may wonder why a lambda function can be important, but this is easily identified if you think of a function like map or filter in python.</p>
<p><strong>Use a Lambda Function Along With The Filter Function</strong></p>
<p>Filter is a very important Python function that gets a list as input and returns a new filtered list, according to our presets. To use filter, we provide it with a list and a function that filters that list. This is where a lambda function is most times used. Let&#8217;s take a look at this interesting example :</p>
<pre class="brush: python;">
list = [1,2,3,4,5]

newList = filter(lambda x: x - 1, list)
print newList
</pre>
</pre>
<p>After this is executed, it returns [2,3,4,5], but do you understand why ? First of all, we create a lambda function that gets an integer and returns the same integer subtracted by 1. Now, filter works like this. If the function returns true, the item is returned to the newList. Each element of the list is passed through the lambda function for evaluation. The first integer value of the list is 1. When subtracted by 1, it returns the integer 0. However, 0 means False as you know and the element is not passed to the newList. The second element 2 becomes 1, 3 becomes 2 and so forth and all these values, since they are not 0, are evaluated as true and passed to the newList.</p>
<img src="http://www.codercaste.com/wp-content/plugins/pixelstats/trackingpixel.php?post_id=765&amp;ts=1283913487" style="display:none;" alt="pixelstats trackingpixel" title="How to Create And Use Lambda Anonymous Functions in Python" /><img src="http://feeds.feedburner.com/~r/Codercastecom/~4/2O3vVqTJ9rw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.codercaste.com/2010/03/29/how-to-create-and-use-lambda-anonymous-functions-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.codercaste.com/2010/03/29/how-to-create-and-use-lambda-anonymous-functions-in-python/</feedburner:origLink></item>
		<item>
		<title>Top 10 PHP Techniques That Will Save You Time and Effort</title>
		<link>http://feedproxy.google.com/~r/Codercastecom/~3/ULZph9IZFLU/</link>
		<comments>http://www.codercaste.com/2010/03/28/top-10-php-techniques-that-will-save-you-time-and-effort/#comments</comments>
		<pubDate>Sun, 28 Mar 2010 05:03:53 +0000</pubDate>
		<dc:creator>Spyros Panagiotopoulos</dc:creator>
				<category><![CDATA[PHP Programming]]></category>
		<category><![CDATA[how to code php]]></category>
		<category><![CDATA[php advice]]></category>
		<category><![CDATA[php best]]></category>
		<category><![CDATA[php techniques]]></category>
		<category><![CDATA[php tips]]></category>
		<category><![CDATA[php tricks]]></category>
		<category><![CDATA[top 10 php]]></category>

		<guid isPermaLink="false">http://www.codercaste.com/?p=756</guid>
		<description><![CDATA[What would happen if you tried to use a mirror as a surfboard ? Well, you may succeed in taming the waves for a little while, or even a big while, but deep inside, you know that this is not really the right way to do it. Weird as it may sound, the same principals [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.codercaste.com/wp-content/uploads/2010/03/makes_eat_time.jpg"><img class="alignleft size-thumbnail wp-image-759" title="makes_eat_time" src="http://www.codercaste.com/wp-content/uploads/2010/03/makes_eat_time-150x150.jpg" alt="makes eat time 150x150 Top 10 PHP Techniques That Will Save You Time and Effort" width="150" height="150" /></a>What would happen if you tried to use a mirror as a surfboard ? Well, you may succeed in taming the waves for a little while, or even a big while, but deep inside, you know that this is not really the right way to do it. Weird as it may sound, the same principals apply to php programming. I&#8217;ve heard of people trying to learn PHP by studying it for like a weekend or more, but allow me to say, this is a pretty bad approach to learning this programming language.</p>
<p><span id="more-756"></span></p>
<p><strong>Why is The Learning PHP Process Different Than Any Other Programming Language ?</strong></p>
<p>By nature, PHP is all about knowing what to do. If you have the knowledge on how to do something in PHP, actually doing it is most of the times really really easy. I would actually pay to know some of these things beforehand. In PHP, doing things the way you think them will most probably result in doing them the wrong way. Not because you&#8217;re a bad programmer, but because there are some standard tricks of the trade that you cannot really avoid using, if you want to write good and maintanable code. Let&#8217;s talk about these 10 techniques that you really need to know about :</p>
<p><strong>1. How to Properly Create a Website Index Page</strong></p>
<p>Creating your website index page is the first thing to do for every website that you create. I&#8217;ve actually created a post that will help you <a href="http://www.codercaste.com/2010/01/16/php-design-patterns-how-to-properly-create-a-website-index-page/">properly create a website index page</a>.</p>
<p>2. <strong>Use the Request Global Array to Grab Data</strong></p>
<p>There is actually no reason to use $_GET and $_POST arrays to grab values. $_REQUEST, is another global array that fetches you either a get or form request. Therefore, it&#8217;s most times more convenient to use something like this to parse data :</p>
<pre class="brush: php;">$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 0;</pre>
<p><strong>3. Debugging PHP is About var_dump<br />
</strong></p>
<p>If you&#8217;re looking for php debugging techniques, i have to say that var_dump is most times the way to go about it. This command is all you need to echo php information. There shouldn&#8217;t really be many cases where you need anything more than dumping values in PHP, in order to debug your code.</p>
<p><strong>4. PHP Handles The Code Logic, Smarty Handles The Presentation</strong></p>
<p>I think i&#8217;ve said this many times before, but Smarty usage (or other template system), is critical for creating organized PHP code.<a href="http://www.codercaste.com/2009/09/29/using-smarty-as-a-template-engine-for-your-php-websites/"> Learn to use smarty as a template engine for your websites</a>, it will pay off, i promise.</p>
<p><strong>5. When You Absolutely Need Global Values, Create a Config File</strong></p>
<p>It is a bad practice to create global values for everything. There are limited cases where you would actually need to do so. Doing it for database tables or database connection information is a good idea, but do not use global variables throughout your PHP code. Moreover, it is always a better idea to keep your global variables at a single config.php file.</p>
<p>6. <strong>If NOT Defined, Access Denied !</strong></p>
<p>If you&#8217;re creating your pages the correct way, there will absolutely no reason for anybody to access any other php page other than index.php or home.php. The idea is that once index.php is accessed, you utilize get variables in order to open the needed pages. Your index page should contain something like :</p>
<pre class="brush: php;">define('yourPage',1);</pre>
<p>Then, your other pages should contain this :</p>
<pre class="brush: php;">if (!defined('yourPage')) die('Access Denied');</pre>
<p>What this does, is preventing direct access to your other php pages. Therefore, any user who tries to access your other web pages, not through index.php, gets an &#8220;Access Denied&#8221; message.</p>
<p><strong>7. Create a Database Class</strong></p>
<p>If you&#8217;re doing database programming (pretty common in PHP), it would be a very good idea to create a database class to handle any database management functions. A good way to do it is by creating functions like :</p>
<pre class="brush: php;">

    public function dbExec($query)
    {
        $result = $this-&gt;db-&gt;exec($query);
        if (PEAR::isError($result))
            errorRedirect($result-&gt;getMessage(), true);
        else
            return $result;
    }
</pre>
<p>This is an example function from an actual project i&#8217;m creating. This one just receives a query and executes it. It also handles any errors that may occur. You could also include sanitization code here, but i prefer to do it using a sanitization function like :</p>
<pre class="brush: php;">

	// checks if arguments given are integer values not less than 0 - has multiple arguments
	function sanitizeInput()
	{
		$numargs = func_num_args();
	    $arg_list = func_get_args();

	    for ($i = 0; $i &lt; $numargs; $i++) {
			if (!is_numeric($arg_list[$i]) || $arg_list[$i] &lt; 0)
	            errorRedirect(&quot;Unexpected variable value&quot;, true);
	    }
	}
</pre>
<p><strong>8. A php File Handles Input, a class.php File Handles Functionality</strong></p>
<p>It is pretty important that you learn not to mess the code that retrieves user input and redirects it to any functions, with those actual functions. The idea is pretty simple. The php file gets any input that we need and then redirects execution to a function residing to the class file. For example, let&#8217;s suppose that a url is like &#8220;index.php?page=profile&amp;action=display&#8221;. The profile.php file retrieves the url and gets that action is &#8220;display&#8221;. Then, using a simple switch, we execute the actual display function like :</p>
<pre class="brush: php;">

require_once PROJECTROOT.'libs/messages.class.php';

$message = new Message();

switch ($action)
{
    case 'display':
        $message-&gt;display();
        break;

...
</pre>
<p>Again, this is part of a project that i create. You see that i include the messages class and then initiate the switch check. $message is just an object that is used to call functions inside the class.</p>
<p>9. <strong>Know Your SQL and Always Sanitize</strong></p>
<p>As i mentioned before, a database is 99% of times important for any php created website. Therefore, you need to know many things about how to use sql properly. Learn to combine tables and more advanced techniques. I promise there will be mysql tutorials soon in codercaste.com. Let me present you an example of a function that uses mySQL and sanitazes using the function seen on point #7 :</p>
<pre class="brush: php;">

    private function getSentMessages($id)
    {
	$this-&gt;util-&gt;sanitizeInput($id);

        $pm_table = $GLOBALS['config']['privateMsg'];
	$users = $GLOBALS['config']['users'];

        $sql = &quot;SELECT PM.*, USR.username as name_sender FROM $pm_table PM, $users USR
		    WHERE id_sender = '$id' AND sender_purge = FALSE AND USR.id = PM.id_receiver AND is_read = TRUE
		    ORDER BY date_sent DESC&quot;;
	$result = $this-&gt;dbQueryAll($sql);

        return $result;
    }
</pre>
<p>At first, we sanitize the user input (the message id at this point, that is passed through a GET variable) and then we execute our sql command. Notice the usage of sql here. You need to learn how to use aliases and combine tables.</p>
<p><strong>10. When You Need Just an Object, Use a Singleton Pattern</strong></p>
<p>It happens pretty often in PHP that we just need a single object created one time and then used globally throughout our whole program. A good example of this is the smarty variable that has to be initialized once and then is used all over the place. A good way to do that is a Singleton pattern, where an object is just created once and for all. The way to do this is like :</p>
<pre class="brush: php;">

    function smartyObject()
    {
        if ($GLOBALS['config']['SmartyObj'] == 0)
        {
            $smarty = new SmartyGame();
            $GLOBALS['config']['SmartyObj'] = $smarty;
        }
        else
            $smarty = $GLOBALS['config']['SmartyObj'];
        return $smarty;
    }
</pre>
<p>Notice that we have a global smarty variable (initialized in config.php in example) and if it equals 0, we go about creating a new smarty object. If not, it means that the object is already created and we just need to return it.</p>
<p>Hope these 10 techniques are as helpful to you as they are for me and i would really like to listen to what you think is your most important PHP technique.</p>
<img src="http://www.codercaste.com/wp-content/plugins/pixelstats/trackingpixel.php?post_id=756&amp;ts=1283913487" style="display:none;" alt="pixelstats trackingpixel" title="Top 10 PHP Techniques That Will Save You Time and Effort" /><img src="http://feeds.feedburner.com/~r/Codercastecom/~4/ULZph9IZFLU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.codercaste.com/2010/03/28/top-10-php-techniques-that-will-save-you-time-and-effort/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		<feedburner:origLink>http://www.codercaste.com/2010/03/28/top-10-php-techniques-that-will-save-you-time-and-effort/</feedburner:origLink></item>
		<item>
		<title>What is the Best and Fastest Javascript Framework to Use?</title>
		<link>http://feedproxy.google.com/~r/Codercastecom/~3/RzLWE1DjUII/</link>
		<comments>http://www.codercaste.com/2010/03/26/what-is-the-best-and-fastest-javascript-framework-to-use/#comments</comments>
		<pubDate>Fri, 26 Mar 2010 18:58:31 +0000</pubDate>
		<dc:creator>Spyros Panagiotopoulos</dc:creator>
				<category><![CDATA[Javascript Programming]]></category>
		<category><![CDATA[dojo framework]]></category>
		<category><![CDATA[javascript framework performance speed]]></category>
		<category><![CDATA[mootools framework]]></category>
		<category><![CDATA[protype framework]]></category>
		<category><![CDATA[yui framework]]></category>

		<guid isPermaLink="false">http://www.codercaste.com/?p=750</guid>
		<description><![CDATA[Choosing the right Javascript framework to use along with your website programming code can be a pretty crucial decision. As a developer, you need to think in terms of performance and features. There are actually tons of different javascript frameworks out there and to be sincere, there has been a situation where i needed to [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.codercaste.com/wp-content/uploads/2010/03/runner.jpg"><img class="alignleft size-thumbnail wp-image-751" title="runner" src="http://www.codercaste.com/wp-content/uploads/2010/03/runner-150x150.jpg" alt="runner 150x150 What is the Best and Fastest Javascript Framework to Use?" width="150" height="150" /></a>Choosing the right Javascript framework to use along with your website programming code can be a pretty crucial decision. As a developer, you need to think in terms of performance and features. There are actually tons of different javascript frameworks out there and to be sincere, there has been a situation where i needed to pick one for a large scale project i was programming.</p>
<p><span id="more-750"></span></p>
<p>The first thing that i had in mind was speed. I wanted the library to be lightweight and effective. I could live without some features, but performance is really critical. You do not really want your users waiting over client code that is executing on their browsers.</p>
<p>I remember that i had 3 frameworks in mind at the time. They were mootools, yui and prototype. I wouldn&#8217;t really know which one was faster. At the time, i was playing the well known Ikariam browser game and i noticed that they were using YUI. Ikariam, though a nice  game, is pretty slow on its javascript handling. So, i thought that YUI may have not been a good choice. Then, i also noticed that tribal wars was using mootools. I was always fascinated on their client side scripting. Their game runs really fast. This made me think that mootools was probably the best choice, BUT i needed proof.</p>
<p>Luckily, there is a tool (in mootools website), that can help us make out which js library is faster. You can find the tool here :</p>
<p><a href="http://mootools.net/slickspeed/">Javascript Frameworks performance test</a></p>
<p>If you run the test (do it, it&#8217;s fun), you will notice that mootools, along with Dojo, are the fastest frameworks. So, now you now. Choose wisely <img src='http://www.codercaste.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' title="What is the Best and Fastest Javascript Framework to Use?" /> </p>
<img src="http://www.codercaste.com/wp-content/plugins/pixelstats/trackingpixel.php?post_id=750&amp;ts=1283913487" style="display:none;" alt="pixelstats trackingpixel" title="What is the Best and Fastest Javascript Framework to Use?" /><img src="http://feeds.feedburner.com/~r/Codercastecom/~4/RzLWE1DjUII" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.codercaste.com/2010/03/26/what-is-the-best-and-fastest-javascript-framework-to-use/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.codercaste.com/2010/03/26/what-is-the-best-and-fastest-javascript-framework-to-use/</feedburner:origLink></item>
		<item>
		<title>How to Use the Linux Df Command to Calculate Disk Free Space</title>
		<link>http://feedproxy.google.com/~r/Codercastecom/~3/FVGEbEfZ0iM/</link>
		<comments>http://www.codercaste.com/2010/03/25/how-to-use-the-linux-df-command-to-calculate-disk-free-space/#comments</comments>
		<pubDate>Thu, 25 Mar 2010 04:17:37 +0000</pubDate>
		<dc:creator>Spyros Panagiotopoulos</dc:creator>
				<category><![CDATA[Linux Tips]]></category>
		<category><![CDATA[calculate free space unix]]></category>
		<category><![CDATA[free space on linux]]></category>
		<category><![CDATA[linux df command]]></category>

		<guid isPermaLink="false">http://www.codercaste.com/?p=744</guid>
		<description><![CDATA[If you&#8217;re mostly a Windows user or programmer and are porting to linux, you may be thinking that a command that would help you determine the free disk space of your computer would be pretty useful. Luckily, there exists such a tool and is called DF (Display Free disk space). To get information about the [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.codercaste.com/wp-content/uploads/2010/03/harddisk.jpg"><img class="alignleft size-thumbnail wp-image-745" title="harddisk" src="http://www.codercaste.com/wp-content/uploads/2010/03/harddisk-150x150.jpg" alt="harddisk 150x150 How to Use the Linux Df Command to Calculate Disk Free Space" width="150" height="150" /></a>If you&#8217;re mostly a Windows user or programmer and are porting to linux, you may be thinking that a command that would help you determine the free disk space of your computer would be pretty useful. Luckily, there exists such a tool and is called DF (Display Free disk space).</p>
<p><span id="more-744"></span></p>
<p>To get information about the disk space on your system, you can just execute :</p>
<pre class="brush: bash;">df -h</pre>
<p>-h stands for Humanly readable, so it&#8217;s pretty easy to remember. Upon execution, you get back something like :</p>
<pre class="brush: bash;">

Filesystem      Size   Used  Avail Capacity  Mounted on
/dev/disk0s2   113Gi   89Gi   23Gi    80%    /
...
</pre>
<p>This example is generated on my macintosh pc, so it may defer in your case. As you can see, i have a total of 113GBytes on free space and i&#8217;m currently using 89GBytes (hmm, i have to free up some space). This leaves me with 23GBytes on available free disk space and thus i&#8217;m using 80% of the hard disk capacity.</p>
<img src="http://www.codercaste.com/wp-content/plugins/pixelstats/trackingpixel.php?post_id=744&amp;ts=1283913487" style="display:none;" alt="pixelstats trackingpixel" title="How to Use the Linux Df Command to Calculate Disk Free Space" /><img src="http://feeds.feedburner.com/~r/Codercastecom/~4/FVGEbEfZ0iM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.codercaste.com/2010/03/25/how-to-use-the-linux-df-command-to-calculate-disk-free-space/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.codercaste.com/2010/03/25/how-to-use-the-linux-df-command-to-calculate-disk-free-space/</feedburner:origLink></item>
		<item>
		<title>The Basics of Cascading Style Sheets Explained</title>
		<link>http://feedproxy.google.com/~r/Codercastecom/~3/_nhSa8YNFZI/</link>
		<comments>http://www.codercaste.com/2010/03/19/the-basics-of-cascading-style-sheets-explained/#comments</comments>
		<pubDate>Fri, 19 Mar 2010 23:41:02 +0000</pubDate>
		<dc:creator>Spyros Panagiotopoulos</dc:creator>
				<category><![CDATA[Cascading Style Sheets (CSS)]]></category>
		<category><![CDATA[change font in css]]></category>
		<category><![CDATA[change font size in css]]></category>
		<category><![CDATA[css basics]]></category>
		<category><![CDATA[css font]]></category>
		<category><![CDATA[css paragraph]]></category>
		<category><![CDATA[introduction to css]]></category>

		<guid isPermaLink="false">http://www.codercaste.com/?p=740</guid>
		<description><![CDATA[Have you ever heard the expression &#8220;Don&#8217;t judge a book by its cover?&#8221;. Chances are that you have. If you want to create nice websites, you have to understand that people DO judge books by their cover, which is why the expression exists at first place. Since looks really matter, you have to know how [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.codercaste.com/wp-content/uploads/2010/03/CSSEditLogo.png"><img class="alignleft size-thumbnail wp-image-741" title="CSSEditLogo" src="http://www.codercaste.com/wp-content/uploads/2010/03/CSSEditLogo-150x150.png" alt="CSSEditLogo 150x150 The Basics of Cascading Style Sheets Explained" width="150" height="150" /></a>Have you ever heard the expression &#8220;Don&#8217;t judge a book by its cover?&#8221;. Chances are that you have. If you want to create nice websites, you have to understand that people DO judge books by their cover, which is why the expression exists at first place. Since looks really matter, you have to know how to use CSS in order to stylize your webpages. In this post, i will tell you some of the basic CSS programming knowledge that you need to have in order to move on with it.</p>
<p><span id="more-740"></span></p>
<p><strong>How do CSS work ?</strong></p>
<p>CSS is today&#8217;s standard in stylizing web pages. Its usage is pretty straight forward and easy. As, you know, in HTML, we are using elements like &lt;p&gt; or &lt;h1&gt; in order to create our paragraphs, headers and more. When we create a paragraph, we sometimes need to change the text size or font inside a paragraph, for instance. CSS is all about making our lives easier in doing so, without repeating the same things over and over.</p>
<p><strong>Change The Text Size and Font Using CSS</strong></p>
<p>Using just plain HTML, we could stylize our paragraph like :</p>
<pre class="brush: css;">

&lt;p&gt;
&lt;font size=&quot;3&quot; face=&quot;Times&quot;&gt;our text here &lt;/font&gt;
&lt;/p&gt;
</pre>
<p>While this would work, there is a problem here. What if we wanted to do that on every paragraph of our HTML code ? This would turn out to become pretty tedious. Thankfully, this is where CSS comes to our rescue. Using a simple CSS tag, we can stylize our every paragraph like :</p>
<pre class="brush: css;">
p  {
    font-family: Times, serif;}
    font-size:0.875em;
    }
</pre>
<p>Does that make sense here ? Now every paragraph of our text is stylized using these attributes. You may ask what happens if you just want to stylize certain paragraphs. Well, in that case, you need to utilize a more advanced CSS technique, called classes. If you&#8217;re more interested in that, take a look here :</p>
<p><a href="http://www.tizag.com/cssT/class.php">CSS Classes</a></p>
<p>I will be creating tutorials about CSS classes and more in the future for sure.</p>
<img src="http://www.codercaste.com/wp-content/plugins/pixelstats/trackingpixel.php?post_id=740&amp;ts=1283913487" style="display:none;" alt="pixelstats trackingpixel" title="The Basics of Cascading Style Sheets Explained" /><img src="http://feeds.feedburner.com/~r/Codercastecom/~4/_nhSa8YNFZI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.codercaste.com/2010/03/19/the-basics-of-cascading-style-sheets-explained/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.codercaste.com/2010/03/19/the-basics-of-cascading-style-sheets-explained/</feedburner:origLink></item>
		<item>
		<title>PHP Design Patterns – How to Properly Create a Website Index Page</title>
		<link>http://feedproxy.google.com/~r/Codercastecom/~3/MV8l1IUgz4A/</link>
		<comments>http://www.codercaste.com/2010/01/16/php-design-patterns-how-to-properly-create-a-website-index-page/#comments</comments>
		<pubDate>Sun, 17 Jan 2010 02:19:09 +0000</pubDate>
		<dc:creator>Spyros Panagiotopoulos</dc:creator>
				<category><![CDATA[PHP Programming]]></category>
		<category><![CDATA[create index page php]]></category>
		<category><![CDATA[php coding]]></category>
		<category><![CDATA[php design patterns]]></category>
		<category><![CDATA[php index page]]></category>

		<guid isPermaLink="false">http://www.codercaste.com/?p=735</guid>
		<description><![CDATA[If you are a newcomer to PHP programming but an experienced programmer overall, chances are that you find PHP pretty simple to program with. PHP is actually a combination of C++ and Perl, created so that we can write our websites along with database management and more. In PHP, there is a very important difference [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.codercaste.com/wp-content/uploads/2010/01/php.png"><img class="alignleft size-thumbnail wp-image-736" title="php" src="http://www.codercaste.com/wp-content/uploads/2010/01/php-150x150.png" alt="php 150x150 PHP Design Patterns   How to Properly Create a Website Index Page" width="150" height="150" /></a>If you are a newcomer to PHP programming but an experienced programmer overall, chances are that you find PHP pretty simple to program with. PHP is actually a combination of C++ and Perl, created so that we can write our websites along with database management and more.</p>
<p><span id="more-735"></span></p>
<p>In PHP, there is a very important difference between writing code and writing good code. Of course, this is true for every programming language, let alone PHP. Knowing how to properly design your website&#8217;s index page is the first and important step towards creating a solid website.</p>
<p><strong>The Amateur Way to Write Your Index Page</strong></p>
<p>The typical way to write your index page, if you are not really that knowledgeable in PHP, is just go about coding whatever there is for the index page. For instance, suppose that our index page has a login form and some introductory text. Our approach would be to just write the code for the index page and then, for every link on that page, create another page. This would mean that we now have an index.php page, a contact.php page, a mail.php page and more.</p>
<p>Don&#8217;t feel bad if you do it this way. I&#8217;ve done it myself and every new PHP programmer has done so as well. However, it&#8217;s time to learn of a more efficient way to code in PHP.</p>
<p><strong>The &#8220;index.php?page=home&#8221; Way</strong></p>
<p>Have you noticed that many websites follow this pattern ? Instead of having a home.php page, you see something like &#8220;index.php?page=home&#8221;. The same happens for every page of the website. What happens is that the index.php page includes the code of the other webpages, as asked. The variable page that you notice in the url is actually a typical $_GET type global variable that you can read in order to identify what is the page that the browser asks for. Here is the actual code of a typical index page :</p>
<pre class="brush: php;">

$page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 'home';

switch($page)
{
    case 'home':           break;
    case 'mail':           break;
    case 'contact':        break;
    default:
        $page = 'home';
}

include(&quot;$page.php&quot;);
</pre>
</pre>
<p>This is a very basic example as you see. The index page just gets the $_REQUEST['page'] global variable ($_REQUEST is a union of $_GET and $_POST, retrieves whatever is available). Now the switch starts. But why have a switch and not just include the php page ? Well, this is actually a security measure against file inclusion attacks. It is always good to handle unexpected input. If an attacker somehow manages to upload a new php page, say hello.php, this index page, without the switch structure, would execute it normally when instructed with index.php?page='hello'. However, if the switch is there, hello.php never gets executed. Instead, the default home.php gets executed. This is always a very good practice and you should really stick to it. Of course, there is much more in protecting PHP code, but this is a small addition as well.</p>
<p>You could now go about creating your own template for writing websites. Remember that it is very important that you know of the essential PHP requirements in order to write much more efficiently than usual. Also, if you are not familiar with it, pay special attention to <a href="http://www.codercaste.com/2009/09/29/using-smarty-as-a-template-engine-for-your-php-websites/">Smarty and learn to use it to create your templates</a>.</p>
<img src="http://www.codercaste.com/wp-content/plugins/pixelstats/trackingpixel.php?post_id=735&amp;ts=1283913487" style="display:none;" alt="pixelstats trackingpixel" title="PHP Design Patterns   How to Properly Create a Website Index Page" /><img src="http://feeds.feedburner.com/~r/Codercastecom/~4/MV8l1IUgz4A" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.codercaste.com/2010/01/16/php-design-patterns-how-to-properly-create-a-website-index-page/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://www.codercaste.com/2010/01/16/php-design-patterns-how-to-properly-create-a-website-index-page/</feedburner:origLink></item>
		<item>
		<title>How to Filter Lists in Python</title>
		<link>http://feedproxy.google.com/~r/Codercastecom/~3/d0w0buAYco4/</link>
		<comments>http://www.codercaste.com/2010/01/11/how-to-filter-lists-in-python/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 21:55:52 +0000</pubDate>
		<dc:creator>Spyros Panagiotopoulos</dc:creator>
				<category><![CDATA[Python Programming]]></category>
		<category><![CDATA[filter lists]]></category>
		<category><![CDATA[python append]]></category>
		<category><![CDATA[python filter]]></category>
		<category><![CDATA[python filtering lists]]></category>
		<category><![CDATA[python list]]></category>
		<category><![CDATA[python tuple]]></category>

		<guid isPermaLink="false">http://www.codercaste.com/?p=720</guid>
		<description><![CDATA[One of the very important things that Python offers to programmers, is the great lists handling functions. Lists are one great data type that you can utilize for lots of different tasks. Since Python is a high level language, it makes our handling lists a real breeze. What is a Python List ? A Python [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.codercaste.com/wp-content/uploads/2010/01/list2.jpg"><img class="alignleft size-thumbnail wp-image-732" title="list2" src="http://www.codercaste.com/wp-content/uploads/2010/01/list2-150x150.jpg" alt="list2 150x150 How to Filter Lists in Python " width="150" height="150" /></a>One of the very important things that Python offers to programmers, is the great lists handling functions. Lists are one great data type that you can utilize for lots of different tasks. Since Python is a high level language, it makes our handling lists a real breeze.</p>
<p><span id="more-720"></span></p>
<p><strong>What is a Python List ?</strong></p>
<p>A Python list is simply a data type containing values of the same type that can be changed dynamically. It can be initialized having just two elements and then we can go on adding more elements or delete some elements as well. On the other hand, the other important Python data structure, tuples, is the same as lists only immutable. Thus, it cannot be changed on runtime.</p>
<p><strong>Why Do You Need to Filter Lists ?</strong></p>
<p>What happens with standard Python programming is that we tend to create lists all the time. We could be either reading a file and creating a list with its words, or maybe getting a list of the files of our current directory. Whatever the case, lists are used quite a lot and if you have been programming in Python for just a small period of time, chances are that you have already used them at least once. The problem is that lists alone are not enough. Most times we need some time of filtering in order to throw out some elements and only keep the important ones. A good example could be the case of getting a list of files. Then, we just want to keep the ones that are of *.mp3 filetype. This is where Python starts to become really versatile, as you will see below.</p>
<p><strong>How to Filter Lists in Python ?</strong></p>
<p>The simplest way to filter a list is the one show below. We just have a list of filenames and we want to recreate that list so that it does not contain the files that do not have &#8220;mp3&#8243; as their filetype.</p>
<pre class="brush: python;">

list = [&quot;1.mp3&quot;,&quot;2.txt&quot;, &quot;3.mp3&quot;, &quot;4.wmv&quot;,&quot;5.mp4&quot; ]
temp = []

for item in list:
    if item.find(&quot;.mp3&quot;) != -1:
        temp.append(item)

for item in temp:
    print item
</pre>
<p>In this example, we have a list that we traverse using a simple for. Then, we have another temporary list and whenever we locate an element having &#8220;.mp3&#8243; as a substring, we add it to our new list. In the end we just print the new list and get the filenames we opted for.</p>
<p>Sometimes, we just need to quickly create a sublist of our starting list. Say that we just need the first two elements of our list. This can be done like this :</p>
<pre class="brush: python;">

list = [&quot;1.mp3&quot;,&quot;2.txt&quot;, &quot;3.mp3&quot;, &quot;4.wmv&quot;,&quot;5.mp4&quot; ]

list = list[:2]

for item in list:
    print item
</pre>
<p>The syntax [starting:ending] determines the sublist we need to create. If no starting index is specified, it defaults to the first element. If you specify the ending index as n, you get the n-1 elements. So, li[:2] gets you elements li[0] and li[1].</p>
<p><strong>The Elegant Way to Filter Lists</strong></p>
<pre class="brush: python;">
def isMp3(s):
    if s.find(&quot;.mp3&quot;) == -1:
        return False
    else:
        return True

list = [&quot;1.mp3&quot;,&quot;2.txt&quot;, &quot;3.mp3&quot;, &quot;4.wmv&quot;,&quot;5.mp4&quot; ]
temp = filter(isMp3,list)

for item in temp:
    print item
</pre>
<p>This is probably the best and most elegant way to filter a list in Python. We utilize the python function filter() here. What this does is take a function and our list to be filtered as its 2 parameters. For each element of the list, this function is executed and the parameter is the next element of the list. If this function returns true, the item is added to the resulting list, else it is not. Once finished, filter() returns the new list, which we print out as you see in the example above. If you want, you can also check <a href="http://docs.python.org/library/functions.html">the map() function</a> as well.</p>
<p>This concludes this small post about filtering lists in Python. I reckon these techniques pretty important in writing efficient code. Python is mostly about doing things fast. Hence, using the built in functions can save you time (and money?) and also transform your code to an elegant state of the art (or at least make it bearable <img src='http://www.codercaste.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' title="How to Filter Lists in Python " /> )</p>
<img src="http://www.codercaste.com/wp-content/plugins/pixelstats/trackingpixel.php?post_id=720&amp;ts=1283913487" style="display:none;" alt="pixelstats trackingpixel" title="How to Filter Lists in Python " /><img src="http://feeds.feedburner.com/~r/Codercastecom/~4/d0w0buAYco4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.codercaste.com/2010/01/11/how-to-filter-lists-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.codercaste.com/2010/01/11/how-to-filter-lists-in-python/</feedburner:origLink></item>
	</channel>
</rss><!-- Dynamic page generated in 5.470 seconds. --><!-- Cached page generated by WP-Super-Cache on 2010-09-07 22:38:07 -->
