Friday, January 30, 2009

Getting uTorrent to work on Windows 7

I'm loving Windows 7 (beta build 7000). It's fast, stable, and feature packed. I know the retail version will be butter.

That's not to say there aren't some quirks though. The good news is that Windows 7 seems to do a (much) better job than Vista at helping you solve your problems (I've successfully fixed all of reported issues, like the common MSI installer errors, using Solution Center).

Now, I recently got a new router (D-Link DIR-628 Wireless N) which works GREAT. I just tried to do some torrenting using uTorrent though, and the dreaded yellow-light in uTorrent indicating a connection problem came on.

No problem, right? I went into my router's interface and forwarded the port (click here for details on how - it's simple and something everyone who uses a router should know how to do). It didn't work though! What!? I didn't have this issue 2 days ago before I switched routers...hmmm.

Well, this is the quickest solution ever. It turns out that this combination of a router and Windows 7 is the only time I've seen the Windows Firewall actually block the port's traffic! Just disable your Windows Firewall (go to your control panel to do it) and you're good to go.

Figured I'd save someone 10-minutes of time if possible.

Thursday, January 29, 2009

EOTD -- 1.29.2009

It's about time for another Epic of the Day.

Today's is another song; Misty Edwards - You Won't Relent, from the ablum Relentless.

Normally, I can't get too into Misty's music (definitely talented, but the style is often too monotone and/or repetitive... it's hard to describe), but this track and at least one other from the same album is MASSIVELY EPIC.

There's something to be said about a well-executed crescendo of tension, militant drumming merged with epic rock, solid dark chord progression, beastly guitar riffs, and of course epic lyrics that describe God's relentless pursuit of men (and there is NONE more epic than God).

Enjoy. And go cop that album!


Thanks to J.Demchack for the track!

Construction Kick-Off

At the start of what is sure to be a super-packed, incredibly awesome year(s) of construction for God's Kingdom and His church (especially here at Healing Streams WWC), I've been busy doing some construction myself.

I got some new hardware and gadgets that are cool enough to merit a rearrange of the my work area, plus there was some ceiling mounting that needed to happen. Needless to say, Fry's Electronics and Home Depot got hit up by me several times without shame. The end result is great though. AND I got an excuse to bust out the power-drill, stud-finder, and zip-ties.

Ahhh, man moments.

This is the year it all begins - the greatest move of God in history, full of an epic revival, awakening, building, tearing-down (the enemy of course), and EPICNESS for days. Trust me, it's not rhetoric.

Thursday, January 22, 2009

Free at last

Free at last. Free at last! Thank God Almighty! I'm free at last!

Friday, January 16, 2009

Validate a Youtube URL for PHP and Javascript

I like the idea of posting random small useful things here, if only to help someone else along the way for whatever purpose. I think I'll do it more often if I can.

Here's a quick, but useful code snippet.

I'm working on a project that uses the Youtube API and I relies on a user to input a Youtube video URL, plus grab the video ID of that video from the URL.

Of course, since you don't want a user inputting a malformed address, it's necessary to validate that it is proper - ideally both on client-side for quick feedback, and on server-side for extra security.

The functions below use regular expressions to validate a youtube URL and returns the results in the form of an array.

PHP Example:
/*FUNCTION: validate_youtube_url
Returns: array(valid URI:Boolean, Error Message or Video ID:String, match results:Array)
*/

function validate_youtube_url($str, $protocol = '(http://)|(http://www.)|(www.)'){ // Default to requiring http://, http://www., or www. prefix

$protocol = str_replace('.', '\.', str_replace('/', '\/', $protocol)); // escape those reg exp characters
$protocol = ($protocol != '') ? '^(' . $protocol . ')' : $protocol; //if empty arg passed, let it it match anything at beginning
$match_str = '/' . $protocol . 'youtube\.com\/(.+)(v=.+)/'; //build the match string
preg_match($match_str, $str, $matches); // find the matches and put them in $matches variable
if(count($matches) < 3){ //No matter what protocol/prefix, we should have at least 3 matches
return array(false, 'Invalid URI', $matches); //bad URI
}else{ //so far so good....
$qs = explode('&',$matches[count($matches)-1]); //the last match will be the querystring - split them at amperstands
$vid = false; //default the video ID to false
for($i=0; $i<count($qs); $i++){ //loop through the params
$x = explode('=', $qs[$i]); //split at = to find key/value pairs
if($x[0] == 'v' && $x[1]){ //if the param is 'v', and it has a value associated, we want it
$vid = $x[1]; // set the video id to the val
return array(true, $vid, $matches);
}else{
return array(false, 'Missing ID', $matches); //invalid querystring - couldn't find the video ID
}
}
return array(false, false, false); //everything went wrong....ouch
}
}
$u = validate_youtube_url('http://youtube.com/watch?v=_ZSbC09qgLI&feature=rec-HM-rev-rn');
echo $u[1];
Javascript Example:
/*FUNCTION: validate_youtube_url
Returns: array(valid URI:Boolean, Error Message or Video ID:String, match results:Array)
*/

function validate_youtube_url(str, protocol){
if(!protocol && protocol != ''){
protocol = '(http://)|(http://www.)|(www.)';
}
protocol = protocol.replace(/\//g, '\/', protocol).replace(/\./g, '\.');
protocol = (protocol != '') ? '^(' + protocol + ')' : protocol;
match_exp = new RegExp(protocol + 'youtube\.com\/(.+)(v=.+)', 'gi');
var matches = match_exp.exec(str);
if(matches.length < 3){
return Array(false, 'Invalid URI', matches);
}else{
var qs = matches[matches.length-1].split('&');
var vid = false;
for(i=0; i<qs.length; i++){
var x = qs[i].split('=');
if(x[0] == 'v' && x[1]){
vid = x[1];
return Array(true, vid, matches);
}else{
return Array(false, 'Missing ID', matches);
}
}
return Array(false, false, false);
}
}
var u = validate_youtube_url('http://youtube.com/watch?v=_ZSbC09qgLI&feature=rec-HM-rev-rn');
alert(u[1]);

Thursday, January 15, 2009

'Wake up, Joshua.' I'm up.

Lately, God has been talking to me a lot about 'waking up'. Not necessarily as in an early morning rise from slumber, but more like the 'Wake up, Neo' Matrix type of arousal. The references and reminders have been everywhere for the last week or two (it seemed to be the focus of tonight's prayer hour at church as well).

I was at a mini-get-together with a few friends from high school at my friend's mentor's house on Saturday. I hadn't seen the mentor and his wife in a while and we started having some small talk conversation. You know how that goes; ease in with simple questions, bear some awkward silence and head-nods, then re-attempt the strike-up with a '...Sooo, how has...' phrase. Good times. They're great people though and it doesn't take long to get past that. Anyway, in the process someone asked me 'What do you like to do in your spare time?'. Easy question. No problem. I should be able to answer this one and keep moving the conversation along.

Not quite. I opened my mouth to answer and then it shut. I tried again, and looked around like an idiot, but still no words. At this point, my brain clicked on and had a conversation aloud with me. 'Hmm, good question. What exactly do I like to do in my spare time anymore? In fact, what spare time? Heellllooooo...? Is there anyone with a life here?'. How have I spent my time?

Allow me to articulate the situation:

It's as if large chunks of my life, years, are just densely fogged hazes reflecting memories of autonomous motions. As if I were sleep-walking and not fully aware of life. The realization of these ambiguous blocks often results in a sobering gaze of nostalgia, frustration, and remorse; wondering why and how time has passed by so effortlessly and without bearing more fruit.

Ah, but God in His sovereignty... He revealed to me the source of the problem two months ago: Sin. Wait! Before you think this is going cliche, keep reading. I believe you'll be enlightened.

See, I've learned that sin {definition}, while seemingly unpunished in the immediate, is a slow-stabbing, waterboarding, coma-inducing assassin. Over time, it forms cataracts and drains light from your eyes, causing them to grow dim. Your life and all of its potential slows to a crawl and congeals. Everything becomes normalized, with no thing outweighing another, as if a glacier traveled the course of your priorities and desires. Illusions and slight-of-hand become the norm, inevitably fooling you to believe that down is up, up is down, precious metals are dirty coal, and dung is a fine-meal. You fall asleep. It's a deceptively peaceful euphoria that makes time and the rewards of enduring its tests escape from you; they run with a gait measuring days, weeks, months, and years. And since you decided to drive your own life rather than let the {real} Architect take the wheel, you could easily follow the tangent of any one of life's dangerous curves and plummet off of a cliff. Sin steals your gifts and talents, shelving them and packing them away with lies for labels to devalue them. It perverts efforts of good into selfish ambitions that exemplify Romans 7:15-25. Your time, talents and treasures - everything meant for service to God and given as gifts from The Same - rot until you are left barren.

In my case, I had spent so much time of my life in sin that the realities of this fatal sleep were all too common. The natural response is to make futile attempts at righting yourself. Isolating yourself from certain people, coming up with routines to keep you on track, making oaths to yourself and/or God {be careful!}. Even non-Christians do it. Just take one look at the New Year and all the resolutions and promises it brings. Of course, it's been my observation that the majority of those solutions and promises derail quite quickly.

If you haven't noticed this effect in your own life, look closer. Closer. Keep going. Zoom and enhance. Interpolate non-existant pixel data from a low resolution image to show the face of the cluprit, just like an episode of CSI. Now do you see it? Yeah, I told you - it's a quiet ninja indeed. So what's the solution? How do we wake up? Paul answers that in Romans 7 as well.
"What a wretched man I am! Who will rescue me from this body of death? Thanks be to God—through Jesus Christ our Lord!
So then, I myself in my mind am a slave to God's law, but in the sinful nature a slave to the law of sin." Romans 7:24-25
Some may think this is a weak answer. Others may argue that they have tried Jesus, with all they have, but it didn't work. I can say that many times I tried to seek God wholeheartedly but still continually failed to escape sin. Oh, but that's the beauty of it all. To those that argue the answer is weak, the Bible clearly states that God uses weak things to shame the strong. To those that argue they tried already to no avail, the Bible clearly states that this race we are on isn't a sprint for the swift or strong, but life is about enduring to the end.

If you seek God, His Kingdom, and His righteousness without ceasing, He'll give you a wake up call, draw back the curtains, brew the coffee, turn on the music, full-hand slap your bare-back, toss you in the shower, and wake you up! Re-read that Romans 7 scripture above. Similar to the Matrix, He will 'free your mind'. And while your body may still be bound to a fallen world where deception and lawlessness abound, He gives you both the desire and the power to do what pleases Him.

That wake-up call can be a number of things. For me, it was a true experience of God disciplining me a couple months ago, causing me to lose the trust, friendship, and possibilities thereof of someone dear to me. For others, it may be a close-call, sudden epiphany, or whatever. However it comes, it's up to you to catch it and wake up! You have to respond to the blinking green cursor on the screen. And I'm betting you'd be surprised just how many wake-up calls He sends us...every day. I've learned that you shouldn't be bitter with God for His discipline, but rather, thank Him for loving you enough to do it!

As for me - I'm awake now. That's no boast in myself. No. There are so many things God has done for me that I simply can't take credit for even if I tried. I do boast in Christ's complete work for me, though. And that's what I know empowers me to accomplish every desire, dream, and vision He's given.

Strange? Possibly. Long blog entry? Definitely. But I've learned, especially in the last 2 months, to trust God's dealings with me. If He wants to use the Matrix as a learning tool, by all means - I'm so glad He talks with me at all!

My cataracts are gone. Hindsight isn't the only thing in 20/20 anymore. Every day gets better. Efficiency goes through the roof. Opportunities aren't overlooked or mishandled. Skills are perfected. Favor is lavished. I'm up. Praise God.
"I'm somewhere in the future, and I look much better than I look right now."

Monday, January 12, 2009

AJAX proxy using PHP and cURL

I'm in the middle of making a useful javascript-based web-app that needs to get some data from a well-known web-service that uses the REST API. The ideal way to get the data (in my case, some XML) is to use AJAX. Simple enough, right? Of course not.

Since the request URL is on a different domain (or sub-domain), the AJAX HTTPrequest object will throw the angering error 'Access to restricted URI denied' code: 1012. Which basically translates to "Sorry. You can't access remote data from any location outside of your current domain". It's a necessary security feature in browsers, but a sometimes frustrating problem for developing mash-ups or other web-apps.

Now, there are of course workarounds for this problem without using AJAX:
  1. You can use dynamic script tags and place them in the 'head' element of your document (created programmatically with javascript, preferrably by directly manipulating the DOM) and set the 'src' attribute to the remote URL. In the case that you are loading XML, you should also set the 'type' attribute of your script tag to 'text/xml' so you can immediately access the XML object via javascript. Check out iFormattable's blog entry or Mark McLaren's Weblog entry for more info on this solution.

    This generally works just fine for most people, except when the URL is too long for the browser, or if the parameters passed need to be POST rather than GET. The problem I ran into with it is that I wanted to have access to the 'innerHTML' of that script tag to play around with the contents, but since it's not directly accessible to the Document Object Model (to the best of my knowledge), I couldn't.... stubborness, I know, but still... Ahhhhhh!!!!

  2. You can perform the request using Flash or some other environment with its own security sandbox and spit the data back out to javascript using the Flash ExternalInterface command (or FScommand and getURL for older versions of Flash player). The process would look something like this:

    • Embed the Flash object in your HTML (static or dynamic, doesn't matter)
    • Create a javascript function that calls the ExternalInterface of the Flash object (or setVariable for older versions - not recommended) to trigger an event listener or fire a function in Flash and pass the remote URL and parameters
    • Flash does its thing with the urlRequest object and retrieves the data
    • The callback function for the completion of that urlRequest then calls the ExternalInterface again and sends the data back to javascript.

    The benefit to this is that Flash allows cross-domain requests as long as the remote server has a crossdomain.xml file set up. Also, it doesn't require any server-side language or setup on your part (platform independent). The problem, obviously, is that it is completely unreasonable and inelegant from a programming standpoint, plus it requires both javascript to be enabled and Flash to be installed, which is generally OK but still more exclusive than AJAX alone.

    Of course, if this was packaged in an easy to use zip file bundled with a javascript class and some well-tested, lightweight libraries like SWFobject and Mootools or jQuery....hmmmmmm.

  3. You could set up a server-side script to be a proxy for retrieving the data. This is the method I chose since it's easy, concise, and 'elegant'.
I figure I should post the code here. It uses PHP and the cURL library. Also, the javascript is based on the Mootools 1.2 framework, but it could be any other framework or regular old DOM references.

PHP code (file named 'remote_proxy.php' or whatever somewhere on your server):
$post_string = http_build_query($_POST);
$c = curl_init();
$url = $_GET['url'];
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c,CURLOPT_POSTFIELDS,$post_string);
$src = curl_exec($c);
curl_close($c);
echo $src;

Javascript code
function ajax_it(url, urlparams){
var time_qs = 'randtime=' + $time(); //Random time to keep fresh
var params = '';
for(i in urlparams){ //Loop through the pairs in urlparams object to create the POST string + escape the values
params += i + '=' + escape(urlparams[i]) + '&';
}
var ajax_result = new Request({ //do the AJAX request
url: 'http://yourserver.com/remote_script.php?url=' + escape(url),
method: 'post',
onComplete: function(response){
alert(response); //alert the response from the proxy
}
}).send(params);
}

ajax_it('http://someremoteserver.com/api/rest/', {param1:value1, param2:value2}); //Call it

See? Simple, clean, and on useful for multiple projects. Hopefully it will help someone somewhere with something. Let me know if it helps, or if you have any other solutions.

Now, about that option number 2....

Thursday, January 1, 2009

Kingdom Manifest

It's a new year!

Ah, 2009 - you are destined to contain incredible and epic events and blessings for me. Ah-ah-ah...shhhh....don't argue..you don't have a choice when God says so. That's right. Submit. That's better :-)

You know, God has been good to me, and it's always getting better. The theme for the year at Healing Streams and for the body of Christ: Kingdom Manifest.

Manifest: readily perceived by the senses and especially by the sight

Get ready - it's happening whether you like it or not ;-)