Flatiron Blogger Magazine

When Being Out of Order is in Order by on 08/17/2017
Working on the front end of an application often requires us to handle several tasks at once — in order to send and receive data as well as to reflect changes in our interface. With Javascript as a single threaded language, that may at first seem like an awkward fit, but through asynchronous code we can work around this.The Call StackWe will start with a short review of Javascript’s call stack. As tasks are called in Javascript, they are placed in a stack. Javascript has just a single call stack, meaning it only handles one task at a time. When a function executes, it gets pushed onto the stack. When the function returns, we pop it off the stack.Asynchronous BehaviorWhen I first heard the term asynchronous, I thought about what it means to be in sync. A couple is “in sync” when they think about things the same way. Dancers are “in sync” when their timing is just right for that last move. So, if these people aren’t in sync, that would mean the couple is off on different trains of thought and the dancers are not following the beat. Asynchronous means not occurring at the same time. So what is asynchronous behavior in coding?It can be easier to define asynchronous code by comparing it to synchronous code. Synchronous code executes in the order it is written. It works like a relay race. Each line needs to get handed a baton before it can start its run. Asynchronous behavior is more like a restaurant where if it is faster for a restaurant to serve the person who arrived after you first, they can.A simple example of asynchronous behavior can be seen with the setTimeout method:console.log("quesadilla");window.setTimeout(function() { console.log("pineapple");}, 5000);console.log("ice cream");Even though the line console.log("pineapple") appears before the line console.log("ice cream"), when we run this in the console we get:quesadillaice creampineappleWhile the server prepared to log “pineapple” it went ahead and executed the task of logging “ice cream”. We could of course have it wait to finish logging pineapple before it could log ice cream with the following code:console.log("quesadilla");window.setTimeout(function() { 1+1 //This is just here to force the timeout to take place}, 5000);console.log("pineapple");console.log("ice cream");The following image displays synchronous behavior. If task 2 needs to wait a while before executing, task 3 must wait as well. This would be like a waiter not giving a customer a drink due to another customer arriving first, and their pizza isn’t ready yet. (I don’t know about you, but I’d prefer to eat at more efficient restaurants.)On the other hand, this image displays asynchronous behavior. If task 2 needs to wait a while before executing, task 3 goes ahead and executes during this wait time. This would be the more typical setup where the waiter would go ahead and give the second customer a drink as the first customer’s pizza continues to bake in the oven.The Event LoopWait, so if Javascript works with a call stack, where tasks are supposed to be called in order, how is it possible that tasks can run out of order? Let’s look at our code once more:console.log("quesadilla");window.setTimeout(function() { console.log("pineapple");}, 5000);console.log("ice cream");On line one, console.log("quesadilla"); is added to our stack. It is then executed and leaves the stack. At first glance, you’d think that the next line in our stack would be console.log("pineapple") but this is wrong. It is actually window.setTimeout(), which is then followed by console.log("ice cream"). Where does console.log("pineapple") go then? Well, the stack can’t possibly look at it until window.setTimeout() is complete. console.log("pineapple") then gets to be put into a queue. The Javascript engine regularly checks the queue for tasks that are ready to be added into the stack. Once the timeout is complete, console.log("pineapple") gets sent into the queue from which it can join the stack and get executed.Why all the extra trouble?Asynchronous code generally looks more complicated than synchronous code, so why even use it? Well first of all, as we saw earlier, sometimes if you make sure to run all tasks in order, you can waste time. Furthermore, if you stuck to solely synchronous code in Javascript, every time a script ran, your site would become unresponsive. Clicking around would be useless and users are never that receptive to that kind of delay. By executing tasks out of order, we can accomplish more without interrupting users’ actions.https://www.pluralsight.com/guides/front-end-javascript/introduction-to-asynchronous-javascripthttp://www.sohamkamani.com/blog/2016/03/14/wrapping-your-head-around-async-programming/
So you want to style your website Here are 10 good things to know (or, more realistically, simply be aware of) when starting your CSS journey. Included below are some common gotchas and some less-common but good-to-know tactics and approaches that might help to curb your manic CSS-related Stack Overflowing.
Ruby on Rails Generators (and how to undo them) by on 08/17/2017
Generators in Rails have a lot of power and can save you a lot of time. They can also create a bit of a mess if you don’t which use each one serves. Below is a list of rails generators that you can make use of.Usage: rails generate GENERATOR [args] [options]General options: -h, [--help] # Print generator's options and usage -p, [--pretend] # Run but do not make any changes -f, [--force] # Overwrite files that already exist -s, [--skip] # Skip files that already exist -q, [--quiet] # Suppress status outputPlease choose a generator below.Rails: assets controller generator helper inherited_resources_controller integration_test mailer migration model observer performance_test resource responders_controller scaffold scaffold_controller session_migration taskI’ve highlighted the four generators I’ll cover in this post.rails newRunning the rails new PATHterminal command will give you the bare bones of a rails project. The first thing that needs to be done is to create a directory that will house your Rails app.Next you run the command after navigating into the newly created directory and run the rails new command with the name of your app in place of PATH you will see that Rails automatically generates a folder bearing the name of your new app and tons of files inside.This is not all the files. Just a snippet.For any of you who have done work with web apps before and haven’t used rails you’re probably thinking…Ruby on Rails stresses the following principles:guides.rubyonrails.orgThe rails new command starts you out with a basic configuration and com boilerplate code that adheres to the above principles.rails generate scaffoldLet’s first talk about one of the rails generators that you should probably avoid, scaffold , since it will create a lot of extra stuff that you generally don’t need. The scaffold generator creates a full set of model, a database migration for that model, a controller to manipulate it, views to view and manipulate the data, and a test suite for each of the things listed before. This doesn’t give you much flexibility in how you want things to interact since it’s all being created for you and there’s a chance something could go wrong if you don’t follow the proper naming conventions for Rails.rails generate controllerThe rails generate controller ControllerName terminal command generates the view files, test files, and the controller files needed for the newly created controller.This command does not create the model files needed for your application and it also doesn’t create any migration files to create tables in your database for you but rails does have commands for that!rails generate modelThe rails generate model NAME fields command creates our migration for us to create a corresponding table in our database (even pluralizing to keep with conventions!) and creates the fields based on what you pass in after the name of the model. See the example below.The command also creates the test files and creates a directory for the views for the model but falls short of creating any views which may or may not be what you need for your task. What if you forgot to add a column into your table or you want to create a new table in your database after already creating the model manually? Rails has a command for that!rails generate migrationYou can create a migration using the above command. If you follow some conventions Rails with try to fill in the migration for you though it might be easier to just create a migration and fill in the extras yourself. Running the following command:Generates the following code:As you can see Rails can be powerful if given the information in the format that it expects.Undoing Generations with rails destroyIf you accidentally create a model, migration or controller it can be undone by running the command rails destroy AccidentallyCreatedThing . As a side note both generate and destroy can be substituted with just the first letters of each of the word, g and d. See the example below where we undo the migration we created above.As you can see Rails removed file associated with the migration named create_dogs .Now that you know about generator and destroy enjoy the magic of Rails.Sources:List available generators in rails applicationGetting Started with Rails - Ruby on Rails GuidesThe Rails Command Line - Ruby on Rails Guides
Redux in React. by on 08/16/2017
You may have ended up in a similar place as myself. You just learned all about React but can’t go one google search without seeing the word Redux in all the results that come up. The intent of this post is not to teach you all about Redux, but to help provide a high level overview of how to two work together in a working, usable application.Redux is a Javascript library.There is absolutely no intrinsic connection between React and Redux. They are separate libraries.What is it?Redux documentation definition: “Is a predictable state container for javascript applications”What does this mean?What do we gain by using it?Let’s say we want to build an application that displays a list of movies and when a list item is selected, we get a detailed view related to that specific item. Using Redux and React, we can build a model for our app that looks something like this:Redux manages the data contained inside our application.React manages the views contained inside our application.When Redux describes itself as a state container, it really means a collection of all the data that describes the app. This does not just mean hard data such as the list of movies in the diagram above but also includes more meta level data properties such as which movie is currently selected. Imagine our Application state looked something like this: {   movies: [     {title: ‘Harry Potter’},     {title: 'Lord of the Rings’},     {title: 'Taken’},     {title: 'Titanic’}   ],   activeMovie: {title: 'Harry Potter’} }We can break that active state into what redux would call reducers. A reducer is a function that returns a piece of the application state. For example, based on that application state and our modeled react/redux application above, we can create the following reducers.moviesactiveMovieWe will be looking at what it looks like to get started with our movies reducer and see how we can tie it to a react component. Our goal is to simply render our list of movies onto our page! We would adjust our file structure just a bit to now accommodate our newly introduced reducers. We would create a reducers directory and add two new files:                              src   =>   reducers   =>   movies.js                                                              =>   index.jsWe will start looking at these files in more details.movies.js within our reducers directory will contain our Application state! It will simply look like this:It exports our array of objects containing the list of movies (activeMovie has been removed from the state for the purpose of this walk-through.)So what does our secondary file index.js within the reducers directory contain? Let’s take a look because this will look a bit funky:Notice the two imports on top. We are bringing in a function called combineReducers from the Redux library and we are also bringing in our list of movies object. As your app grows more complex, you’ll want to split your reducing function into separate functions, each managing independent parts of the state. That is what #combineReducers will do for us. You can read more in redux’s documentation here. For the purpose of this high level breakdown we won’t be looking too deep into this. Just know that had we had more functions within our MoviesReducers, we’d be able to break it down into individual functions tied to different keys. Here we are just taking what we have and tying it to the movies key.  Lets briefly talk about containers.A container is a react component that has a direct connection to the state managed by redux. Containers are sometimes called smart components and you may see smart component being used in the redux documentation.At what point do components get promoted to containers?We only create containers for components that care about a particular piece of state.Let’s look at the exciting part of our app. We created this container called MovieList. We put this in our container because it is directly tied with a piece of state as we will walk through now. Take a look at the code below. It shouldn’t look too foreign.We are importing another new library. react-redux is a library that helps us connect out redux states to our react components. This library is not a part of React or Redux. We are importingimport { connect } from react-redux  In our container, we will use a function that becomes available to us from our newly imported react-redux library.  mapStateToProps - Takes in one arg (state).  - to take app state as an arg  - what the function returns will be accessible within the container via 'props’ (usually an object)  the connect function is what actually says take this component and this  mapStateToProps and return a container and that is what we export.  export default connect(mapStateToProps)(BookList)  ** if state changes, the component will re-render
Using the Google Maps API with React by on 08/16/2017
Before I was a Flatiron by on 05/23/2017
Although my time at Flatiron School has been by far the most intense experience I have had in the tech or programming world thus far, I have done my share of related projects before I arrived here. The first project I remember was from my time in kindergarten when I brought in an incredibly simple robot I built for show-and-tell. It consisted of a board, two motors, a switch to control the direction of each wheel and a battery. After watching a couple classmates drive around the classroom on my creation I was hooked.I first started “programming” in scratch and LEGO Mindstorms before I was in middle school. Scratch is a visual way of doing very basic programming and animating developed by the MIT Media Lab. As a child I made all sorts of fun little games and animations for my friends to play with.sample scratch code utilizing pre-existing blocks instead of written codeLEGO Mindstorms is a similarly block-based and visual language, but was built by LEGO specifically for their robotics set.Example of LEGO Mindstorms software (left) and simple robot (right)I gradually moved on to more and more complex LEGO creations, including robotic arms, a humanoid who could walk, numerous drawing and line following robots, and, the one my parents were least happy about, an automatic lego rifle that would fire 27 lego bricks per second.It wasn’t until middle school that I made the big shift from visual and abstract programming to coding, and until high school before I was able to do anything complicated with it. I migrated from Scratch to Python and Lego Mindstorms to Arduino and C++. Suddenly things became a lot more complicated. No longer was I playing with things that were designed to fit together. Although projects became exponentially harder, with that came far more freedom than I had previously. Instead of being limited by the pieces that came in a kit or the simple blocks that Scratch had, now the only things holding me back were knowledge, time, and cost.C++ in Arduino editor (left) Arduino connected to breadboard and LED’s (right)Despite loving Python, and building a number of simple programs in it, my focus shifted more towards robotics in high school. I built a number of robots during this time, both at home and in school, as the president of their robotics club.This experience culminated in the robot I’m working on now, which currently can navigate by touch, be controlled by my phone, talk, sing, monitor its battery level, and utilize sonar.My RobotI hope to use what I learn here at Flatiron to add a Raspberry Pi to my robot and have it run a webserver, so I can control it from anywhere in the world, as well as use the more powerful processor for image processing, more complex programming, and more.Other Projects:These are less code/Flatiron related, but I have built my own computer, touchscreen linux tablet, and numerous smaller projects. I helped (somewhat peripherally) with the building of a lamp with tentacles that point lights at where a user specifies, either through a webserver or Amazon Alexa and a coffee table that draws pictures in sand, also controlled by a webserver. I have worked on and built too many other things to list here, but I’d be happy to chat about other projects or details about the ones here any time.
The Magic of Rails by on 06/12/2017
After having spent all this time on Sinatra and other topics building out each method and class by hand, I was completely shocked when, during a lecture on rails, the instructor typed rails g scaffold and suddenly, as if by magic, every file and class he needed appeared.Not only did it create the files he needed and name them correctly, it created a fully working (if basic) CRUD web application supported by a database with a single line of code. We watched as he went on to build all sorts of things that would usually take at least several minutes of configuration with only a line or two in terminal, including models, migrations, and controllers. I was so impressed by the capabilities of Rails to make my life easier that I just had to dig a little deeper and find out what it can do.Rails has several types of terminal commands:The first, rails console, creates an IRBesque sandbox where we have access to all of our Rails methods. Rails server, or rails s, is equivalent to shotgun in sinatra and will launch your web app on localhost with default port 3000. bin/rails is used for creating rake tasks, dbconsole drops you into a console for whichever type of database you are using (eg. sqlite3, Postgres, etc.), and new creates a new project with a lot of MVC formatting and other rails syntax. In this post I am mostly going to focus on rails generate.The most initially impressive generate method that Rails has, in my opinion, is the one mentioned previously: scaffold. Although scaffold has a pretty big wow factor, (as building a working app with one line tends to do) it can be less useful than many of the other generate commands that Rails offers. This is due to the fact that most projects that a programmer will work on are each relatively unique. When you use scaffold, you often have to go back and refactor a lot before you can turn your project into what you’re trying to build. When you use scaffold, you end up with all this:You won’t need the vast majority of these files for a basic project. Some methods we may use more often are the migration, controller, and model generators.When I initially saw the migration generate method I thought that it would be less useful than the other things listed here. It seemed to be almost identical to rake db:create_migration NAME=example_nameI was very wrong, and I think that this is not only one of the most useful generate options, but also a place where the “magic of rails” is most apparent. This is due to the fact that, if you follow certain naming conventions, Rails has the awesome ability to actually parse the name to figure out what you want, and then actually write the code to do it for you.http://edgeguides.rubyonrails.org/active_record_migrations.htmlThe controller creation ability is also pretty powerful, and can be seen in action below.You can create models with :Creating a model like this will also create a corresponding migration to make a table with the fields you entered. For examplewill create not only a model that looks like this:but also a migration like this:A helpful table for each generate method and what you can expect it to produce can be seen here.A helpful table showing what will be generated (from http://bshap27.github.io/2015/03/15/Generators-Cheat-Sheet.html)Even though I have just started using Rails and seen only pieces of what it can do, I am already completely enamored with it and what it can do. I can’t wait to use it to build more interesting and complex web applications, and I hope that this post helps others do the same.some other sources you can check out for info about this are:The Rails Command Line - Ruby on Rails Guideshttp://edgeguides.rubyonrails.org/active_record_migrations.htmlRails Generators Cheat Sheetthanks Mirna for finding some of these :)
What is ECMA? by on 07/03/2017
When we first started our time with Javascript, we had a lesson that covered some of the history of the language, including the many iterations of it, the browser wars, and the standardization of it. We learned that an organization called ECMA was responsible for that unification. I decided to look into ECMA a bit more.ECMA was founded to standardize computers and computing in Europe in 1961. It accepts both small and large companies as members, as long as they are involved in computing and software development, even in a marketing aspect. Its members include Google, Microsoft, Apple, IBM, and many other influential and massive companies, along with many less well known organizations.Their member list can be found here.I found that ECMA, which is short for the European Computer Manufacturers Association, is responsible for a whole lot more than just standardizing JS. They also had many other integral projects, such as standardizing CD-ROM volume and file structure, creating FAT12 and FAT16 file systems, creating the U3D file format for compressing 3 dimensional projects in a standard way, and even creating JSON in its modern form.ECMA’s main purpose is developing standards and technical reports. Their publications and standards are free and open to access by anyone. They often cooperate with national, European and international organizations.A list of ECMA projects can be found here:More than 400 ECMA Standards and 100 Technical Reports have been published. Over two thirds of which have been adopted as international standards and/or technical reports.In 1991 they changed their name to ECMAinternational to reflect their global reach.
Compiled vs. Interpreted languages by on 07/24/2017
When we look at all of the different programming languages out there, we see that they are divided into two categories: compiled languages and interpreted languages.To understand the difference between those, you must first start at the most basic levels of how a computer works. Distilled to its most basic state, any software of or program consists of the ones and zeros of binary, each representing an on or off value. A hard drive is a series of those ones and zeroes grouped into bytes and then kilobytes and so on. Unfortunately, humans don’t speak in base two so we needed some level of abstraction if we wanted to build anything efficiently. Thus Assembly and Assembler were born. Assembly is a text based programming language, where almost every word has a direct cognate in machine code (binary). Unlike binary, however, a CPU (Central Processing Unit) cannot understand it. That’s where Assembler comes in: Assembler is the compiler for Assembly.What Assembler, and any other compiler, does is it translates the keywords and symbols that we use into binary that the computer can understand. According to Wikipedia, “A compiler is computer software that transforms computer code written in one programming language (the source language) into another computer language (the target language).”Gradually languages got more and more abstract from their machine code correspondents, and compilers became more complex to support them. Although we could now write comprehensive code in a way that makes sense to programmers, there are several significant drawbacks to compiled languages that lead to the development of interpreters and interpreted languages.Good compilers are extremely hard to write; interpreted languages are much easier to implementYou have to wait for code to compile before you run it, making it much harder to test and write on the flyrelevent XKCDvery hard to test because all of the code is compiled first and then run; interpreted languages let you figure out what’s broken much more easilyDue to all of these, a brilliant creation was born: interpreters. Interpreters initially ran through your code line by line and translated each line into a sequence of subroutines already compiled into machine code. This had a huge drawback though: looping and iteration caused certain lines to be compiled over and over again. This was inefficient and caused code to run slower.Many languages that are defined as interpreted, including Ruby, actually use a combination of compiling and interpreting, called intermediate representation. Intermediate representation is when an interpreter runs through code multiple times, first transforming code into a graph structure and then converting it into actual machine code. This graph structure allows things like re-arrangement, such as how ruby hoists variable declarations, and flow analysis. Flow analysis is when the computer figures out values to assign variables interspersed through the program.Having the computer break apart the code and then run each line has many advantages, such as:dynamic scoping of variables and declarationsplatform independencemuch better testing and errorsdespite these advantages, there are some disadvantages to interpreted languages:much slower execution, due to a programming having to be gone through multiple times for each runsometimes hackers can inject code into interpreters to change the course of executioncode can be copied of reverse engineered much more easily by competitorscan be less reliableEach type of language has many pros and cons, and there are many languages that use a combination of the two. Keep in mind, however, that you can do anything that you would do in a compiled language in an interpreted one, and anything you would in an interpreted language in a compiled one.
Dealing With Data by on 08/15/2017
Datasets will often be incomplete, contain gaps or blank rows, or inconsistent in formatting. This can lead to a variety of problems. Bugs can occur if you are expecting one datatype and get another, issues can arise when you try and sort or perform operations on inconsistent data, and sometimes you won’t be able to find entries if you are searching for the wrong thing.This is especially a concern when you are taking in data from another source and seeding your own database with it. I came across this issue when I was trying to seed my Postgres database from a CSV file for my final project at Flatiron School. My dataset had examples of all of the concerns I listed previously. To deal with this, I wrote a data ingestion script in Ruby to read one CSV file, clean up the data, and then write to a new blank file. I then seeded my database with the new file.the first step is to require Ruby’s built in CSV library, which contains methods that allow you to read, parse, and write to and from CSV files. Here I also make sure that both the necessary files are being passed in: the original data and the new file to be written to.Next, I declare the column headers that Postgres will use to import the data. I create an empty array to add data to and another array that stores the information it reads from the original CSV. I also include a block to prevent it from including blank rows here.I iterate over the old list and add all of the values to a new list here. The reason you have separate arrays and iterate from one to the next here, although I’m not doing it, is so you can choose not to include certain rows with a simple unless keyword here.This is a lot of code, but this final step both cleans up the data and writes it into the new file. Each line checks if the field is empty in that row and then pushes either the value or null/ ’Not Available’. I also use ruby commands like strip (to remove whitespace from before and after values), downcase (to standardize everything as lower case), and squeeze with an argument of a space (to collapse large spaces in strings into just one space). I also take the opportunity here to add id’s to each row, which Postgres then uses as primary keys.Although this is a relatively simple script, it has saved me massive amounts of effort in finding, formatting, and operating on my data, and would have saved me even more had I implemented it sooner. I hope this is able to help some of you if you come across some, shall we say, challenging datasets.a resource I emulated thoroughly can be found here:Automating CSV parsing with Rubyruby docs on the CSV library:Class: CSV (Ruby 2.0.0)another resource I used:A Guide to the Ruby CSV Library, Part I - SitePoint
Bootstrap & Materialize by on 07/27/2017
React: Shortening Long Sign-In Forms by on 08/15/2017
Machine learning is being hailed as the next big industry changer for software engineers and for good reason.  Machine Learning is basically a process by which a software learns by itself through multiple iterations.  Formerly the realm exclusive to data scientists and academia, machine learning is already being used extensively in big companies and there seem to be no signs of this trend slowing down.  With multiple resources and libraries popping up along with how hot AI is there seems to be no better time to learn.  The problem is the intimidation factor.  I’m already learning how to code from scratch in 3 months (currently in my 2nd month), can I really do a deep dive into machine learning at this time?
React, 3 reasons to use it by on 08/15/2017
React is Facebook’s answer to Google’s Angular, both of which are Javascript frameworks, and while both have their own pro’s and con’s it does seem like React is winning the hypothetical race between themselves (to me, as a disclaimer I have very limited exposure to Angular). So what is it and why is it so popular?
Component Lifecycle Methods: Render Methods by on 08/13/2017
I’ve been building React projects for the last few weeks and I keep finding myself returning to the chart below (pulled from a lesson in the Learn.co curriculum). It summarizes the inputs and use cases for the four Component Lifecycle Methods related to rendering.
React Router Basics by on 07/25/2017
“Now you’re speaking my language…” by on 10/06/2016
HTTP otherwise known as HyperText Transfer ProtocolWhat is HTTP?HTTP is the language of the internet. It was brought about to enable people to have a standard of communication between each other. HTTP is spoken between clients and servers. A client makes HTTP requests and the server accepts these requests and sends back to the client an HTTP response. HTTP connections are created and data is transmitted through sockets and once the server gives a response, the socket connection is closed. There are four main request methods that the client sends out to the server which are GET, POST, PUT, and DELETE. The GET method says “ I want a data”, POST method says “ I want to send you data”, PUT method says “I want to change data that I’ve already sent”, and DELETE method says “ I want to delete data that Ive sent.” To identify what these request are asking for we must look at the URI(uniform resource identifier) to determine what data needs to be delivered to the client. The HTTP request starts with the client connecting to a host server (a server listening for incoming messages) and sending a Request Message which contains a Message Header, a blank line separating the header and the body, then the Message Body(which is optional). The Request Message Header contains a Request Line which is the first line of the header, and the Request Headers which a variable number of key pairs. An example of the request line format looks like :[METHOD] [Request URI][HTTP Version] => GET/index.html HTTP/1.1A request body may be sent to the server and its body content begins after the empty space after the request header. Content length is important for it will determine how large the message body is.After the request has been received, an HTTP Response is sent back to the client. The server is communicating with the client request with a message and the requested data. The HTTP Response Message is formatted in similar way to the HTTP Request Message. It contains a Status Line in the Response Header, and a blank line space to separate the Response Header and the Response Body. The Status Line is formatted in this way :[HTTP Version][HTTP Status Code][Reason Phrase]=>ex. HTTP/1.1 200 OKThe HTTP response Body content contains the resource that was requested and the Headers will usually contain metadata describing how to handle the body content.
Whats next? SQL… by on 10/17/2016
Structured Query Language otherwise known as SQL is the language that we use to communicate to our databases to store and retrieve data. It is a standard language in that it has syntax, logic and operators to perform operations. When we think of SQL we generally think of four operations that we perform regularly against our databases — INSERT, SELECT, UPDATE, and DELETE. To create new records in our database, we use the INSERT command to tell the database that we are “inserting” new data into our database under the assumption that we have already made a table in our database with established columns. To select pre-existing records form our database we use the SELECT command to tell the database what it is we are looking for. SELECT and its counterparts FROM and WHERE are our primary tools for getting information from the data stored in our database. To update existing records in our database we use the UPDATE command to tell the database that we are updating data currently stored in our database. Here we also use the WHERE clause that specifies a matching condition for which records we want to update and SET to specify which columns we want to update with their new values. To remove existing records in our database we use the DELETE command to tell the database that we are removing data from our database. The WHERE clause is used again to specify a matching condition for which records we want to remove. While we covered the basic “CRUD” operations our databases derive most of their value to us and our applications with more advanced query operations especially in the context of an RDBMS. RDBMS or Relational Database Management System is a database that is complaint with the relational model theory. This theory states that while the data we have maybe unique in its own right, it still has meaningful relationships to other dat stored in our database and and RDBMS helps us manage these relationships. Just like how we like our programming to be DRY we also want our data to be the same and prevent duplication or redundancy. One of the key factors of a relational database is that we have uniqueness records so that we can later identify single unique records. Many records may have duplicate values in their columns so most times we need unique identifier that only identifies a single row in a table. To achieve this we define a primary key on our table that we be guaranteed to be unique to that table and can be referenced from other tables directly. This is often an integer that is auto incrementing so that we don’t have to determine the new value when records are inserted. A secondary function of defining primary keys is that we can created our relationships from other tables based on the unique primary key on our primary table. These relationships are called constraints in that we say a certain value must exist in our primary table for our secondary table records to have proper context. Foreign key relationships must always match a non-primary key column in one table to the primary key column of another table. Since we have created related data in different tables we need a way to piece them together to have meaning when querying our database. With our key relationships defined, we can use the power of JOIN to retrieve meaningful results from our fragmented database. There are multiple types of JOINS but the most common of them is INNER JOIN. This will give us a set of rows as a result with columns specified from both tables as a single row. We remove duplication at the database level but we can query our database in ways that show duplication in our queries without storing data that way.
SQL vs NoSQL by on 05/25/2017
The simple reason why there are so many different database systems is that it is not possible for any system to achieve all desirable properties at once. Traditional SQL databases have been built to provide the full functional package that include a very flexible data model, sophisticated querying capabilities including joins, and transactional guarantees. On the other end of the spectrum, there are key-value stores that scale with data and request volume but barely offer any functionality apart from simple lookups.SQL and relational databases have been the go-t0 databases for many years however the need to process higher volumes and varieties of data at a rapid rate has altered the nature of data storage for developers which leaves the question, “Which type of database do we use?”Before we answer that question we must look and the differences these two types of databases have.SQL databases are primarily referred to Relational Databases(RDBMS) whereas NoSQL databases are referred to as non-relational databases. SQL databases have predefined schemas and NoSQL have dynamic schema for unstructured data. SQL databases are vertically scalable while NoSQL are horizontally scalable. SQL databases are scaled by increasing the hard-ware while NoSQL databases are scaled by increasing the databases server in the pool of resources to reduce the load. SQL databases emphasizes ACID properties (Atomicity, Consistency, Isolation, and Durability) whereas the NoSQL database does not.To answer the question above as to which database we should use, it all depends on the application being built. If you’re looking for speed, a NoSQL database seems like the right fit, but if you’re looking for reliability then go with a SQL database. Someone might argue to go with both, during hours of high traffic hours store the data in a NoSQL database for fast data retrieval and during low traffic hours, move the data into a SQL database to ensure the safety of the data stored.
Rails vs Node.js? Which to use? by on 06/13/2017
At first I thought that the two were used in the same way but found out with a lot of research that to compare these two would be like comparing apples to oranges.So lets review what Rails is…Rails is a server-side framework written in Ruby which utilizes the MVC architecture, providing default structures for a database, a web service, and web pages. Rails emphasizes convention over configuration, don’t repeat yourself (DRY), and the active record pattern.Node.js, on the other hand, is a platform built on Chrome’s JavaScript runtime for easily building fast and scalable network applications (It compiles the javascript code to native machine code instead of interpreting bytecode which gives a major performance boost to javascript). Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.I think a better comparison would be to compare it a server side framework like Express.jsWhen a Rails application answers a request, it goes through a few layers of Rack middleware and Rails GEMS to process and respond to that request. You know that ActiveRecord object you are using? It doesn’t require that you specify in advance the table columns because it uses introspection. Rails has all these look-ups and mappings to connect controllers, models and views to core Rails objects and GEMS. These look-ups make it faster to develop in Rails but there’s a tax. Node and other frameworks like Express are fast because they don’t provide this convenience and don’t charge this tax. It just takes longer for the team to connect up the objects.When it comes to speed of development, no matter how fast you are with Javascript and Node.js, Ruby on Rails has the game locked down when it comes to development speed. You can develop a CRUD application complete with database migrations in just a few commands via the command line using generators. Rails purists don’t use generators, but there is no denying they save time.Node.js on the other hand if you’re building a web application is a little more involved, you need to find the modules, include them and then follow along with the instructions for integrating them with something like Express (also a module install).The way Node works is that it makes you string together different components to build an application, this gives you flexibility but it takes considerably more time considering you need to download a module for practically everything.There is no definitive answer. Use whatever you are comfortable with choosing, especially if you’re building a website or application and you’re going to be the only developer.Both Rails and Node can achieve the same results, I would argue that Rails is perfect for situations where you need to move quickly (prototyping, functional CRUD app in the space of an hour) but a Node.js skeleton app or Git repository with some pre-grouped Node modules can be just as fast as well.
Value vs. Reference in Javascript by on 07/05/2017
Javascript has 5 data types that are passed by value: Boolean, null, undefined, String, and Number. We’ll call these primitive types.Javascript has 3 data types that are passed by reference: Array, Function, and Object. These are all technically Objects, so we’ll refer to them collectively as Objects.PrimitivesIf a primitive type is assigned to a variable, we can think of that variable as containing the primitive value.var x = 10;var y = 'abc';var z = null;x contains 10. y contains 'abc'. To cement this idea, we’ll maintain an image of what these variables and their respective values look like in memory.When we assign these variables to other variables using =, we copy the value to the new variable. They are copied by value.Both a and x now contain 10. Both b and y now contain 'abc'. They’re separate, as the values themselves were copied.Changing one does not change the other. Think of the variables as having no relationship to each other.ObjectsVariables that are assigned a non-primitive value are given a reference to that value. That reference points to the object’s location in memory. The variables don’t actually contain the value.Objects are created at some location in your computer’s memory. When we write arr = [], we’ve created an array in memory. What the variable arrreceives is the address, the location, of that array.Assigning by ReferenceWhen a reference type value, an object, is copied to another variable using =, the address of that value is what’s actually copied over as if it were a primitive. Objects are copied by reference instead of by value.var reference = [1];var refCopy = reference;Each variable now contains a reference to the same array. That means that if we alter reference, refCopy will see those changesReassigning a reference variable replaces the old reference.var obj = { first: 'reference' };When we have a second line:var obj = { first: 'reference' };obj = { second: 'ref2' }The address stored in obj changes. The first object is still present in memory, and so is the next object:When there are no references to an object remaining, the Javascript engine can perform garbage collection. This just means that the programmer has lost all references to the object and can’t use the object any more, so the engine can go ahead and safely delete it from memory. In this case, the object { first: 'reference' } is no longer accessible and is available to the engine for garbage collection.Passing Parameters through FunctionsWhen we pass primitive values into a function, the function copies the values into its parameters. It’s effectively the same as using =.var hundred = 100;var two = 2;function multiply(x, y) { // PAUSE return x * y;}var twoHundred = multiplyByTwo(hundred, two);In the example above, we give hundred the value 100. When we pass it into multiply, the variable x gets that value, 100. The value is copied over as if we used an = assignment. Again, the value of hundred is not affected. Here is a snapshot of what the memory looks like right at the PAUSE comment line in multiply.We refer to functions that don’t affect anything in the outside scope as pure functions. As long as a function only takes primitive values as parameters and doesn’t use any variables in its surrounding scope, it can’t affect anything in the outside scope.A function that takes in an Object, however, can mutate the state of its surrounding scope. If a function takes in an array reference and alters the array that it points to, perhaps by pushing to it, variables in the surrounding scope that reference that array see that change. The array has been mutated and affects information present outside the function. This can cause undesired side effects that can be difficult to track down.Many popular array functions, including Array.map and Array.filter, are therefore written as pure functions. They take in an array reference and internally, they copy the array and work with the copy instead of the original. This makes it so the original is untouched, our outer scope is unaffected, and we’re returned a reference to a brand new array.
ES8……… 9, 10? 11? 12? by on 07/25/2017
ECMAScript 2017 8th editon (ES2017/ES8) has been officially released and published a few weeks ago, let’s figure it out some important changes. All of these are available with Node 8 and with the latest version of browsers without babel or any polyfills.Object.valuesLike Object.keys, but for values.Such as Object.keys do, the Object.values method returns an array of a given object’s own enumerable property values instead of keys.https://medium.com/media/32d700f2c8471f4009ce1c56e9c5c43e/hrefObject.entriesIf we merged Object.keys and Object.values, that would be Object.entries. It return an array of [key, value].The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs.https://medium.com/media/787a8030b4989c079e0739d0b39ab524/hrefpadStartPad a string from the start until the given length is reached.The padStart() method pads the current string with another string (repeated, if needed) so that the resulting string reaches the given length. The padding is applied from the start (left) of the current string.https://medium.com/media/30c92e7922ef7957367823d918fade88/hrefpadEndPad a string from the end until the given length is reached.The padEnd() method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end (right) of the current string.https://medium.com/media/3185f71117cfd8fd022fd97c124dca25/hrefTrailing commas in function parameter listshttps://medium.com/media/6880d417af1a2391352bbf7e13657387/href
Tips for your next Web App by on 08/15/2017
UX for beginners1. Provide a similar experience, regardless of the deviceVisitors are coming to your site using many different types of devices: they can visit your site on their desktop or laptop, tablet, phone, music player or even their watches. A big part of UX design is ensuring that no matter how the visitor sees your site, they should have a similar experience regardless of the device they are using.2. Design easy-to-use clear navigationNavigation is a cornerstone of usability. Remember, it doesn’t matter how good your website is if users can’t find their way around it. That’s why navigation on your site should be:Simple (Every site should have the simplest structure possible)Clear (Navigation options must be self-evident for visitors)Consistent (Navigation system for the home page should be the same on every page)Design your navigation in a way that gets visitors where they want to go with the least amount of clicks as possible while still being easy to scan and locate where they need to go.3. Changing the color of visited linksLinks are a key factor in this navigation process. When visited links don’t change color, users can unintentionally revisit the same pages repeatedly.4. Make it easy to scan your pagesWhen users visit your site they are more likely to quickly scan the screen than they are to read everything there. Therefore, if a visitor wants to find content or complete a task, they are going to scan until they find where they need to go. And you, as a designer, can help them with that by designing good visual hierarchy. Visual hierarchy refers to the arrangement or presentation of elements in a way that implies importance (e.g. where they eyes should focus first, second, etc).5. Double check all linksA user can easily become frustrated when they click a link on the site and receive 404 error page in response. When visitors are searching for content, they expect every link to take them where it says it will and without a 404 error or to another place they weren’t expecting.6. Ensure that clickable elements look like onesHow an object looks tells users how to use it. Visual elements that look like they are links or buttons, but aren’t clickable (i.e. underlined words that aren’t links, elements that have a call-to-action but are not hyperlinked) can easily confuse users. Users need to know which areas of the page are plain static content, and which areas are clickable (or tappable).
Fun fact — the first time I encountered Capybara it was, in fact, the rodent variety as seen above, when my mom thought it would be a good idea for me to work at a zoo one summer when I was fourteen. Yes, really.After reading a bit about Test Driven Development (TDD) and Capybara, and using Test Driven Development for many of the lessons I have done while learning how to code, I realized that while Test Driven Development might not always suit every project, learning how to write tests (both the how and the why) would be a great skill. Whether building out my own projects, or someday in the future perhaps adding functionality into a new codebase and working with other developers, I know at some point I’m going to be expected to be able to write tests and not just rely on tests that are already built in, or solely using error driven development.I decided to try out writing some Capybara tests of my own, from scratch, in relation to a small ruby web app, just to get a feel for the process, from start to finish, and document as I go, so thatI have a small reference guide for myself for the logic and the methodology.What is the difference between Capybara and RSpec?RSpec tests are generally used for testing your controllers and models. For a model, an RSpec test might check your validations, both of when an instance is or isn’t valid. RSpec tests are also used for controller tests, but writing out controller tests can sometimes get redundant. One benefit of Capybara tests is that it can check both the controller and the view almost bundled together, under the category of “feature.” Essentially, Capybara checks a page to see 1) that the information is displayed there and 2) how it is displayed. If your controller isn’t working properly, you won’t be getting your view pages, and thus your Capybara tests aren’t going to pass either.Setting up the blog appFirst things first, I’m going to make a blog app about dinosaurs completely from scratch.I used the Learn.co guide on Rails testing as reference, and am using some basic commands to generate my directory and file structure:$ rails new dinosaur-blog -TThen, per the instructions, I want to add gem ‘rspec/rails’ and ‘capybara’ to my Gemfile, and finish up by generating a spec folder.bundle installbundle exec rails g rspec:installI also have to require ‘capybara/rails’ in rails_helper.rb and integrate Capybara and RSpec in spec_helper.rb using require ‘capybara/rspec.’Brainstorming my objectives (a “pre-test”, if you will)Now, since my set up is pretty much ready to go, the basis of using Test Driven Development is to come up with tests before actually writing any of my code. This is something new to me, but since it’s a pretty basic web app, I figured I could come up with some ideas of the functionality I want ahead of time. This actually makes a lot of sense, because how can I really build something without knowing what I’m trying to build?ObjectivesI’m going to think through everything for my app, although I know that writing all of these tests would be a combination of both RSpec and Capybara tests. For this blog post, I’m only going to walk through one sample Capybara test, but I know that having a strong foundation of logic will help me in the future as I’m learning to write other tests. So. What do I need to start with while building this app?ObjectivesHave a landing page that is an index with a list of the name of each dinosaur in my databaseEach of those names is a link to an individual pageOn each dino page, I can see: a picture of the dinosaur, in a header, its name and the period during which it lived, and a fun factI can add a new dinosaur by clicking a button on the bottom of the index page, which brings me to a form where I add in each criteria (all of them are required)I can edit a dinosaur by clicking a link on the bottom of the dinosaur’s individual page, which brings me back to the form that I can then updateOkay, this seems like a good place to start. Number 3 seems like a good fit for a Capybara tests, because I know that it’s going to check to make sure the view is rendering, that I can see certain (dynamic) information on the page, and that the information in formatted in a certain way.Now, although I have seen a lot of Capybara tests, I don’t really have any idea how to write them from scratch. So, I pulled up the RubyDocs for Capybara to start exploring the DSL.Capybara DSLThere is a lot of very, very long documentation for Capybara. The main takeaways that I got were:Capybara tests are case sensitive!The documentation has information that relates to both classes and methods, which you can see listed out on the sidebar if you are looking for something specific.Capybara tests fall into one of the following categories in terms of what is being tested: navigation, clicking links and buttons, interacting with forms, querying, finding, scoping, working with windows, scripting (in drivers that support JavaScript — not relevant here), modals, and debugging. You can also write tests using sessions.Writing a Capybara Features TestNow, I’m going to get my sample test going. Remember that I have already addedgem 'capybara' to my Gemfile. Then, I added a features folder with a dino_specs.rb file under my specs folder.Finally, I started writing some sample navigation tests, again based on those I had already seen from Learn.co. Here is the example that I looked at for reference.My objective here was:On the dinosaur’s individual page, I want to see in a header, its name and the period during which it lived, and in a sentence, a fun fact about itrequire 'rails_helper'describe 'navigate' do before do @dinosaur = Dinosaur.create(name: "My First Dino", period: "When I lived", fact: "Dinosaurs are really cool") endit 'shows the name on the show page in a h1 tag' do visit "/@dinosaur.id">dinosaurs/#{@dinosaur.id}" expect(page).to have_css("h1", text: "My First Dino") endit 'shows the period on the show page in a h2 tag' do visit "/@dinosaur.id">dinosaurs/#{@dinosaur.id}" expect(page).to have_css("h2", text: "When I lived") endit 'shows a fun fact on the show page in a p tag' do visit "/@dinosaur.id">dinosaurs/#{@dinosaur.id}" expect(page).to have_css("p", text: "Dinosaurs are really cool") endendThen, I ranbundle exec rspec spec/features/dino_spec.rbAnd, moment of truth…Here are the failures:I have never been happier to see failing Capybara tests!!!!!!!Each of them are related to navigation and note that I don’t have my routes set up! This is great — my test is working! Obviously this is just the first step of many, and as I’m building my code, the failures or errors will change.Take AwaysThe logistics of writing tests with Capybara is fairly simple, once you have the correct folder structure and gems installed. That said, I wrote one of the most simple tests that I could, just to see if I could get things working. I’m sure it will become more complicated as I try to write more complex and interdependent tests.As for using the DSL, what was most helpful for me was looking at models that are similar to what I’m creating and using them as reference until I get more familiar with the syntax and best practices for Capybara.Knowing why you’re testing and how to make flexible but useful tests really seems to be something you just have to learn by doing. I read lots of blogs and resources, and basically all of them said, you can try to learn it by reading references or the docs, but really the best thing to do is learn by reading tests, practicing writing tests, and watching more experienced programmers as they develop their tests. Capybara is really just another kind of programming, and a lot of developers consider that when you’re writing tests, the code is just as important as the code that builds your program.What’s NextDuring the writing of my Capybara tests, I also explored writing RSpec tests, as mentioned earlier in the post. I found this great resource, RSpec Testing for Beginners, Part 1 by Ed Wasserman, which gives a great setup for building out a quick RSpect setup using rails with a dummy model. I did have trouble translating this information into something I would be able to integrate into my own programs, so this will definitely take a bit more for for me to figure out and start using on my own, but I think it would be a great skill to have.ResourcesRuby Rails Testing - Learn to code online.Rspec Code Tutorials by Envato Tuts+File: README - Documentation for teamcapybara/capybara (master)
Remember Why Writing Tests is a Good Idea?In short:It’s extremely useful for debugging to have testsIt forces you to reason through things and think in terms of small, manageable bits of codeIt will help with division of responsibilitiesIt will make you more impressive when you try to get a job if you have TDD skillsEveryone keeps telling me it’s fun? The Mocha tag line is actually “simple, flexible, fun.” (I am not sure about this YET, but I think at least in Mocha, the nyan cat will help me feel more motivated.)Also, RuPaul, in his infinite wisdom, claims, “Fulfillment isn’t found over the rainbow-it’s found in the here and now.” Hopefully I will find fulfillment en route to the nyan cat rainbow.Getting StartedSo, how should I start writing mocha tests, and build a small application to see if I can actually do TDD? Even with my capybara testing, I only got the red, I didn’t get the green or the refactor. So, I’d like to try to get an entire set of tests written and passing!InstallFirst, I visited the Mocha site for some insight into where to start.Install Mocha by running the following code in your terminal$ npm install --global mochaStart your projectIn your terminal, run the following:$ npm install mocha $ mkdir mocha_test_app$ cd mocha_test_app$ touch test.js$ touch package.json$ atom . I followed the following example from Mocha to ensure that everything was set up and communicating correctly:var assert = require('assert');describe('Array', function() { describe('#indexOf()', function() { it('should return -1 when the value is not present', function() { assert.equal(-1, [1,2,3].indexOf(4)); }); });});Then, I set up a small snippet of JSON that allows you to run “test” in the terminal to execute the Mocha test:{"scripts": { "test": "mocha --reporter=nyan test.js" }}Make sure you are actually using JSON and the brackets around the entire piece of code, otherwise the test will not pass!Now, you can test the code using “npm test” in the terminal:Got the first test, and it’s passing! Now that I’m sure that everything is set up correctly, I’m going to get rid of this test (it’s not really related to what I want to do), and start thinking through the code challenge I’m going to work on.The Code ChallengeFor this test, I’m going to try working on a common code challenge that’s presented during Junior Developer job interviews (because, why not?).This one is, according to the internet, reportedly used during interviews at Microsoft.Write a function in your favorite programming language that will accept any two strings as parameters and return “1" if they are anagrams and "0" if they are not.LogicFirst of all, what are we testing here? Really, at a very basic level, we are looking at the characters in two strings, and seeing if those match up exactly.A common example is “silent” and “listen.”Made with Wordsmith anagram animatorIf I were just looking at two words, such as the words above, and I were doing this without a program, I would probably write both of the words out, and go through each letter of the first word, cross it out, and cross out the same letter (if it exists) in the second word. This seems like it would be very easy to do with paper, but might be a bit complicated with code.Another way to do it would be to put both words in alphabetical order, and see if they are exactly the same. This is something I would NOT be able to do easily on paper, because I have to recite the entire alphabet each time I try to figure out where a letter goes, but it is probably something a computer could do very easily!So, most simplistically, I am expecting my code to:Have a function called anagramDetectorThis function should take two arguments, both of which should be stringsThe function should split each string into it’s characters and put them in alphabetical orderThen, it should compare those two arrays. If they are equal, return 1. If they are not, return 0.Figuring out how to write testsThere are several libraries you can use when deciding how to write your test assertions, or essentially the structure and syntax of your tests. Chai is particularly popular, but since the program I am working on is a small code challenge which does not need a lot of test cases, I’ve decided to go with expect.js, which is even simpler and very straight forward. The API is also simple to understand and implement.Here is an example from the documentationmath.jsfunction add (a, b) { return a + b; };test.jsdescribe('test suite', function () { it('should expose a function', function () { expect(add).to.be.a('function'); }); it('should do math', function () { expect(add(1, 3)).to.equal(4); });});Following this template, I wrote my first test as follows…var expect = require('expect.js');describe('test suite', function () { it('should expose a function', function () { expect(anagramDetector).to.be.a('function'); });…and got my first test to fail!HOORAY FAILING TEST!I’ll repeat this process for each test I need to write as I progress in my code, until I get all my tests to pass an my code working as expected!