Saturday, December 29, 2007

Identifying Hardware

CPU Architecture


Installing Gentoo Linux reminds me that there are times when a GNU/Linux user can benefit from knowing the details of their hardware. uname is a great command to accomplish this.

$ uname -a # a for all information
Linux livecd 2.6.19-gentoo-r5 #1 SMP Thu Apr 5 15:05:48 UTC 2007 i686 Intel(R) Celeron(R) Celeron(R) CPU 2.93GHz GenuineIntel GNU/Linux


Here, uname tells us that a LiveCD is running with Linux kernel version 2.6.19-gentoo-r5. It's compiled for i686 multiprocessor systems. The processor in use is a Intel Celeron and it's clocked at 2.93GHz.

PCI Bus


Another great command for learning about your hardware is lspci. If your Linux kernel isn't using some of the hardware on your computer, you may find that lspci won't list any details about those certain pieces of hardware, however. Here's an example of it in use:

# lspci -v
00:00.0 Host bridge: ATI Technologies Inc R200 AGP Bridge [Mobility Radeon 7000 IGP] (rev 05)
Flags: bus master, 66MHz, medium devsel, latency 64
Memory at b0000000 (32-bit, prefetchable) [size=64M]
Memory at b4000000 (32-bit, prefetchable) [size=4K]
Capabilities: [a0] AGP version 2.0


For brevity, I've only included the first piece of hardware found on the PCI bus. We can also list the hardware in a tree, which is great for seeing what pieces run through various busses.

# lspci -tv

The -v switch just makes the output a little more verbose.

Tuesday, December 25, 2007

Searching

Finding Files with an Index


Linux provides an easy way to create an index of files for fast future searching. updatedb would have been used in the past, and still can be, but a newer implementation just uses it as an alias to call slocate with a switch. What's slocate? It stands for secure locate and is like the original locate command, which searches through the index for a given file, except that it doesn't list files that one has no permission to view.

# slocate -u # update file index

Once the file index is up to date, one can find any given file quickly using the following command.

$ slocate filename # locate any file with filename in its name

You may wish to review the man page for slocate as well because this command supports things like case insensitive search and regular expressions!

Finding Files without an Index


But what if we don't have an index of which to search through for the desired files? We can still use the find command. Here's an example:

$ find / -iname filename

Here, find is instructed to start searching at the root of the file tree for files with the name of filename, while ignoring their case.

Binary Files


whereis is a great command for locating binary files that are stored in a standard path. For example, if we want to find where the ls command is:

$ whereis ls
ls: /bin/ls /usr/share/man/man1/ls.1.gz


This tells us that the ls command has the path of /bin and the man pages are located in /usr/share/man/man1/ls.1.gz.

Finding Commands


There are times when one may wish to find a suitable program for a given task. For example, I may wish to find commands that deal with searching.

$ apropos search
apropos (1) - search the manual page names and descriptions
badblocks (8) - search a device for bad blocks
bzegrep (1) - search possibly bzip2 compressed files for a regular expression


Here apropos shows us that apropos itself, badblocks, and bzegrep can be used to search for different types of things. Remember, if you install new programs with new man pages, be sure to run mandb to update the list that apropos searches through.

Sunday, December 23, 2007

Linux I/O Redirection


Redirection with Files


Let's get started with a few simple examples of redirection:

command > filename # Redirect command's output to a new or overwritten file
command < filename # Use filename's contents as standard input for command


The first command would overwrite an existing file. So what if we want to only append command's output to a file?

command >> filename # Append command's output to filename

If you're a C++ programmer, you can remember the difference between this and the first output redirection command by recalling that C++ uses the >> operator to add to a stream, not replace it.

Speaking of C++, it uses three main streams:
stdin: 0
stdout: 1
stderr: 2

If we want to save standard error to a file, we can:

command 2> error_output

We could do the same with standard output, or even redirect standard error to standard output:

command 2>&1

And that's the basics of using I/O redirection with files. What if we want to send the output of one command to another as it's input? Linux allows us to do this using pipes.

Pipes


We can pipe the output of one command into the input of another:

first_command | second_command

We could even create a named pipe that delivers one command's output to another as input. The cool thing about named pipes is that they allow programs in different terminals and among different users to communicate. As Linux treats named pipes as ordinary files, we can even set their permissions!

mkfifo name_of_pipe # create a named pipe
command > name_of_pipe # direct output to named pipe as if it's a file
command < name_of_pipe # accept input from named pipe; can be done as different user


Now you have the basics of redirection with files and pipes! Have a nice day :)

Thursday, December 20, 2007

C++ Reference
Who's sick of always having to think about C++ syntax instead of getting into the flow of coding an idea? I am, so I put a reference sheet together. If you'd like a copy please feel free to email me at my full name in lower case and without spaces at gmail (dot) com.

Wednesday, December 19, 2007


Hero of Allacrost: Engine Overview

Until today, I would have had to shamefully admit that I a have barely considered another person's code beside my own. I'm not talking about example code. Rather, I'm referring to looking at another person or group's large-scale program and attempting to figure out how they structured it at a high level. If you haven't done this yourself, I can say from my my recent experience that it's an eye opener for considering different ways of doing things. Most importantly it allows one to see how a successful program is designed.

Today I'll be reviewing Hero of Allacrost. It's an up and coming C++ RPG in the Open Source world. Although it's not a full game as of yet, a tech demo has been released and the team is well on it's way to expanding it into a full story-driven game.

Originally when I had decided to look into how an RPG game engine was designed, I thought it would require slogging through code multiple times in a chaotic attempt to understand the engine's structure. Thanks to the work by some easy to understand authors gaining insight into their engine turned out to be rather painless, much to my relief.

Allacrost makes extensive use of the singleton design pattern. The defining point of singleton classes is that they can only be instantiated once. Attempting to instantiate them again common returns a pointer to the already instantiated instance. Allacrost has audio, video, scripting, input, global, mode, and system singletons, among others. They are instantiated in main.cpp so that whatever uses them later on doesn't have to worry about setting them up. One can pretty much guess what these singleton's do, based on their names, except for the mode singleton, which leads us to the next defining point of the Allacrost engine.

Allacrost uses a concept of game modes. Example modes include map exploration, battling, shopping, paused gameplay, the menu screen, and even quit confirmation. Multiple modes can exist at the same time on a stack, with the mode at the top being the one that the game actually runs. Each mode requires three functions:
  • Reset(): Prepares a mode, which has just reached the top of the mode stack, for use again.
  • Update(): Allows a mode to do its processing.
  • Draw(): Draws a mode.
The real power of modes is evident in the idea that the engine can be expanded to include new modes in the future.

Speaking of updating a mode, Allacrost uses time-based movement as opposed to fixed movement. This allows the game to take advantage of fast computers while at least running on older computers. From reading the Allacrost Quick Start Guide, I learned that the sleep function, which would be required with fixed movement on fast computers, has a varying accuracy across different operating systems. Besides any modern operating system will divide processing power between the running processes. Allacrost still makes use of the sleep function while in pause mode due to it's low use of the processor.

The input singleton accepts input from a keyboard or joystick and provides it to the rest of the engine in a queue of commands, such as move up. Each command has three accessors: pressed, released, and state. A command is pressed during the first main loop iteration that it is detected in. Released is similar. That leaves state, which is only true if the button triggering a given command is currently down.

The audio singleton makes use of the OpenAL and Ogg Vorbis libraries. It treats sound and music similarly, but distinctly and with differing features. While one song can play at a time, there may be a number of sound effects in use at once. To keep things simple, as all programs that are actually completed must, Allacrost refers to music and sound files by filename, excluding path and extension. All music files are stored in a single directory, while sound files are stored in another. There are no category folders for audio beyond that. Audio can be played, paused, stopped, and unloaded, among other things.

Next up, we have the video singleton. OpenGL is used for graphics, DevIL for images, and SDL_ttf for fonts. One common problem game programmers face is what the heck to do with different screen resolutions. Is a game's difficulty balanced really balanced when you can see more of the map just because you are using a higher screen resolution than someone else. Allacrost gets around this by dividing the screen with a coordinate system. The video singleton has a function that allows the programmer to choose the coordinate system, so for example, the screen can be 32 arbitrary units across and 24 arbitrary units high. The Allacrost team uses this to ease tile placement in map mode. Another point of interest with the video singleton is that it permits drawing on the screen using a cursor that can have it's location set absolutely or relatively, among other things. Relating to the video singleton, the GUI singleton uses unicode for displaying text so that the game can be translated to languages of other alphabets in the future.

What RPG would be complete without a scripting language? Allacrost wouldn't and that's why it uses the Lua scripting language. Of interesting note, Lua is also the Roman goddess whom soldiers would offer their seized weapons to. Anyway, the Lua scripting language can be bound with C++ allowing the Allacrost team to rapidly create game content to fill their engine with. Scripts can be stored in a binary or text mode. It makes no difference to the engine, although binary scripts will naturally run faster. The engine can read them using functions like bool readBool (const char *key) and int readInt (const char *key). The key just identifies what variable in a given table (as Lua calls a scope) should have it's value returned.

Finally, one more topic I feel is of merit in this summary of the Allacrost Getting Started Guide is error handling. The Allacrost team uses their own Exception class, upon which all other exceptions are derived from. If an exception unwinds the stack all the way back to the main game loop, the game crashes with a message. Smaller errors, such as failing to load a file, are handled immediately through the boolean return value of related functions.

With the above said, Hero of Allacrost is definitely a game to keep an eye on. Even if it goes nowhere, the existing documentation and code is something to learn from! Best of luck to the development team. You guys, and girls if there are any, rock!

Tuesday, December 18, 2007

Monitoring the Load in Linux


uptime

If you'd like quick information about the amount of work your system is doing, look no further than uptime. This handy little program displays the current time, system uptime, number of current users, and load averages over the last 1, 5, and 15 minutes.

Everything is pretty strait forward, except for load averages. A load average is the average number of processes that are using the CPU or waiting for something such as IO or even the processor itself, among other things.

Here's an example of uptime in action:
$ uptime
14:14:38 up 4:13, 2 users, load average: 0.30, 0.44, 0.44

Here, the time was 2:14pm. My system has been up (running) for 4 hours and 13 minutes. There are currently two users logged in, and for about a third of the past 1, 5, and 15 minutes, one process on average has been using my CPU or waiting for something else.

top

While uptime specifies the amount of work one's system is doing, top describes just what work is being done. Here's an example session of top, exited with q for quit:

top - 11:16:42 up 1:34, 3 users, load average: 0.63, 0.65, 0.40
Tasks: 108 total, 3 running, 105 sleeping, 0 stopped, 0 zombie
Cpu(s): 15.2%us, 1.7%sy, 0.0%ni, 82.9%id, 0.0%wa, 0.0%hi, 0.2%si, 0.0%st
Mem: 450816k total, 443132k used, 7684k free, 28236k buffers
Swap: 497972k total, 34704k used, 463268k free, 99940k cached

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
6176 samuel 16 0 266m 96m 27m R 10.2 21.9 5:22.29 firefox-bin
6310 samuel 15 0 135m 35m 19m S 3.6 8.1 1:22.64 rhythmbox
5187 root 15 0 212m 51m 7560 R 1.7 11.6 2:56.52 Xorg
6206 samuel 15 0 81316 20m 11m S 0.2 4.6 0:03.92 gnome-terminal
6426 samuel 15 0 2368 1156 884 R 0.2 0.3 0:00.04 top
1 root 18 0 2948 1852 532 S 0.0 0.4 0:01.21 init


Notice the first line is the output of uptime? The column headings a little way down, starting at the left, describe the Process ID of a given process, the USER who appears to own the process, it's priority, nice value (modifyable priority), amount of VIRTual memory in use, physical ram RESources in use, SHaRed ram in use, process State, percent of the CPU in use, percent of ram MEMory in use, minutes:seconds.hundredths of seconds that the process has used the processor for, and the name of the process itself. To learn more about what top can do for you be sure to press h while it's running to get a list of hotkeys. If you make any changes, you may wish to use the W hotkey to save them for next time.

dstat

dstat provides handware usage statistics for a variety of systems as one can see in the following example:

$ dstat

----total-cpu-usage---- -dsk/total- -net/total- ---paging-- ---system--
usr sys idl wai hiq siq| read writ| recv send| in out | int csw
24 6 68 2 0 0 | 95k 27k| 0 0 | 0 10k| 422 1091


Regarding the CPU, we can see usage based on the user, system, and the amount of the processor that isn't being used at all. We can see disk, network, paging, and system access as well.

free

If you just want to know how much ram is free and swap space (the overflow of ram that is stored on disk), free is the command to use! The only extra switch I recommand is -m which displays the output in megabytes instead of the kilobytes which is the default.

total used free shared buffers cached
Mem: 440 432 8 0 24 167
-/+ buffers/cache: 240 199
Swap: 486 0 486


In case you're wondering the shared column is obsolete. Buffers just refers to the memory in use by the Linux kernel itself.

pstree

pstree is a great little command that displays a tree of the child processes created by each parent process. Here's an example:

init─┬─NetworkManager───3*[{NetworkManager}]
├─NetworkManagerD
├─acpid
...

Monday, December 17, 2007

Linux Firewalling


iptables is Linux's modern firewall, implemented within the kernel. It can monitor different types of packets, on different paths, and process them in various ways.

Chains are an important first concept in learning iptables. They contain lists of rules that are matched against packets and targets that describe what to do with the packet. A target can be a user-defined chain, ACCEPT, DROP, QUEUE, and RETURN (which directs the packet back to the chain that called this one). If the packet can't be matched to any rule in the chain, the policy decides the ultimate target.

A set of chains make up a table. Depending on one's kernel configuration and loaded modules, different chains may exist. Without anything special, one could expect the following tables to be present:
  • filter, the default table, has the built-in chains: INPUT, FORWARD (for packets routed through the computer), and OUTPUT.

  • nat, for packets that create new connections.

  • mangle, for specialized packet alteration.

  • raw, mainly for allowing certain packets to bypass connection tracking.


Argument Summary


Really, this entire article is a summary of man iptables, but this is especially true for the following commands, which represent only a portion of the vast array available in iptables:
  • -A, --append chain rule-specification

  • -D, --delete chain rulenum

  • -I, --insert chain [rulenum] rule-specification

  • -L, --list [chain]
  • : Displays basic information about the chains in a given table.
  • -F, --flush [chain]: Deletes all the rules from a given chain.

  • -Z, --zero: Zeroes out the various counters.

  • -N, --new-chain chain

  • -X, --delete-chain [chain]: Without a given chain, all custom chains in the table are deleted.

  • -P, --policy chain target

  • -s, --source [!] address: A name or IP address is acceptable.

  • -d, --destination [!] address: A name or IP address is acceptable.

  • -j, --jump target: A jump isn't required if counting packets is the only desired effect.

  • -v, --verbose: Shows the packet and byte counters for each rule, among other things.

  • --line-numbers: Shows the rule number of each rule in the chain that's displayed.


So how does one go about blocking a website, for example, using iptables? Like this:
iptables --table filter --append OUTPUT --destination www.digg.com --match owner --uid-owner samuel --jump REJECT --reject-with icmp-host-unreachable
Here we are working on the filter table's OUTPUT chain. Every outbound packet originating on this computer must travel through this chain of rules. The destination we are attempting to match in this rule is www.digg.com. Optionally, we only care if I'm the one initiating this connection. Instead of just dropping the packet, which would cause the browser to hang for a while, it is clearly rejected.

Persistence


Ah, now I can finally get some work done :) But wait, when you reboot your computer the firewall rule will be gone. What we need to do is save the firewall rule so that we can restore it upon system startup:
iptables-save > /root/firewall_rules # Initially save the firewall rules.
By the way, you may wish to try iptables-save on it's own first just to make sure that there are no firewall rules that another program has currently setup, which would otherwise mingle with your own. Now fire up your favorite text editor to create a startup and shutdown script. I'll use GEdit:
gedit /etc/init.d/firewall
Paste the following into the new file and save it:
case "$1" in
start|"")
echo Loading firewall rules...
iptables-restore < /root/firewall_rules
;;
stop)
echo Saving firewall rules...
iptables-save > /root/firewall_rules
;;
esac

And that's it! Now your custom firewall rules will persist between sessions. Happy Hacking!

Sunday, December 16, 2007

Comparing Files in Linux


sdiff, much like it's counter part diff, provides a great way to compare files in GNU/Linux! A good mnumonic to remember the command is by thinking of it as the "side-by-side merge of file differences." Here's an example of how it works.

First, create two files, beginning with textfile1:
Apples
Oranges
Bananas


... and the second file, textfile2:
Apples
Oranges
Strawberries
Bananas


With two files to compare, let's run sdiff on them:
$ sdiff --width 10 textfile1 textfile2
Apples Apples
Oranges Oranges
> Strawberr
Bananas Bananas


sdiff contains a few additional features of interest:
  • --output=FILE

  • --ignore-case

  • --ignore-all-space


And that's it, so remember: When you need to quickly compare files in Linux, sdiff is a convenient method!

Sunday, October 28, 2007

Balancing the Academic Life with Friends

Phew! Midterms are almost done! I just have one more in about two weeks. And when all is said and almost done, regarding exams, I remember one thing after coming back to school after two years of working for it: focus is everything! Let's face it: time is limited. We're going to need to cut some excess and focus only on what is important in life if we want to be in control of our academic lives. For me, hobby programming doesn't even make the cut and that's very important to me. Which activities will make it for me? I know that studying everything again and again until it's mastered is important. Eating right is important and so is going to the gym and visiting with friends. Oddly enough, I feel most relaxed at the gym when under physical pressure and especially after a challenging work out.

Friends are an interesting topic when it comes to academic focus. I have decided that for the rest of this month and next, notwithstanding any previous arrangements, I will spend no time with friends who I can't further my core goals in life with at the same time. That means I aim to forget about watching movies with friends, doing nothing with friends, and the like. If I'm going to spend my time with them, I want it to count. There is so little time already, and as exams have proven, good marks in university are no joke. For those who have decided to enjoy their lives without a knowledge seeking goal, my white hat's tipped to them, but I unfortunately don't have time or wish to join.

It seems to me that it's not just what one does with friends, as a knowledge seeker, it's also who the friends are and who their friends are. We have a word for this: community; and that's also very important in the academic lifestyle. When the pressure becomes unbearable, I found that nothing beats, except for possibly exercise, surrounding one's self with a whole community of friends going in the same direction. Although I'm a Christian, I don't have any church community at this point in life. I live in another city, away from most of my family. I have fewer friends than I would like. Although I appreciate them (but not all the time), not all of my room-mates are close friends. But in all of this, I have gained something of immense value over the past week: community. It all started when I joined my friend at the university for a study session. As an aside, if that person happens to read this, she will know who she is and as she continues reading, I want her to think about how immensely I appreciate and love her without passing "the line." Before the study session, we went to the Computer Science Students Association meeting together. And what kind of personalities should we find here, pray tell? I still don't know about all of them but there are a few, and a few are many when it comes down to what I am looking for, who are tactful, friendly, commutative (yes, I should work on that one), and who seem to have taken charge of their lives, especially as they relate to school. For example, one of the individuals at the meeting used to be an electrician... Until he pulled his arm a bit too far and could never string wire in the ceiling again. Woops, there goes the career he built for himself in life thus far. What did he do about it? He went back to school for a computer science degree. Now having previously been established in life, our electrician friend is visibly older than the student body at large. That's not to say he's a complete old man yet. What I'm getting at though is that even though he is older than his fellow students in general, he participates in the student community as a friend who seeks knowledge and takes responsibility for what he can, given his surroundings at the university instead of using his age as a reason to go about his degree without being connected to other students. Now that, I have a lot of respect for too! Will there be others in this new community who are as incredible as the aforementioned individuals? I don't know, but at least they are all attempting to accomplish what I am: A university degree in computer science. When my mind isn't strong enough to keep the pressure at bay in the future, I'll be able to surrounding myself with this community and this community will remind me that the life I have chosen is fun and is possible.

Sunday, August 12, 2007

Defining Success


Success is important to me. At times it's not so much the result, but rather knowing that I'm not wasting my life in a generic and average way. In the past when I have felt unproductive, I'd step up the pace only long enough to be getting somewhere. After attaining my desire to feel fulfilled, I would stop working and repeat the process over and over, getting virtually nowhere. In my desire to live a fulfilling life, weeks would pass where I knew that I was simply wasting my time. Maybe it's the hacker in me, but I find it immoral, for myself, to live without getting anywhere. Simply being alive in and of itself is amazing. It would be a shame for me to waste my life without doing anything with it. With my lethargic default nature and mentality of life, I knew that I would have to make a change. If you find yourself in a similar situation, the only requirement to start getting out is a desire for success.

A great way to turn a desire for success into results is to create weekly to-do lists. Simply write out all the tasks, including check boxes for each, of what you would need to accomplish in the week to consider yourself successful. You can add tasks based on chunks of time or completion. The idea is to divide your weekly goals into units that are just a bit harder than what you are comfortable with. Make each task require some effort but not so much that you get discouraged and quit.

Be careful not to include too many tasks at first as your list may take more effort to complete than you had originally anticipated. Just start with a few tasks and build momentum by completing every single one in the allotted week. Seeing everything become checked off is a great way to build excitement and put all the more effort into next week's list. Add more difficult tasks to next week's check-list until you fail to complete everything for the given week. Then add a few less for the week after. The idea is to fail half of the time and succeed the other half. Failure means that you are attempting things outside of your abilities and success means you are achieving your goals of what's important to you.

An alternative of to-do lists is to schedule your time. I find that scheduling all of my time instead of using to-do lists didn't work as well for myself because things change. For example, I may plan at the beginning of the week to spend two hours during an evening to write program code. This would be done without knowing my situation during that evening so if something comes up, such as an assignment deadline or my boss asks me to work extra, I would find it much harder, if not impossible, to complete my goal. Alternatively, a to-do list offers a greater sense of control as one can choose when to complete a certain task at times when more information about other obligations and new plans is available.

Life is said to be a journey. I believe this and think that it's not where you end up, it's what you did with your time on the way there that counts for the most. People can always look at where they are in life and see ways to improve. It becomes very hard to declare one's self successful if something could have been done better. I propose a more genuine approach is making the most of one's time. Writing to-do lists does just that!

Thursday, August 09, 2007

Learning How to Run


Running is a great way to lose weight, think better and faster, relax, and build discipline. It's also one of the cheapest ways. The only things required is a watch and nice pair of running shoes. I recommend a comfortable pair of Nike running shoes which cost about $100. The pair I bought are surprisingly light, made with nylon mesh, and above all else comfortable.

Can't run for longer than two minutes without feeling like a knife is twisting your stomach? That was me just a few months ago. I had lifted weights already for over a year but running was out of the question. I had no stamina and simply didn't want to run enough to actually put in an honest effort. That all changed when my back started hurting. At first it was when I lifted weights but then it prolonged to the point I couldn't even sit in cushioned chairs without some degree of pain. I immediately started caring about my posture but I couldn't just continue aggravating it by lifting weights like I was used to. So, what do you do when you want to exercise but weight lifting is out of the question? You run! This catalyst was what I needed to get started. Now a few months later, I can run for over half an hour, non-stop, and I don't even lose all my breath! The exciting thing is that you could too.

As I mentioned, the first step to running is wanting to. This involves setting a goal. Personally I decided that I wanted to be able to run for fifteen minutes, non-stop, and have enough breath after to be able to have a conversation with a friend. I further declared to two esteemed friends that I would run five times a week for no less than twenty minutes of run-a-minute walk-a-minute until I could meet this goal. I had already been running for a week or two so I could just barely accomplish this. I also had a few months of summer ahead of me so there was plenty of time before I would have to resort to buying an indoor track pass and settle for subpar scienery. Still the goal seemed daunting and I knew the effort required to achieve it would hurt. This combined with the promise I made to my friends made failure a most unacceptable option.

From nearly the beginning, I took a systematic approach to running. A twenty minute session would involve running for a minute and then walking for a minute. I was utterly exhausted after these sessions for a few weeks. At the beginning I felt sore even on my off days. This brings up an important point. Everyone starts at a different level. I recommend to start running on one minute intervals like I did, but only for as long as you can without feeling tingly or having your vision change colors on you when you stop. If you can't even for a few intervals, why not start by simply walking for regular and longer distances than you are used to? The important thing is pushing yourself gradually. With this in mind, I eventually started running for two minutes and walking two minute during my twenty minute sessions. Then I started running for three minutes and walking for three. Naturally, I decreased my walking to two minutes. This continued for a few weeks. By now I had already been practicing for a few months and it seemed that I wasn't moving fast enough to complete my goal of running for fifteen minutes for the end of the summer.

One day, I decided that I would go for my goal and see how close I could make it. I ran in the direction of my relatives home, thinking that if I could make it, I would like to sit down for a bit after and drink some water. (I still can't drink or eat much before running without experiencing cramps, but it's getting better with practice.) After three minutes of running non-stop I was feeling pretty tired, but I kept on going. After seven and a half minutes, I was really tired but the thought of already being half done kept me going. Then after thirteen minutes, something really cool happened. Although I was panting hard by then, I noticed that my run wasn't getting harder. As long as I could maintain focus, I would achieve my goal. I kept my eyes closed for a good portion of those last two minutes and nearly stopped but I made it! I slowly walked to my uncle and aunt's home and talked with them for a while: goal complete! The next day, I ran for ten minutes, non-stop, instead of fifteen and was extremely tired after, just like the last day, but never the less I had run non-stop for a personally impressive amount of time. I had already started running home from work, which took about half an hour, when running a minute and talking the next, but now I could actually start running almost the entire distance without stopping. I seized the opportunity and before long was running the entire distance home from work. I can now make it in about twenty minutes for free whereas the bus takes about double that time for $2. I am still impressed that I can run and run without stopping now. The effort has finally paid off and it feels great.

Sunday, August 05, 2007

Promising God

Don't do it! In the Christian context, the bible teaches us that when we make promises to god, they can be used against us. James 5:12, of The Message translation, declares that we shouldn't emphasize statements with tag lines like "I swear to God", try to speed God up by bargaining with him, or tempt god with anger against us, as we may fail and then have lied directly to god!

As a person, I have an understanding of the universe that is limited by what I am able to see and comprehend. That means I may not be thinking of every possibility when I say something. As well, some situations are outside of my control. When then should I, or anyone else this applies to, make a promise that can be unforseeably hard to keep or, worse still, impossible to keep? Why should someone voluntarily risk being called a lier to his or her god?

Making promises to god creates red tape. They needlessly complicate what someone can or can't morally do. One who makes such a promise has to continually think about it to ensure that it's not being violated. The promise should probably even be written down if it lasts a long time. What if the promise keeper were to forget about it?

Not keeping a promise to god is as good as actively committing a crime against someone else. A feeling of immense guilt may arise because in the back of one's mind, there are two basic choices carry it through or shirk it some more. This is in opposition to having wronged someone in the past as it is in the current tense specifically. If one no longer wishes to carry through on a promise made to his or her god, he or she had better hope that his or her god will release the promise out of mercy. Not following through with god's wishes would create a situation where one is opposing his or her god and, by definition, god never ever loses a power struggle. His reputation can't be compromised at any cost.

An RPG Coding Quest: Simple Shooter

Wahoo! I've finished programming a small game I call Simple Shooter! It all started with a three hour crash course in C++ programming for my friend who hasn't programmed in years. Those initial 3 hours I spent tutoring my friend turned into about twenty as I continued to work on it after. Now, I'm left with a side scrolling space shooter with two enemies and a scrolling background! Mad props to my friend Peter who created the ships using Blender! Although this game is very simple, I have learned a few things about programming in the process:

Every module of a program should be segregated, by class for example. If the sprites were isolated, they same code, with minor changes of course, could be used in nearly any two dimensional game.

In gaming, giving the effect of something as opposed to actually providing it can be just as good, if not better. The ships could have been programmed to move really fast with the camera following them and the background could have been still but just appeared to move, due to a changing viewpoint, but that would have only served to complicate the code, introduce errors, and provide no noticeable difference in game play.

Programs don't have to be perfect! It took about twenty hours to program this game. Granted, I haven't programmed my own game in years before this, however it still goes to show that programming for a particular situation without caring about future expandability and caring about code that follows coding guidelines and the standards set forth in other areas of the same code is enough to think about. The important thing is getting the job done and still easily being able to understand what is going on by looking at the existing code at a later point in time.

If you know me in real life and would like a one-on-one tutoring session that results in a similar game, please let me know!

Thursday, July 26, 2007

C's Static Keyword


After this post you shouldn't find the static keyword confusing in C anymore! Let's get started...
The first context we find static variables is in functions. First, it's important to understand that there are two types of "storage classes" in C. The first is auto, short for automatic, which is the default if no storage class is specified. This means that a variable is automatically destroyed upon exit from the code block inside a function or function itself that it's defined in. The other storage class in a function is static. This means that a variable maintains the static memory allocation that is defined in it's first execution through the respective line of code. This static variable stays around until program termination. It doesn't even get reinitialized on a second pass through it's respective line of code, so it's great for counts and other things internal to the function that shouldn't be divulged to the outside world.
At this point you may be wondering about static variables in a global scope or, put another way, at the file level. Either these static variables would be in a header or implementation file. In the implementation file, they wouldn't be visible to clients of the implementation because they would only have access to the header file, in the first place. In the header file, that is included in other files, the static variable definations would also be included, and since included they would be statically visible to their respective header file and all files that use that header. Like static variables, global variables at the file level, retain their values from program execution to termination. Thus, there is absolutely no reason to make global variables static.
In the second context, we find static functions. Say we want to include a private function in a header for consistancy and completness. By doing this, we would normally make the function public to everything else that includes its respective header file. However, if we prepend the function prototype and definition with the static keyword we can still keep it private as originally intended. Now you may be thinking, "Wait just a minute, Samuel! In the previous paragraph, you stated that static variables at the global scope were still public thanks to being able to include them, along with the rest of their header, in the same code that wouldn't be able to access static functions in the same included header file. Pardon me, but this seems a bit inconsistent!" It is and that's all there is to know about the static keyword in C.

Wednesday, July 25, 2007

Rebooting One's Brain

Once in a while I find myself working on a task that requires infinite effort to complete in my current state of mind. That's to say that no matter how hard I work, it's not hard enough and I serve only to frustrate myself by attempting it further, no matter how much I want to get it done.
In these situations the best thing I can do is walk away. This illustrates one of the reasons it's such a bad idea to leave a task for the last minute. By working on things early there is a lot less stress because there is time to screw up and try again. Numerous other people also recommend walking away from the situation temporarily. Often the answer comes when a calmer state of mind is reached.
Any given task that's impossible to complete in the current state of mind serves to prevent other, completable, tasks from being given attention. On several occasions I have focused on one thing only to become depressed and waste an entire day accomplishing nothing. What does one do when he or she realizes that nothing is being accomplished? Procrastinate! This downward spiral can only be broken by working on something else before the impossible task consumes the worker. Best of all if the impossible task is given a rest soon enough, one's moral doesn't have to suffer through other situations that are otherwise unrelated.

Saturday, July 21, 2007

An Officially Productive Week

I am so tired and fulfilled! You see, I just completed my officially productive week. I read, programmed, exercised, volunteered, and taught. Now that I look back, I was nearly constantly working during this last week! Wahoo! During the last few weeks I have felt somewhat down about not fulfilling my calling to make something of my time. I used this feeling of defeat to entice myself to victory for a week by stating that I would officially call myself productive should I complete the above set of tasks. That's not to say that I didn't change any tasks half way through. Instead, I had a clear idea of the amount of effort I wanted to put into my week and a conscious default, which helped steer clear of random web surfing and starring off into space. Work hard and play hard, right? I finished off with reading one of Steve's posts on productivity. He concluded by saying that the most productive thing someone can do is find his or her essence if he or she hasn't already. Otherwise, one could go on and on working hard without accomplishing anything. This makes sense because seeking out one's essence is like seeking out a conscious direction to take one's entire life.

What is my essence? Hmm. I haven't thought of this question for a long time. My essence is to have fun, love others, love myself, work hard both physically and mentally, not care about what others think or be proper, live with a free conscience, and so on. How about some simplification? If I factor out laziness, my essence would subconsciously be understanding and exploiting that understanding up to this point. Just for fun let's take a look at my accomplishments this past week and see what goes with understanding. I read The Prince and some more details from the C++ Programming Language. These books are filled with understanding both in terms of leadership and technology. Programming was putting my understanding to use. Exercising increased my ability to understand through an increase in blood flow to my mind. Teaching is giving back knowledge. The odd one out was volunteering. That was for feeling worthwhile and doing something nice for another person without expecting anything back. Fun fun.

I suspect that maintaining this week's level of productivity is very possible in the coming weeks even though I am so exhausted right now. I just have to be more of a hard-ass when it comes to managing my time. That means no watching Hannibal Lecture eat living people's faces off... again, last night. That's trash anyway so I won't be missing much more than a bit of suspense. I should have gone to bed earlier. This all falls back to the three pillars of sustained productivity as I see them: eating healthy, sleeping minimally and regularly, and exercising until one can't exercise anymore. It's also very important to consciously plan relaxing time. By relaxing I don't mean sitting on the couch watching TV. I am referring to doing something very exciting. If I were married, that would probably be dancing with my girlfriend. I say girlfriend so as to denote a consciously fed desire for continued romance. If I were single, which I am (yay), it could be something as simple as throwing a flying disc with a friend without any fear of rejection. The beautiful thing about using sports to unwind is it brings life to a whole new and exciting level. This level requires hard work all the time but it is so much more alive then the lethargic alternative of drifting through life without any plan. When one doesn't have a plan, he or she is swept up by laziness or another person's "optimal" plan. Not so optimal for one's self now is it?

Saturday, July 07, 2007

Updating a Game World

Picture a game world with terrain, ground level sprites, air-born sprites, and weather. From the water tiles to the movements of the clouds high above, nearly everything in this world requires updates to their states. For example, the water may need to jump by 15 frames in the span of a second or a cloud may need to move by 20 pixels in 1 minute. This brings one to the question of what is the best way to update the various parts of the game world. How should updates be handled at the higher levels of the game world? Specifically, how should updates be stored and when should various parts of the world be updated?
Updates can be stored in one of two ways. First updates can use ticks, the smallest amount of measurable time which increments once with each processor tick. As a benefit, updates can be applied at different intervals to different parts of the game world without storing any extra information. One could update a space ship 100 ticks into the future once in a second and simultaneously update a snail the same number of ticks once in a minute. Extraneous information is minimized in this implementation as both the snail and space ship updates could take into account their last tick count when considering the magnitude of the current update. Compare this with the second way of representing updates: storing updates as the time since the last update. If we update our game world by one second, we either need to update each object in it by the same amount of time or store the update time accumulated for items that aren't updated and update them by the sum of accumulated time when the time finally comes. The first method may seem neater so far, but consider a sprite with a complex AI and movement. If we update it by providing a new tick count, the sprite would need to recalculate all of it's actions from the beginning again and again, wasting valuable time.

Another way to approach the way updates are stored is by mixing the two approaches. Updates can be represented as tick counts at the higher levels and then lower level implementations may process the updates by differentiating them with the last tick count. This would allow for not having to update everything at the same time while still only doing the processing of what is necessary internally at the lower levels.

One issue still remains, what should be done when the tick count reaches it's maximum and has to wrap back to the beginning? If the last tick stored is greater than the current tick we know that the count has been wrapped and we could simply sum the difference between the old count and the max and the new count to find out the current amount of ticks that have past since the last update.

Wednesday, April 11, 2007

Samuel's C++ Coding Style

File Comments

Each header file should begin with a asterisk comment box that states the classes fully qualified name, followed by a copyright notice of the form (C) 2007 by Your Name on the next line, followed by a blank line, followed by a concise description of the file. Since implementation files would effectively have the same beginning comment box, it can be ignored in the implementation.

Header Guards

The first two lines of every header file is a header guard. Although some files may not require this guard, using it consistently should help reduce errors. The header guard variable should be in upper case letters with underscores used as spaces, in the format FILENAME_H. A blank line should proceed the guard.

Includes

Because of the small number of includes in any given header file, there should be no blank lines between them. There are blank lines before and after the includes though. The includes are ordered from the most general system ones to the most specific user includes.

Namespaces

Namespaces are all lower case. If a name must be multiple words, underscores should separate them. To prevent the global namespace from becoming polluted, everything should be defined within an appropriate namespace and members should be qualified on each use.

Lines

A line can be up to 80 characters long and no longer. Some consoles are only able to display up to 80 characters per line and this allows them to view the source code without awkward line breaks. If a line must be split, this should be done in the most natural place for the situation. Also, the orphaned line should be indented to whatever seems best for the situation at hand. If a method is quite short, the entire method may be placed on a single line for a compact look.

Indentation

Indentation should be composed by two spaces each. This prevents different programs and their different numbers of spaces that make up a tab from messing up the code's alignment. This is the minimum amount to make an easily noticeable difference in indentation. It is also a small number which allows the most code to be written per line without breaking the line.

Braces

Opening braces are always located at the end of another line of code. This is because closing braces sometimes have instantiated variable names directly after themselves, also on the same line. A brace should be before and after a tiny single line method, on the same line, without any spaces between the line's text and the surrounding braces.

Parenthesis

Parenthesis are always preceded by a space, except if there is no argument list, for readability and consistency. Comma separated lists have a single space after each comment.

Variables

Variables should be entirely lower case with necessary spaces replaced by underscores. When variables appear in comma separated lists, pointer and reference modifiers should be immediately followed by their respective variable names without spaces.

Classes

The words and initials making up the name of a given class should start with capitals. Although single word classes are preferred, underscores should replace any necessary spaces. The access specifiers should be indented at the same level as the outer part of a given class itself. Groups of similar class members should be grouped together. The groups include variables, constructors and a destructor, mutators, accessors, and action methods. Each group should be separated by a blank line for readability. Due to the generalised nature of overloaded operators, they should appear first in their respective groups.

Nested Class Comments

The lines immediately before a nested class should form a comment box similar to the one at the beginning of the file, except that no copyright notice is given this time around.

Naming

Method names should be verb focused. Conversion methods should be prefixed with "to_". Methods that retrieve part of the associated object's state should be prefixed with "get_". An exception is boolean accessors which should be begin with "is_". Mutators should start with "set_".

Saturday, March 24, 2007

The Key to Entrepreneurial Self-Discipline

Do you have the required level of self-discipline to work for yourself, as an entrepreneur, for just one hour a day for a minimum of five days a week? If so, could you double the time? Does anyone want to make a bet for how long I can keep this up?

Wednesday, March 21, 2007

Winning an Argument Won't Give You What You Really Want

Answering before listening is both stupid and rude. (Proverbs 18:13, The Message)

A few days ago, my roommate and I had a yelling match against each other. We were both *so* right and the other had no right to get in the way of the obvious truth. Of coarse, this didn't work. We both wanted the other to yield without asking why the other's view was so important in the first place. Proverbs 18:13 came to my mind but I didn't like it. How could I bear listening to another's opinion regarding something that I fervently held as my own business. Still, as Lex Luther would say, one can never have too much information. Since the equation of how things would work out between me and my roommate was unsolvable, I took the Bible up on it's suggestion, which was humbling to say the least when it involved *my* own business. I cooked breakfast for my roommate and asked him all about his views regarding our disagreement. I did my best to understand and repeat what he said back in my own words without even getting into my opinions. He was quite reasonable. Then something else happened that I didn't expect. I genuinely appreciated his stance for the first time since our disagreement and couldn't explain how happy I was. The situation wasn't solved yet, but still, the equation had been simplified immensely. Over the next few days I thought about it and finally sent an email to my roommate.

I maintain my stance with appreciation for a good portion of yours.

Short and sweet! Originally I had planned to send a massive letter explaining my view and, to some extent, my self-righteousness. After thinking about the situation for hours and asking others for their general opinions, I realized that some people will simply disagree with my fundamental beliefs and others won't. Either way, there are usually reasons. This response did more than a whole letter could have. It did even more than arguing with my roommate and having the last word could have. This one-sentence reply showed respect for my roommates view while being true to myself and my self-respect. Originally my roommate was upset that I didn't listen to him. Now, he got his wish and I got mine, which is far more important than agreeing over a situation.

Wednesday, March 07, 2007

The Joy of Linux

The Joy of Linux, by Michael Hall and Brian Proffitt, isn't so much a technical discussion of Linux as much as it's a focused look into the community and culture behind it. In a continuously witty and upbeat style, the book begins with one of the authors learning how to install a digital camera in Linux. Sure it took unimaginably longer to do in Linux than it would have in an officially supported Windows environment, but human capital and the number of friends the author has increased as a result. Beyond the joy Linux hackers experience in learning a new programming language, the book delves into topics such as Free and Open Source software, corporate acceptance, choice, and more than anything else the community of users willing to help each others out. I recommend this book to anyone who wants to know what long time Linux users enjoy about their favorite OS. As someone who has used Linux for some time now, I found The Joy of Linux an easy going and refreshing read.

Thursday, March 01, 2007

Accurate Floating Point Addition

Will G, a friendly university tutor, asks "Does changing the order from largest to smallest first, among an infinite set of numbers following the pattern 1, 1/2, 1/3, etc, ever change the result's level of accuracy?" The sum is certainly the same no matter which way it's added up in real life because no matter how small a number is, it can always be represented by a fraction. However, a computer's floating point arithmetic doesn't use fractions. This creates the possibility of a loss in precision when adding an insignificant number to a relatively significant number. The set of numbers mentioned earlier can be added using the pattern 1 + 1/2 + 1/3 and so on. The running sum becomes exceedingly more significant relative to the next number being added. Eventually, the next number being added will become so insignificant relative to the running sum that it experiences a loss in precision! Consider adding the smallest numbers before the larger. The running sum becomes increasingly significant, once again, but so does the next number being added. Sure there will be a loss in precision, but it will be much less than adding the largest numbers together first. The order that a diverse set of numbers is added on a computer makes a difference, indeed!

The best way to add a diverse set of numbers together is by sorting them by magnitude, beginning with the smallest. Then proceed to add the numbers together from the front of the list. Once again, this ensures that as little precision as possible is sacrificed by the computer for the sake of using the floating point method of arithmetic.

Wednesday, February 28, 2007

aterm


aterm is a highly configurable and lightweight terminal emulator. Some features include pseudo transparency with tinting, a configurable scrollbar, and fully customizable fonts. Generally speaking, aterm has more cool non-essential features while xterm has more practical features. In particular, xterm doesn't have transparency. At the same time, aterm's lack of practical features contributes to a smaller memory footprint than xterm has.

Not all window managers honor a graphical program's request to be borderless. While KDE goes as far as allowing the user to toggle a checkbox to remove a window's border, the Unix Window Manager doesn't even honor a programs request to be borderless. This makes it hard to make a terminal emulator look as if it's part of the desktop background. Although I didn't have any success with it, a patch has been circulating the Internet that allows for aterm to be borderless even while being run in a window manager that doesn't support this request.

aterm's default look is a little drab. I recommend launching it using the following options:

aterm -tr -sh 20 +sb -fn courier

In plain English, this launches aterm using transparency with 20% of the root window's graphic, no scrollbar because Shift + PgUp/Dn work too, and the courier font because the default is ugly. Use xfontsel if you want to see what other fonts are also available on your particular system.

Wednesday, February 14, 2007

Galatians

St. Paul wrote to the Galatians urging them to return to living by faith in Jesus. After all, Jesus died as a perfect man on the cross so that we wouldn't have to pay for our sins if we would accept his sacrifice. The Galatians had become traits to Christ by returning to their traditional lives of following the law of the Old Testament. St. Paul believed that there were a few Galatians who were attempting to get the rest to follow the law again just so that they could brag about winning people over to their side and look good. Although disgusted by the situation, St. Paul had faith in the Galatians to return to their faith in Jesus. One last interesting point mentioned in Galatians: Even though we, as Christians, have freedom in our lives, it is still possible for us to destroy it.

Friday, January 19, 2007

The Environment of Response

Trevor, a high-school friend, once suggested that without a response to an argument provoking statement, one would simply find it hard to argue. Consider two people living together where no agreement of one directing the other's actions has taken place. One day, the garbage can becomes full and one of the roommates commands the other to take it out. Having committed to no agreement in this regard, the receiver of the command indignantly replies "No! If you want to take out the garbage, do it yourself." Pause! At this point our roommates find themselves at opposite ends of "what should be done." Each roommate may very well dig in his or her heels and argue against the attack seen coming from the other. So what does replying to this flame bait finally get each of our roommates? Nothing! In fact, it cements both in their respective views all the more, making it harder to come to an agreement and, if either feels self-justified in what he or she said, the other person look bad.

Considering this dilemma, I realized making a statement or suggestion sets up an environment in one's mind that any reply must travel through. In the example above, even if the indignation was justified, a fact remains: The solid no answer still traveled through the environment setup by the commanding roommate; an environment where fulfillment of the command was the only valid result. By sending a different answer through the environment to the commander of that environment, both the environment and the commander were insulted. Boom! The commander is now in a position to disagree with the answer and argue in favor of keeping the original environment. Worst of all, the responder has already began the process of arguing and, therefore, looking bad to the commander.

Not to worry! Understanding and being able to identify this type of situation is the hard part. Perhaps, our commander in the situation above commands something else on a later occasion. Another environment of required obedience is immediately setup. However, this time there is no responder. He or she simply walked away or stood by quietly. The listener decided to put aside his or her ego during the initial moments of the command and, most importantly, reject the flame bait. In the aftermath, the listener's ego has been greatly strengthened in knowing that his or her self-respect has remained with self-control in the new situation. Realizing this makes providing no answer, or better yet, exposing the hostile environment so that some real agreement can be arrived at thoroughly worthwhile.

If one decides against responding in a hostile environment, when should a response be giving? A response is best received when it's explicitly asked for without implied judgment. In both situations above, the commander expressed no desire to know what the other person thought. In these cases, the safest approach the receiver could take in protecting his or her self-respect is to simply state an unwillingness to participate in an environment that doesn't allow each person's views to be openly discussed.

Before responding to the next high-impact statement one is faced with, perhaps it's best to consider the explicit environment one is responding in and attempt to improve it.

Jonah

Jehovah illustrated how little sense it makes for one to complain about the lack of something that he or she didn't work to create or maintain through the biblical narrative of Jonah.

Our story begins with Jonah, son of Amittai, being called by Jehovah to travel to the city of Nineveh and warn the people there of their impending doom. The people from Nineveh were committing sins to a great magnitude and God could no longer ignore their insolence. With that, Jonah sailed for Tarshish, which was in the opposite direction of Nineveh. Of coarse this was a big no-no and a fierce storm erupted during the voyage. The sailors threw over all the excess cargo in an attempt to keep the boat floating. The situation only became worse and they decided to figure out who had sinned against his or her god. Sure enough, drawing straws revealed Jonah as the guilty one. Coincidence? I think not! Jonah explained that he was running away from God and that the storm would evaporate upon throwing him over. They threw Jonah overboard and the storm subsided. Finally Jonah made the right choice! As a bonus, the sailors worshipped and made vows to God when they realized that he was in control of the environment!

It must have seemed like the end for Jonah as the water closed in around him. But it wasn't! A giant fish swallowed Jonah. Jehovah kept Jonah safe for three days and nights inside the fish until Jonah finally prayed to God. Jonah thanked Jehovah for saving him from a watery grave, exalted him, and said that he would finally fulfill God's command. With that, the fish spit Jonah out on a shore and Jonah headed straight for Nineveh. It's not every day that a fellow traveler could tell another that he or she had just spent three days and nights alive in a giant fish after nearly drowning, but Jonah could have. Bringing bad news to a city is uncomfortable enough, but that totally owns! Jehovah certainly isn't a god of comfort and convenience!

Arriving in Nineveh, Jonah proclaimed the people's impending doom. It must have taken Jonah some time because the diameter of the city was a three day walk! Upon hearing Jonah's message from Jehovah, the people believed him and immediately mourned in repentance. Even the king included himself! Like Jonah had already apparently thought, Jehovah relented on the city's judgment because of the people's change in heart!

Jonah sulked off to the East country side near the city and waited to see if anything would happen. During the night a broad-leafed tree grew up. Impressive! God could certainly make plants grow fast for his purposes. It provided some much appreciated shade for Jonah during the next day. God had also sent a worm, which chewed through the tree. In another day it withered and died. On top of that, a hot wind came from the east. Jonah became faint and started wishing that he were dead. There is no wonder that my friend suggested that Jonah must have really been emotionally unstable.

At the end of the biblical narrative of Jonah, God asked Jonah why he was upset over his grace which saved the city and the worm that destroyed the tree, when, in both situations, Jonah had done nothing to create or maintain either. What annoys you that you honestly have no ownership in?

Thursday, January 11, 2007

Daniel

The book of Daniel has two major parts. The first is the story of Daniel, renamed Belteshazzar by King Nebechanezzer, and his adventures in the royal service. The second part is a prophecy concerning the wars of the kings of Greece sorrounding Daniel's time. Following is a discussion of the first part.

Because of Israel's repeated disloyalty to Jehovah, they were overtaken by the Babylonian king, Nebechanezzer. It is under this premise that we meet Daniel, an up and coming star who was clearly filled with God's power. He along with his friends, Hananiah, Mishael, and Azariah, were taken into training for King Nebechanezzer's royal service. Daniel and his friends grew exceedingly wise on a diet of only vegetables and water. When Belteshazzar finally met them, they impressed him more than any of their peers. The king renamed Daniel as Belteshazzar, Hananiah as Shadrach, Mishael as Meshach, and Azariah as Abednego.

One day, King Nebechanezzer had a troublesome dream. He decided that his magicians should interpret it without being told what it was. Their knowledge of the king's dream in the first place would act like a proof that their interpretation of it was also genuine. Of coarse the magicians couldn't interpret it and they even let the king know strait up. The king got mad and declared that all of his magicians and wise men were to be put to death on a certain day unless they could recall and then interpret the dream. Sadly, this included Daniel and his friends! After asking for Jehovah's help, Daniel told the king his dream and what it meant, without first being told what the dream actually was. Daniel was elevated for the interpretation and the king honored him greatly.

On another occasion, Shadrach, Meshach, and Abednego were made to stand in front of the king's statue of a false god. No pressure. Then the king commanded everyone there, including Daniel's three friends, to bow down and worship his new god at the band's sound. Fearing god, Daniel's three friends refused to listen to the king's command. The king called them forward and gave them one more chance to listen. The king was enraged to find them refusing again. He ordered a furnace heated up several times hotter than normal and had them thrown in. The flames were so hot that the men who threw them in were themselves burned alive. It didn't take long for the king and those with him to see Daniel's friends walking around in the flames, invincible. There was even a fourth being, algelic like in appearance, with them in the furnace. Calling them out of the blaze, the king then declared that anyone who'd badmouth their god would be destroyed!

Having already gained the king's trust, Nebechanezzer told Daniel another dream. Daniel interpreted that a big tree in the dream was the king himself. The tree being chopped down and stunted with an iron plate simbolized the king losing his domain and being thrown out of society. However, after learning humility, the king was reinstated. He even wrote a letter to others around the world declaring the greatness of God.

Belteshazzar's son, Belshazzar, eventually succeeded him as king. Together Belshazzar and his royal friends had a drinking party. God didn't like seeing the silverware from his temple being used in such a shameful and profane manner so he sent a hand to write a foreign language on the wall. Having heard of Daniel, Belteshazzar called for him and asked for an explanation. Daniel said that because of the king's sin, the kingdom would be given away. Of coarse the prophecy came to pass soon after. After all, Daniel had a knack from God for telling the future.