Skip navigation.

sub Blog

return @entries;

Posts tagged with "code"

Dissecting others' code is so fun

,

These two lines should be more than sufficient to review the code I am looking through right now:
$lollerskates = $db->sql_query($rofl);
if($roflcopter = $db->sql_fetchrow($lollerskates))

Today's tiny and easy but very nice JavaScript.

<form method="post" action="">
<!-- some lines here about something useful //-->
<input type="submit" value="Submit" onclick="if(!confirm('Do you really want to submit?')) return false;" />
</form>


Basically, it asks you with a nice popup box if you really want to submit, and if you press cancel, it will not proceed. Easy, neat and very useful!

My journey to Perl, day 2

,

Preparing for my summer internship, I am reading up on and studying Perl. Today's subject has been Twitter, using the module Net::Twitter, and even though it might have been easy, I have struggled a bit (without success) in regards of OAuth. I will, however try more to get this working as I would like, even with OAuth. In the end, I got tired of
[Tue Apr 21 13:58:28 2009] [error] Missing required parameter 'token' at /usr/lib/perl5/site_perl/5.8.8/Net/OAuth/Message.pm line 74.
so I gave it up. But I still managed to do something. The script can be tried out at http://robert.leep.no/perl/twitter.pl!

Read more...

My journey to Perl, day 1.

,

I've started delving into Perl today. Well, I spent a good share of the day to simply figure out how the heck mod_perl was supposed to work, but after some advice from nicomen, things started rolling, and soon I started digging myself down through the book and, hopefully, the understanding.

My first real WTF about Perl, when using it to improve and dynamicalize web pages, was that I didn't have any way of getting POST and GET (or rather, when the user submits a form with either POST or GET as the method) in the Perl script, as I for instance have in PHP (where I can use the arrays $_POST and $_GET).

Acknowledging this, I found a that I had to read the data from Perl's STDIN, and I found a heavy piece of script that did about this. "Heck, do I have to do this everytime I want some data?", I thought, and started digging through the code.

After fiddling with it at the end of work today, I finally got something working:

sub getPost
{
        my %_POST, $r, @parts;
        %_POST = ();
        read( STDIN, $r, $ENV{ "CONTENT_LENGTH" } );
        @parts = split( /\&/, $r);
        foreach my $p (@parts)
        {
                my($n, $v) = split( /\=/, $p);
                $v = uri_decode($v);
                $_POST{ "$n" } = $v;
        }
        return %_POST;
}


What this code does, is basically that it reads the string submitted by the form (which is of the form a=something&b=somethingelse&c=somethingelseagain). It then splits the string on "&" and then stuffs the entries splitted into an array @parts and iterates through the array of elements that looks like a=something and splits each string on "=" and puts it into the hash %_POST. An example of how it would look with my initial string example would be:
$_POST{"a"} = "something"
$_POST{"b"} = "somethingelse"
$_POST{"c"} = "somethingelseagain"


One question that might arise: What happens if the string contains "=" or "&" or other special characters? It's quite simple really; when submitting the initial form, everything's uri encoded. For instance, "=" will be shown as "%3D".

I then tried to make another script call my initial Perl module (cuddingly named HTTPerl for a poor pun and no laugh), which didn't prove to be an easy task. HTTPerl.pm, the file name of the module, must, apparently, be in one of the folders of Perl's include folders (@INC). However, getting the current folder added to there was no simple task, and I still do not know how I can do that. Apparently, most that asked on other forums stated "Hah, no, you can't", or failed miserably trying to get it working as a workaround.

In either way, I made a test script for today's work, and it's accessible from http://shael.ath.cx/test.html. Below is the entire script in its "glory". I have not included the test.html file since it is merely a form. NB! There's a bug going on for some reason; half of the time the script won't load, giving an "Server Misconfiguration Error", while the other half it runs perfectly. I am puzzled by this, as the log file says that Perl exited with this error:

[Thu Mar 19 21:01:06 2009] [error] "getPost" is not exported by the HTTPerl module\nCan't continue after import errors at /home/robert/public_html/perl/skript.pl line 2\nBEGIN failed--compilation aborted at /home/robert/public_html/perl/skript.pl line 2.\n

Any ideas to why it is like this? I am empty of ideas.

HTTPerl.pm
#!/usr/bin/perl
package HTTPerl;
use base 'Exporter';

our sub getPost
{
        my %_POST, $r, @parts;
        %_POST = ();
        read( STDIN, $r, $ENV{ "CONTENT_LENGTH" } );
        @parts = split( /\&/, $r);
        foreach my $p (@parts)
        {
                my($n, $v) = split( /\=/, $p);
                $v = uri_decode($v);
                $_POST{ "$n" } = $v;
        }
        return %_POST;
}

our @EXPORT_OK = ('getPost');
our @EXPORT = {'getPost');
1;


Skript.pl
#!/usr/bin/perl -I .
use HTTPerl 'getPost';
%_POST = getPost();
print "content-type: text/html\n\n";

print "<html><head><title>Testing the script</title></head>";
print "<style type=\"text/css\">* { font-family: Verdana; font-size: 10px; } h1 { font-size: 16px; }</style>";
print "<body><h1>Using the information</h1>";
printf("<p>Hello %s!<br />You're %d years old and you just said: '%s'.</p>", $_POST{"name"}, $_POST{"age"}, $_POST{"text"});
print "</body></html>";

Summer internship at Opera!

, , , ...

I was in an interview yesterday, and luckily, it turned out well. I was offered a summer internship at Opera Software ASA, where I'd be juggling between the task I currently have here (1 day/week), and 4 days going for QA/Bug fixing at My Opera. As such, I am now delving into the world of Perl, so that I am prepared to start digging through the code.

Since I have quite an experience with PHP, the transaction shouldn't be that tough, but I am still learning myself basic things, such as functions. I've decided to try to recode my homepage into using Perl as its backend, but this has to be a project to be developed over time, as I am getting a Java project at school released about now.

In either way, expect some Perl code to show up in this blog over time. :smile:

Home again!

, , ,

I am back in Oslo! It's good to be come back to Anniken when you've been away for a week! :smile:

Yesterday went quite fast by, and we didn't do much more than to eat and sleep. We watched an episode of Poirot while we ate taco. Yum! And something amazing happened when we were going to bed. As I put my hand around Anniken's tummy, something started moving in there! What a weird and amazing feeling! :D The little one inside is almost 17.5 weeks old, and we're going to an ultrasound the 25th of March. I'm very anxious and eager to know what sex it is, as I haven't fully decided upon liking or disliking names. Well, not entirely true: I've disliked many names that I either don't like or associate with people I don't like. I can't for instance call a girl for Brunhild. It just doesn't seem right.

Today we've played some Lord of the Rings Online. To my disappointment, I have been unable to get it running on Linux, so I have to boot the computer into Windows in order for me to be able to play it. When we got inside the game and go to the North-Downs, I suddenly realized why I stopped playing the game. Everything is too collossal. We played it for about 1.5 hours, and in that time we did like 3 quests. 3 quests. Most of the time went by to explore the greatly oversized area, and with vague expressions such as «To the north west of here lies two graves, explore them», time went into searching, as the area to the north west covered about 10% of the total map. To put it like this: The time it takes to run from one side of the map to the other is about 30 minutes. The width of the field we had to run was about 3 minutes, and the height about the same. We had to run all the way around to find the graves, and that's like 30 minutes of running just there if we were unlucky (which we were!). If my maths aren't entirely wrong, a worst case scenario would be like 3x3x3 minutes, which is 27 minutes. The game is fun to play, but it has its serious flaws. Lastly: All the enemies we slayed during this yielded us 30-40 experience (with rested bonus giving us twice of what we should have). This wouldn't have been much of a problem, if we hadn't needed like 50 000 experience to get to the next level.

Lastly, I've been thinking of redesigning and recoding my homepage. As it is now everything is hard coded, and if I were to change my projects or my curriculum vitae, it takes some extra time. I'll see what the next week brings. :smile:

Learning Python

I've been trying to learn the programming language Python lately, and for greater justice I quote XKCD (which Espen reminded me of):

Closing in on the last exam

, ,

Tomorrow I have my final exam for this semester (and, for that matter, this year). It is in "Programming", which basically is to understand and code in Java. The earlier exams have been mostly about coding various tasks, but this year, of course, they've changed the form of the exam to something else.

In the previous years, they've given exams which allowed us to bring own notes and books regarding the subject, which was quite alright since there are no answers to a programming task, just various methods to do the same (simply put. It may be only one "good" option, but there are many possibilities). This year, however, they're disallowing us to bring books and notes, and instead we have to know it all by ourselves, which isn't any problem, since I know most of the stuff in this course.

What I am afraid of, though, is all the poorly written questions we may be asked. If the mid-term tests were of any relevance, I am feeling gravely for this. I did score 85% and 95% (all errors except one on the first test were just me not thinking straight and the last was poor Java adaptation into the Norwegian language), but I noticed that some of the questions didn't provide any correct answer. For instance, we had a question which was something like:

Which of the following Java code is not valid, and we got about 5 different choices to choose from. All the code was something like for(int i = 0; i < myString.length(); i++), but the problem was that all options were misspelled. Seriously, none of the code given were correct. The code we were given was for(int i = 0; i < myString.lenght(); i++), and even though it's a small error, imagine what they could screw up at something as large as an exam. Unfortunately I could not comment on this, so I pretended that length was spelled correctly and chose the most correct accordingly.

I have been home alone since Friday morning, when Anniken traveled to Skien. I'm going after her tomorrow, and I'm looking very much forward to it. :-)

Project work in "webproject"

,

Web project is one of the courses I am most anxious about getting to work with this year. I feel that the course is a bullseye for what I want to do when I have completed my studies, thus I want to score good at it.

What bothers me most is that the project itself weighs more than the complete product. It means that to score good we have to polish every last bit of documentation and project planning. Furthermore, should we deliver too late on one of the deliveries we are automatically pulled down on grade, something which makes me quite anxious about delivering it on time. And I mean on time. 8:01 is -1 degree.

I sent an e-mail to our teacher to ask whether our approach to the project was OK or not, and it was. This is our current thoughts of the project:

Leep (the name of the project, I'll describe it later on) aims to be a website for technology, much like for instance slashdot. This site, however, will be fetching news from other technology sites, though either RSS or through scanning through the different websites' source codes (given that they have "usable" source codes) and to put them up on our site as links to their sites with an intro and perhaps an image on our site. In addition, we are going to allow for users to register and write news of their own. All news articles will be allowed comments [from registered members].

To make the project run smoothly, we have decided to create a Google Code site for it, in addition to a closed Google Group for internal discussions. To top this, we are planning on running a project development blog at Blogspot. We chose Blogspot since it allows for us to use the same usernames as we use to log into Google Code and Google Groups. Another tool we'll be using is Google Docs, as it easily allows us to work in real time on documents that all have access to.

Leep was originally planned to be an abbreviation for the word "Leep er et prosjekt" (English: Leep is a project), although we might want to change project with portal now, since that's what it'll be. A news portal. I hope that we'll be able to pull this off.

The horror of making layouts in Swing

This week I've been working on a mandatory task in Java Programming. It's quite simple, but I figured I'd make a challenge to it by adding a GUI. I have been working with Java GUI earlier on, but I barely remembered the horrors of how annoying the layout manager can be.

Let's start off with a simple example, and how it usually works.



This is quite simple, it contains a text input box, a button and a label, three quite easy things to stuff into the JPanel.

// ...
JPanel panel = new JPanel(); 
JLabel label = new JLabel(""); 
JTextField text = new JTextField(15);
JButton button = new JButton("Press me!"); 

panel.setLayout(new GridLayout(3, 1)); // A grid with 3 rows, 1 column.
panel.add(text); 
panel.add(button); 
panel.add(label); 
getContentPane().add(panel); 
validate(); // To refresh the frame making changes to it visible


Fair enough, right? Right. But when you are making more complex solutions, things get a much more nasty.

Now I do not say that I am an expert of Java and its GUI functions, but some of the aspects are quite annoying. Nested layouts are very messy. Let's take another example:



JButton button; 
JLabel nc, n, a, p; 
JTextField numbercode, name, amount, price; 
JPanel behind, panel; 

behind = new JPanel(); 
panel = new JPanel(); 

button = new JButton("Display receipt");
button.addActionListener(new Listener()); // I won't add the code for this class

nc = new JLabel("Number code: ");  
n = new JLabel("Name: "); 
a = new JLabel("Amount: ");
p = new JLabel("Price: "); 

numbercode = new JTextField(10); 
name = new JTextField(50);
amount = new JTextField(3); 
price = new JTextField(7); 

behind.setLayout(new GridLayout(2, 1));

panel.setLayout(new GridLayout(4, 2));
panel.setBorder(BorderFactory.createEmptyBorder(30,30,10,30)); // A cute border

// Let the fun begin
panel.add(nc);
panel.add(numbercode);
panel.add(n);
panel.add(name);
panel.add(a);
panel.add(amount);
panel.add(p);
panel.add(price);

behind.add(panel); 
behind.add(knapp); 
getContentPane().add(behind);
validate(); 


Now, I might not have used the best variables (I probably should have used label_ and button_ or such as prefixes for the different element types), but the thing is that it gets quite complexly in the end with even more nested layouts.

I know that there are different layout types, but I found grid to be the easiest. Though grid has some flaws, for instance: If my main window is 200 pixels in height and I have a GridLayout(2,1) for a JTextField and a JButton, I will get a JTextField of 100 pixels in height and a JButton with 100 pixels in height. I miss the possibility to set custom heights of different rows. There are other layout managers offering this, but I do not feel like I want to write 50 lines of code to be able to get this simple layout. A good example of the above scenario is this:



I will continue study this and hopefully figure out to use Swing's layout managers better. It seems I will be stuck with Java for quite some time.

Download Opera, the fastest and most secure browser
November 2009
M T W T F S S
October 2009December 2009
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30