Archive for the ‘Coding’ Category.

Converting upper/lower case on the command line in Linux

A quick and simple way to convert upper/lower case on the command line in Linux is to use the “tr” (translate) utility.

To convert uppercase to lowercase:

tr [A-Z] [a-z]

To convert lowercase to uppercase:

tr [a-z] [A-Z]

And in a shell script:

VALUE="A Mixed Case String"
UPPER=`echo $VALUE | tr [a-z] [A-Z]`
LOWER=`echo $VALUE | tr [A-Z] [a-z]`

ISO Date/Time in java

took me a while to figure this one out, you’d think getting a standarized date/time would be a bit simpler…

put the following in a class

private final static SimpleDateFormat dateFormat;
static {
    //as per ISO 8601
    dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    //make sure the formatter requires an exact string
    dateFormat.setLenient(false);
    //set "timezone" to Universal Time Coordinates (GMT adjusted by leap seconds)
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}

and the following elsewhere in the class:

//to create a string
String nowString = dateFormat.format(new Date());
//to parse a proper string to a date
Date nowDate = dateFormat.parse(nowString);

Java ActionEvents and ActionListeners

an ActionListener is an interface for receiving action events, a class that should process action events should implement this interface, then be registered with a component.

an ActionListener can be registered with any object capable of it, typically this is an instance of an AbstactButton class like a JButton or JMenuItem.
Continue reading ‘Java ActionEvents and ActionListeners’ »

Pointers and References

declaring the variables:

	int A;
	int *pA;
	int B;
	int *pB;

at this point, A is a container for an integer, and B is a container for a pointer to an integer.

in the body of the code, a “*” can be seen as “the value pointed to by”, and “&” can be seen as “the address of”, as in (using the above delarations):

	A = 100; //directly sets the value of A
	pA = &A; //now pA contains the address of A
	pB = pA; //now pB contains the value of pA, which is the address of A
	B = *pB; //now B contains the value that is pointed to by pB

now both A and Bcontain “100″, and both pA and pB contain the location of A.

 

	cout << "A:  " << A << endl;    //displays value in A
	cout << "B:  " << B << endl;    //displays value in B
	cout << "pA: " << pA << endl;   //displays address in pA
	cout << "pB: " << pB << endl;   //displays address in pB
	cout << "*pA: " << *pA << endl; //displays value pointed to by pA
	cout << "*pB: " << *pB << endl; //displays value pointed to by pB
	cout << endl;

would show something like the following (note that [ADDRESS] would actually be a memory location):

A:  100
B:  100
pA: 0x[ADDRESS]
pB: 0x[ADDRESS]
*pA: 100
*pB: 100

 
at this point, setting the value held by A could be done in any of the following ways:

	A = 200;
	*pA = 200;
	*pB = 200;

*pB can be used to set the value of A because pB contains the address of A.

note that B contains the same value as is in A, but is now independant of it. in the above example, A was set, then pA was set to it’s address, then pB was set to the contents of pA, then B was set the the value pointed to by pB.

Random Content in Wordpress

this example is for WordPress, but the concepts should work fine anywhere.

a quick note, though they are not in the code examples, it is important that the code go between <? and ?> bits. any syntax highlighting editor should make it plain where they are needed.

 

the simplest version of this would be to add the following to your template where you want the random content to show up:

//this line is only needed for PHP versions prior to 4.2
//srand((float) microtime() * 10000000);

$content = array(
	"just some text",
	"some more text",
	"yet more text",
);

$key = array_rand($content);
echo( "<p>" . $content[$key] . "</p>" );

 

to turn this into a function available throughout the theme, add the following to the end of the “functions.php” (it is in your theme folder).
if this file does not exist, you can create it.

//this line is only needed for PHP versions prior to 4.2
//srand((float) microtime() * 10000000);

$content = array(
	"just some text",
	"some more text",
	"yet more text",
);

function get_random_content() {
	global $content;
	if( is_array($content) ) {
		$key = array_rand($content);
		return $content[$key];
	}
	else {
		return "";
	}
}

function echo_random_content() {
	echo( "<p>" . get_random_content() . "</p>" );
}

this will allow you to add the following to any spot in your templates:

<? echo_random_content(); ?>

or better yet, wrap the call in a check:

<? if( function_exists("echo_random_content") ) { echo_random_content(); } ?>

 
 

if you want to extend this idea further, for example into different “databases” of content:

//this line is only needed for PHP versions prior to 4.2
//srand((float) microtime() * 10000000);

$content = array(
	"text" => array(
		"just some text",
		"some more text",
		"yet more text",
	),
	"other" => array(
		"just some other text",
		"some more other text",
		"yet more other text",
	),
);

function get_random_content($from) {
	//this is the default if no "$from" is set
	return get_random_content("text");
}

function get_random_content($from) {
	global $content;
	if( is_array($content) ) {
		if( isset($quote[$from]) ) {
			$key = array_rand($content[$from]);
			return $content[$key][$from];
		else {
			//this is the default if "$from" does not exist
			$key = array_rand($content["text"]);
			return $content[$key]["text"];
		}
	}
	else {
		return "";
	}
}

function echo_random_content() {
	echo( "<p>" . get_random_content() . "</p>" );
}

all that has been added is another dimention to the array, some error checking, and the ability to select the array to draw from.

this version will allow you to add the following to any spot in your templates:

<? echo_random_content(); ?>
<? echo_random_content("text"); ?>
<? echo_random_content("other"); ?>

or even better:

<? if( function_exists("echo_random_content") ) { echo_random_content(); } ?>
<? if( function_exists("echo_random_content") ) { echo_random_content("text"); } ?>
<? if( function_exists("echo_random_content") ) { echo_random_content("other"); } ?>

 

the code still does not check for the possibility of empty or erroneous content, but if you create a variable in echo_random_content() and use it to hold the results of get_random_content(), you can check if it is empty, contains bad characters, swap newlines out for break tags, or whatever else you would like.

JQuery and “Automagic” toggling div tags

inserting the following jquery code in the page:

$(document).ready(function(){
	$("a[name^='pack-']").click(function () {
		var _name = $(this).attr('name');
		//$("div[name='"+_name+"']").slideToggle("slow", function () {
		$("div[name='"+_name+"']").toggle("slow", function () {
			if( $("a[name^='"+_name+"']").text()=='[-]' ) {
				$("a[name^='"+_name+"']").text('[+]');
			}
			else {
				$("a[name^='"+_name+"']").text('[-]');
			}
		});
	});
});

the div will toggle it’s visibility as per the toggle() or slideToggle() methods, and alter the link text used to activate the behavior.

this allows the following simple HTML to be used to enable the jquery element toggling effect.

<span>Title<a name="pack-1">[-]</a></span>
<div name="pack-1">
content content content content content.
</div>

even better, disabling it is as simple as commenting out the chunk in the $(document).ready()), or by not including the javascript at all.

ActionScript based clock

a simple analog clock based on shapes.

download

all the ActionScript is all contained in a single file: Clock.as
this is added into the movie with #include “Clock.as” on the frame level

if there is interest, I’ll rewrite this as an object, add a few more options, and improve the script a bit.

it can be made small
(Either JavaScript is not active or you are using an old version of Adobe Flash Player. Please install the newest Flash Player.)

or large
(Either JavaScript is not active or you are using an old version of Adobe Flash Player. Please install the newest Flash Player.)

Method to get data of a single wordpress post

function get_post_content($id) {
	global $wpdb;
	$query =
		" SELECT ID, post_title, post_excerpt, post_content, post_content_filtered "
		."FROM $wpdb->posts "
		."WHERE ID = '$id'";
	$pages = $wpdb->get_results($query);
	if( ! empty($pages) && isset($pages[0]) ) {
		//echo( 'Title: '.$pages[0]->post_title."\n" );
		//echo( 'ID: '.$pages[0]->ID."\n" );
		return $pages[0]->post_content;
	}
	return '';
}

note that this method does not distinguish between posts that have or have not been published, this allows the content of an unpublished post to be used eleswhere.

a Flash dice roller

a Flash dice roller using custom-rendered virtual dice.
(Either JavaScript is not active or you are using an old version of Adobe Flash Player. Please install the newest Flash Player.)

of course, this could be customized to match a particular sort of roll and style of game.
the next version contains the ability to set all of the attributes from the HTML page, and to send the results back to it’s containing HTML page.

for example, in firewater productions’s game “Chaos University”, the standard is 5 dice:
(Either JavaScript is not active or you are using an old version of Adobe Flash Player. Please install the newest Flash Player.)

Flash loading progress animations

a simple image vewer, mostly put together to test transition effects and loading progress animation.
note: none of the viewers will ever load anything, the xml media list has only one dummy entry (to force it to continuously show the loading progress animation).

a shape based animation

an iconic clock, another shape based animation

a graphic based animation, this uses a single image, an offset, and a mask

a graphic based animation, this rotates a single image

A simple Flash game

a simple flash game thrown together quickly for the sole purpose of testing an ActionScript library.

Example of a Flash application passing data to the containing page

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Quisque sollicitudin accumsan est. Sed volutpat elit ut diam. Mauris placerat placerat sem. Nullam non pede eget tellus adipiscing tempor. Duis ullamcorper. Cras sem justo, lacinia a, tempus vel, facilisis in, dui. Mauris eros erat, ultricies non, mattis nec, pulvinar at, libero. Proin purus. Donec interdum. Nam consequat dui. Ut nec leo. Nulla purus est, rutrum et, pretium ut, lacinia sollicitudin, felis. Nulla facilisi. Aliquam nibh eros, tempor vel, tincidunt eu, luctus id, metus. Praesent pellentesque.
This text is replaced by the Flash movie.

Flash Player and and a Javascript capable browser are requred.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Quisque sollicitudin accumsan est. Sed volutpat elit ut diam. Mauris placerat placerat sem. Nullam non pede eget tellus adipiscing tempor. Duis ullamcorper. Cras sem justo, lacinia a, tempus vel, facilisis in, dui. Mauris eros erat, ultricies non, mattis nec, pulvinar at, libero. Proin purus. Donec interdum. Nam consequat dui. Ut nec leo. Nulla purus est, rutrum et, pretium ut, lacinia sollicitudin, felis. Nulla facilisi. Aliquam nibh eros, tempor vel, tincidunt eu, luctus id, metus. Praesent pellentesque.
This text is replaced by the Flash movie.

Flash Player and and a Javascript capable browser are requred.

Method to draw an ellipse

Notes:
as this method uses a series of lines to construct the curve, a low angular change will result in a smoother curve. however, if a higher value is used, this will construct what appear to be “warped” polygons. for example, an angular change of 45 degrees (Pi/4 rad) will give an eight sided polygon. changing the dx and dy will still result in an elliptical shape.

ActionScript:

with( MovieClip_Object ) {

	//center of ellipse
	var x0 = Stage.width/2;
	var y0 = Stage.height/2;
	//ellipse bounds
	var dx = 300;
	var dy = 100;
	//angular change
	var dn = 1 * (Math.PI/180);

	var r,x,y;
	lineStyle(1, 0x000000);
	for( var n=0; n<2*Math.PI; n+=dn ) {
		x = dx*Math.cos(n);
		y = dy*Math.sin(n);
		moveTo(x0+x,y0+y);
		x = dx*Math.cos(n+dn);
		y = dy*Math.sin(n+dn);
		lineTo(x0+x,y0+y);
	}

}

Bobble Head

A rather silly “bobble head” animation

in this version, the backend bases the force to apply on the number of clicks, it is also possible to base the force applied on the distance the head is dragged, or on length of time the head is clicked.

Simple Trig With ActionScript

angle conversion:

var angle_deg = angle_rad * 180/Math.PI;
var angle_rad = angle_deg * Math.PI/180;

find (x,y) from angle and radius:

var x = radius * cos( angle_rad );
var y = radius * sin( angle_rad );

a minor issue you will come across in ActionScript is that all of trigonometry functions in Math are based on the angle in radians, and a MovieClip’s _rotation property is based on the angle in degrees (this is not a bug or a flaw, but rather a design decision).

so a bit of simple algebra…

using a ratio:

angle_in_degrees/degrees_in_a_rotation = angle_in_radians/radians_in_a_rotation

one full rotation from origin to origin is 360 degrees or 2π radians:

plugged into the ratio:

angle_in_degrees/360 = angle_in_radians/2π

and solving for either variable:

angle_in_degrees/360 = angle_in_radians/2π

( angle_in_degrees/360 ) * 360 = ( angle_in_radians/2π ) * 360

angle_in_degrees = ( angle_in_radians * 360 ) /2π

angle_in_degrees = ( angle_in_radians * 180 ) /π

angle_in_degrees = angle_in_radians*180/π

and

angle_in_radians/2π = angle_in_degrees/360

( angle_in_radians/2π ) * 2π = ( angle_in_degrees/360 ) * 2π

angle_in_radians = ( angle_in_degrees/360 ) * 2π

angle_in_radians = ( angle_in_degrees/180 ) * π

angle_in_radians = angle_in_degrees*π/180

  • Tags

  • Categories

  • Need Code Written?

  • Need a Coding Job?

  • Archives