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 11-20 of 26 total

Actionscript _XML Class

import _String;

dynamic class _XML extends XML {
	function _XML() {
		
	}
	
	public function $N(tag,xmlNode,xmlNodeArray){
		if (xmlNode == undefined) var xmlNode = this;
		if (xmlNodeArray == undefined) var xmlNodeArray:Array = new Array();
		var nodeArray:Array = new Array();
		
		for (var x=0; x<xmlNode.childNodes.length; x++) {
			if (xmlNode.childNodes[x].nodeType == 1){
				if (xmlNode.childNodes[x].nodeName == tag) xmlNodeArray.push(xmlNode.childNodes[x]);
				$N(tag,xmlNode.childNodes[x],xmlNodeArray);
			}
		}
		return xmlNodeArray;
	}
	
	// If multiple, returns a nodeValue Array
	// If single, returns a nodeValue String
	public function $V(tag,xmlNode) {
		if (xmlNode == undefined) var xmlNode = this;
		var n = $N(tag,xmlNode);
		if (n.length == 1){
			var nV = n[0].firstChild.nodeValue;
			if (nV != undefined){
				nV = escape(nV);
				nV = _String.Replace(nV,"%C2%93","%22");
				nV = _String.Replace(nV,"%C2%94","%22");
				nV = unescape(nV);
			}
			return nV;
		}
		else {
			var vArray:Array = new Array();
			for (var i:String in n) {
				vArray[i] = n[i].firstChild.nodeValue;
				if (vArray[i] != undefined){
					vArray[i] = escape(vArray[i]);
					vArray[i] = _String.Replace(vArray[i],"%C2%93","%22");
					vArray[i] = _String.Replace(vArray[i],"%C2%94","%22");
					vArray[i] = unescape(vArray[i]);
				}
			}
			return vArray;
		}
	}
}

Actionscript _String Class

dynamic class _String {
	// Replace a string or substrings within a string
	static function Replace (the_String, search_String, replace_String, occurrences, backward) {
		if (search_String == replace_String) return the_String;
		var found = 0;
		if (backward == true) {
			var pos = the_String.lastIndexOf(search_String);
			while (pos>= 0) {
				found++;
				var start_String = the_String.substr(0, pos);
				var end_String = the_String.substr(pos + search_String.length);
				the_String = start_String + replace_String + end_String;
				pos = the_String.lastIndexOf(search_String, start_String.length);
				if (found == occurrences) pos = -1;
			}
		}
		else {
			var pos = the_String.indexOf(search_String);
			while (pos>= 0) {
				found++;
				var start_String = the_String.substr(0, pos);
				var end_String = the_String.substr(pos + search_String.length);
				the_String = start_String + replace_String + end_String;
				pos = the_String.indexOf(search_String, pos + replace_String.length);
				if (found == occurrences) pos = -1;
			}
		}
		
		return the_String;
	}
	
	// Convert delimited (comma by default) String to an Array
	static function toArray(string, separator:String) {
		var list = new Array();
		if (typeof(string) == "string"){
			if (separator == undefined) separator = ",";
			if (string == null) return false;
			var currentStringPosition = 0;
			while (currentStringPosition<string.length) {
				var nextIndex = string.indexOf(separator, currentStringPosition);
				if (nextIndex == -1) break;
				var word = string.slice(currentStringPosition, nextIndex);
				list.push(word);
				currentStringPosition = nextIndex+1;
			}
			if (list.length<1) list.push(string);
			else list.push(string.slice(currentStringPosition, string.length));
		} else {
			list.push(string);
		}
		return list;
	}
}

RandomLib - A random class

The class can be used to select one or a group of item(strings, objects, anything) from the entire collection of items. It include randomly select, randomly select unique.
It also include function to randomly select weighted items and randomly select unique weighted items. Weighted items are items assigned a weight, so it can show up more frequently than ones with lower weight. This could be great on making sites need reward some user more than other, or PHP games.

<?php
/*********************************
RandomLib Version 1.0
Programmed by : Chao Xu(Mgccl)
E-mail        : mgcclx@gmail.com
Website       : http://www.webdevlogs.com
Info          : Please email me if there is any feature you want
or there is any bugs. I will fix them as soon as possible.
*********************************/
	
class random{
var $data = array();
function add($string,$weight=1){
	$this->data[] = array('s' => $string, 'w' => $weight);
}
function optimize(){
	foreach($this->data as $var){
		if($new[$var['s']]){
			$new[$var['s']] += $var['w'];
		}else{
			$new[$var['s']] = $var['w'];
		}
	}
	unset($this->data);
	foreach($new as $key=>$var){
		$this->data[] = array('s' => $key, 'w' => $var);
	}
}

function select($amount=1){
	if($amount == 1){
		$rand = array_rand($this->data);
		$result = $this->data[$rand]['s'];
	}else{
		$i = 0;
		while($i<$amount){
			$result[] = $this->data[array_rand($this->data)]['s'];
			++$i;
		}
	}
	return $result;
}

function select_unique($amount=1){
	if($amount == 1){
		$rand = array_rand($this->data);
		$result = $this->data[$rand]['s'];
	}else{
		$rand = array_rand($this->data, $amount);
		foreach($rand as $var){
			$result[] = $this->data[$var]['s'];
		}
	}
	return $result;
}

function select_weighted($amount=1){
	$count = count($this->data);
	$i = 0;
	$max = -1;
	while($i < $count){
		$max += $this->data[$i]['w'];
		++$i;
	}
	if(1 == $amount){
		$rand = mt_rand(0, $max);
		$w = 0; $n = 0;
		while($w <= $rand){
			$w += $this->data[$n]['w'];
			++$n;
		}
		$key = $this->data[$n-1]['s'];
	}else{
		$i = 0;
		while($i<$amount){
			$random[] = mt_rand(0, $max);
			++$i;
		}
		sort($random);
		$i = 0;
		$n = 0;
		$w = 0;
		while($i<$amount){
			while($w<=$random[$i]){
				$w += $this->data[$n]['w'];
				++$n;
			}
			$key[] = $this->data[$n-1]['s'];
			++$i;
		}
	}
	return $key;
}

function select_weighted_unique($amount=1){
	$count = count($this->data);
	$i = 0;
	if($amount >= $count){
		while($i < $count){
			$return[] = $this->data[$i]['s'];
			++$i;
		}
		return $return;
	}else{
		$max = -1;
		while($i < $count){
			$max += $this->data[$i]['w'];
			++$i;
		}
		
		$i = 0;
		while($i < $amount){
			$max -= $sub;
			$w = 0;
			$n = 0;
			$num = mt_rand(0,$max);
			while($w <= $num){
				$w += $this->data[$n]['w'];
				++$n;
			}
			$sub = $this->data[$n-1]['w'];
			$key[] = $this->data[$n-1]['s'];
			
			unset($this->data[$n-1]);
			$this->data = array_merge($this->data);
			++$i;
		}
		return $key;
	}
}
}
?>


example useage

<?php
  $timeparts = explode(' ',microtime());
  $starttime = $timeparts[1].substr($timeparts[0],1);
	include ('class.random.php');
	$random = new random;
	$random->add('this have weight 1000, ', 1000);
	$random->add('this have weight 1, ', 1);
	$random->add('this have weight 200, ', 200);
	$random->add('this have weight 500, ', 500);
?>
The random items:<br />
one weights 1000, one weights 1, one weights 200, one weights 500<br />
Result for randomly select 1 item:<?=$random->select()?><br />
Result for randomly select 3 item:<? print_r($random->select(3))?><br />
Result for randomly select 3 unique item:<? print_r($random->select_unique(3))?><br />
Result for weighted randomly select 1 item:<?=$random->select_weighted()?><br />
Result for weighted randomly select 3 item:<? print_r($random->select_weighted(3))?><br />
Result for weighted randomly select 3 unique item:<? print_r($random->select_weighted_unique(3))?><br />
<?php
	  $timeparts = explode(' ',microtime());
  $endtime = $timeparts[1].substr($timeparts[0],1);
  echo 'time spent',bcsub($endtime,$starttime,6);
?>

Load a PHP Class automatically upon instantiation (PHP5)

When you instantiate a class, it will try to load the file automatically.
function __autoload($class_name) {
    require_once("classes/" . $class_name . ".php");
}

Usage:
$auth = new Auth;

Will automatically load the file "classes/Auth.php"

Model from Table Name

Get the Rails model based on the table name. Assumes standard table name conventions.

def model_for_table(table_name)
  table_name.classify.constantize
end

Javascript Manipulate Class Names

I often have to manipulate class names of objects in javascript.
But className can have multiple classes in it.
These functions deal with that.

// ----------------------------------------------------------------------------
// HasClassName
//
// Description : returns boolean indicating whether the object has the class name
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to add
//
function HasClassName(objElement, strClass)
   {

   // if there is a class
   if ( objElement.className )
      {

      // the classes are just a space separated list, so first get the list
      var arrList = objElement.className.split(' ');

      // get uppercase class for comparison purposes
      var strClassUpper = strClass.toUpperCase();

      // find all instances and remove them
      for ( var i = 0; i < arrList.length; i++ )
         {

         // if class found
         if ( arrList[i].toUpperCase() == strClassUpper )
            {

            // we found it
            return true;

            }

         }

      }

   // if we got here then the class name is not there
   return false;

   }
// 
// HasClassName
// ----------------------------------------------------------------------------


// ----------------------------------------------------------------------------
// AddClassName
//
// Description : adds a class to the class attribute of a DOM element
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to add
//
function AddClassName(objElement, strClass, blnMayAlreadyExist)
   {

   // if there is a class
   if ( objElement.className )
      {

      // the classes are just a space separated list, so first get the list
      var arrList = objElement.className.split(' ');

      // if the new class name may already exist in list
      if ( blnMayAlreadyExist )
         {

         // get uppercase class for comparison purposes
         var strClassUpper = strClass.toUpperCase();

         // find all instances and remove them
         for ( var i = 0; i < arrList.length; i++ )
            {

            // if class found
            if ( arrList[i].toUpperCase() == strClassUpper )
               {

               // remove array item
               arrList.splice(i, 1);

               // decrement loop counter as we have adjusted the array's contents
               i--;

               }

            }

         }

      // add the new class to end of list
      arrList[arrList.length] = strClass;

      // add the new class to beginning of list
      //arrList.splice(0, 0, strClass);
      
      // assign modified class name attribute
      objElement.className = arrList.join(' ');

      }
   // if there was no class
   else
      {

      // assign modified class name attribute      
      objElement.className = strClass;
   
      }

   }
// 
// AddClassName
// ----------------------------------------------------------------------------


// ----------------------------------------------------------------------------
// RemoveClassName
//
// Description : removes a class from the class attribute of a DOM element
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to remove
//
function RemoveClassName(objElement, strClass)
   {

   // if there is a class
   if ( objElement.className )
      {

      // the classes are just a space separated list, so first get the list
      var arrList = objElement.className.split(' ');

      // get uppercase class for comparison purposes
      var strClassUpper = strClass.toUpperCase();

      // find all instances and remove them
      for ( var i = 0; i < arrList.length; i++ )
         {

         // if class found
         if ( arrList[i].toUpperCase() == strClassUpper )
            {

            // remove array item
            arrList.splice(i, 1);

            // decrement loop counter as we have adjusted the array's contents
            i--;

            }

         }

      // assign modified class name attribute
      objElement.className = arrList.join(' ');

      }
   // if there was no class
   // there is nothing to remove

   }
// 
// RemoveClassName
// ----------------------------------------------------------------------------
  

classify() for alternating rows, columns, etc.

I often want different rows in a table to alternate in color, and I do this by assigning each row a class name and styling it with CSS. This is a simple helper method designed to return a class name based on the given row count.

It is also convenient for me to assign a class to table cells based on the type of content they hold. For example, if I have a cell with a float value in it, I want to display it with a monospace font, whereas if I have a cell with a string in it, I want to display it in a serif font.

# Determines the CSS class based on either the count given
# (returns 'even' or 'odd' as the CSS class name) or the class
# given (returns the string version of the class, lowercased,
# as the CSS class name)
def classify( count_or_class, include_class_text = true )
  if count_or_class.class == Fixnum
    value = ( count_or_class % 2 == 0 ? 'even' : 'odd' )
  else
    value = count_or_class.to_s.downcase
  end

  if include_class_text
    'class="' << value << '"'
  else
    value
  end
end


Example usage with alternating 'even'/'odd' row class names:
<table>
<% count = 0 %>
<% @collection.each do |value| %>
  <tr <%= classify( count ) %>>
    <td><%=h value %></td>
  </tr>
  <% count += 1 %>
<% end %>
</table>


Example usage with data type class names:
<tr>
<% @columns.each do |column| %>
  <% data = row.send( column.name ) %>
  <td <%= classify( data.class ) %>>
    <%=h data %>
  </td>
<% end %>
</tr>

BlankSlate: Clean an object class to its bare minimum methods in Ruby

From http://onestepback.org/index.cgi/Tech/Ruby/BlankSlate.rdoc

class BlankSlate
   instance_methods.each { |m| undef_method m unless m =~ /^__/ }
end

Temporarily overriding class methods in Ruby

By Tobi / xal from IRC, and seemingly related to this.

class Object
  def mock_methods(mock_methods)
 
    original = self
 
    klass = Class.new(self) do
 
      instance_eval do       
        mock_methods.each do |method, proc| 
          define_method("mocked_#{method}", &proc)
          alias_method method, "mocked_#{method}"
        end            
      end
 
    end
 
    begin
      Object.send(:remove_const, self.name.to_s)
      Object.const_set(self.name.intern, klass)
 
      yield
 
    ensure
      Object.send(:remove_const, self.name.to_s)
      Object.const_set(self.name.intern, original)
    end
 
  end
end
 
class Duck
  def quak; puts "Quak";  end
end
 
Duck.new.quak #=> "Quak"
 
Duck.mock_methods(:quak => Proc.new { puts 'Wuff' }) do  
  Duck.new.quak #=> "Wuff"
end

php javascript class encode

Badly formatted post broke our parser. Please edit!
« Newer Snippets
Older Snippets »
Showing 11-20 of 26 total