Showing posts with label novice programming. Show all posts
Showing posts with label novice programming. Show all posts

Monday, 7 July 2014

Foraying into JavaScript

Today begins the day where we learn JavaScript. My experiences with JavaScript are numerous, though how fruitful it is varies. At times, they go great. Othertimes, they don't. My biggest JavaScript run-ins are a somewhat-unfinished mod for Skyrim using the CreationKit's JavaScript-based papyrus, or when I tried to make Android apps. JavaScript is fairly difficult and compared to Ruby, a lot less 'face-value readable'.

So our first exercise in learning how to apply JavaScript to webpages is to make a very simple calculator and guessing game. Straightforward, very simple. And below are the notes I took as we were going through it as a class.



JavaScript gives us the power to make dynamic things happen on the client side. Where Rails and the Rails stack processes and renders views server-side, but java-script tells the user to render on the client. Browsers all accept JavaScript. ECMAScripts organize JavaScript and standardize it. It allows the user to interact with the Document Object Model, or the DOM. We can send smaller requests to the server via JavaScript instead of large chunks of whole views so it becomes more dynamic.

By default, a submitted form in HTML with no direction will send a get request to itself with the params. It won't actually send anything; but the params itself need to be obtained through the URL - which is the name field in the input tags:

    <input type="number" name="left">

This will make a query-param get request with left having a value of what we had put in, with all params separated by ampersands:

    /calculator.html?left=5&operator=*&right=3

--
HTML has a callback for forms, called onsubmit, which allows us to call javascript function. JavaScript functions can be passed around and will not run until called. Callbacks listen for events and will do an action when it happens. To prevent the forms from doing it's defalt behaviour for submit (as described abve - get request to itself), we can use return false in the onsubmit form.


To begin writing javascript in the html file, we can use <script> tags in the header.

To define a function in JavaScript, we define it with function:

    function calculate() {
       
        }

Where parameters are required, all functions must contain a param bracket (). All variables in the function need to be defined by 'var' then the name of the variable, and then to obtain params from the elements on the website we can call getElement on document. Specifically, we can getElementById (for example, our input type friend called left), thus:

    var left = document.getElementById("left").value

But we have to make sure that we defined "left" as an ID in the form itself:

    <input type="number" name="left" id="left">

In addition to being able to define and store param variables, we can also log them:
    console.log(left)

When we do:

    if (operator == "+") {
        console.log(left + right);
    }

We'll be adding the var left with var right. However, they might come out as strings:

    log:
    3 + 2
    32

Which doesn't work for us. We have to typecast them (basically, turn them into integers in this case). Type casting in JScript basically parses in a parameter to a constructor and makes a number object:

    var left = Number(document.getElementById("left").value;

And now we re-run the submit:

    log:
    3 + 2
    5

If we wanted to do live debugging, we can put in a debugger statement:

    <script>
            function calculate(){
            var left = Number(document.getElementById("left").value);
            var right = Number(document.getElementById("right").value);
            var operator = document.getElementById("operator").value;

            debugger;

            }
    </script>

It will pause the script as it is running upon reaching the debugger. It allows us to debug whenever it makes a request for a parameter or call anything in that context. Very useful.

Javascript will allow us to append or add dynamically to the view. So if we want to display the results of our calculation. To where we want our calculation result:

    <p>Result: <span id="result"></p>

We also have to make sure that we specify the variable and get the element by its ID:

    var result = document.GetElementById("result");

And then we also have to allow the variable to change the value of a particular element in our calculation itself by calling innerHTML on the variable:

    if (operator == "+") {
    result.innerHTML = left + right
    }

And that should do it!


Complete gist here .

Friday, 27 June 2014

A month of Metis

By the end of today, it will have been 4 weeks since I started learning at Metis. There's a lot that I've learned, and it's impressive when I think of how now I have the fundamentals to already build something great.

If there's something that really draws me into programming, it's that sense of creation you have at your fingertips. You can code together magnificent pieces of software, like how an artisan handles his craft - this is the builder of the tech era.

At Metis, broadly the four weeks covered the following:
  1. HTML/CSS
  2. Ruby
  3. PostgreSQL
  4. Sinatra, irb
  5. Ruby on Rails
Most importantly, I feel are not just knowing the tools that we have at our disposal, but also the fundamentals behind these tools, and practices that help us to be more effective and efficient. We've had to build from ground up methods in Ruby, Sinatra and Rails that are so easily simplified into one-line commands, or we've had periods of free time to come up with our own code and write a solution, and get what we want in our apps.

One huge draw is the fact that programming is like a game, or a puzzle. There's many ways to solve these puzzles, and you learn that some ways are faster than others, while others are more effective or clean to look at. There's a bit of joy when I go back to old code I've written, see what I've done, grin and rewrite what I could've done better now that I'm a month into the study.

I wrote some code for the zombie dictionary a few weeks back, now, and maybe when I go back to it it'll be significantly different by the end.

That said, over the weekends I'm slowly working on getting to know Vim, and while it more or less functions similarly between Unix and Windows systems, the fundamental differences between them will take me some time to adjust - for example, we utilize Homebrew, Vundle, Thoughtbot's RCM, and dotfiles to handle and manage packages, bundles and configuration settings for Vim. With the exception of Vundle which has its own set of installations for Windows, everything else is made for a UNIX system in mind. However, I'm learning of several softwares that emulate similarly. For homebrew, I've learned of chocolatey ; and quick searches for dotfile installers and bundlers for windows have turned up a few that I still need to go through.

Given this, an important thing that I learned is the core differences in how OSX handles its system-wide installations compared to Windows (which uses environmental variables to set PATHs), and the inner workings of the dotfiles we've been installing. Ultimately, it helps me understand what is being changed 'under the hood' when we brew a bundle or run RCM. (Most of the dotfiles change internal settings in Vim, Git, RailsVim and TMux among many others).

Like I said, there will be a part two for that, so that should be coming following further dives into converting from Sublime Text to Vim.

Friday, 20 June 2014

Rails and Resources, Part 2


The all-important table! It's crucial this week that we have most of this table down, and honestly, I wish I wrote this blog post before our weekly quiz. Definitely would've helped!

Basically, each action here is a method defined in the table_controller.rb file (in this case, wombats). The paths are defined in the routes.rb file (under resources :wombats) in their most default state. Each path functions under a particular HTTP verb protocol. Using rails, we don't have to fully type a link in HTTP, but we can use rails code (link_to or form_for) to quickly make the connections between the records within the database (via the controller, that takes in the instances of said models with the corresponding tables based on the action used) and back within our html.erb file.The instance variable objects are basically stored references to particular database segments (such as the records we're looking for in Class.find(:id)), so when we link_to the instance variable, Rails already knows what and where we're referring to.

I know one of our classmates is working on a blogpost to fully describe the actions, so I'll be leaving this blogpost short and link to hers when she's finished.

Wednesday, 18 June 2014

Rails and Resources, Part 1

This week, we began studying Rails. Compared to last week, I didn't run into any bumps between UNIX/Window differences thus far, so that was a relief. My PSQL is set up correctly (though I've yet to dig through security allowances and authentication more than I needed to - I'm almost sure that we'll be going through that, though), and I'm able to install rails with some ease.

This is probably the part that I had a few hiccups compared to the easy installs the UNIX terminals had, but this was all just because I didn't have all the installations ready.

Basically, I installed ruby, but not particular gems and additional devkits that were necessary to set things up for installing rails. Luckily, when I tried to install Rails, the error messages were -very- helpful (it's important to read them!) in pointing me at what I needed to do next. First, I needed to install JSON via gems, but then when I was told I couldn't install JSON via gems, they pointed me to make sure I had the devkit in my PATH if I installed it already. I don't think I installed the ruby devkit.

First things first, I needed to get the Ruby Devkit 's latest version. Once that was done, I ran the gem install command for the JSON version I needed (ruby gems will tell me what the exact version and command I needed once I tried to install rails on failure). After that, it was a simple matter of using 'gem install rails' and I was set.

Rails is fairly easy to comprehend, given that we spent the last week working with the stuff 'under the hood' - it makes all the things we did in Sinatra and PSQL so simple and straightforward, and there's lots of ways to shorten the process of pulling database entries onto a website.

Two of the most crucial things we had to consider however, was how the entire Rails system worked from request to response, and the other was the Seven Route Resources (tm?).

First, the Rails system from Request to Response: assuming the database is already made:

From the Browser, we make a Request to the App Server. It receives the path specified in the request, and properly routes it through a controller. The controller may instantiate the Model, which allows it to pull, change and request information from the database. From there, it renders the view based on what information it has and has been given, which becomes the response sent through the App Server and back to the Browser which displays the response, likely as an HTML file.

Browser refers to the user, or the browser who is navigating the html page and making the request.
The command 'rails s' boots up the App Server.

Routes
refers to the routes.rb. It takes the Path of the url and accordingly performs the correct action via the controller.

Controller refers to the tablename_controller.rb. This is where the various actions are defined (akin to methods). What it exactly does depends on what Route is taken in the previous step. Primarily, it will set instance variables for the Model and View to use. It can pull/send database records/changes on request based on the Route via the Model, and render the View with the information it has before sending the response to the request back to the Browser. In the case of a redirect (HTTP code 3xx), it will not use Model or View and return the redirect response to the browser, which will initiate a new request to render the target URL.

Models refers to the modelname.rb file. When it gets instantiated, it's akin to using "tablename = Class.new". As classes in Rails in this case inherit ActiveRecord::Base, the object 'tablename' here is of type ActiveRecord and has access to the specific commands we use in Rails. Depending on what the controller requests, it may pull some information (.find, .where), pull all the information (.all), create a new entry (.new, .create) with the associated database table (which the Model is named after).

View refers to the .html.erb file. This is where the html.erb file containing all the text, code, and variable references are laid out. The Controller will read and render when it requests for it.

DB refers to the database.



====
Browser --request--> App Server --> [Rails Stack: Route --> read path --> Controller --> Proceed based on path:
====
Controller <--instantiates and requests based on routed path--> Model <--pull, change, create entries--> DB

AND/OR

Controller -- Reads based on route -->View --Rendered --> Controller --> App Server --returns response --> Browser

OR

Controller -- Receives redirect route --> App Server --returns response --> Browser
 ====

That sums up the entire process. Hopefully, this will help others understand as well. Thanks to the instructors for being patient and making this clear. Next part, I'll describe the Actions/Paths associated in the Resources in Rails.

Thursday, 12 June 2014

Coding on Windows in a UNIX-heavy class, Part 1

Part 1 because I am sure I'll be writing more about this down the line.

Most of the class in Metis is taught using Mac OSX. I've quickly learned that many and most programmers use Mac OSX, LINUX and other unix platforms (at least, among those I've seen in my stay in Boston). Developing on Windows is pretty unpopular - this much I've been told by people I've spoken to.

I've been loaned a mac prepared and ready for use by Metis, as I've brought my Windows 7 laptop along to the course (most of those in the course and the instructors are most familiar and are using Macbooks). I'm familiar with Macs, I've used them every now and then in University, but I was born and raised on Windows. Feeling like I can keep up despite the OS differences, I decide to stay on the Windows while bringing the Mac with me just in case it proves too much.

Week 1, there wasn't much of a difference. Week 2, we've begun work on SQL, ruby gems, multiple ruby versions, etc. and there are tons of UNIX specific programs and commands that my Windows didn't have. Being the only windows user in the class, the pressure was high for me to just boot up the Mac - but I decided to keep pressing on. It required a lot of googling during the lecture itself, and even making sure I was ready before the classes even start.The instructors are able to help if I asked though (the godsend of having 2 at once), but I feel like that I should be able to overcome any issues from my choice on my own.

I have to say: it was a little nervewracking, but it's a feeling I'll have to get used to. I have to make sure I could catch what was being taught in the lectures while at the same time searching for many solutions to whatever thing I needed to do. Once I was on the same page, there was a terse feeling of relief - I wasn't sure when the next time the software would do something unexpected from what was explained and I had to fix it up myself.

Summing up what was taught in the last few days - I'll write a more detailed post later - but we started the week with PostgreSQL. I first installed PSQL with the following links' assistance. It's important to make sure it works and verify that it works on pgAdminIII (easiest way to check. The instructions make it clear):

PostgreSQL for Windows
PostgreSQL Installation tutorial

Once it works out, PSQL should work on your command prompt. You can open git or cmd (I'll set up Vim later in the week) and type:

psql


Now, when I type it out, it asks me for a password (which you establish when you first install psql). However, when I enter anything, it says I've given a wrong password for my user. I think this has to do with the installer I use (hours of googling reveal that not everyone can face this issue) and certainly the others in the class didn't have this problem. So what happened?

Either it was some sort of PC configuration or just how I installed it, the PSQL user profile postgres isn't the default one set when using the psql command in prompt or git - thus it defaults to inputting my computer user profile as the one accessing the psql command. That's not exactly what I want, so I have to specify who's using it (using the installed PSQL shell that came in with the PSQL installation though, by default uses the postgres superuser for accessing the database). The --help command, that is:

psql --help

Is immensely useful because it lists all the other commands and arguments you can attach to psql. So, to access psql, I can use

 psql -U postgres

 in command prompt/git, will let me specify the username to postgres. Then, it will ask me for a password, after putting it in I will have access to the database. By default, the database is postgres - so if I made a new database photo-gallery I have to specify the database:  

psql photo-gallery -U postgres 

One password input later, I'm in the photo-gallery database. That's great and all, though it gets annoying every time to input the user name and password (and in one instance using psql, I found that my password input isn't masked, which is a huge gasp. I've googled for fixes and ways to simplify the process to make it similar to how the Macs seem to have no issue entering/exiting/doing postgres commands, and there's a few suggestions. I'll get more indepth once I commit to a choice on how in another post, but these are the gist of the solutions:

 -Make an alias that automatically inputs the username postgres each time
-Edit the authentication process for users that aren't postgres as well as password input
-Just use a linux-emulator (I'll describe this later)
 -Adjust a configuration 

Again, maybe it's just how my computer is set up, but none of those are straight forward. The other issue is, when you google for a solution, 80% of the solutions, if I don't specify for it, are for OSX/Linux/Ubuntu, not for Windows OS. Another issue is, there are 4-5 different answers on stackoverflow (a godsend of a resource next to programming documentation), but most of them aren't really much in the way of instructions (they assume you know your stuff most of the time,) so you google for particular things in those instructions and so on until you get what you want. Making aliases on git,the way its set up for me doesn't seem to work (I'll be googling to find where the config file it loads from is located) because there seems to be 2-3 different config files (according to the results I'm getting at stack overflow).

Similarly with psql. There's many ways to fix the issue in adjusting configuration, it seems, which is nice and all - though all of them seem to carry some kind of security concern - which is probably much clearer the more I learn about databases, how remote connections connect to my database, etc will allay any fears I have (Hence, why this is part 1). There's neat blogs and pages that explain the important types of security authentication for databases that I'll be reading into for when I get in-depth.

That said, I found a nifty little blog by someone familiar with the installer I used that explains a little about this issue on psql via EnterpriseDB: Dave's Postgres Blog

But enough about psql; there are other things that I had to do googles for mid-lecture and that was for a way to change ruby versions that are installed on your computer. For Mac OSX, they used Chruby and rvm; for Windows, I found pik.

Pik mimics a lot of commands that rvm and chruby does - we haven't used it substantially, but I have it ready (and it's important to make sure it is). By default, when installed pik only works on command prompt, not git; and it goes back to finnagling one of the config files for git to get pik commands to work on it.

While it is possible to install pik using ruby gems, I did an install through the .msi file on pik's GitHub page. Again, it might be with how I installed my ruby (I installed x64 version of Ruby 2.0.0, but installing pik via the gem only gave me pik 0.2.8 whereas the latest version was 0.3), but at the end of the day, I had to edit my %PATH% environment variables to make sure pik properly worked. It's important to understand Environment_Variables on windows and making sure I knew my %PATH% and what it does so I can be sure that things can work (it's crucial in trying to make sure your PC functions when you install new programs through prompt, etc.)

I'll probably touch on pik and %PATH% a lot more when we actually start using rvm/chruby in class, however. But I got mine working to a point where I can change ruby versions.

That's about it for this post; however there are some very crucial pages I'm keeping tabs on. The first is a page for Windows and Unix equivalents ! It's pretty important. There's several terminal commands on UNIX based consoles referenced in class which are essentially synonyms for what Windows uses. It's a good cheat sheet to have and look through. The other is a linux emulator, Cygwin . I came across this while searching for ways to change ruby versions on windows and a post described using Cygwin to use rvm on a windows PC. I didn't really read into it, but it'll be a good thing to turn to in case I ever find something on UNIX that is not yet replicable in a Windows environment.