Monday, December 28, 2015

Language Summaries: Ruby, Java

Ruby

Ruby is the cool new kid on the block that everybody wants to know more about. It's shiny. It's fun. And it can be used for web development.
  • feel: organic  (splat arguments, etc.)
  • typing: loose (A number becomes a string when it needs to; type is determined by context)
A quick Google of "learning ruby" will reveal some nice online resources with which to learn Ruby. Codecademy will teach you syntax. "Learn Ruby the Hard Way" makes no assumptions about prior experience and provides a nice, simple workflow that lets you follow along and write real code while getting used to navigating your filesystems, the terminal, and other programming basics.

AppAcademy, a coding bootcamp (one among many,) offers crash courses in Ruby on Rails (a web development framework) that can take amateur coders with potential and turn them into entry-level professionals -- assuming you can pay them $5k up front, quit your day job for 3-9 months, move to San Francisco or New York, and survive there until you find a job (as much as 6 months after you've finished the bootcamp).

Java

Java is like a bad high school science teacher. Everything has to be just so. If things are not just so, then we shall not proceed until things are just so.
  • feel: rigid (methods take a precise number of parameters)
  • typing: strong (Every object has a known type. To change this type, a type-change assignment statement must be made. This is known as type casting. Example shown below.)
Button sillyButton
sillyButton = (ImageButton)stupid

I got my start with Java in an undergraduate elective, where we used the Eclipse IDE to write, manage, and compile code. Since then, I was lucky enough to have the opportunity to put Java to use in a real project (one of the directors of the CAMCOR lab at UO wanted to do some data cleaning and analysis, so I sketched up a package to do the job.) Netbeans, a popular Java text editor, was my best friend for that project.


Saturday, October 3, 2015

Centering An Element on a Web Page

1. Give the element a width
2. Set its margins to auto

Like this:

div {
  width: 200px;
  margins: auto;
}

If you don't give it a width, and it doesn't have a small enough width by default, setting the margins to auto won't have an effect.

Wednesday, September 30, 2015

Shell Scripts 101

Creating and writing to files

Shell scripts allow you to automate terminal routines. This can be helpful for streamlining your workflow. Plus, it's fun.

Shell script files end in .sh and are executed with the "sh" command from the terminal. So, you can create a shell script by typing "touch myScript.sh". You can write a basic script to the file by typing "nano myScript.sh" and typing up a script like:

echo "Hi. What's your favorite color? "
read COLOR
printf "Oh, so your favorite color is $COLOR. Mine is macaroni orange. "

Once you save (write out , ^O) your script and close nano to return to the terminal, you can execute it by typing "sh myScript.sh". Your terminal will then ask you what your favorite color, get your response, and tell you that its favorite color is macaroni orange.

Or you can simply skip the touching and nanoing and type into the terminal "echo "Hi. I'm a shell script." >> myScript.sh


Creating shortcuts to folders

You can also create shortcuts to folders very easily (so you don't have to type a long path every time you want to navigate there, or remember a convoluted path) by following the instructions here. You'll have to quit the Terminal app and restart it for these changes to take effect.

Using the manual

When the "help" command doesn't bear fruit, use the "man" command instead. (Example: man ls) Press q to quit the manual once it's been "opened".

Or, just use this awesome site, Explain Shell. (example result linked.)

Copying directories

http://stackoverflow.com/questions/14922562/how-do-i-copy-folder-with-files-to-another-folder-in-unix-linux

Sunday, August 2, 2015

Writing a Game in Pure Javascript

Javascript is pretty cool. 
It's a game. In pure js.

Recently I've been using Raphael, an SVG graphics library, to write a game in JS. This has been an amazing hands-on exercise in learning how to write decent javascript. Translation: A lot of the game's code is not decent. It works, but it's not very modular, it's not very pretty, and it's not very best-practices-y.

Still, it's been great fun. I can't think of a way better than game programming to learn js. It's almost automatically test-driven, it's very visual, and you can share the results with non-coder friends without boring them to death.

Atom has been my text editor of choice for this project. Its smooth integration with Github is no joke. (This project has also provided a little basic practice for Github, which I desperately needed.)

Atom. Pretty colors.

As of now, the game logic is fully functional. A person can load up the page and play against the computer in 1v1, 2v2, or 3v3 format. The next step? Setting up server functionality and user-login system so that people can play PVP. A ranking system would be nice!

I find myself using the Raphael documentation naturally at this point, which is a great sign of progress. (Said documentation is absolutely beautiful, by the way.) I also find that I use the game as an escape from my homework, of which I suddenly have huge amounts, due to starting my Master's degree at U of Oregon in June. The accelerated 1-year program is stressful. Is it weird that I look forward to the times when I get to go home and just code?

Sunday, May 17, 2015

Not Sure What It Is? Call It an API!

WARNING: RANT BELOW

As I began to dive into programming, I kept running into this term, "API." I quickly learned that it stood for "Application Programming Interface." This told me exactly nothing about what it actually did.

I have now concluded that an API is a catch-all. Anything can be an API -- any little chunk of code, codebase, web service, or more. As far as I can tell, the dictionary definition might as well be:

API -- A useful codeish thingie of any size.

As proof of this conclusion, I offer two exhibits. 1. AppNexus. 2. A sentence from developer.android.com.

Exhibit 1 : The AppNexus API

I recently attended a meetup at which the topic was just "The AppNexus API." Apparently, this API called AppNexus is a project that makes online advertisements better somehow. In other words, it's a huge codebase worth millions of dollars, with 6 or more teams working on it. And yes, it's called an API.


Exhibit 2 : This Sentence

"A drawable resource is a general concept for a graphic that can be drawn to the screen and which you can retrieve with APIs such as getDrawable(int) or apply to another XML [...]"
Wait. Did they just call "getDrawable(int)" an API? Like, the same word that was used to describe a multi-million dollar codebase/tool?

That's right. Apparently this method is an API.

Conclusion

I propose that the term "API" be replaced, in all instances, with hibberdefoo. Or perhaps glumbobber. It's the same number of syllables. It lends equivalent meaning to whatever description it's used within. In fact, it's probably MORE useful, since whoever hears the term can intuitively understand that it doesn't mean anything whatsoever.

#theEnd

Personal Update

I started my digital life on Nintendo and MS-DOS. I remember playing Reader Rabbit and Math Blaster on my parents' computer from a young age.

In middle school, I started playing more and more Xbox, and less and less Gamecube. Microsoft lured me in with the Halo franchise and its addictive multiplayer gameplay and matchmaking system. While in college, I would become one of the top 3 players in Colorado's competitive Halo community (see my Halo blog.)

This March, I sold my Xbox One after only three months of ownership. Finally, in April I've broken Bill Gates' stranglehold on my soul. Steve Jobs' replacement (whoever the hell it is) can have it instead.

I got a Mac. Yippee. The end.

Objects in JavaScript, Classes in Java

Coming from a Java background, it's easy to understand objects in Javascript.

A Javascript object with a constructor is like a class in Java.

Once you define an object with a constructor, it becomes like an object "type", or as a Java guy would say, a "class." Instances of this object/type/class may be instantiated with the "new" keyword, and their methods and properties can be accessed with dot notation.


Thursday, February 5, 2015

Learning Log -- SVG, HTML, XHTML -- Feb. 4, 2015

I sometimes use these "Learning Logs" to help me keep my thoughts collected while I work. Feel free to check out my thought process, but don't expect a polished article.

First thing I learned today

Opening index.php in a browser without running a PHP server means that all elements that include any PHP will become non-functional, while all other elements will function (display) as normal.

<svg width = "400" height = "100">
 <rect x="<?php echo $strokeWidth/2?>" y="<?php echo $strokeWidth/2?>" width="<?php echo $length?>" height="<?php echo $length?>"
    style="fill:blue;stroke:black;stroke-width:<?php echo $strokeWidth?>;fill-opacity:.7;stroke-opacity:1" />

 <rect x="<?php echo $coord2?>" y="<?php echo $strokeWidth/2?>" width="<?php echo $length?>" height="<?php echo $length?>"
    style="fill:yellow;stroke:black;stroke-width:<?php echo $strokeWidth?>;fill-opacity:.7;stroke-opacity:1" />

 <rect x="<?php echo 2 * $coord2 -1 ?>" y="<?php echo $strokeWidth/2?>" width="<?php echo $length?>" height="<?php echo $length?>"
    style="fill:green;stroke:black;stroke-width:<?php echo $strokeWidth?>;fill-opacity:.7;stroke-opacity:1" />

 <rect x="<?php echo 3*$coord2 -2?>" y="<?php echo $strokeWidth/2?>" width="<?php echo $length?>" height="<?php echo $length?>"
    style="fill:red;stroke:black;stroke-width:<?php echo $strokeWidth?>;fill-opacity:.7;stroke-opacity:1" />
 
    </svg>

This is probably because the browser, as it parses the file, ignores any "broken" elements, that is, elements that it doesn't understand. So, something like...

<rect x="<?php echo $strokeWidth/2?>" y="<?php echo $strokeWidth/2?>" width="<?php echo $length?>" height="<?php echo $length?>" style="fill:red;stroke:black;stroke-width:<?php echo $strokeWidth?>;fill-opacity:.7;stroke-opacity:1" />

...just gets ignored. Instead of the PHP server echoing a value to be placed in the 'height=" " ', the browser parses ' height="<?php echo $length?>" ' -- that is, it thinks the value of 'height' is "<?php echo $length?>", which doesn't make any sense. So, the whole <rect> element gets ignored. (Its parent <svg> element is unaffected, since it has no PHP in it.)

Experimenting with the <use> tag

<!DOCTYPE html>
<meta charset="utf-8">
<svg width="500" height="500">
<rect id="useIt" width="200" height="150" />
<use x=100 y=300 fill="red" width="300" xlink:href="#useIt" />

</svg>

Notes:

HTML5 --> No <html> tag needed, just doctype declaration and <meta charset=...> tag (for security)

Within the <use> tag...

  • it doesn't matter if an attribute is to the left or right of the xlink:href attribute
  • cannot override attribute values set by the original svg element with ID "useIt"
    • so, including 'width="400" ' doesn't do anything, since width was already declared as 200 in "useIt"

SVG Coordinate System: Text vs. Images

The "x" and "y" attributes set the location of the SVG element. But it's a bit different between text and images. For an image, the upper left corner of the image is placed at x,y. For text, the lower left corner of the text is placed at x,y. Bit unintuitive.


Friday, January 16, 2015

Learning Log -- Linux Install Attempt, and more Python Installations

I sometimes use these "Learning Logs" to help me keep my thoughts collected while I work. Feel free to check out my thought process, but don't expect a polished article.

So far, I've...
  • downloaded a .iso file for Ubuntu. This was annoying because Chrome kept crashing at the end of the large download. I ended up having to switch to Firefox after two failed attempts.
  •  Copied the .iso file to an empty USB stick, tried to boot from it, didn't work. Boot menu gave two options UEFI and non-UEFI, neither worked -- all booted to Windows.
  • Burned the .iso file to an empty DVD, tried to boot from it, didn't work. Tried both the "file system" option and the "CD/DVD" options when burning.
  • Formatted the USB stick as directed here --> (Create a Bootable USB Stick), copied the .iso to it, and tried to boot from it. Still booted to windows. 
After that, I found the BootFromCD article on help.ubuntu.com, which told me my .isos haven't been burning properly, as indicated by the lack of a multi-folder filesystem present on the drive when viewed in Windows Explorer. (The pictures in the article help.) So, I'm heading over to their BurningIsoHowto article, which is going to help me a bit.

---

5 minutes later:

After reading that article for a sec, here's what I'm doing next:
  • checking the md5 sums for the .iso I downloaded -- DONE
  • Continuing thru the BurningIsoHowto article and eventually booting Linux from the disk.
---

15 minutes and many googles later:

This article tells me I need a mounting program. None of the other articles mention this. Maybe they suck. OK, let's find a mounting program.

I've heard "daemon tools" twice, so, trying to get it. It's a bit sketchy. This thing is supposed to be free, but I keep finding myself in places where they're trying to get me to spend money.

NOW SOMETHING WANTS ME TO SAVE A .EXE. UMMMMMMM

OK, after looking at reviews on cnet, looks like Daemon Tools distros have been carrying various undesirables going back at least as far as last fall. So, let's look for another option.

---

Went back to using a DVD instead.

5 minutes later:

googled "burning an iso from command prompt", found this useful article, which gave me the command to use:

isoburn /q drive:\file.iso

Which, in my case, translates to:

isoburn /q C:\Users\David\Downloads\ubuntu-14.04.1-desktop-amd64.iso

(This appears to be the only way to access the Windows disc image utility that so many articles mention.) The burn appears to have been successful, since an Ubuntu install window popped up when I put the CD back in the drive after labeling it.

Restarting computer now. Fingers crossed: next OS I see should be Ubuntu, not Windows.

---

Crossing fingers worked and didn't work. Ubuntu came up, but it was very glitchy:


My computer was also making loud noises while this screen was up. So, I turned it off before it could get any further. (Was it frying my parts? I didn't wait around to find out. I'll consider letting it boot fully if I get the same result again.)

I'm going to try burning another DVD, this time with the "verify after burning" checkbox checked.

---

No luck. I got the same behavior as before. This time I toughed it out, but there was no reward, just this screen, which persisted for 5 minutes or so before I decided it wasn't going to change. After trying a few keys and getting no response, I turned off my computer again.






My best guess at this point is that this version of Ubuntu (14.04.1) doesn't support my video card, which is the AMD Radeon HD 6670. At this point, I've had about enough of Linux installation attempts for the day. Linux: 2, Me: 0.

---

Fortunately, the immediate point of the Linux install was to solve a Python issue, which I now see another way to solve. Earlier I was having problems downloading large files because Chrome was crashing at the end of each large download. Now I've switched over to Firefox for the time being. So, I'll try downloading a Python installation that comes with the desired libraries already installed.

First step, uninstall Python 2.7 via the Start menu. Done

Note: Might also try uninstalling my other Python versions if this doesn't work.

Next, download Python(x,y) from here. Just like I did before from Chrome, but this time I'm in Firefox, so the download won't crash at the end and waste 20 minutes of download time.

OK, downloaded it, starting the install. Oops, it's telling me that I still have Python 2.7 installed. Maybe I need to restart the computer for the registry changes to take effect. Let's try that.

After restart, same error message. Buh. OK, let's plow through it this time with the "install anyways" button. The only other option seems to be uninstalling my other Pythons (3.3, 3.4) and I'd rather not if I can help it.

Installation completed. Moment of truth. Run Grimm's script.

GREAT SUCCESS!


OK, now I just have to combine it with the adapted example script, and I'll be done. Wow.

Rough draft:

from xml.dom import minidom
import matplotlib.pyplot as plt

doc = minidom.parse("posts.xml")

# doc.getElementsByTagName returns NodeList

viewCounts = []
scores = []

rows = doc.getElementsByTagName("row")
for row in rows:
        if (row.getAttribute("Id") == 1):
               viewCounts.append(int(row.getAttribute("ViewCount")))
                scores.append(int(row.getAttribute("Score")))
               
plt.plot(viewCounts,scores)
plt.title('StackExchange data -- ViewCount and Score')
plt.xlabel('ViewCount')
plt.ylabel('Score')

plt.show()


Result: not what was desired.



After some typecasting, still not getting results. Time to take a peek at what's going on under the hood with some print statements. Let's add a counter variable, increment it over every iteration of the for loop, and print the first 50 instances of the relevant variables.

OK, there was an issue with the attributes having null values. Fixed that by only appending the value if it was truthy (existing.)  But, still the same graph result.

Eureka. Changed "Id" to "PostTypeId" after printing the arrays and finding they each had one value in them, as opposed to the expected thousands.


Achievement unlocked/mission complete/QED, which when pronounced phonetically rhymes with bed, which is what I will go to now.

Thursday, January 15, 2015

Learning Log -- Python, XML, matplotlib, troubleshooting

I sometimes use these "Learning Logs" to help me keep my thoughts collected while I work. Feel free to check out my thought process, but don't expect a polished article.

Trying to learn how to use Python to interact with an XML file. The eventual goal is to plot some attributes of the xml file's nodes in scatter-plot fashion using a Python library called matplotlib. First, I need to learn how to work with XML through Python.

Starting here: https://docs.python.org/3/library/xml.dom.html#module-xml.dom

The page talks about something called SAX, which I know nothing about. Apparently when parsing XML, we choose between SAX and DOM. I know DOM stands for Document Object Model, but I don't really know what it means, in practical terms. So, good time to learn more. I went and found this thread, which explains the difference well:

http://stackoverflow.com/questions/6828703/what-is-the-difference-between-sax-and-dom

I guess SAX triggers events while the XML is being parsed, while the DOM parses the XML first and then triggers events.

Now that I understand a little more about XML and the DOM, time to use Python to interact with XML through the DOM. Apparently the stuff you use to interact with XML in Python comes with the base Python download, so I won't need to install any extra libraries just yet.

I'm using this video to see an example:

https://www.youtube.com/watch?v=aCksVW1YUHs

The video linked me to some source code here, which I copy-pasted and adapted into this:

from xml.dom import minidom
import matplotlib.pyplot as plt

doc = minidom.parse("staff.xml")

# doc.getElementsByTagName returns NodeList

rows = doc.getElementsByTagName("row")
for row in rows:
        if (row.getAttribute("Id") == 1):
                rid = 1
                viewCount = row.getAttribute("ViewCount")
                score = row.getAttribute("Score")

There is some confusion about whether to use Python 3.4 or 2.7, or if it matters. (I have both installed.) I think the conclusion is that matplotlib is for Python 2.7, so I'll do everything in 2.7.

Tried to run Grimm's sample code -- got error:

ImportError: No module named six

So, googled the error. Found out: This error means that matplotlib depends on a module named six and that I haven't installed the library which contains the six module.

The six module is pretty cool, being a compatibility library. I downloaded it. Now I have to figure out what to do with the thing I downloaded. Apparently there's a thing called a python wheel. By googling "Install python wheel", I found a video that explains this a little bit.


Basically, I didn't need to download the six module after all -- pip will download and install it for me when I type this into the command line and press Enter:

pip install six

So, six is now installed. I try running Grimm's code again and get this:

ImportError: matplotlib requires dateutil

Oops, looks like I didn't follow the instructions for matplotlib very well. They say that I need to install a number of python libraries. So, I'll try to use the installer tool I downloaded. pip install numpy. An installation occurs, but an error happens. It's a complicated one and something I've never dealt with before. I ignore it for now. I'll circle back to it if things aren't working after I install the rest of the libraries.

Well, I got an error message that told me the error was important, so looks like I'll have to fix it. I google the error and find this:

http://stackoverflow.com/questions/2817869/error-unable-to-find-vcvarsall-bat

Which points me to this:

http://stackoverflow.com/questions/6551724/how-do-i-point-easy-install-to-vcvarsall-bat

Which tells me that I need to have Visual Studio installed, which raises the question, "Don't I have to pay for that or something?" But I suspect that's off. So I google "Is visual studio free?" The answer seems to be NO--there's a trial version. But I'd rather just go back and install Linux finally. That'll be its own post.