Skip navigation

Category Archives: Programming

I needed to round up to two decimal places for currency (you always round up when using money), but for some reason the internet didn’t want to share that information with me, so here it is.

PHP:

//  Takes a decimal and rounds up (never down)
function round_up($val, $precision) {
  return round($val + pow(10,-$precision-1), $precision);
}

Javascript:

function round_up (val, precision) {
    power = Math.pow (10, precision);
    poweredVal = Math.ceil (val * power);
    result = poweredVal / power;

    return result;
}

So, using round_up (1.432, 1); would return 1.5. For currency you’d want to set the precision (the number of decimal places you want) to two.

I’d like a problem that for once hasn’t already been solved by someone else.

I had a set of markers which needed to be all on screen, and for some reason there’s no .zoomToShow method. Fortunately it’s pretty simple to create yourself.

//  Make an array of the LatLng's of the markers you want to show
var LatLngList = array (new google.maps.LatLng (52.537,-2.061), new google.maps.LatLng (52.564,-2.017));
//  Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds ();
//  Go through each...
for (var i = 0, LtLgLen = LatLngList.count(); i < LtLgLen; i++) {
  //  And increase the bounds to take this point
  bounds.extend (LatLngList[i]);
}
//  Fit these bounds to the map
map.fitBounds (bounds);

And that’s pretty much it. Then, of course, I found that someone had already done this before, but for version two of the API.

After lurking in #javascript for a while I noticed that a lot of the developers there look down on people using jQuery and Prototype. Their view is that you’re just getting one step away from the actual language, and you’re leaving key programming skills behind.

I acknowledge that that’s true, but I don’t see why it matters. All languages are essentially frameworks of a lower level language. PHP is basically a framework for a load of C libraries. C is just a framework for assembly code. Assembly is just a framework for binary programming. Yes, by using PHP you lose a lot of functionality of C, but that’s just because PHP is filling a market with no need for hardware manipulation and the like.

Same with jQuery. If you use $.get() you lose the ability to do the request synchronously (I’m aware that you could just use $.ajax(), but I’m making a point), which isn’t really a big loss to most people when compared to the benefits.

Javascript isn’t exactly the most uniform language around, which IE not supporting half the stuff Opera does, and Safari doing things differently to Firefox it’s a really hard language to code for. You spend more of your time finding work-arounds for each browser than actual logic. The frameworks available all do that for you, making sure that there’re no compatibility issues between browsers, and that $(‘#element’).slideUp() does exactly the same on every browser.

I’d go as far as to say don’t even bother learning about document.getElementById means. It’s so clumsy and awkward when compared to $().

Due to those functionality additions though it’s obviously a little bit slower. I’ve not noticed any speed decrease, but in an “every microsecond counts” environment there would be a noticable difference. But Javascript engines are getting faster and faster so does it really matter? The average person doesn’t even notice a difference.

It’s just programming evolution. It happens to every language. I wouldn’t be surprised if a few forward thinking browsers decided to just store a copy of the latest framework versions locally, so they’re instantly available to every website without having to download the same file hundreds of times from different servers.

I was looking up information about the resolution of Game Boy Colour, and found it to be a few different sizes depending on what version you own. But I don’t remember playing any games on a 640 x 350 screen. The smallest resolution available is 160 x 140 which may have made more sense, but I was still unsure.

Ah, I remember it well.

Ah, I remember it well.

I decided to look around my house to find my Game Boy and my Link’s Awakening cartridge so I could just count the pixels, but apparently my sister is holding them hostage somewhere. I had to settle for a screen shot and found the image to the right.

That’s pretty much how I remember it, to scale and everything. But the resolution of 320 x 288 doesn’t fit any of the resolutions for any figures I can find. And even then each pseudo-pixel is 4 x 4.

That must mean that developers were able to set the resolution they wanted to work with, and the Game Boy just scaled it up or down to fit the screen.

Come to think of it, that makes absolute sense, being as we don’t have four different versions of the game for four different consoles. Although, I’m not exactly sure how at the moment, since by just looking at the numbers I can’t see how they’d all factor to the same scale. Maybe some games just have a border around them. I can’t remember that though.

I’m pretty sure my body doesn’t work on a 24 hour day cycle. I went to bed around 2300 two nights ago, and got up around seven. Though I’d been lying in bed awake, trying to sleep for much longer. I say I got about five or six hours sleep that night. I went to bed at ten tonight, and was awake by two. I feel I could stay awake until tonight now. I’m not tired or anything. Maybe so little sleep has just become a habit.

My sleep schedule isn’t why I’m here.

I’m doing some tests with the canvas element, and decided to make a class for it. You can see it over at the GBCanvas github I set up for it. (I’ve never used github. Just heard a lot about it.) The code is kinda broken at the moment though.

The class is based on the idea of pseudo-pixels, where you have a 300×300 canvas, and can set it to have ten rows and twelve columns. Then you can manipulate each of those segments, which I’ve decided to call pixels. The “GB” comes from Gameboy, because I figured it’d be cool to remake Zelda with canvas.

I want to add an edit mode so the user could do something like

$(document).ready (function () {
  var canvas = new gbCanvas ('canvasid1');
  canvas.editModeOn (true);
});

Which would allow clicking of a pixel and it fills it with a chosen colour. I  mostly want this feature so I can create pixel art, and then get the raw data:image/png data, which I can import into the project whenever. I’m aware I could just create sprites in Paint or something and import the file, but I don’t want to. I’m fond of imposing restrictions stubbornly unto myself.

After a few rethinks, I figured it would be fair simple to just bind a click event to the canvas

//  Turns on edit mode so onclicks are registered and bubbled
this.editModeOn = function (mode) {
  if (mode) {
    //  .click is a jquery thing
    this.canvasDiv.click (this.editModeClick);
  }
}

And then working out which pixel was clicked, and filling it with colour

  this.editModeClick = function (event) {
  //  getSelectPoint just returns an array with the X and Y coord of the click
  //  relative to the top left of the image (to avoid problems with scrolling)
  clickPoints = getSelectionPoint (event, this.canvasID);
  console.log (clickPoints);
  //  Work out which "pixel" they just clicked
  var coordWidth = parseInt (clickPoints[0] / pixelWidth);
  var coordLength = parseInt (clickPoints[1] / pixelHeight);
  console.log (coordWidth + ', ' + coordLength);
  this.colourPixel (coordWidth, corrdLength);
}

This doesn’t seem to work because the event is rarely passed. It is sometimes, but hardly ever. The function is bound correctly. It’s entirely a problem with the event being passed – something I’ve always had trouble with if I’m honest…

Update: Ladies and gents, do yourself a favour and check all your variables before you go bitching on your blog about your code not working. The event was being passed fine. The problem with my code is that since it’s a function that’s being bound to an event, it effectively loses it’s place in the instance of the class, so it no longer has access to the this variable.

My problem was that this.cavasID was undefined.

So, I fix that by simply passing it “this”. Changing the bound event function to something like this:

this.editModeClick = function (event, _this) {
  console.log (event);
  console.log (_this);
  clickPoints = getSelectionPoint (event, _this.canvasID);
  console.log (clickPoints);
  //  Work out which "pixel" they just clicked
  var coordWidth = parseInt (clickPoints[0] / _this.pixelWidth);
  var coordLength = parseInt (clickPoints[1] / _this.pixelHeight);
  console.log (coordWidth + ', ' + coordLength);
  _this.colourPixel (coordWidth, corrdLength);
}

That’s all well and good, but now I’m confused as to how to bind it…

this.canvasDiv.click (this.editModeClick (event, this));

The event needs to be the first argument, but I’ve no idea how to pass the event here… That obviously doesn’t work (event is undeclared).

Edit: Of course it was something ridiculously simple.

var self = this;
this.canvasDiv.click (function (event) { self.editModeClick (event, self) } );

Check me out being awake before lunch time, five hours in fact. I’ve not seen the morning where the sun isn’t totally glaring in a while. I had egg in bread! I propose this shall be a good day.

I decided to come update here because it’s mine to update, even if I have nothing to say. And because I have nothing else to do till nine o’clock, when I want to start work. I’ve not decided what work I want to do though. I do have two “you really should get these done” projects though – a secret one, and a WordPress landing page – so probably those first.

I decided to do a night project (in which I see how far into a project I can do in one night), and I got my facebook people to give me the idea for it. Ended up being “porn”, so I started making a porn reddit. To be honest though, after an hour I got distracted by Alias or Greek or some other show and only got a bit done, but I still plan on continuing it.

As always, tonnes of other ideas. Mostly being stopped by my not spending enough time with OAuth though.

I’ve not really updated this blog in a while because I’ve been lazy. I’ve really improved on my politics which I really could write  about. I figured I’ll actually start vlogging, from my YouTube account, and I’ll embed the videos here. I make a lot of political arguments on reddit too, and at some point I’ll link to some of my important ones. Although, they mostly get downmodded.

These are things I do know (though I don’t understand public/private keys), but since I’m having problems with signing OAuth requests, I figured I’d brain dump my knowledge, filling in any gaps with research and hoping that I’ll understand why my signing isn’t working. If nothing, I’ll have a blog post about encryption to help people. I’ll mostly be talking about encryption to do with OAuth though.

If you’d rather hear about this from someone that knows what they’re talking about, rather than someone who’s building up their knowledge as a lone wolf and possibly going in the wrong direction, then you’ll want this post on security architecture.

OAuth wants to let one website access a user’s private data on another website, using HTTP. That basically means that all requests are made through URLs (either which get parameters, or through post data). That kind of data can be snooped on by malicious people through a man in the middle attack where the data can actually be changed before being sent to the server, or someone could just store it by watching wireless communication, or if you have a virus on your computer/router/access point which is relaying traffic to someone.

For instance, a customer could click the URL:

http://www.orderadrink.com/drink_order.php?drink=tea&customerid=1234

But then an attacker could see the request, and before it gets to the server where the order would be processed, they could change it to:

http://www.orderadrink.com/drink_order.php?drink=coffee&customerid=1234

And then the customer gets coffee for some reason unknown to them… OAuth fixes that problem by hashing the parameters with a salt (passphrase) that only the consumer (the person sending the request) and the service provider (the person receiving the request) knows. For instance, when I signed up for a developer API account with Google they gave me a phrase that I keep secret. Only Google and I know it.

For instance, the consumer and service provider could both decide that they want to do rot13 on all the parameters. So we take “drink=coffee&customerid=1234” and rot13 it making “qevax%3Dgrn%26phfgbzrevq%3D1234″ (we need to do a urlencode() on it too, since it’s a GET parameter). Then we send this URL to make our order:

http://www.orderadrink.com/drink_order.php?drink=tea&customerid=1234&hashed=qevax%3Dgrn%26phfgbzrevq%3D1234

Now, if the hacker decided to change “tea” to “coffee”, orderadrink.com would notice because the parameters no longer match the hashed version, so they wouldn’t allow the action to happen.

Any hacker worth is salt (pun unintended) would immediately notice that that’s just rot13 and would change the hash accordingly. So we use a more sophisticated method of scrambling the parameters. One of those methods offered by OAuth is HMAC-SHA1.

This encrypts the data you give it using a sort of cypher. Damn near impossible to guess, or even to work out. Whilst, it’s not impossible to crack, it’s rarely worth the cracker’s CPU time (which could take years if we’re lucky). So I send the parameters hashed using HMAC-SHA1, using the secret phrase Google gave me, and they just decrypt it to check if the values match up.

I was planning on doing public/private key explanation too, but I really don’t understand it… I’ll go and do more research and maybe do another post on it. I think that’s the problem I’m running into with OAuth; I’ve chosen the signature method that is “more complex and requires key generation and a longer learning curve”. That’ll show me for jumping in at the deep end. I’ll just work with HMAC-SHA1 for a while, which I do understand.

Blogs were first made as soap boxes so allow me to get up on mine and moan for a little bit.

I’ve been trying to figure out OAuth, so I can use the YouTube API on a project I’m working on. It’s had a fair bit of coverage too; it was talked about at i/o last year, twitter has made it fairly popular, and so a lot of others have joined in too. It doesn’t look like it has much of a developer community though… The freenode room has 13 people in it, compared to #linux, #wordpress or #php’s usually maxed out rooms.

Because of the apparent lack of individual interest though, I’ve literally been able to count the number of resources I’ve seen on one hand. There’s this developer’s guide by Google, the oauth spec, there’s some code examples and a library – but I wouldn’t really say they’re for new comers to this scene, and then there’s a pretty comprehensive documentation.

I’ve not really been helped much by any of that, though.

I was mostly just told to use the library to do what I needed, but there’s not much documentation, and the examples given aren’t really explained. Maybe I’m just not as smart as I need to be… And I think that’s what annoys me so much. I’ve really tried hard – and it’s not like I’m a help vampire or anything – I’ve actually put a lot of work in before asking in the #oauth channel. I’ve read, and reread, that spec, but I’m still a littlelot confused.

I wrote a function to nab a request token (pastebin link should stick around for a month – it’s broken anyway, you’re not missing much if you don’t get to see it), which essentially creates a URL. But that’s not correct. I was just told to use the library but I don’t even know where to start with it…

I’m not complaining about the current work that’s being done; I think it’s awesome that the current developers are working on it and at least some people are benefiting. I really don’t mean to be offended anyone. I guess I just felt like moaning; the entry barrier to this stuff just feels too high.

Sigh.

Ages ago I was trying to find a cool start page which I could set for my homepage; I’d grown bored of Reader because it stopped me going to other websites. I stuck with /r/funny for a while before switching to the Onion. Ultimately they weren’t giving me what I wanted, so I decided to make my own.

So I made this RSS quilt type thing, and it’s pretty perfect for me at the moment. By default it uses data from the combined RSS feeds of Reddit, BBC, the Guardian, and Ars so it’s a pretty nice pool of information for me. It only shows the headlines too, and that’s all wanted. Putting the body of the articles on would take up way too much space.

Dark items are newer items, whilst lighter items are older. Eventually they get so old they’re barely visible – but you can mouse over them to see it clearly again. Not that I’d want to, if it’s that old I’ve probably already read it. It checks for updates to the feeds every four minutes too, and then inserts them nicely into the page (in an element that you can see, so it’s not inserting elements at the bottom of the page where you won’t notice). It adds new elements in italics too, just to make them extra prominent.

Article order is always randomised

You can change the feed by clicking the modulo symbol in the navigation bar. You’ve got to put the actual RSS feed URL into that though. You can also nab the bookmarklette (click the question mark in the navigation bar) and that will hopefully find the RSS feed for the website you’re looking at when you click it.

Using it in full screen mode is cool. 100% filled with information, pretty much.

Not quite finished yet though, still a couple extra things I want to add: some option (without adding more text to the page) to say “I’m tired of seeing this story, get rid of it” and have that data locally stored in the browser. If the article is a picture post, or at least has a prominent picture in it, then show the picture rather than the headline. Add options to change the gradient from black to lighter to other colours. Dynamically insert an entire new feed (this shouldn’t be that hard, just need to rejig some logic around).

Follow

Get every new post delivered to your Inbox.