Archive for Uncategorized

Ext Js 4: Merging store data

In a project I’ve been working on I needed to get a bunch of different stores of data and then have a separate store that would contain all of them combined. This was to save on ajax calls. I couldn’t find anything as far as native methods that would merge stores but I did come up with a solution.

var emptyArr = [];
 
var aggregatedStore = new Ext.data.ArrayStore({
		data: emptyArr,	
		fields: [{name: 'field1'},{name: 'field2'}]
	});
var singularStore = new Ext.data.JsonStore({
		autoload:true,
		proxy: {
			type: 'ajax',
			url: '/getDataPlease',
			reader: {
				type: 'json',
				root: 'fieldRoot'
			}
		},
		fields: [{name: 'field1'},{name: 'field2'}]
 
	});

So what I want to do here is push the contents of singularStore into aggregatedStore. What I ended up doing is adding a listener on singularStore load to accomplish this:

var emptyArr = [];
 
var aggregatedStore = new Ext.data.ArrayStore({
		data: emptyArr,	
		fields: [{name: 'field1'},{name: 'field2'}]
	});
var singularStore = new Ext.data.JsonStore({
		autoload:true,
		proxy: {
			type: 'ajax',
			url: '/getDataPlease',
			reader: {
				type: 'json',
				root: 'fieldRoot'
			}
		},
		fields: [{name: 'field1'},{name: 'field2'}],
                listeners: {
			'load': function(store, records, successful) {
				aggregatedStore.loadData(records,true);
			}
		}
 
	});

Now I can use singularStore to get just the data from that url. I can then add that load listener to any other store and use aggregatedStore to show the combined data.

How do I use traits in PHP 5.4

The biggest change in PHP 5.4 is the addition of traits to the object-oriented programmability. Traits prevent code duplication by allowing multiple classes to include a collection of methods implemented as a trait. This means multiple classes can include the same method implementations without duplicating code.

Traits improve on interfaces because they include not only the function definition, but also the implementation. Traits can also use other traits, meaning that one trait could be a collection of others. So, if you had traits Roll and Bounce, you could have trait Movements that used both Roll and Bounce.

trait HelloWorld {
    public function sayHello() {
        echo 'Hello ';
    }
 
    public function sayWorld() {
        echo 'World!';
    }
}
 
class MyClass {
    use HelloWorld;
    public function sayHelloWorld() {
        $this->sayhello();
        $this->sayWorld();
    }
}
 
$h = new MyClass();
$h->sayHelloWorld();      // outputs "Hello World!"

In implementing traits, the keywords trait and insteadof were added to PHP. Usage of trait is outlined above. The PHP keyword insteadof is used for conflict resolution. Here’s an example of how to use insteadof:

trait A {
    public function smallTalk() {
        echo 'a';
    }
    public function bigTalk() {
        echo 'A';
    }
}
 
trait B {
    public function smallTalk() {
        echo 'b';
    }
    public function bigTalk() {
        echo 'B';
    }
}
 
class Talker {
    use A, B {
        B::smallTalk insteadof A;
        A::bigTalk insteadof B;
    }
}
 
class Aliased_Talker {
    use A, B {
        B::smallTalk insteadof A;
        A::bigTalk insteadof B;
        B::bigTalk as talk;
    }
}

How to Fix Text Links in the iPhone-Slide Plugin

On a previous post I told you all about this amazing plugin I found that would create a slider that takes advantage of the iPad’s touch and drag functionality.

However, if you didn’t use it just for images and had the slides contain text, you may have noticed that the links within the slides would not work. This plugin appears as it was mainly created to swipe through images, and not necessarily for content with text links.

I went into the plugin (jquery.iphone-slide.js) and changed a few things so it would do my bidding:

OLD CODE:

helpers.goto_url(thislink);

NEW CODE:

var thislink = $(event.target).parent("a").attr("href");
if(!thislink){var thislink = $(event.target).attr("href");}
if(thislink){
   window.location(thislink); //similar behavior as clicking on a link
}

Turns out the __mouseup function was preventing the default action and the “helpers.goto_url” function only opened image links. But now it’s set up to do everything, Cheers!

Simple CSS gradient

CSS has continued to simplify common design operations and CSS3 doesn’t show any signs of that trend changing. Gradients, which have been around for awhile now have commonly replaced the old way of creating custom images for a couple quick css lines of code.

.orange-gradient
{
background: #f78d1d; /* initial background for default */
background: -webkit-gradient(linear, left top, left bottom, from(#faa51a), to(#f47a20)); /*Webkit Chrome/Safari etc.. */
background: -moz-linear-gradient(top,  #faa51a,  #f47a20); /*mozilla*/
filter:  progid:DXImageTransform.Microsoft.gradient(startColorstr='#faa51a', endColorstr='#f47a20'); /* IE */
}

This would make a great orange gradient for a background. Another great trick is to reverse the gradient on hover

.orange-gradient:hover
{
background: -webkit-gradient(linear, left top, left bottom, from(#f47a20), to(#faa51a));
background: -moz-linear-gradient(top,  #f47a20,  #faa51a);
filter:  progid:DXImageTransform.Microsoft.gradient(startColorstr='#f47a20', endColorstr='#faa51a');
}

Add this class to a button or link, add some padding and you have a quick and great-looking button.

Creating a simple jQuery slide-down login form

jQuery can really add some great touches to a website and one that is easy to do is a slide-down form.

<div id ="login_container"> 
<a href="#" onClick="openForm()">Login</a>
<div id="login_form">
<form action="" method="post" name="form1">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="pword" /><br />
<input type="submit"  /><br />
</form>
</div>

Obviously we want to initially hide the form and display it on the “Login” link:

#login_container
{
    position:absolute;
    top:100px;
    left:300px;
}
#login_form
{
    display:none;
    background:#FFFFFF;
}

There is a very important part lying in that CSS and that is the container needs to be absolutely positioned. Otherwise it will push all other block elements down when the form flies open.

Finally, we need the jQuery to make it all happen

function openForm()
{
	 if ($("#login_form").is(":hidden")){
              $("#login_form").slideDown("slow");
	}
	else{
		$("#login_form").slideUp("slow");
	}
}

Now you have a great UI component that gives a user access to the login form at anytime but doesn’t clog up the design.

How Do I Add Data to a Spark DataGrid in Flex Mobile?

When coding for mobile developments in flex (Flash Builder), I had a hard time populating the dataGrid element because it doesn’t use arrayCollections like lists do.  The data source is actually bounded to the IList data type.  An example of setting it up is listed below.

<s:Application
    <fx:Script>
        import mx.collections.IList;
        [Bindable] public var dataGrid:IList = new ArrayList([
            {firstName: "John", lastName: "Doe", phone: "1231231234", email: "test@test.com"},
	    // ... whichever variable names in the DataGrid
        ]);
    </fx:Script>
    <s:DataGrid id="dataGrid" dataProvider="{dataGrid}" width="100%" height="100%">
        <s:columns>
            <s:ArrayList>
		<s:GridColumn dataField="firstName"/>
		<s:GridColumn dataField="lastName"/>
		<s:GridColumn dataField="phone"/>
		<s:GridColumn dataField="email"/>
            </s:ArrayList>
        </s:columns>
    </s:DataGrid>
</s:Application>

This DataGrid example has a column per property( GridColumn) and dataField attribute is used to select the dataProvider object property to display in that column.  The dataProvider is  a list of the object properties that are defined in the dataGrid (firstname, lastname,phone, email) and their values for that row.

Project Euler Problem 17

I’ve been having some fun doing the first few problems of Project Euler and figured I’d share my solution to problem 17 here.

The Problem
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.

If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?

NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of “and” when writing out numbers is in compliance with British usage.

The Solution
The reason I love this solution is I found a PHP library that writes out these numbers for you. It comes from PECL 1.0 and is part of PHP 5.3 via that NumberFormatter class. This class did most of the work for me.

<?
$res = "";
 
$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
 
for($i = 1; $i format($i));
	if($i > 100 && $i % 100 != 0) {
		$res .= 'and';
	}
}
echo strlen($res)."\n";

My first submission was incorrect and I quickly figured out it was because the NumberFormatter class was missing the “and” after the hundreds. I simply added that at the end since we’re only looking for a count and came up with the correct result.

Installing the NumberFormatter class in Debian squeeze was pretty easy. I simply had to install the PHP5 international compatibility package: sudo apt-get instal php5-intl

How do I perform integer division in PHP

PHP’s division operator returns a floating point result from the division operator unless both operands are integers and they are evenly divisible (the result is an integer). I was recently working on Project Euler Problem 13 and needed to do integer division, something I haven’t come across in PHP before.

Integer division in PHP is pretty straight forward. Casting the result as an integer will yield an integer. That is:

var_dump(25/7);         // float(3.5714285714286) 
var_dump((int) (25/7)); // int(3)
var_dump(round(25/7));  // float(4)

Project Euler Problem 10

I’ve been having some fun doing the first few problems of Project Euler and figured I’d share my solution to problem 10 here.

The Problem
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.

The Solution
My solution is fairly simple, testing primality for all the numbers below 2,000,000. If prime, adding them to a running total.

/**
 * Calculate the sum of all the primes below two million. 
 **/
#include 
#include 
using namespace std;
 
bool isPrime(long num) {
	if(num<=1)
		return false;
	for(long i=2; i<=sqrt(num*1.0); i++)
	{
		if(num%i==0)
			return false;
	}
	return true;
}
 
int main () {
	long upperlimit = 2000000, sum = 0;
 
	for (long i = 2; i < upperlimit; i++) {
		if(isPrime(i)) {
			sum += i;
			cout << "Prime found: " << i << endl;
		}
	}
 
	cout << "The sum of primes below " << upperlimit << " is " << sum << endl;
 
	return (0);
}

The interesting part of this problem for me was I updated my primality test to include the fact that if a number n has a factor greater than sqrt(n) it must also have one less than sqrt(n), so we only have to test up to sqrt(n) in our primality test:

bool isPrime(long num) {
	if(num<=1)
		return false;
	for(long i=2; i<=sqrt(num*1.0); i++)
	{
		if(num%i==0)
			return false;
	}
	return true;
}

Project Euler Problem 9

I’ve been having some fun doing the first few problems of Project Euler and figured I’d share my solution to problem 9 here.

The Problem
A Pythagorean triplet is a set of three natural numbers, a b c, for which,a^2 + b^2 = c^2
There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.

The Solution
This is pretty basic and inefficient, but I decided to loop through a and b, calculating c from the difference.

#include 
using namespace std;
 
int main () {
 
        for(int a = 1; a < 1000; a++) {
                for(int b = 1; b < 1000; b++) {
                        cout << "a: " << a << " b: " << b << " c: " << (1000 - a - b) << " a^2 + b^2: " << (a * a + b * b) << " c^2: " << (1000 - a - b) * (1000 - a - b) << endl;
                        if(a * a + b * b == (1000 - a - b) * (1000 - a - b)) {
                                return (0);
                        }
                }
        }
        return (0);
}

There you have it, the program stops at a^2 + b^2 = c^2 where c = (1000 – a – b). I then took a*b*c to get the answer.