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-10 of 21 total  RSS 

Using the XSLT function document()

I found an XSLT solution recently using the built-in function document() to include an additional XML document into the current XML document.

Using the file lunch.xml with drink.xml I can show what is available for today's lunch menu.

file: lunch.xml
<food>
  <item name="banana"/>
  <item name="apple"/>
  <item name="custard"/>
  <item name="crisps"/>
</food>  


file: drink.xml
<drinks>
  <drink name="water"/>
  <drink name="orange"/>
  <drink name="lemonade"/>
  <drink name="cream soda"/>
  <drink name="tea"/>
  <drink name="coffee"/>
  <drink name="blackcurrant juice"/>
  <drink name="ginger ale with lime"/>
</drinks>


file: lunch.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="food">
<html>
  <head><title>Food menu</title></head>
  <body>
  <h1>To eat</h1>
  <ul>
  <xsl:apply-templates select="item" />
  </ul>
  <h1>To drink</h1>
  <xsl:value-of select="document('drink.xml')/drinks/drink[2]/@name"/>
  </body>
</html>
         
</xsl:template>

<xsl:template match="item">
  <li><xsl:value-of select="@name"/></li>
</xsl:template>

</xsl:stylesheet>



output:
<html><body>
<h1>To eat</h1>
<ul>
<li>banana</li>
<li>apple</li>
<li>custard</li>
<li>crisps</li>
</ul>
<h1>To drink</h1>orange</body></html>

ARGV Parser

This function parse ARGV and return a string.
See exemples for more informations :

// Go : http://blackh.badfile.net/wordz/

Function :

  def options(param)
  
	i = 0
		ARGV.each  { |valeur|
		
    		if (valeur == '-' + param.to_s)
				return ARGV[i+1]
			elseif (valeur != '-' + param.to_s)
				return false
			end
		i += 1
		}
		
   end


Usage :

// cmd> ruby test.rb -o foo

	out =  self.options('o')

	if (out != false and out.empty? == false)
                   puts out # print -> foo
	end

Using the XSLT sum function

This XML and XSLT code is an example of storing and displaying a car mileage log. Notably the XSLT sum() function displays the total no of miles.


file: car_log.xsl
<?xml version="1.0"?>

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
      
    <xsl:template match="car_log">
      <div>      
        <p>Total miles this month: <xsl:value-of select="sum(records/entry/miles)" /></p>
        <xsl:apply-templates select="records"/>
      </div>
    </xsl:template>
    
    <xsl:template match="car_log/records/entry"><xsl:variable name="pos" select="position()"/>
    <div class="record">
      <dl>
        <dt><label for="trip"><xsl:value-of select="@title"/>trip</label></dt>
        <dd>
          <input type="text" id="trip{$pos}" name="trip{$pos}" value="{trip}" size="{@size}" />
        </dd>
          
        <dt><label for="miles"><xsl:value-of select="@title"/>miles</label></dt>
        <dd>
          <input type="text" id="miles{$pos}" name="miles{$pos}" value="{miles}" size="2" />
        </dd>
          
        <dt><label for="description"><xsl:value-of select="@title"/>description</label></dt>
        <dd>
          <input type="text" id="description{$pos}" name="description{$pos}" value="{description}"  />
        </dd>        
      </dl>
    </div>
    </xsl:template>
    </xsl:stylesheet>

file: car_log.xml
<car_log>
  <summary>
    <project>car_log</project>
  </summary>
  <records>
    <entry id='17962'><date>Wed Dec 12 20:00:33 +0000 2007</date><trip>trip to the supermarket</trip><miles>11.8</miles><description>my first trip with the GPS installed</description></entry>
    <entry id='18024'><date>Fri Dec 14 11:45:09 +0000 2007</date><trip>driving around the park</trip><miles>26.1</miles><description/></entry>
    <entry id='18173'><date>Thu Dec 20 01:21:27 +0000 2007</date><trip>trip to the supermarket</trip><miles> 8.5</miles><description/></entry>
    <entry id='18174'><date>Thu Dec 20 01:34:26 +0000 2007</date><trip>visiting parents</trip><miles>12.7</miles><description/>
    </entry>
  </records>
</car_log>

output
Total miles this month: 59.1
...

create and call an oracle function

create or replace function "ORACLE_FOO"
(foo_arg1 in NUMBER)
return NUMBER
is
rt NUMBER := 0;
begin
  IF foo_arg1 > 1 THEN
    SELECT 1 INTO rt;
  ELSE
    SELECT 2 INTO rt;
  END IF;
  RETURN (rt);
end;

SELECT ORACLE_FOO(1) FROM dual;

Validate email and domain

// Vlidate email and domain name
<?php

function validate_email($email){

$exp = "^[a-z\'0-9]+([._-][a-z\'0-9]+)*@([a-z0-9]+([._-][a-z0-9]+))+$";

if(eregi($exp,$email)){
	if(checkdnsrr(array_pop(explode("@",$email)),"MX")){
		print("$email is ok.<br>");
			}else{
			print("$email is ok. But domain is not.<br>");
			}
				}else{
				print("$email is not ok.<br>");
				}   
}

validate_email("shantanu.ok");
validate_email("shantanu.ok@gmail.com");
validate_email("shantanu.ok@fsjaldkfjlsfjsljflsfjsldk.com");

?>

PHP Copyright Updater

// PHP Copyright Updater
// by Evan Walsh
// NothingConcept.com

This code will automatically change the copyright on your site as the year changes. Tested and approved by me.

Just call this in one of your PHP files by including the file with this code in it:

<?php
//Licensed under the GPL v2
//by Evan Walsh of nothingconcept.com
function copyright($site,$year) {
    $current = date(Y);
    if($year == $current) { $eyear = $year; }
    else { $eyear = "$year - $current"; }
    echo "All content &copy; $eyear $site";
}
?>


Example: <?php include('functions.php'); ?>

Then place <?php copyright("Sitename","2007"); ?> or something similar in the place you want the copyright to display.

Simple as that.

Particle Swarm Optimization

Particle Swarm Optimization written in Python, more infos and a pretty printer here : http://www.biais.org/blog/index.php/2007/01/14/13-metaheuristic-particle-swarm-optimization-pso-in-python

# Particle swarm optimization
# Maxime Biais : <http://www.biais.org/blog/>

from random import uniform
 
class PSO:
    def __init__(self, pop_size, min, max, phi, phi2, lr, maxiter, func):
        self.func = func
        self.pop = []
        # 0: position, 1: velocity, 2: fitness
        self.min = min
        self.max = max
        for i in xrange(pop_size):
            self.pop.append([uniform(self.min, self.max), 
                                   uniform(-1, 1), 0])
        self.evaluate()
        self.gdest = self.pop[0]
        self.pdest = self.pop[0]
        self.phi = phi
        self.phi2 = phi2
        self.lr = lr
        self.maxiter = maxiter
    
    def update_velocity(self):
        for i in self.pop:
            i[1] = self.lr * i[1] + uniform(0, self.phi) \
                    * (self.pdest[0] - i[0]) + uniform(0, self.phi2) \
                    * (self.gdest[0] - i[0])
 
    def evaluate(self):
        for i in self.pop:
            i[2] = self.func(i[0])
 
    def move(self):
        for i in self.pop:
            i[0] += i[1]
 
    def __cmp_by_fitness(self, a, b):
        return cmp(a[2], b[2])
    
    def run(self, update_func=False):
        for i in xrange(self.maxiter):
            if update_func:
                update_func()
            self.update_velocity()
            self.move()
            self.evaluate()
            self.pop.sort(self.__cmp_by_fitness, reverse=0)
            self.pdest = self.pop[0]
            if self.pdest[2] < self.gdest[2]:
                self.gdest = self.pdest

PHP: Dynamically call a function from list of allowed actions

This function simply calls another function based on the argument, assuming that argument ($action) is in the "allowed" list of actions.

settings-config.php
$settings['actions'] = "list,view,delete,update";


Catalog-class.php
public function process_action($action) {
	global $settings;
	
	$allowed_actions = explode(",",$settings['actions']);
	if (is_numeric(array_search($action, $allowed_actions))) {
		$f_name = "product_" . $action;
		$this->$f_name();
	} else {
		$this->error_msg = 'ACTION_NOT_ALLOWED';
	}
}
private function product_list() {
}
private function product_view() {
}
private function product_delete() {
}
private function product_update() {
}
private function product_create() {
}


Even if product_create() exists, if you do process_action('create'), it will not work... it's basically like a function wrapper.. or something like that...

UPDATE: Yes I know I could have created an array like
$settions['actions'] = array('list','view','delete','update');
but I've modified this code a bit for snippet/display purposes... anyways this is just a reminder for myself, not of actual use or interest for others... comments are welcome though :D

PyS60 - DaemonS60

// description of your code here

import appuifw
import e32
import thread

lock = e32.Ao_lock()
lockTHR = thread.allocate_lock()

###### Sostituisci questa funzione con quello che vuoi fare eseguire
i = 0
def funzDaemon():
	global i
	while(1):
		lockTHR.acquire()
		e32.ao_sleep(1)
		open('E:\\Others\\tmp.txt', 'a').write(str(i)+"\n")
		i+=1
		lockTHR.release()
####################################################################

appuifw.app.title = u'DaemonS60'
appuifw.app.exit_key_handler = lambda:lock.signal()

print 'DaemonS60 - Start'

thread.start_new_thread(funzDaemon, ())

lock.wait()

print 'DaemonS60 - Stop'

Just #@$% do it!

If you have an unreliable network feed and want to run something like rsync, scp, etc. without having to babysit it a simple function can be used to prefix a command. The function looks like this:

# Function to force a command to try until it works.
# Name means "JUST #@$% DO IT!"
JFDI () {
  COMMAND=$*
  while ! $COMMAND ; do echo "Retrying..." ; done
}


Using it is simplicity itself:

# command that can fail and annoy
rsync -avz /my/local/directory/ myuser@host:~/my/remote/directory/

# command that won't give up ever
JFDI rsync -avz /my/local/directory/ myuser@host:~/my/remote/directory/
« Newer Snippets
Older Snippets »
Showing 1-10 of 21 total  RSS