Monday, 28 September 2015

Holy Radical Randomizers, Batman!

Hey, good morning.

Just a little technical snippet which, as usual, may or may not be useful. However, I believe most seasoned programmers already have something like that in their arsenal.

In previous web tutorials such as The Ngerng Effect and The Random Quote Google Gadget, I used a line of code to generate random numbers. It worked. But it was hellishly difficult to read. And that kind of gets in the way if you're trying to explain a concept.

What we need to do here is make a function for it. I'm going to demonstrate this using JavaScript first. The line for creating a random number is, according to W3Schools:
Math.floor((Math.random() * x)+y)

x is the maximum number you wish to generate, and y is the minimum.

So if we make a function like so...
function generaterandomno(x,y)
{
    return Math.floor((Math.random() * y)+x);
}

Now I can just call a random number without all the technical mumbo-jumbo. Here, I use JavaScript  to create a varianble randomno and assign a random value between 1 to 100 using the generaterandomno() function.
var randomno=generaterandomno(1,100);

However, this formula is flawed. It's perfect if the value of x is 1 or 0, meaning, you only want to generate a random number with a minimum value of 1 or 0, like a random number from 0 to 100, or 1 to 100. Anything greater than 1, and the formula falls flat.

Thus, if you want a random number from, say, 10 to 100, what you really should be doing is generating a number from 0 to 90, and then adding 10 to the result.

Which also means the formula is more like this.
Math.floor((Math.random() * (x-y+1))+y)

The additional +1 is supposed to compensate for the Math.floor() function, which rounds down. Math.random() gets a number between 0 and 1, which is a floating point. And Math.floor() turns the result into an integer.

Note that this probably doesn't handle cases where the value of x and/or y is a negative number. And until I have a reason to find out, we're not going there.

In other languages...

The principle is similar, though the quirks vary from language to language. Generally, the older langugaes seem to have the problem outlined above while newer languages simply get that out of the way.

In, PHP, this is how I'd do it. That's because PHP already kindly provides just such a function. Apparently someone in the open-source community decided to simplify the process.
$randomno=rand(1,100);

In C/C++
int generaterandomno(int x, int y)
{
    srand (time(NULL));
    return (rand() % (y-x+1)) + x;
}

int randomno=generaterandomno(1,100);

In Java (sans import utility and class notations)
public int generaterandomno(int x, int y)
{
     Random rnd= new Random();
     return rand.nextInt(y - x + 1) + x;
}

int randomno=generaterandomno(1,100);

In C# (sans import utility and class notations)
public int generaterandomno(int x, int y)
{
    Random rnd = new Random();
    return rnd.Next(x,y);
}

int randomno=generaterandomno(1,100);

In ASP
function generaterandomno(x,y)
    Randomize
    generaterandomno = Int((rnd*(y-x+1)))+x
end function

Dim randomno=generaterandomno(1,10)

In QBasic
FUNCTION generaterandomno(x AS SINGLE,yAS SINGLE)
    RANDOMIZE TIMER
    generaterandomno = INT(RND * (y-x+1)) + x
END FUNCTION

DIM randomnogeneraterandomno(1,10)

There it is, a list of randomizer functions in some of the languages I remember. A useful list if I ever need to generate random effects.

y still confused? Didn't I x-plain it well enough? (heh heh)
T___T

Tuesday, 22 September 2015

Self-checking September: GE 2015 from one Web Developer's perspective

September 11th, 2015 - The 2015 Singapore General Elections came and went, with the People's Action Party winning big at the polls. In the aftermath, I've had time to indulge in a bit of reflection...

Whoa, cowboy! This isn't a political blog! 

Well of course it isn't. What I'm about to say is tech related, or at least work related. Bear with me.

It's no secret that I'm not a huge fan of the PAP. In particular, I despise their grovelling fanboys, but that's another tale for another day.

One of my pet peeves this election has been Emeritus Senior Minister Goh Chok Tong (who, for the remainder of this blogpost, simply be referred to as ESM Goh). I'm aware of his not-inconsiderable contributions to our Nation, and fully acknowledge them. However, I could not quite shake the impression that ESM Goh did not want to defend his ward Marine Parade, and even resented the fact that citizens would be given the chance to vote him out. In fact, he appeared disdainful of the need to justify his near-silence in Parliament over the last term. Some quotable quotes below.

"I spoke up once, but once was enough. It was impactful. That's all I need to say." - ESM Goh Chok Tong

"For many years, the PAP was the only party in Parliament. Had the PAP gone corrupt in those years? Until the 2011 election, there were very few opposition MPs in Parliament. Had the PAP let the people down? We are our own checks, the integrity of our leaders and our MPs… not this seductive lie of check and balance." - ESM Goh Chok Tong

The latter, incidentally, was referenced in a speech by Mr Pritam Singh of the Worker's Party. "Ownself Check Ownself", since then, has become quite a catchphrase, often used mockingly, among Opposition sympathizers.

My thoughts regarding ESM Goh went along the lines of - dude, you've done a lot for our country and all, but you're not above the law. You've got to respect our democratic process. What's with the attitude?

A week later, I had my answer. The elections being over, I thought about it some more and remembered an episode from my misspent youth.

It was 2008. I had quit drinking and quit my job because a friend needed a programmer on his rather ambitious web project. I threw myself into my work day and night, committing uncountable hours of sweat and toil to this endeavor. It was my baby. I built the system from ground up. It was a labor of love. 


Yep. A labor of love.
Brick by fuckin' brick, baby.

That's when my buddy-turned-boss began to annoy me. It started small. I would submit a layout proposal and he would then hail one of our mutual friends to take a look and give some critique. My what-in-the-blue-hell-are-you-thinking expression was barely contained. My boss enthusiastically explained that he just wanted more feedback from different sources - the more the merrier, right?

Suuuure, mate. How about you hire him to do the work and I just come in and critique? The more the merrier, right?

And then one evening while I was tinkering with the system as usual, a stranger sauntered into the office. My boss introduced him as a friend of a friend, and said he had asked him to take a look at our product and see if he had any insight to share. The stranger swaggered around a bit, smiled at me and said "well, remember the system documentation, OK? Documentation's very important."

OMG really?! Thanks so
much for telling me. I
totally  wouldn't have
guessed.


No shit, Sherlock.

I seriously considered introducing my keyboard to his smug condescending face, but... well. It was a good keyboard. Besides, it wasn't really his fault. The one truly responsible for my annoyance was my clueless jackass of a boss right there. He had really thought that any free professional advice was a steal, especially since he wasn't the one doing the work. Buddy, you smell that? I just farted. It's free, too.

(Editor's Note: Honestly, to all the clueless jackass bosses out there, if you truly want quality professional consultation, that shit doesn't come cheap. The free stuff is something anyone, me included, could just pull out of his arse. Remember, you heard it here first. You're welcome, jackasses!)

Yes, technically I was an employee and my role was to deliver and get paid. My feelings didn't matter. Technically, more feedback from various sources is a good thing. But emotionally... well, I was invested in the system. And to simply grab any Tom, Dick or Harry, an outsider with no stake in what I was doing, to tell me how I should work? That felt utterly disrespectful.

Is this story starting to sound familiar yet?

I'm willing to admit my thoughts and feelings weren't very professional then. Perhaps I simply needed to step back, look at the big picture and keep my developer's ego in check. But how can I feel so vehemently about this, and at the same time feel so strongly that Opposition representation is needed in Parliament? OK, perhaps it's ridiculous of me to even attempt to equate one web project with the lifelong task of Nation-building. But still... if I could feel so strongly regarding a web project I'd been involved with for months, how would ESM Goh feel about some unknown upstarts butting into a project he'd been involved with for most of his life?

Boggles the mind. I guess this makes me a huge hypocrite, doesn't it?

Were voters simply being insensitive to his feelings? Or does ESM Goh need to step back, look at the big picture and keep his ego in check?

I honestly don't know. There's never an easy answer, is there?

The fairest thing I can say is, if you've poured your heart and soul into something and interference is encountered, a certain amount of angst is par for the course. But external appraisal is all part of due process. And at some point, we're going to have to accept it.

Till next time, go easy on the self-checking. Too much self-checking can cause blindness.
T___T

Thursday, 17 September 2015

Your AJAX Starter Kit (Part 2/2)

All right! You have the front-end HTML and the back-end PHP script. Now it's time to unite them.

Use this code. Place it in the ajax_frontend() function of your HTML file.

ajax_test.html
        function ajax_frontend()
        {
            var xmlhttp;
            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }

            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    var backendresponse=xmlhttp.responseText;
                    document.getElementById("ajax_placeholder").innerHTML=backendresponse;           
                }
            }

            xmlhttp.open("POST","ajax_backend.php",true);
            xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xmlhttp.send("user=teochewthunder");
        }


The code first creates an object, the XMLHttpRequest object which we will name xmlhttp. Different methods have been used for cross-browser compatibility.

So we use the open() method to query the server. In it, we specify the method to be a POST, and the URL of the back-end script. GET works as well, but POST is usually the more versatile option.

The method setRequestHeader() specifies more properties of the back-end script, and lets the server know what kind of content it's expecting. There are more variations on this, but this will do for your starter kit.

And then there's the send() method which sends the value(s) over to the back-end script.

After that, it asynchronously listens for a response from the server  using the property onreadystatechange and status. These properties change every time there's a response to the listener.

For more on these properties, follow this link. (http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp)

readyState has to be 4 (meaning "Done") and status has to be 200 (meaning "OK") before the script can progress further. Once the all-clear is given, the output of ajax_backend.php will be sent through the responseText property. And that's when I put the data in a variable named backendresponse (rename as you see fit) and assign it to the innerHTML property of the ajax_placeholder div.

If your script works, this is what you should see upon running your HTML file from the server.



Is this it?

Hell no, this isn't it! But it will do for a start. There are many variations on this theme. For instance, you may be using multiple asynchronous calls to populate different named divs in your HTML file, obtaining data from multiple back-end scripts.

There's tons you can achieve with this simple and unassuming piece of code. Save this somewhere in your personal code depository. You'll copy and paste this as your basic AJAX building block in your web applications, and expand on it when required. In fact, I did exactly that for the CAPTCHA web tutorial.

Have lots of fun with this!

All clear? Got any queries? By all means, send() them over.
T___T





Monday, 14 September 2015

Your AJAX Starter Kit (Part 1/2)

AJAX stands for Asynchronous JavaScript And XML, and is a technology that marries the front-end capabilities of JavaScript with the back-end code of other scripting languages such as PHP, C# and ASP.

For more on AJAX. follow this link. (https://en.wikipedia.org/wiki/Ajax_%28programming%29)

There's plenty you can do with AJAX. With it, you can make your web application perform like a desktop application, eliminating (or at least suppressing) many of the limitations of traditional web applications.

What I'd like to do here today is assemble an AJAX Starter Kit - basic components of AJAX that a web developer can use to make his very first AJAX-driven application. What we need is the following:

- A HTML placeholder for content.
- A back-end script for producing said content. (Example will be in PHP)
- JavaScript to combine the HTML with the back-end script.

Bear in mind that everything here is a bare-bones example. Your AJAX code would ideally be more complicated than this, otherwise you wouldn't really need AJAX, would you? These are just the building blocks. They're meant for you to expand on. There is actually a lot more to AJAX than what I'm about to show you. But as a start, well, you could do worse.

Here's the HTML.

ajax_test.html
<!DOCTYPE html>
<html>
    <head>
        <title>AJAX Starter Kit</title>
        <script>
            function ajax_frontend()
            {

            }
        </script>
    </head>
    <body onload="ajax_frontend();">
        <div id="ajax_placeholder" style="border:1px solid #000000;width:200px;height:100px;">

        </div>
    </body>
</html>


Here, I've set the function ajax_frontend() to fire off when the body loads. Feel free to change the name of the function, or set it to fire off on some other event such as a button click.

The div with an id of ajax_placeholder is exactly what it says - this div is a placeholder for your ajax-driven content. Again, feel free to change the id of this div.

This is what the front-end looks like when run on your browser.



And here's the back-end.

ajax_backend.php
<?php

if (isset($_POST["user"]))
{
    echo  $_POST["user"] . " says ";
}

echo "Hello, world!";
?>


This may seem overly simplistic. "Hello, world"? Really? But bear in mind that this is just an example. You could make your back-end script access a database for records or perform some calculations. The end result is, the text output of your code should appear in the ajax_placeholder div.

This is what your output should look like when you run it from the server.


Because there's nothing posted to the script, it says only "Hello World". Later, your AJAX code will send a value for your back-end script to use.

Easy so far?

Of course, this is just a front-end file and a back-end file. The whole point is to link them together. And that's the part that bears close examination.

Next

The AJAX call.


Wednesday, 9 September 2015

Web Tutorial: The HTML5 Placeholder Effect

Howdy.

Today I'm going to take you on a trip down memory lane, to a time before HTML5. In particular, we're going to explore the placeholder attribute, which was introduced by HTML5.

What does it do? 

Glad you asked! When added to a text field, it displays the specified text in greyed-out font, by default, as a hint. The concept of placeholder text is not new, but it used to involve more. Let me show you what I mean. Let's look at the HTML here. Does it have a placeholder attribute?
<!DOCTYPE html>
<html>
    <head>
        <title>HTML5 Placeholder</title>
    </head>
    <body>
        <input id="txtSearch" maxlength="50" value="search" placeholder="search" >
        <input type="button" value="Go" >
    </body>
</html>

Now, when you run the page, it shows a search textbox with a button (which, for the purpose of this tutorial, does nothing but look pretty. Kind of like Kim Kardashian). Click on the textbox and the word "search" disappears. When you fill in the text, it's in black. When you click elsewhere, if there's text in the box, it remains black. If there's no text, the word "search" appears again and goes grey.


The time before HTML5 

Now I'm going to show you what developers did before HTML5 introduced this useful little attribute. Use the same HTML, but leave out the placeholder attribute. Instead, add a class and call it notext. Add the styles as well, in the head tag. By default, the txtSearch text box is styled as noclass. It will only be styled as textentered when you, well, enter text.
<!DOCTYPE html>
<html>
    <head>
        <title>HTML5 Placeholder</title>

        <style>
        .notext {color:#999999;}
        .textentered {color:#000000;}
        </style>
    </head>
    <body>
        <input id="txtSearch" maxlength="50" class="notext" value="search">
        <input type="button" value="Go" >
    </body>
</html>

Add the onfocus and onblur events. On either, you will call the same function, but with a different argument.

More on the onfocus event. (http://www.w3schools.com/jsref/event_onfocus.asp)
More on the onblur event. (http://www.w3schools.com/jsref/event_onblur.asp)

<!DOCTYPE html>
<html>
    <head>
        <title>HTML5 Placeholder</title>

        <style>
        .notext {color:#999999;}
        .textentered {color:#000000;}
        </style>
    </head>
    <body>
        <input id="txtSearch" maxlength="50" class="notext" value="search" onfocus="tt_placeholder(1);" onblur="tt_placeholder(0);" >
        <input type="button" value="Go" >
    </body>
</html>

Now add the tt_placeholder() function.
    <head>
        <title>HTML5 Placeholder</title>

        <style>
        .notext {color:#999999;}
        .textentered {color:#000000;}
        </style>

        <script>
        function tt_placeholder(varfocus)
        {
            var searchbox=document.getElementById("txtSearch");

            if (varfocus==1)
            {
                if (searchbox.className=="notext")
                {
                    searchbox.value="";
                    searchbox.className="textentered";
                }
            }
            else
            {
                if (searchbox.value=="")
                {
                    searchbox.value="search";
                    searchbox.className="notext";
                }
            }
        }
        </script>

    </head>

We'll use a nested If-else block for this. First, grab txtSearch as an object.

Then check if the argument entered in the function is 1 or 0. It's 1 if txtSearch is focused, and 0 if not.

If txtSearch is focused and the class is notext (meaning no text has been entered yet), the word "search" disappears.

Try it!


Also, the class is changed to textentered and any text you enter will be in black.


The code checks if any text has been entered. If so, it leaves well enough alone. But if not, it reverts to its original state, with the value "search" in the text box, in greyed font. Check it out! Clear the text in the textbox and click somewhere else!


How is this useful?

It ain't. Most browsers now render the placeholder attribute quite handily. This is just to give you an appreciation of how much code you save typing every time you use the placeholder attribute. One of the driving maxims behind HTML5 is "less code, more markup". This has led to one of the most frequently-used pieces of code ever, being encapsulated into a HTML attribute for your convenience.

All clear? Don't be blur. Focus!
T___T

Saturday, 5 September 2015

App Review: Agent Alice

A month ago, I downloaded Agent Alice, a mobile game from Wooga. It's one of their offerings from the "Hidden Object" genre, playable on Android and iOS.


What's special about Agent Alice, anyway? To be honest, very little. You click around the screen to find hidden objects. There's no time limit - you simply get more points if you solve the puzzle faster.

In other words, at its core, just like most other games of that genre.

The Premise

The protagonist, Agent Alice, is an investigator with ESP. She gets drawn into cases of a supernatural slant, where her psychic abilities come in useful. At the start of every scene, there's a mission brief followed by the good ol' Treasure Hunt.



The Aesthetics

Gorgeous. Absolutely gorgeous. The art department outdid itself there. The scenes are beautiful (though they get rather cluttered at the higher levels due to the sheer amount of objects you have to find), and the characters are very quaintly rendered.


Alice, in particular, is one smoking hot babe.


The Experience

Solving the puzzles net you rewards such as Action Points (you use these to play the hidden object puzzles), Stars (used for advancing the plot and playing other mini puzzles) and Cash (spent when the game asks you to wait for an allotted amount of time and you don't feel like waiting).



There is no way to lose in this game. Making incorrect decisions simply wastes Stars, which you can earn back anyway.



The Interface

It's pretty much a no-brainer. Right off the bat, you know where everything is and it takes very little deliberation to figure out where to touch next. Simplicity at its best.

What I liked

The art, of course. I can't emphasize this enough. For what amounts to just another mobile game, a great deal of effort was put into art direction.

The storyline isn't bad either. Just enough to keep me engaged, but not so addictive that I feel compelled to spend money just to find out what happens next.

Agent Alice is great for casual gaming. No consequences for failure, rewards for success... it doesn't get any more casual than this. Makes no demands on your time whatsoever. You can leave the game for as long as you like, and be ready to pick up again when you decide to resume playing.

The mini-puzzles are a mixed bag. Some of the mini-puzzles deserve a special mention. They add to the game. Others, not so much.

Jigsaw puzzles - always fun.
Mini shooting game sequence.
Nicely done. Good timing required.
Mix-and-match. Far 
trickier than it looks.
A memory-combination thing.
Simple, yet fun.
This one's a fresh challenge.
manipulate the pieces to find a clear
path from Point A to Point B.

What I didn't

Replay value isn't great. Gets repetitive after a while. Then again, that's pretty much a given considering its genre, and the fact that it is a plot-driven game.

Some of the mini-puzzles are just a little too simple. Seriously, they shouldn't even have bothered with those. The objective of these mini-puzzles is mostly to see how fast you can touch or swipe repeatedly, and reward you with Action Points based on that. It's just a little trite.

Rotate all the tiles to form the
correct image. Lots of fast tapping.
Swipe the screen repeatedly till the
grime is cleared off. Really?
A variation on the above. Swipe
till fingerprints are revealed.
then tap and hold.

Also, the waiting times. There are times the game makes you wait for hours, days even, unless you have Cash (or spend actual money to buy Cash). But I suppose the designers need some way to make money off this game.

Conclusion

Worth a download, if you don't want a game you have to obsess over and spend a lot of time playing. And also if you're a sucker for good hand-painted graphics.

My Rating

6.5 / 10

Have a go at Agent Alice, and tell me how you find it. (hur hur)
T___T