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 11 total  RSS 

PHP Dynamic Checkbox Table Creator (data retrieved from MySQL DB)

Hi All.
This is a function for Dynamically Create a Checbox Table retrieving information for from a MySQL Database.
As it is quite commented, it's also good for learning how this things work :)
Hope you find it useful.
Feedback is welcome.
Cheers
Dan

function dynamic_checkbox_table ($sql_str, $col_label, $col_name, $val_checked="S", $cant_cols_tbl=3){
/*
	by Daniel Neumann
	this script creates dynamically permite a table containing checkboxes 
	getting the data for the checkboxes from a MySQL DB
	$sql_str, SQL select string to retrieve data from DB (see example in last comment line)
	$col_label, DB column that has values for the checkbox label 
	$col_name, DB column that has values for the checkbox name
	$val_checked="S", value when checked (value="" attribute) it uses the same value for all of them. If you whish to use a dynamic value from a DB, you should comment the line (it´s explained next to the code in the middle of the function) and de-comment the other line (check the code,. you'll understand what I mean). Also, you should use this parameter to specify the column name for the values
	$cant_cols_tbl=3, quantity of columns for the table, it defaults to 3
	usage example: dynamic_checkbox_table("SELECT * FROM keywords", "Keyword", "ID_Keywrd");
*/
	
	//connect DB and run query
	$db="MyDB";
	$db_user="MyUser";
	$pass="MyPass";
	$host="localhost";
	@mysql_connect($host,$db_user,$pass);
	@mysql_select_db($db) or die ("cannot connect to DB");
	$q_resultado = mysql_query($sql_str);
	mysql_close();
	if (mysql_num_rows($q_resultado)==0) exit("no rows returned");
	
	$next_row = mysql_fetch_array($q_resultado); //fetch first row
	
	$output = "<table  border=\"1\">\n"; //open table tag
	do {
		$output .= "<tr>\n"; //open row tag
		for ($i=1 ; $i <= $cant_cols_tbl ; $i++ ){ //loops as many times as $cant_cols_tbl
			$row=$next_row; //assign $row, next row will be checking next one, that avoids starting a new row when it's gonna be empty
			$output .= "<td>"; //open TD tag
			$output .= (!$row) ? "" : '<input type="checkbox" name="'.$row[$col_name].'" value="'.$val_checked.'" />'.$row[$col_label]; //create checkbox and data from $row (**** you should comment this line if you whish to use dynamic $val_checked****)
//			echo (!$row) ? "" : '<input type="checkbox" name="'.$row[$col_name].'" value="'.$row[$val_checked].'" />'.$row[$col_label]; //create checkbox and data from $row (**** you should de-comment this line if you whish to use dynamic $val_checked****)
			$next_row = mysql_fetch_array($q_resultado); //retrieve next row
			$output .= "</td>\n"; //close TD
		} //close for loop
		$output .= "</tr>\n"; //close row
	} while ($next_row); //close do-while (and checks if there's another row)
	$output .= "</table>\n"; //close table
	return $output; 
}

The eval side of Ruby

The eval method in Ruby executes the code from within a string.
eval("puts 'Hello World'")

output:
Hello World

Pull JavaScript code dynamically into your web page at run-time.

Using the JavaScript keyword Eval() with AJAX makes it possible to dynamically add JavaScript code at run-time to your web page.

Here's the complete code dynalert.html, dynalert.js, and dynalert.cgi

file:dynalert.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	"http://www.w3.org/TR/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
		<title>dynalert</title>
		<meta http-equiv="Content-Type" content="type=text/html; charset=ISO-8859-1" />
		<script type="text/javascript" src="dynalert.js"></script>
	</head>

	<body>
<p id="i1">123 </p><input type="button" value="go" onclick="update()" />
	</body>
</html>


file: dynalert.js
function populatePage(results){
  eval(results);
}

//send the update
function update() {

	var strServer = "dynalert.cgi";
	url2 = "";
	SubmitRBData(strServer,"?" + url2);

}

function SubmitRBData(strUrl, strPostFields) {
	http.open("GET", strUrl + strPostFields, true);
	http.onreadystatechange = handleHttpResponse;
	http.send(null);
}
function handleHttpResponse() {

	if (http.readyState == 4) {
		if (http.status == 200)
		{
		results = http.responseText;
		populatePage(results); // string response
		}
	}

}

function getHTTPObject() {

	var objXMLHttp=null

	if (window.XMLHttpRequest)
	{
		objXMLHttp=new XMLHttpRequest()
	}
	else if (window.ActiveXObject)
	{
		objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
	}

return objXMLHttp

}

var http = getHTTPObject(); // We create the HTTP Object


file:dynalert.cgi
#!/usr/bin/ruby
# dynalert.cgi

require 'cgi'

cgi = CGI.new

#title = cgi['title']

puts "Content-Type: text/html"
puts
puts "function transcript(){ alert('and Bob said this idea might work.');}"
puts "alert('this is a success');"
puts "alert('we can now pass back anything we like');"
puts "transcript();"
puts "oNew = document.createElement('strong');"
puts "oNew.innerHTML = 'yes - this is bold text';"
puts "document.getElementById('i1').appendChild(oNew);"


The 0-1 Knapsack Problem in C

This is a dynamic-programming algorithm implementation for solving the the 0-1 Knapsack Problem in C.

Further explanation is given here.

#include <stdio.h>

#define MAXWEIGHT 100

int n = 3; /* The number of objects */
int c[10] = {8, 6, 4}; /* c[i] is the *COST* of the ith object; i.e. what
				YOU PAY to take the object */
int v[10] = {16, 10, 7}; /* v[i] is the *VALUE* of the ith object; i.e.
				what YOU GET for taking the object */
int W = 10; /* The maximum weight you can take */ 

void fill_sack() {
	int a[MAXWEIGHT]; /* a[i] holds the maximum value that can be obtained
				using at most i weight */
	int last_added[MAXWEIGHT]; /* I use this to calculate which object were
					added */
	int i, j;
	int aux;

	for (i = 0; i <= W; ++i) {
		a[i] = 0;
		last_added[i] = -1;
	}

	a[0] = 0;
	for (i = 1; i <= W; ++i)
		for (j = 0; j < n; ++j)
			if ((c[j] <= i) && (a[i] < a[i - c[j]] + v[j])) {
				a[i] = a[i - c[j]] + v[j];
				last_added[i] = j;
			}

	for (i = 0; i <= W; ++i)
		if (last_added[i] != -1)
			printf("Weight %d; Benefit: %d; To reach this weight I added object %d (%d$ %dKg) to weight %d.\n", i, a[i], last_added[i] + 1, v[last_added[i]], c[last_added[i]], i - c[last_added[i]]);
		else
			printf("Weight %d; Benefit: 0; Can't reach this exact weight.\n", i);

	printf("---\n");

	aux = W;
	while ((aux > 0) && (last_added[aux] != -1)) {
		printf("Added object %d (%d$ %dKg). Space left: %d\n", last_added[aux] + 1, v[last_added[aux]], c[last_added[aux]], aux - c[last_added[aux]]);
		aux -= c[last_added[aux]];
	}

	printf("Total value added: %d$\n", a[W]);
}

int main(int argc, char *argv[]) {
	fill_sack();

	return 0;
}

dynamic rails img headers

// description of your code here

find views -name [a-z]\*rhtml | xargs -n1 grep -H "@page_title" | grep -v "<%" | sed "s/\@page_title = //" | sed "s/rhtml/png/" | sed "s:views/::" | sed "s:/:_:g" | sed "s:^:public/images/beta/headers/hdr_:" | sed "s/  //g"

Add a jar file to Java load path at run time

Sometimes it is necessary to amend the class load path at run time. For example, dynamically adding jar files containing user-configurable JDBC data sources. The way this is done is truly monstrous -- the URL Path format was only revealed when a colleague looked into the Java library sources.

import java.net.URL;
import java.io.IOException;
import java.net.URLClassLoader;
import java.net.MalformedURLException;

public class JarFileLoader extends URLClassLoader
{
    public JarFileLoader (URL[] urls)
    {
        super (urls);
    }

    public void addFile (String path) throws MalformedURLException
    {
        String urlPath = "jar:file://" + path + "!/";
        addURL (new URL (urlPath));
    }

    public static void main (String args [])
    {
        try
        {
            System.out.println ("First attempt...");
            Class.forName ("org.gjt.mm.mysql.Driver");
        }
        catch (Exception ex)
        {
            System.out.println ("Failed.");
        }

        try
        {
            URL urls [] = {};

            JarFileLoader cl = new JarFileLoader (urls);
            cl.addFile ("/opt/mysql-connector-java-5.0.4/mysql-connector-java-5.0.4-bin.jar");
            System.out.println ("Second attempt...");
            cl.loadClass ("org.gjt.mm.mysql.Driver");
            System.out.println ("Success!");
        }
        catch (Exception ex)
        {
            System.out.println ("Failed.");
            ex.printStackTrace ();
        }
    }
}

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

go from model to associated table name and back

Given a table object, it returns the related string object; e.g. SubAttribute => 'sub-attribute'. Useful if you want to make a list of all your tables with perhaps their fields listed out to the side.

def stringify_table( table, replace_char = '-', pluralize = false )
  string = table.to_s.gsub( /([A-Za-z])([A-Z])/, '\1' << replace_char.to_s << '\2' )
  string = string.pluralize if pluralize
  string
end


Given a string akin to the name of a table, it returns the related table object; e.g. 'sub_attributes' => SubAttribute.

def tablify_string( string )
  eval( string.to_s.gsub( /_id/, '' ).singularize.split( '_' ).collect { |word| word.capitalize }.join )
end

A dynamic form of the class statement.

These 2 methods are equivalent.
# method 1
class X(object):
    a = 1

# method 2
X = type('X', (object,), dict(a=1))

Gmail-Like Incremental Search //JavaScript Class


Implements a GMail-like auto-complete.

[UPDATED CODE AND HELP CAN BE FOUND HERE]


@REQUIRES Event-Listener

//Requires http://www.jsfromhell.com/geral/event-listener

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/dhtml/incremental-search [v1.0]

IncrementalSearch = function( input, callback, className ){
	var i, o = ( o = this, o.l = [], o.i = input, o.c = null, o.s = { e: null, i: -1 }, o.f = callback || function(){}, o.n = className || "", o );
	for( i in { keydown: 0, focus: 0, blur: 0, keyup: 0, keypress: 0 } )
		addEventListener( o.i, i, function( e ){ o.handler.call( o, e ); } );
};
with( { p: IncrementalSearch.prototype } ){
	(p.constructor.fadeAway = function( o ){
		o instanceof Object ? ( this.trash = this.trash || [] ).push( o ) && setTimeout( this.fadeAway, 200 ) : arguments.callee.c.trash.pop().hide();
	}).c = p.constructor;
	p.callEvent = function( e ){ this[e] && this[e].apply( this, [].slice.call( arguments, 1 ) ); };
	p.highlite = function( e ){ ( this.s.e && ( this.s.e.className = "normal" ), ( this.s = { e: e, i: e.listindex } ).e.className += " highlited", this.callEvent( "onhighlite", this.l[ this.s.i ], this.s.e.d ) ); };
	p.select = function(){ this.s.i + 1 && ( this.i.value = this.l[ this.s.i ], this.callEvent( "onselect", this.i.value, this.s.e.d ), this.hide() ); };
	p.hide = function(){ ( this.c && this.c.parentNode.removeChild( this.c ), this.c = null, this.l = [], this.s = { e: null, i: -1 }, this.callEvent( "onhide" ) ); };
	p.next = function(){ var e = ( e = this.s.e ) ? e.nextSibling || e.parentNode.firstChild : null; e && this.highlite( e ); };
	p.previous = function(){ var e = ( e = this.s.e ) ? e.previousSibling || e.parentNode.lastChild : null; e && this.highlite( e ); };
	p.handler = function( evt ){
		var o = this, t = evt.type, k = evt.key, e = /span/i.test( ( e = evt.target ).tagName ) ? e.parentNode : e;
		t == "keyup" ? k != 40 && k != 38 && k != 13 && o.show()
		: t == "keydown" ? ( k == 40 && o.next() ) || ( k == 38 && o.previous() )
		: t == "keypress" ? k == 13 && !evt.preventDefault() && o.select()
		: t == "blur" ? o.constructor.fadeAway( o )
		: t == "click" ? o.select()
		: t == "focus" ? o.show()
		: o.highlite( e );
	};
	p.show = function(){
		var cS, found = 0, o = this, i = o.i, iV = i.value, d = document, c = ( o.hide(), o.c = d.body.appendChild( d.createElement( "div" ) ) );
		( c.className = o.n, cS = c.style, cS.display = "none", cS.position = "absolute", o.callEvent( "onshow" ) );
		o.f.call( function( s, x, data ){
			if( !( x.length == undefined ? ( x = [x] ) : x ).length )
				return;
			var j, l = 0, i = o.l.length, e = c.appendChild( d.createElement( "div" ) );
			for( j in ( o.l[i] = s, e.className = "normal", e.d = data, e.listindex = i, !found && i == o.s.i && ++found && o.highlite( e ), x ) )
				e.appendChild( d.createTextNode( s.substring( l, x[j] ) ) ).parentNode.appendChild( d.createElement( "span" ) ).appendChild( d.createTextNode( s.substring( x[j], l = x[j] + iV.length ) ) ).parentNode.className = "selectedText";
			for( x in ( e.appendChild( d.createTextNode( s.substr( l ) ) ), { click: 0, mouseover: 0 } ) )
				addEventListener( e, x, function( e ){ o.handler.call( o, e ); } );
		}, iV );
		if( !c.childNodes.length )
			return o.hide();
		for( var x = i.offsetLeft, y = i.offsetTop + i.offsetHeight; i = i.offsetParent; x += i.offsetLeft, y += i.offsetTop );
		( cS.display = "block", cS.left = x + "px", cS.top = y + "px", !found && o.highlite( c.firstChild ) );
	};
}



Example

<style type="text/css">
/*container da lista*/
.autocomplete{
	cursor: pointer;
	border: 1px solid #999;
	border-top: none;
	background: #eee;
}
/*caracteres que combinaram*/
.autocomplete .selectedText{ font-weight: bold; color: #008; }
/*items não selecionados*/
.autocomplete .normal{ border-top: 1px solid #999; overflow: hidden; white-space: pre; }
/*item selecionado*/
.autocomplete .highlited{ background: #ddf; }
</style>

<form action="">
	<fieldset>
		<legend>Preenchimento dinâmico</legend>
		<label for="list" >Emails</label>
		<input autocomplete="0" type="text" name="list" id="list" />
		<br />
		<label for="ip" >Lista de IPs</label>
		<textarea name="ip" rows="3" cols="20" id="ip"></textarea>
		<br />
	</fieldset>
</form>

<script type="text/javascript">
//<![CDATA[

var list = [ "192.168.0.1", "192.168.0.2", "192.168.0.3", "192.168.1.1", "192.168.1.2", "192.168.1.3", "200.168.0.1", "200.168.0.2", "200.168.0.3", "200.168.1.1", "200.168.1.2", "200.168.1.3" ];
new IncrementalSearch( document.forms[0].ip, function( search ){
	for( var i in list )
		if( !list[i].indexOf( search ) )
			this( list[i], 0 );
}, "autocomplete" );


var names = [ "João Alves <joao@123.com>", "Jonas Raoni Soares Silva <jonas@abc.com>", "Roberto <rob@net.net>", "Maria Fernanda <mariaf@i.tu>" ];

function retrieveNames( search ){
	search = search.toLowerCase();
	for( var i in names ){
		if( search ){
			for( var j = 0, indices = []; j = names[i].toLowerCase().indexOf( search, j ) + 1; indices[indices.length] = j - 1 );
			this( names[i], indices, i );
		}
		else
			this( names[i], 0, i );

	}
}

x = new IncrementalSearch( document.forms[0].list, retrieveNames, "autocomplete" );


//]]>
</script>


« Newer Snippets
Older Snippets »
Showing 1-10 of 11 total  RSS