Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS 

A simple loop in Ruby

This loop repeats 10 times, with each iteration it increments the variable 'i' by 1 and displays it's value.

i = 0
10.times do
  i += 1
  puts i
end

Treating first/last loop iterations differently

Sometimes, you need to iterate over a list of items and treat the first and last element differently from the rest. This tends to produce really messy code, which can be avoided using the following snippet.

Imagine you have a list of Kittens, and you want to print out a summary of them, saying "My kittens are called Bob, James, John, and Ally." You need to treat the first and last element of the list differently from the rest, lest you end up with superfluous commas in the text. You also need to deal with the cases of there being only one kitten, or no kittens at all.

To do this, you can avail yourself of a Counter class that keeps track of where you are in the iteration:
String kittenDesc = "I have no kittens.";
Counter kc = new Counter(kittens);
for (Kitten k : kittens) switch(kc.next()) {
	case one:   kittenDesc =  "My kitten is called " + k.getName() + "."; break;
	case first: kittenDesc =  "My kittens are called " + k.getName();     break;
	case item:  kittenDesc += ", " + k.getName();                         break;
	case last:  kittenDesc += " and " + k.getName() + ".";                break;
}

package com.zarkonnen.util;

import java.util.Collection;

/**
 * Used for keeping track of where you are in a collection/array being iterated over. Use by
 * initialising with the collection/array before the loop and embedding a switch on the next() Mode
 * value into the loop.
 *
 * LICENCE: This code is licenced under a BSD licence. Feel free to alter and redistribute.
 *
 * @author David Stark, http://www.zarkonnen.com
 * @version 1.0 (2007-07-11)
 */
public class Counter {
	/**
	 * An enumeration of modes identifying where in the collection/array we are.
	 */
	public enum Where {
		/** The only element of an array/collection of size 1. */ one,
		/** The first element. */                                 first,
		/** The last element of the array/collection. */          last,
		/** Any other element somewhere in the middle. */         item
	}
	
	private int size;
	private int nextIndex = 0;
	
	/**
	 * @param c A collection to keep track of. If its size changes between now and the
	 * iteration, strange things will happen.
	 */
	public Counter(Collection c) {
		size = c.size();
	}
	
	/**
	 * @param a An array to keep track of. If its size changes between now and the iteration,
	 * strange things will happen.
	 */
	public Counter(Object[] a) {
		size = a.length;
	}
	
	/**
	 * @return A Where enum value for where in the array/collection we now are:
	 * <ul>
	 * <li><strong>one</strong> at the only element of an array/collection of size 1</li>
	 * <li><strong>first</strong> at the first element</li>
	 * <li><strong>last</strong> at the last element</li>
	 * <li><strong>item</strong> at any other element</li>
	 * </ul>
	 */
	public Where next() {
		return size == 1         ? Where.one   :
		       nextIndex++ == 0  ? Where.first :
		       nextIndex == size ? Where.last  :
		                           Where.item  ;
	}
	
	/**
	 * @return Which index of the array/collection we're currently at.
	 */
	public int index() {
		return nextIndex == 0 ? 0 : nextIndex - 1;
	}
}

Using cycling through input variables in PHP using foreach

This is a simple mechanism for cycling through all the inputs to a PHP script. If you're using $_GET (variables in the query string), $_POST (variables posted with a POST method on a form) or even $_SESSION (variables stored in the session) you can use this technique.

This snippet prints out all the variables in the $_GET variable (the query string) .

foreach ($_GET as $key => $value)
{
print "$key has a value of $value";
}

ForLoop: a simple for loop in xslt

<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
### begin_: file metadata
    ### <region-file_info>
    ### main:
    ###   - name : ForLoop: a simple for loop in xslt
    ###     desc : |
    ###         Do a simple for loop in xslt displaying hello world.
    ###         Call this from any source xml file.
    ###         It works independently of the data in the xml.
    ###     date : created="Thu 2005-12-01 11:30:52"
    ###     last : lastmod="Thu 2005-12-01 11:30:57"
    ###     lang    : xslt
    ###     tags    : xml xslt loop for hello_world
    ### </region-file_info>
    -->
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html"/>

<xsl:template match="/">

<html>
<head><title>Say Hello Ten Times!</title></head>
<body>
    <b>I am going to say hello Ten Times!</b>
<!-- begin_: Send_Loop_To_HTML -->
    <xsl:call-template name="for.loop">
     <xsl:with-param name="i">1</xsl:with-param>
     <xsl:with-param name="count">10</xsl:with-param>
    </xsl:call-template>
</body>
</html>

</xsl:template>


<!--begin_: Define_The_Output_Loop -->
  <xsl:template name="for.loop">

   <xsl:param name="i"      />
   <xsl:param name="count"  />

   <!--begin_: Line_by_Line_Output -->
   <xsl:if test="$i &lt;= $count">
      <br /> <b><xsl:value-of select="$i" />.</b>Hello world!
   </xsl:if>

   <!--begin_: RepeatTheLoopUntilFinished-->
   <xsl:if test="$i &lt;= $count">
      <xsl:call-template name="for.loop">
          <xsl:with-param name="i">
              <xsl:value-of select="$i + 1"/>
          </xsl:with-param>
          <xsl:with-param name="count">
              <xsl:value-of select="$count"/>
          </xsl:with-param>
      </xsl:call-template>
   </xsl:if>

  </xsl:template>
</xsl:stylesheet>

Using ao_sleep

In python for series 60, the use of e32.ao_sleep is encourage
over time.sleep. AO stands for 'Active Object' approach to
cooperative multi-tasking. When an object go to 'ao_sleep'
other active objects can run.
import e32
e32.ao_sleep(5)  # sleep for 5 seconds

There is another usage ao_sleep(interval, callback)
where ao_sleep will return immediately but the callback
will be called after the interval (in another thread?)

This could be used to create a repeat loop for every interval.
I show this in a previous snippet.
import e32, time

def showtime():
  print time.clock()
  e32.ao_sleep(1, showtime)  # sleep then call itself again

showtime()  # start the loop
« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS