Flatiron Blogger Magazine

What does it feel like to be a programmer? by on 06/23/2017
In short: not much different from being any other human. I’ve been learning to code intensively over the past couple of months, and while I’ve become much more comfortable with writing applications, I haven’t undergone some sort of radical transfiguration. Becoming fluent in e.g. JavaScript makes you no more a wizard than becoming fluent in e.g. French makes you a frog (or themed nyancat.)Not a consequence of learning French. (via Giphy)Of course, my transition has been a longer, more circuitous and less dramatic (or exciting) of a journey than it has for some others who go through these kinds of immersive programming programs; for starters, I always knew I wanted to be an engineer — I just didn’t really know what kind — and I ended up going through a traditional, 4+ year undergraduate program in mechanical engineering, followed by a 2+ year graduate program in biomedical engineering). Even before then, I picked up the tip of the iceberg of Java in high school in an independent study (emphasis on the independent: my school didn’t have any CS instructors, and I was just given a textbook with problem sets), and while I picked up the basics of array manipulation, I didn’t really understand what I was doing: I just learned to start any given program with public static void main (String args[]) and sandwich the good stuff (if you can call basic array manipulation “good stuff”) between the curly braces which followed. The one required CS course I had in college was a total snooze and left me feeling similarly empty, without any real understanding of what I could do with C++ or what object-oriented programming was. To me, programming was an obtuse, niche discipline that a few bona fide nerds delved deep into but that the masses could largely ignore.Software engineering: not just for (math) nerds. (via Giphy)It wasn’t till the better part of a decade later that I really woke up to the power of code. I left grad school to join a startup in 3D printing, a field ideally suited to showing mechanical engineers just how clunky the products of their discipline are. It was there I discovered the utility of the open-source microcontrollers that translated software instructions into the physical actions that melted plastic and deposited it in place to make custom parts that existed in the real world. Things that took hours of careful work and patient tweaking could be abstracted away in a few lines of code, and it indeed oftentimes seemed as if the software department at that company were running circles around the mechanical department. Incredulous and intrigued, I tried my hand at hacking on these software-hardware interfaces, and using code to solve problems was so effective that it felt like cheating. Hooked, in my spare time, I built and wrote code for everything from a 3D-printed blinking jellyfish necklace to a garden timer hack that engaged its rain delay functionality if rain was forecast by an API to ponytails that moved like, well, pony tails.Coding with hair.Looking back, my code was garbage — that is to say, while it worked, it wasn’t very readable (I needed copious comments to describe what I was doing) and was borderline imperative, not really taking full advantage of the object-oriented nature of the programming language I was writing. That’s okay, though: no one’s code’s very good in the beginning, and the code I was writing was finally doing things I found useful and/or interesting. I was able to teach myself enough that I was able to explain it to others with no coding experience themselves, and I picked up a gig teaching high schoolers the fundamentals of programming for a couple of months one summer. Being the teacher I never had at their age was a rewarding experience, and realizing I somehow knew more than I thought I did, I started applying to full-time software engineering positions thereafter, only to find out that, while I could logic my way through an open-book, work-at-your-own-pace coding challenge assessment, I still had to try too hard to do well on them, and my code still stunk.When I did land whiteboard interviews, I didn’t know what to do with the marker they’d given me, oftentimes making the mistake of clumsily diving straight into scrawling out some kind of half-pseudocode, half-Python jumbled mess of code instead of pausing to talk through my thought process and sketching out logic flows. During those whiteboard interviews more than ever, I really didn’t feel like a programmer: I felt more like an imposter faking his way though an ordeal while the “real” programmers looking on saw right through me.Wait, are you the real deal?As the definition of insanity is said to be doing the same thing over and over again and expecting results, I decided to switch strategies. While great practice, I was tired of going through countless job interviews and struggling through myriad coding challenges for way longer than I should have. I needed to be able to code in my sleep and teach myself the fundamentals of computer science before I would feel like a programmer — and moreover, before prospective employers would feel like I was programmer. Now, after a couple of months of coding full-time in an education environment, I indeed feel more like a programmer — or I at least feel more comfortable calling myself one — but the transition, I assure you, while marked, was a gradual one. There was no magic moment of radical transformation, just a steady stream of concepts I’d had but a tenuous grasp on before all of a sudden making sense. I’m more or less at the point where I can “code in my sleep” — and indeed, I’d have coding stress dreams — but I still feel like the same person I was before, merely more confident in my skills as a computer programmer.So there you have it: a programmer is a programmer because they’ve just studied the field and practiced working in it a fair amount, the same way a nurse is skilled in medicine because they’ve studied medicine and worked in a hospital for some time, the same way a welder wields their title because they’ve learned from someone else who can do what they do and have practiced their trade a fair amount. Practice doesn’t only make perfect, it seemingly works magic and makes us all who we are — but when it comes down to it, the specialists we may be, we’re all still very much human.
Algorithm Complexity by on 06/22/2017
Think of this post as notes really on a subject I am trying to understand. Algorithm complexity is a formal way to measure how fast a program or algorithm is. It is something that compares 2 algorithms at the idea level, disregarding low-level details like hardware or instruction set given to the CPU.
Anatomy of a Random Question Generator by on 06/17/2017
Please note that this post is a work in progress. I have noted the point in where I will continue below. There are plenty of quizzes online, however if you take it again you’ll already know the answers and will get 100%. Sometimes the quiz will randomize the order of the questions, but you’ll still know them. Sometimes the quiz have a larger question bank to choose from, but after taking the quiz enough times you’ll know all their answers as well.
Objects and Objectives by on 06/21/2017
On Objectives…When I decided to attend a programming boot camp, I intended the journey to be equal parts self-discovery and academic pursuit. After years studying and then going on to work as a commercial pilot and aerospace engineer, I needed a new and interesting challenge. I needed to see what else the world had to offer and programming seemed to offer endless possibilities for exploration. Just as in object-oriented programming, programming skills can serve as packages of functionality that can be applied to concepts across varying subject matters.On Objects…They say, but for a few special cases, “everything in Ruby is an object”. As an object-oriented programming language, Ruby allows us to group functionality and data using “classes”. Classes are the templates for creating objects. Triggering “instances” of these classes allows us apply abstractions of code and logic to different data sets requiring similar manipulation and functionality.Classes OverviewRuby already has several built-in classes, but it also provides a way for us to develop custom classes. Let’s say that we really like aircraft, and want to be able to create a bunch of them for our flight simulation game. We could create a class, Aircraft, that would contain all the components, including data and functionality. Defining the class would start like this :Between the ‘class’ and ‘end’ keywords, we can assign attributes, stipulate data requirements and tell the class what to do with the data it contains. An important part of a class is mandating what data fields each object must contain upon creation. This is accomplished using the ‘initialize’ method. The code shown below shows how we can initialize an object, store data and perform a function, all from within the instance.With these definitions in place, we can create many aircraft instance simply by calling the class Aircraft and providing the arguments required in the initialize function.These explanations are very high-level. In future posts, I will be breaking down the characteristics of a class in greater detail.
How .send() works by on 04/12/2017
The story of #sendLet’s get meta for a minute. Remember the movie ‘Back to the Future’? Of course you do (and if you haven’t seen it, well, that deserves a whole other article). In the movie, Marty travels back in time and nearly alters the course of history when he interferes with his parents meeting and falling in love. His actions threaten his very existence, disrupting the time space continuum and life as he knows it.This is of course fiction, but the idea of one action directly influencing another linked action is all too real.Take the #send method, for instance. It’s a part of Ruby metaprogramming: a feature in which programs are written to write or manipulate other programs. Metaprogramming allows programmers to spend less time writing individual lines of code by having a method do it instead. An example of this is using #attr_accessor in a new class instead of defining setter and getter instance methods over and over. #send is metaprogramming too. It allows you to manipulate a class with methods defined elsewhere in the code. You can use it to test private methods on a class, too. So meta, right?derpHow does it work? Let’s say you have defined a class, Car, below:class Car attr_accessor :engine def initialize(engine) @engine = engine endendIt initializes with an engine attribute. We can create an instance of Car called delorean:delorean = Car.new("flux capacitor")Let’s leave our delorean parked for a moment and define two methods, outside of the Car class, to demonstrate how #send will work here:def drive(name) "Vroom vroom! #{name} is driving around in a regular old car, no big deal."enddef time_travel(name) "SPARKS! FIRE! OMG, #{name} has traveled back in time to 1955! His mom has the hots for him! Ew!"endWe want our delorean to invoke one of these methods depending on what kind of engine it has. Since the methods are outside of the Car class and the delorean object, we can use #send to actually SEND a method to delorean if a certain condition is met:if delorean.engine == "internal combustion" delorean.send(:drive, "Doc")elsif delorean.engine == "flux capacitor" delorean.send(:time_travel, "Marty")endSince the delorean's @engine is equal to "flux capacitor", we sent it the method #time_travel. The first argument of #send is always going to be the method you want to send (in the form of a key), and the second argument is the argument taken by that method (in this case, will “Marty” will be the name accepted by :time_travel). With this in mind, we can expect the following output:"SPARKS! FIRE! OMG, #{name} has traveled back in time to 1955! His mom has the hots for him! Ew!"We have now successfully used #send to send the method #time_travel to the object delorean. Great Scott!
What’s a zero-day attack? by on 05/10/2017
When news breaks of the latest cyber attack, one of the buzzwords you may hear is “zero-day attack.” Sounds like some kind of computer sorcery, but what is it really?zero-day attack in progressLet’s look at one of the most serious instances of one of these attacks. In 2015, a cyber attack targeted the U.S. Office of Personnel Management (OPM). Attackers were able to obtain credentials for a government contractor and used them to gain access to OPM’s network. Inside, they exploited a vulnerability in the network’s security to plant an undetectable piece of malware that quietly siphoned off all manner of government employee information for almost a year. Once the malware was discovered, government security experts had to sift through the massive outdated network to purge any remaining instances of it. Ultimately, millions of personal records of government employees were stolen. The amount of data breached is directly attributed to the time the malware lived inside the OPM network, exporting data unnoticed.This kind of coordinated effort exploits a weakness in software that developers are either not yet aware of, or haven’t yet come out with a patch for. It’s called “zero-day” because once an attack is noticed, the software developers work immediately to figure out where the weakness is located, and how to fix it. You might even say they have zero days to solve the problem.Attackers usually steal information so they can turn around and sell it to the highest bidder. Shady folks online might be interested in fraudulently using credit card and bank passwords. Other shady folks may want a list of email addresses so they can send phishing scams to as many people as possible. Interestingly, neither of these things happened in the wake of the OPM attack, leading experts to believe a foreign government stole the data for intelligence purposes. A similar attack happened to the Democratic National Convention in 2016, where attackers were able to find and exploit in the DNC security, inject malware to gather data, and mine a large amount of it before being discovered. The stolen information was used against the Clinton campaign with the intent to sway the outcome of the presidential election. Sad!I hate this hacker crapTwo steps in the right directionThere is no be-all/end-all defense against a zero-day attack, since by it’s very nature it relies on exploiting vulnerabilities that are unknown to the developer. The key is to detect the breach as quickly as possible to cut of the extraction of data.A common thread with many zero-day attacks is that it starts with stealing the credentials of a verified user. Once an attacker has access One way to significantly lower the possibility of this kind of attack is by requiring two-step verification. Had that been part of OPM’s security, the bad actors who were able to gain access by stealing an contractor’s credentials in the first place might have been thwarted. Imagine if the contractor’s login had to be verified by a random code sent to his cell phone via text. The likelihood of an attacker having access to both his credentials and his cell phone is significantly lower. Of course, it’s not impossible for someone to steal both your work credentials and your phone, but now they need to work twice as hard. If an attacker gets past initial network security, the best bet is to identify the exploit as early as possible so it can be patched. The longer the exploit goes undetected, the more data will be stolen.But my password is encrypted…I’m good right?Nope. Though it is true that a password hashed using something like bcrypt is tough to crack, not all companies or governments use up-to-date encryption. Sometimes the passwords stolen in these attacks use obsolete encryption methods, and are easy to crack via rainbow table or brute force techniques. In the case of the infamous Ashley Madison hack, passwords hashed with bcrypt were stored in the same database as passwords hashed using less secure MD5 encryption. MD5 passwords were easily cracked, and since they correlated with the bcrypt passwords, it made those easier to crack as well.Take the recent Yahoo hacks as another example. Most of the data stolen from Yahoo were old, weakly encrypted passwords, and unencrypted password hints. Why should that matter if say, your bank account’s password has state of the art encryption? Answer: people tend to use the same password for everything. If a hacker gains access to a bunch of old defunct Yahoo email accounts, there is a good chance that some of those account holders used the same password for a credit card or bank account.Zero-day attacks will happen. No matter how secure an organization’s systems are, there will always be attackers probing around for vulnerabilities that the developers aren’t yet aware of. However, through encryption and two step verification, you have a higher chance of deterring an attacker from being able to user your info. Moral of the story: don’t use the same password for Ashley Madison as you do for your bank account.Sources:Inside the OPM Hack, the Cyberattack That Shocked the US GovernmentOnce seen as bulletproof, 11 million+ Ashley Madison passwords already crackedWhy the OPM Hack Is Far Worse Than You ImagineWhat is a Zero-Day Exploit? | FireEyeHacking of Government Computers Exposed 21.5 Million PeopleWhy the "biggest government hack ever" got past the fedsRussian Agents Were Behind Yahoo Hack, U.S. Says
Single User Authentication in Rails by on 05/23/2017
Curry on, my wayward son (closures too) by on 06/21/2017
In JavaScript, functions are first class citizens, meaning they are objects that can be dynamically built. They have some really cool and magical properties, but some of the fancy language surrounding them can be confusing. It’s important become familiar with these concepts and the terms associated with them in order to put the FUN in FUNction.A basic functionLet’s start with a basic function to examine how we can use it as a callback, then a closure, then a curried function. I’m going to use Super Nintendo as an example. (If you don’t know what Super Nintendo is, it was the best gaming console ever.)function superNintendo(game){ return game + " is now on the screen"}The function superNintendo takes in one argument, game, which is a placeholder for the game you want to play. Functions have access to global variables, so I have defined three global variables to represent different games. I pass those into the superNintendo function and show the return values:let zelda = "Zelda: A Link to the Past"let metroid = "Super Metroid"let mario = "Super Mario World"superNintendo(zelda)// "Zelda: A Link to the Past is now on the screen"superNintendo(metroid)// "Super Metroid is now on the screen"superNintendo(mario)// "Super Mario World is now on the screen"Callbacks and Higher Order FunctionsIn the golden days of yore, there was Game Genie. It was a game cartridge that plugged into your Nintendo and accepted another game cartridge in the top port and a cheat code input by the user. Similarly, a function can accept another function as an argument. A function passed as an argument is called a callback function. A function that takes a callback as an argument or returns a function as a result is called a higher order function.The only way to beat ContraThegameGenie function defined below takes two arguments: console, which will be a callback function, and cheatCode, a string.function gameGenie(console, cheatCode){ return `Game Genie activated! ${console}, ${cheatCode} is on!`}Here it is using the superNintendo function and mario variable defined earlier:gameGenie(superNintendo(mario), "infinite lives")// "Game Genie activated! Super Metroid is now on the screen, infinite lives is on!"Callbacks are used all the time in JavaScript, and it’s part of what makes it so powerful. You can set up a function to fire off when another function executes, and have a chain of events by putting callbacks inside callbacks. Event listeners like onClick and onMouseOver can execute a callback function on an event. As you can imagine, this is a key tool in web development. JavaScript many useful higher order functions that are built in, too. For example, map and filter each iterate over and array, and mutate each element in the array with a callback function.ClosuresThey sound scary, but a closure is just a function that has access to variables within its own scope, the scope of its parent function, and global variables. Closures are a great way to separate concerns and keep code DRY. They contain their own inner environment which means you can make a function geared to a specific purpose. Going back to the exampleWe can turn our function into a closure to give it some extra features:function superNintendo(game){ let message1 = " is now on the screen! " return function lives(num){ let message2 = " lives left." return game + message1 + num + message2 }}let playMario = superNintendo(mario)let playZelda = superNintendo(zelda)let playMetroid = superNintendo(metroid)//theses are all closuresplayMario(3)// "Super Mario World is now on the screen! 3 lives left."plaZelda(2)// "Zelda: A Link to the Past is now on the screen! 3 lives left."playMetroid(1)// "Super Mario World is now on the screen! 3 lives left."The superNintendo function now takes in a game as an argument, and returns the inner function lives, which accepts a number argument. lives has access to mario from the global scope, message1 from the scope of it’s parent function, and message2 from its own scope. The variable playMario becomes a closure because it stores mario in the environment of the superNintendo function. playZelda and playMetroid are closures too. The alternative to using a closure here would be to write out the superNintendo function each time; closures help to avoid repetition and keep your code readable.CurryingYour very own cheese pizzaYou may be wondering what was going on with the last few lines above. The number attached to the closure is the num argument for the lives function. We only saved playMario with a game argument. No big deal though, because we can add the num argument now like this:playMario(3)// "Super Mario World is now on the screen! 3 lives left."This is currying. Currying means that the closure does not have to receive all of it’s arguments at once, but separately. We have constructed the playMario function with only one of it’s arguments and it will wait to return until it receives it’s last argument. I like to think of currying as adding ingredients (arguments) to a function one at a time. (Currying is actually named for this dude, not for the spice.) You can give it some arguments now, and other arguments as you go. This can be useful if the arguments in your function depend on other actions in the program. Or, like in this case, if you want to make a closure with one argument of a function, and then curry the second argument if that argument will be a different value each time you call it. If this sounds like if can get really complex really quickly, you’re right. Luckily there are libraries, such as Lodash, that provide a built in currying method.These are some core concepts of functional JavaScript programming and can be used to make your code flexible and powerful. If you have any real-life examples of currying, or a favorite curry dish, feel free to curry it into the comments.
Writing and Programming by on 06/16/2017
Same, same… but different… by on 06/19/2017
Source: GiphyWhile studying for Monday’s rails code assessment, I decided to practice by building out a new app, setting out with the intention of creating an app with similar models/associations to those in our Amusement Park lab.Inspired by my time at Artsy, I decided to see if I could create some basic foundations of a mock online art sales platform over which galleries could list artworks for sale, and users can purchase those galleries’ artworks and additionally add artworks of their own already in their posession.At first my models looked like this:Initially my models looked like the above. Users (collectors), Galleries, and Artitst all had many artworks, and the artwork model served both to store information about indivdual artworks and to be the join table between all these attributes.Soon, however, I realized that I’d made the situation more messy than I’d intended. When I began to plan out the views and controllers, because both a collector and a gallery would need to have login/sign-up views and many of the same attributes, I realized that they were the same…but different…but kind of the same. Both galleries and collectors were users, just different types of users.This would require some aliasing of the artworks’ user references such that there are two different user_ids being referenced. After a handful of migrations to drop the galleries table, add a user_type to the users table, and add correct references for collector_id and gallery_id to the artworks table, I was on my way.My model relationships now looked like the above. An artist still has many artworks/an artwork belongs to an artist, and a user (both gallery and collector) still has many artworks, but a gallery user also has many collector users through artworks and vice versa.To acheive this “users have many users through artworks” situation, I assigned the foreign keys on the artwork model in the following way:Now settled with the correct relationships between models, I thought the rest would be a breeze, however more roadblocks and subsequent learnings were in store.Though many were minor and quick to solve, the primary hitch I came upon was the implementation of the new artwork form. Whether the current user is a gallery listing a work or a collector logging a work they’ve already purchased, they should be able to create an artwork with a title, artist, year, price, etc. Additionally though, a logged in gallery should also be able to indicate a collector who has purchase the work (and leave it blank if not), and a logged in collector should be able to indicate from which gallery they purchased the work. Neither however, should have to indicate themselves in their respective role related to the artwork being created.Utilizing the aliased foreign keys in the form had me stumped for a while, but after some research and debugging, I took the following approach to the shared artwork creation form:Artwork Form (collector view)In this form, if a collector is logged in, their id will get passed to the artwork’s collector_id in a hidden field, and they will be able to choose from all available galleries in a dropdown to associate that gallery’s id to the artwork’s gallery_id . The reverse will occur if the logged-in user is a gallery.This ulimately allowed for creating two separate views for a list of collectors and a list of galleries along with profile views with their related artwork lists and relationships between collectors and galleries through artworks.Collectors Index ViewGalleries Index ViewCollector Profile ViewGallery Profile ViewArtwork ViewThough this app would have a very, very long way to go to being of use, putting it together proved to be a great excercise in implementing shared objects between users of different types.
Persist (a session) like Elizabeth by on 06/18/2017
Lets start things off light…Now that I’ve got your attention lets get to business. For today’s post i’ll be guiding you through how to persist a user’s session (i.e. stay logged in) despite quitting the browser. If you don’t already know typically when a user closes the browser they are signed out of whatever website they were logged in to. We want to right that wrong because lets be honest…. no one likes to log in anymore…. its so 90's.A very broad overview of what we’ll need to do to accomplish this is:In order to persist a session we’ll need to utilize a permanent cookie (a cookie that expires ridiculously far in the future).Knowing that cookies are vulnerable we will need to create a token generator in conjunction with a permanent cookie and a remember_digest to authenticate said cookie.If some of those words sound familiar they should be, much of the authentication code is provided to us via the BCrypt gem.. with a little refactoring of course.Lets get started..First, lets create a migration to add a remember_digest to our User table (similar to a password_digest) then migrate it.Next, we’ll create a method using some ruby magic to generate our token. Here, we are utilizing the SecureRandom module and #urlsafe_base64 to generate a random string of characters, 64 in total. More on SecureRandom here.Both are already provided to us in the ruby standard library, sweet!In similar fashion to the virtual attribute of password for password_digest we need to create a virtual attribute for the token. We can accomplish this by adding an attr_accessor to the User class.Next, we need a method to generate a token, assign it to the user, and save it to the database.creates new token, assigns it to the user, and saves to db.Moving forward we need a method to authenticate the token and remember_digest match. BCrypt already has a method like this which we will simply refactor for our token/digest instead of the password/digest.One last method is needed to to create the permanent cookie discussed earlier for our user id and token and place it in sessions#create.in the sessions controller add our new method to #create.Lastly, we need to slightly refactor #current_user to also check for our cookie and authenticate the token if it is present and we’re done!If done correctly, when you sign in and check your cookies you should see something like this..CHECK OUT THAT EXPIRATION! DAAAAAAMN!Admittedly, the use case for this feature is rather small. Originally, my belief was when a user closes a window or tab (which is quite common) they are signed out. However, after testing this process before and after I realized the user is only signed out if they quit the browser application entirely. Simply closing a window or tab does not log out the user unfortunately making this feature not as useful as I originally hoped since lets be real… how many people actually quit their browser? very few is my bet as I know I rarely if ever do.maybe this topic was a bad choice?Reference:Rails Tutorial
Digital ocean, literally by on 06/19/2017
Bootcamp Life Week 5 - Highlights by on 06/18/2017
Another week has flown by. It was filled with learning, learning, learning, bike riding, eating lots of chocolate, some rain, but some really warm and sunny days, meal prep, gym, and learning. These are my highlights:Having lunch break outside in Bowling Green Park...This park is New York's oldest public park (since 1733) and we are lucky that it is just outside Flatiron School. The park has a very positive vibe and I (and lots of other lunchers) love spending lunch break there - sitting on the wooden benches underneath the trees, in the sunshine, enjoying the warmth, feeling and smelling the sea breeze coming from the nearby sea. This is our location:What are all these tourists doing around the Bull?The biggest attraction new to the park is the bronze statue Charging Bull, or sometimes referred to as Wall Street Bull. Tourists are crazy about it!They want to touch his balls!Oh yeah, people are crawling under the bulls butt to get to its testicles... They stand for virility and cannot hurt to touch them, right?We built an app for an Amusement ParkLike last week we had an all day lab that we solved in pair programming. It was definitely more challenging than the last one and we needed the next morning to finalize it. The task was to build out an app for an amusement park where the user would choose attractions and virtually take rides. What's new this time is the user authentication and authorization feature. Before I started the bootcamp I would have never thought at it would take weeks of learning Ruby before being able to learn and understand the underlying concepts for such simple things like login, logout, and sign up. As weird as it may sound: I am proud to say, "I build an app where you can login and logout!" And... We are approaching project week again!This week has been the most tiring so far. he Rails curriculum got denser with more CRUD, RESTful routes, authentication, authorization, sessions, MVC refactoring, ... For the first time I feel like I need to challenge myself to keep up with the pace. I am not alone. On Feelings Friday almost every single classmate expressed that they felt exhausted.Flatiron was right. When Joe, the school's head of education, spoke to us in orientation in the first days, he mentioned that we should get enough sleep in the first weeks, because it would get difficult after week 3. That said, our class is looking forward to next week because we are approaching the last week of module 2. And this means: Project Week! We'll spend the whole week to create an awesome project in a group of three. Like our last group project this will be a great and fun learning experience. How to divvy up the work, how to merge code, how to solve opposing ideas, etc. And at the end we will have a tangible, maybe ugly, but working app that we'll be proud of. The difference to last week is that we are creating a web app (not CLI) and so it will be something much more visual to work on and to present. Oh hello our new best friends Bootstrap and Materialize!Github repo for our Amusement Park App:https://github.com/qtotuan/rails-amusement-park-web-051517
Pry Into Your Fears by on 06/20/2017
What do you fear more than fear itself? What is fear? Why does it exist?Our brains are arguably the most complex machines known to man, and while many of its workings remain a mystery, there are some parts of it we understand.Our brains are efficient and its primary goal is surviving, reproducing and using the least amount of energy possible to do so. To further its efforts of survival, our brains have a nifty reward center in which it rewards its host (ya, “you”) for doing things it deems fit for its grand plan of survival.Our brains also created and inherited fears which work to keep our bodies on the path of safe travels.Oh, I forgot to mention, this is actually an article about coding. How, you may wonder?If you are a beginner to code, or remember what your amateur days felt like, you may remember the constant feelings of fear, and reward. One minute you are the smartest person in the world because you figured out how to solve a problem you were working on, and the next you feel like the utmost stupidest person in the world because, well, you forgot how to solve the next one.The battle is a tough one and its really hard to learn an entirely new language and logical structure when our brains are constantly bombarding us with subconscious thoughts such as “This is not important!” and “Why are you wasting energy on this, go back to what you know!” and its all time favorite “YOU CAN’T DO THIS!”. But what if I told you there was a way to both change what your brain fears, and what it rewards you for?Introducing Pry. A Ruby tool for hacking our brains fear and reward system (also a huge time saver…)So, What is Pry and how does it work?Pry is a tool that allows us to literally “pry” into our code to see what it is doing, and what will be done to it before it’s actually run. Lets give a super simple example:Say you are tasked with looping through an array of cities and making each word capitalized.cities = ["new york", "new jersey"]This may seem a bit tricky at first, and creating, running and changing methods in the dark will take time, but let’s see what it will look like if we use pry. To run Pry, you need to first install the gem (see here) and you need to require pry on the top of every file you want to use it in. like thisrequire 'pry'cities = ["new york", "new jersey"]def array_captialize(array) updated_cities = array.map do |city| city.split.map(&:capitalize).join(" ") endendNow, I saved you the time and built an already working method, however, what if we weren't sure if this was working, or wanted to see what was really happening inside of it. Well, all we got to do is throw in our Pry and whatever line it is at, it will pause your method so you can see what is going on before your method finishes running. Lets check it outrequire 'pry'cities = ["new york", "new jersey"]def array_captialize(array) array.map! do |city| updated_cities = city.split.map(&:capitalize!).join(" ") binding.pry end endNow, when we call the file in our terminal, this is what we get:notice where the => isWhats happening here? Pry, stopped our method from running, in our case assigning updated_cities to every every index it loops from our original array. So, if our Pry stopped our method from running after the first time, what do you think the return value of updated_cities would be at this point in time?YUP!! we got “New York”. Why? Because our loop only ran once before Pry stopped it in it’s place.So, if I pressed “next” in the terminal and continued the loop Pry will now stop it a second time and we would get: New Jersey!You can even play around with the value of updated_cities right in your terminal. Lets say you were adding a condition to this method that only ran if the size of the given index of updated_cities reached a certain amount. To save you the time of seeing what the index size will be, you can just test it from your terminalwe got 10!As you can see, we got 10 when asking what the size of the current index is. You can play around and manipulate whatever value your Pry is holding at right in the terminal before spending time creating more methods while not being sure if they will work correctly.We are scared of what we don’t understand, so it’s natural to “fear code”. With a tool like Pry, which allows us to really see whats going on with our code, we can spend more time learning, understanding and building good code. And if you use Pry to build code by understanding exactly what is happening at every crucial point, not only will you break through your fear of the unknown, but even better, you will finally experience the “coders high”, which is you telling your brain to reward you for something you deem important.P.S. This was a oversimplified and super simple example of what Pry can do, but hopefully I got you curios enough about Pry for you to start using it for your code.
Ruby Gems: a Link Between Worlds by on 06/19/2017
https://medium.com/media/9ffeaaa1a16bee73b99a449c4f7425c1/hrefWhile getting my feet wet with Rails, I’m understanding more and more the significance of Ruby Gems in the development process. We have already seen gems such as, byebug, bcrypt, bootstrap, better_errors, Sass-Rails, etc. So I was interested in what other gems ruby has to offer and it was seemingly infinite! Level your app up! At this stage in my development career, I narrowed down the plethora of gems based on the extent of my knowledge of rails thus far. Let’s begin…Awesome PrintAwesome Print is a Ruby library that ‘beautifies’ your ActiveRecord objects when you’re inspecting in the console. Once you start to build bigger databases, looking through at User.all, for example, will look overwhelming. So this gem will output the information in a cleaned up hash with key/value pairs. Here is an example:Not so awesome printTo awesome print!Rails PanelWhen loading up the server and testing your app in the browser, we have access to a mini testing REPL that we see when an error page shows up. This is kind of an extension of that feature. Rails Panel is a gem that works in sync with a chrome extension(there is a supporting gem that goes with called MetaRequest). Normally, when we right-click to inspect a page, we have access to information like sessions, cookies and HTML code. This gem will actually give you a tab called Rails that will provide you with even more information such as the HTTP Response Status, the Controller and Action of the route that was hit, the HTTP Verb, request format (HTML, JSON) and response time. On top of that, if you click on a view name, it will open up your Atom to the file that was being rendered. Shiny!PaperclipPaperclip is an easy file attachment library for ActiveRecord. It simplifies the requirements of uploading images and videos onto your app. It manages validations and can transform assigned photos into thumbnails, if needed. There is a prerequisite that works alongside this gem called ImageMagik. All that is needed to validate the attachment is by going to your Models object and putting in validates_attachment_content_type, adding add_attachment to your migration files and adding .input in your simpleform views file.Rails ERDThis is a gem that I feel would help me immensely because I enjoy having visual diagrams when thinking about object associations and relationships. Having visual examples is something that helps me better understand concepts and Rails ERD does just that. It generates diagrams of your ActiveRecord Models to help you visualize connections and it is there for you to reference when building up your application instead of having to keep going back to your schema.DeviseDevise is an authentication solution with 10 different modules included. It has both password and email confirmation, password recovery and resetting passwords, session timeouts and account security for when there are several failed password attempts.Other gem list resources
Yelp(¯\_(ツ)_/¯) API by on 04/20/2017
Open application program interfaces “APIs” are powerful databases for developers to access to build applications that incorporate third party information. APIs are typically mutually beneficial as they benefit developers with an useful source of data but also promote usage and visibility into content created by the API owner. In my series of blog posts, I will aim to provide an overview of different popular APIs that could be integrated into applications. This blog post will tackle the Yelp API.What is Yelp?https://medium.com/media/4218233fe9171998fb4ff0ea82915d74/hrefYelp is a crowd-sourced local business review and social networking platform. Individuals use Yelp as a way to discover new restaurants in specific locations, use reviews, ratings, picture, etc. to determine if they want to visit a restaurant, and review restaurants they have visited. Yelp, overtime, has expanded its services to include a reservation system (competing against Opentable) and a food delivery service, Eat24 (competing against Seamless — seems like a lost cause…). As of the end of 2016, Yelp has 135 million monthly visitors and 95 million reviews.Yelp API — Brief IntroductionThe Yelp API gives developers access to all of the 50 million businesses hosted on the Yelp application. Using the API, users can:Find up to 40 best results for a geographically-oriented searchSort through results using parameters such as ratings, distance, or dollar signsLimit results to specific cuisines or those that are offering a “Yelp Deal” (discounted pricing)Identify and display whether a business has been claimed on Yelp.comConnecting to the Yelp APIAs with all APIs, the first step to accessing all the information Yelp provides is to authenticate users and connect to the API. To do so, a user has to initially set up their application on the Yelp database by submitting information such as “App Name”, “Industry”, “Contact E-mail”, and “Description”.Sample form to set up a Yelp API applicationOnce a new application is created, Yelp provides users with an App ID and App secret code which will both be used to establish a connection to the API.I have deleted the App so don’t bother trying to use my App Secret Code ;)Luckily, Yelp provides a very straightforward template code to apply the App ID and App Secret to establish the connection to the Yelp API. Simply, insert the App ID in the CLIENT_ID Class Constant and App Secret in the CLIENT_SECRET Class Constant and the program will create a bearer token which will be used to access the Yelp API for future search requests made through the user’s application. A couple of things to keep in mind:The JSON gem, HTTP gem, and the OptionParse gem are required to run the connection program. Be sure to install all three gems before trying to establish a connectionThe bearer token is active for 180 days. After 180 days, a user has to create a new bearer tokenYelp limits searches to 40 results. An easy workaround is to call a search on a set of parameters multiple times and collect results in a hash. Be sure not to add any duplicate resultsYelp template codeSearching with the Yelp APIAfter setting up the connection, the next step is to prompt a search. Each search takes in two parameters: a location (can a be a zipcode, address, or city) and a term (can be a cuisine, type of food, and even something other than a restaurant term like hats or tires!). Using the search parameters, the Yelp API outputs an array of 40 restaurant hashes. Using loops, users can iterate over hashes to extract key information that they require. Each hash has the following information:Business IDBusiness NameImage URLYelp Website URLReview CountCategories (Cuisine, Food Type)RatingLocationPricePhone NumberDistance from inputted locationConclusionThe Yelp API is a powerful tool that can allow users to search for specific restaurants in their location to be able to make decisions, extract ratings information, map out details of restaurants in specific regions, and many other various use cases. The API itself is quite simple to connect and the functionality is straightforward enough to be able iterate through results. Hopefully, this was a helpful tutorial and please ask any questions in the comment section. Next time, I will be covering the Twitter API!
Nokogiri by on 05/08/2017
Machine learning is a main driver to the recent acceleration of the evolvement of technology. It allows programs to continue to get “smarter” and more powerful through the analysis of datasets. Simply, machine learning is the act of discovering and patterns buried in large data sets and using that pattern to execute a function. To me, machine learning will play a meaningful role in the development of my venture and as such, I am (slowly) working through an online course about the basics of machine learning taught by Andrew Ng, a Stanford professor. This blog post is to summarize what I have learned so far, mainly delineating between the two main type of machine learning, supervised and unsupervised learning.“Machine Learning”Supervised LearningSupervised Learning is learning that is executed using labeled data points. In other words, parameters are predefined and the algorithm knows that its looking for relationships between predefined parameters. The training data that the algorithm used already has enough details and labels which allow the algorithm to use positions of data points to infer a relationship between multiple variables. Let’s go through an example:Supervised Learning — RegressionSuppose you have a data set of apartment rent pricing in New York City. Each apartment has an attribute of monthly rent and square footage. Therefore, a data set graphed out would look something like this:P = Monthly Rent A = Square FootBased on the above, a machine learning algorithm would analyze the positions of each data point and generate a predictive function that can accurately determine the price of an apartment based on its square footage. The function can be represented by the solid line below.Line represents the relational function between Square Footage and Monthly RentBased on the predictive function, the algorithm will now be able to estimate the price of an apartment based on its square footage. So where does the learning come into play? As more apartments are rented out, the supervised learning platform will add more “real” data points to the graph and the machine learning algorithm will update and change the function accordingly reflect the positions of the new data points. Therefore, as more apartments are rented, the algorithm has more real time data to analyze which will make the predictive algorithm more accurate. The aforementioned example is a form of regression tool of supervised learning. There other version of supervised learning is the classification method in which there are a finite amount of classes (Yes or No).Supervised Learning — ClassificationClassification supervised learning refers to data points that belong to a finite amount of categories. Let me clarify this with an example. A study that requires a classification supervised learning method is determining if a tumor is malignant or benign. Since the two option values for a tumor’s attribute is discrete (malignant or benign), a tumor can only be classified with a finite set of values. So suppose you have a set of data points of for tumors with variables of age, size, and condition (malignant or benign). A graph of a data set may look like the following.X = Benign; O = MalignantA supervised learning algorithm would analyze the given data points and calculate the probability of a tumor of a given size and age to be benign or malignant. A simple algorithm would split the data at a materiality point and use that as a parameter for probability. For example, a simple algorithm would split the data into two, as illustrated below.Line represent the dividing plane for the data setAssume, the triangle is a new patient and the doctor wants to predict if this patient’s tumor would be malignant or benign. Using the above classification supervised learning algorithm, the results would determine that the tumor has about a 20% chance of being malignant and 80% change of being benign. A classification problem can have more than two classes but the only restriction is the number of classes have to be finite.ConclusionSupervised learning is one of the more innovative ways of manipulating data especially in an economy where data is driving key insights. However, supervised learning has its restrictions, mainly being that the data points used have to have predefined explicit attributes. For a set of ambiguous data points with no predefined relationships, supervised learning would be high inaccurate. Luckily this is where unsupervised learning is implemented, which I will discuss more in the next blog post.Machine Learning Introduction: Supervised vs Unsupervised (Part 1) was originally published in Towards Data Science on Medium, where people are continuing the conversation by highlighting and responding to this story.
In my previous blog post, I went over the basic fundamentals of supervised learning. As a reminder, supervised learning is a type of machine learning where the data points used have to have predefined explicit attributes. For this blog post, I want to focus on the second type of machine learning, unsupervised learning. The key distinction with unsupervised learning is that the data points used can be ambiguous with no predefined relationships.Unsupervised Learning OverviewUnlike supervised learning, unsupervised learning develops insights with unlabeled data. As a result, there is no evaluation of the accuracy of the structure that is outputted by the relevant algorithm. An unsupervised learning algorithm analyzes a set of data, groups data points based on perceived similarities and derives conclusions from these similarities. A common example of an unsupervised learning problem is the cocktail party algorithm. Suppose you have two people at a cocktail party speaking over each other so that as a third party listener you cannot tell what each person is saying. To make the example even simpler, suppose on speaker is speaking in English and the other is speaking in Spanish or there is loud music playing in the background. A machine learning algorithm coined blind source separation can recognize different patterns for different sounds and separate the distinct sound sources. See this link for an example. And what is amazing is all of the code to implement to appropriate algorithm is written on one line!Types of Unsupervised LearningUnlike supervised learning which only had two main types, regression and classification, unsupervised learning has many methodologies and number of methods continues to grow with new discoveries. Below are some of the more common ones.Clustering: Cluster analysis or clustering is the task of grouping a set of objects in such a way that objects in the same group (called a cluster) are more similar (in some sense or another) to each other than to those in other groups (clusters).Neural Networks: A neural network is a powerful computational data model that is able to capture and represent complex input/output relationships. Neural Networks require strong training data. Using training data, neural networks can identify relationships between different objects and use that relationship to analyze new sets of data.Anomaly Detection: Anomaly detection is the identification of items, events or observations which do not conform to an expected pattern or other items in a dataset.Blind Signal Separation: Blind signal separation is the separation of a set of source signals from a set of mixed signals, without the aid of information (or with very little information) about the source signals or the mixing process.Natural Language Processing: Natural Language Processing is a way for computers to analyze, understand, and derive meaning from human language in a smart and useful way. NLP uses machine learning to automatically learn patterns by analyzing a set of examples (collection of articles), and make a statical inference.ConclusionUnsupervised learning is a powerful tool that can make sense out of abstract data set using pattern recognition. With enough training these algorithms can predict insights, decisions, and results across a multitude of data sets allowing automation of many industry tasks. The rise of machine learning has truly changed the technology environment over the past few years and will continue to innovate industries and economies.
Simple Auto-Correct from a Noob Perspective. by on 06/18/2017
In our first week of Flatiron School: Web Dev we were working with APIs where we had to make a simple script that after entering a StarWars character would return a list of movies they were in. After getting basic functionality to work my partner and I thought it would be pretty cool to have a simple “did you mean method.”
Courting Javascript as a Rubyist by on 06/20/2017
Six weeks into the Web Development Immersive program at the Flatiron School and I’m smitten with Ruby. It’s hard to not be charmed by a programming language that provides flexibility, finesse, and a lovely library of methods. I often heard people exclaim that programming in Ruby could turn code into poetry.However, next up is JavaScript. During my time learning HTML and CSS, I’d been introduced to JS through the safety of JQuery. I’ve worked with developers that strummed up custom JavaScript to layer over forms to make them more dynamic.I was concerned with understanding the major similarities and differences between the two languages. So, I scoured the Internet and Google to collect tidbits of information to assist me in this transition over to JS.Here’s a collection of those tools and resources.A Brief History of JavaScriptJavascript first came into the scene in 1995 when Netscape, a leading web browser at the time, hired Brandan Eich to create a new programming language. Netscape wanted something they could layer on HTML to make the web more dynamic. The rumor is that ten days later Eich delivered with JavaScript.JavaScript’s reach spread as more websites began to use it. Major web browsers incorporated it into their tools without requiring add-ons. With the widespread use of JS libraries such as JQuery and front-end frameworks like React and Angular, pretty much every website uses JS in some shape or form.JS stayed mostly in the front-end until about ten years ago when AJAX came onto the scene. AJAX stands for Asynchronous JavaScript And XML. Basically, AJAX allowed you to create dynamic web applications with JS that would make requests, receive, and work with server data without reloading the web page. JS back-end frameworks such as Node and Express, continue to advance JS into full-stack usage.OOP and Same, Same but DifferentBoth Ruby and JS are Object Oriented Programming languages. This term should already be quite familiar to you if you have already learned Ruby.Here’s a great OOP description which I came across in my early Flatiron Ruby lessons:“An object-oriented approach to application development makes programs more intuitive to design, faster to develop, more amenable to modification, and easier to understand…….As humans, we’re constantly faced with myriad facts and impressions that we must make sense of. To do so, we must abstract underlying structure away from surface details and discover the fundamental relations at work. Abstractions reveal causes and effects, expose patterns and frameworks, and separate what’s important from what’s not. Object orientation provides an abstraction of the data on which you operate; moreover, it provides a concrete grouping between the data and the operations you can perform with the data — in effect giving the data behavior.”— Object-Oriented Programming with Objective-C, Apple Inc.Need a quick primer on OOP? Check out this five minute video:https://medium.com/media/5798a9576b5a65b387c8fd051c23f8d6/hrefAgain, since Ruby and JS already have this basic structure in common, you will be happy to find out that many of the same concepts you learned for Ruby will exist and be applicable in JS. Elements such as variables, hashes, arrays, methods, loops, classes, and conditionals exist in JS. The major differences between the two may come down to syntax and some logic.Luckily, this path has already been paved before you. Here are a few articles I found that outline this topic:Flatiron School Blog: JavaScript and Ruby: 10 Differences You Need to KnowEdozié Izegbu:Ruby vs JavaScript: A Quick OverviewSkilldrick:Ruby vs JavaScript: functions, Procs, blocks and lambdasRapid Programming: Difference between Ruby and JavascriptAgent Cooper: Side-by-Side Comparison (**very helpful)Error Messages are still your frenemiesBy now, you’ve learned to expect a barrage of error messages to flash on your screen whenever you attempt to run your Ruby programs. Many of them you recognize and receive again and again so converting them over to green is not a problem. There’s always a few that keep you up at night but, eventually, you conquer them.Ruby error messages are descriptive. With tools such as Pry and Byebug, you are able to better understand what is going on with each line of code.I had been warned several times not to get too comfortable with this as the troubleshooting world changes a little bit when you move over to JavaScript. The common consensus I’ve found online is that bug and error handling may be a test of one’s patience and sanity at times.Here are a few resources to review to get you started on the right foot. Of course, if you still hit a wall you can always copy/paste it into a Google search.Eliot Sykes:JavaScript Debugging for RubyistsWebreference:Debugging JavaScript: Understanding JavaScript Error MessagesEloquent JavaScript: Bugs and Error Handling (Chapter 8)Onward!In this video, the dean of Flatiron School, Avi Flombaum, explains why it’s good to learn both Ruby and JavaScript:https://medium.com/media/255b04fffb536af332b83262f88b9401/hrefAs nervous as you might be to learn another language, you’ve already got the knowledge and skills to take on this challenge. Just now that tactics you already learned by this point are still going to serve you well: persistence, creativity, Stack Overflow, and Google.Good luck with JavaScript, although I doubt you will need it. ;)Got comments, other helpful links/resources, or feedback for me? Please feel free to leave them below. Thanks for reading.
Not All Herokus Wear Capes by on 06/19/2017
Now that we’re all basically the next Zuckerberg in the 051517 Flatiron cohort, we should start talking about how to let our friends, family, and loyal twitter followers test out our apps. To do this, you need two things: 1. a sweet web domain name, and 2. a host.Since GoDaddy eloquently educates the entire Super Bowl audience every year on how easy it is to get a domain, I’ll stick to showing people how to host their app using a common cloud platform called Heroku.First things first, go to heroku.com to create an account. It’s free, so the hardest part is coming up with a password better than “dragons.” Once you do this, you’ll be greeted by a screen to create a project. Since we’re amazing devs and know all of the languages, you should probably choose Ruby.Heroku Dashboard before you have any projectsNext step, you need to download and install the Heroku CLI. Once downloaded, you can log into Heroku via your terminal. This will be where you can actually deploy your app. Which is actually a lot easier (initially) than it sounds. You can do this with a few simple commands (assuming the app is ready to go…just scaffold it or something…):heroku creategit push heroku masterheroku run rake db:migrateheroku openThis dope looking website is called Shielded Chamber…and it was made by following the really good tutorial on HerokuYou’re deployed! Obviously there is much more to it than that, and I’ve just begun to explore it. There is plenty of documentation on Heroku’s website, as well as what looks like a thorough tutorial to get you up and running.Things to keep in mind:You have a set number of free “dyno” hours every month. You start with 550, but can get an additional 450 by setting up a credit card with your account (these hours are still free). By default, all apps are limited to a 100 dyno limit.Dyno tiers beyond the free level, if your website is intended for a lot of traffic.You can’t use SQLite3 as your DB type. Check out how to setup ProgresQL at the below resources.Custom domain names (can’t with free account, but you can manipulate your Heroku app name to be unique).**LESSON LEARNED: CHECK YOUR GEMFILE ***Since this is the first time we’ve deployed with a “production” environment in our bootcamp so far, this can have some unintended consequences. For example, if you have a “Require ‘pry’” at the top of any file, but you only have the pry gem in your development section of your gemfile, your app will crash immediately. And then you’ll spend approximately 3 hours troubleshooting random things out of your Heroku ignorance. And then you’ll hate everything. Or so I’ve heard.Good luck (and ask Pat!).Resources:Getting Started on Heroku with Ruby | Heroku Dev CenterRails Deploy to Heroku · railsguides
Chemistry vs. Programming: How similar are they? by on 06/19/2017
Two weeks ago I began the immersive Web Development program at the Flatiron School. Prior to this, I was at Syracuse University working on my Ph.D. in inorganic chemistry. I still actually am a graduate student, but all of my research is done and I just need to finish the dissertation and defend my work. I focused on synthetic inorganic chemistry, which meant that I spent most of my time in the lab making new compounds and analyzing them. Whenever anyone asked me why I liked chemistry, my answer was that I liked the process of making something new.Leading up to the day I started at Flatiron, I knew that my enjoyment of creating things was what attracted me to programming. As part of the program, we’ve been learning about best practices in coding, test driven development, and how to approach writing a new program. It has been during these lessons that I’ve noticed several similarities from the field I came from and the new one that I’m entering.SimilaritiesCreating things that serve a purposeComputer programmers and chemists are both inventors. The goal of their work is to create new things that can be used to improve people’s lives. From software, websites, and apps to medicines, cosmetics, and plastics; we use these products everyday. Inventors need to be creative and resourceful to come up with new ideas and successfully execute them.2. Troubleshooting/problem solvingIn chemistry, it is common for new reactions to not proceed as expected or appear to not have ‘worked’ at all. When this happens you need to analyze the result to determine what you made. Based off of what you have, you determine the next best course of action. In programming, as you build your methods and test the code for a new project, you’re likely to find that everything isn’t working as desired. Even working apps will encounter bugs and errors that will need to be fixed. The specific issue dictates how you go about fixing it.3. Testing of the productWhen a new compound is prepared, its properties are assessed using a variety of analytical methods. Understanding how a molecule behaves provides insight into what applications it could be used for. In computer programming, testing is necessary to verify that the code behaves as intended and to allow for correction of any issues that arise before the product reaches consumers. You need to test for a variety of conditions to make sure your program doesn’t break under different stimuli, but of course you can’t account for every possible scenario.4. Anticipating problemsWhen a chemist is conceptualizing how to synthesize a new compound, aside from making sure the chemistry itself makes sense, it’s necessary to come up with a strategy for how to make the desired product. This requires considering potential pitfalls and how to work around them. Similarly, in programming, you need to consider problems that could occur and make sure your code doesn’t break when it encounters those issues. This can also be extended to the way the code is structured and the use of abstraction. Good programs need to be flexible enough to allow for additional functionality or other modifications to be added at a later point in time.The biggest difference I’ve found is the way a programmer thinks about the project they’re working on. First, you need to make sure you understand what your program needs to be able to do. Then, you break it down into steps. Each method should be responsible for only one task. As you code your method, you need to consider where problems could arise. For example, if one of your methods takes user input that should be in the form of a number, what happens if a user inputs a letter? Does your code check the type of input? How can you ensure your code doesn’t break?As a chemist, how you go about running a reaction is also important but the problems are more tangible. For example, maybe after your reaction you have a solution, but you want crystals so that you can analyze the structure of your compound. You need to try out various crystallization methods until one of them works. Then, it’s a matter of seeing if your crystal quality is good enough for analysis, and if not, what other methods can you try for recrystallization?
At Flatiron School, we’re always taught the fundamentals of how something works before being shown a gem or tool that improves upon or simplifies the basics. We’ve gone from Rack to Sinatra, from Sinatra to Rails, and we manually built out Models, Controllers, and Views before learning how to automatically generate resources from the command line.While reviewing User Sign Up, Password Encryption, Session handling, User Authentication, etc., I learned that there is a Gem that handles everything (and more) that we’ve learned to do manually.That gem is Devise.If you’re going to set your rails app up with Devise, I recommend checking out the official setup documentation and watching a video or two. But to get you started, I’ve provided a brief explanation of what Devise does, and why you may want to use it in your rails application.Devise is made up of 10 different modules, each of which follow the ‘able naming convention.Database Authenticatable: hashes and stores a password in the database to validate the authenticity of a user while signing in. Some of the helpers we’ve created manually so far, such as :authenticate_user!, user_signed_in?, and current_user are created automatically.Omniauthable — adds OmniAuth support. OmniAuth could be its own blog post, but essentially makes it possible for your users to sign in with their Facebook, Twitter, Github, etc. accounts.Confirmable: This module sends emails to allow your users to confirm their email addresses/accounts. Because you’ll be sending emails, you’ll have some additional setup.Recoverable: This makes it possible for your user to recover their password with a forgot password link.Registerable: This handles the new user registration process, including creating the views with forms.Rememberable: This module handles sessions by generating and clearing a token from a saved cookie.Trackable: This module gives us the ability to track the number of times a user signs in, timestamps of when they sign in, and what their IP address is.Timeoutable: Timeoutable takes care of verifying whether a user session has already expired or not,Validateable creates validations for the email and password fields in the user .Lockable: This module locks an account after a specified number of failed sign in attempts.Because Devise is so involved, the team who created it recommends you manually set up authentication for your first rails app. Now that I’ve built a few test apps with manual authentication, I plan on testing out Devise.
Javascript Promise Methods by on 06/19/2017
The promise object serves as a crucial underpinning for asynchronous Javascript operation. Promises are objects that receive their value at the completion of an asynchronous action rather than at its instantiation. This allows the programmer to design separate pathways to handle these objects at some point in the future based on the eventual success or failure of the operation.Promises are essentially stand-ins for future values, so they can be returned, passed as arguments and used in the same way a regular value would.Promises exist in one of three states:Pending — the promise object has been instantiated but has no value.Fulfilled — the async action has been executed successfully.Rejected — the async action has failed due to error.Promises come with several methods that enable you to queue up functions specifically geared toward handling the fulfillment or rejection of the async request..resolve() and .reject()The .resolve() method returns a resolved promise object with a value supplied as an argument. The argument supplied to .resolve() can also be another promise.var resolvedPromise = Promise.resolve('I do')// Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: "I do"}Conversely, .reject() returns a rejected promise object with the reason for failure.var rejectedPromise = Promise.reject('I'm just not that interested in you')// Promise {[[PromiseStatus]]: "rejected", [[PromiseValue]]: "I'm just not that interested in you"}.then()The .then() method takes two arguments: a success response handler and a failure response handler. Both of these response handlers accept one parameter: the value of the fulfilled request or the reason for the failure. Here’s an example of usage:function apiRequest () { fetch('http://exampleapi.com') .then( function(response) { console.log('Success!', response) }, function(reason) { console.log('Failure', reason) })}The return value of .then() is a pending promise. Depending on the success of the request, the associated handler function is called once the main call stack is empty, which either resolves the promise with a value of the handler’s return value or rejects the promise with a value of the returned error.You can chain multiple .then() methods together to create a process flow on a promise object, with the return value of the previous .then() statement being passed to the next.var promise = Promise.resolve(5)promise.then(val => val + 5) .then(val => console.log('And your number is...' + val))// And your number is...10.catch()Rather than using .then() with two arguments, it is preferable to use .then() with a success handler argument in tandem with the .catch() method that takes the failure reason argument. This specific method chain is called composition.function apiRequest () { fetch('http://exampleapi.com') .then( function(response) { console.log('Success!', response) }).catch( function(reason) { console.log('Failure', reason) })}The .catch() method operates exactly as .then() does with the exception that it only deals with rejected promise objects. If It should be implemented as the last method chained to an asynchronous operation..all()The .all() method accepts an iterable as an argument and returns a single promise object when all of the promises in the iterable have resolved. However, if one of the promises inside the iterable is rejected, that rejected promise will be returned.// All values will be processedvar promise1 = Promise.resolve(5)var promise2 = 99var promise3 = 'Dave'Promise.all([promise1, promise2, promise3]) .then(values => console.log(values)) .catch(error => console.log(error))// [5, 99, 'Dave']In the below example, two of the promise objects in the array are rejected, but 0nly the first item to be evaluated as rejected will trigger the .catch() method.// .catch() method will throw on first rejected promisevar promise1 = Promise.reject('Nope')var promise2 = 99var promise3 = Promise.reject('Not Today')Promise.all([promise1, promise2, promise3]) .then(values => console.log(values)) .catch(error => console.log(error))// Nope.race()In contrast to .all(), the .race() method just looks for the first promise in the array to fulfill or be rejected and returns that promise. This method is useful when time is of the essence and you want to display the fastest item to process. This method works well with setTimeout when evaluating runtimes.var promise1 = new Promise(function (resolve, reject) { setTimeout(resolve, 500, 'one')}var promise2 = new Promise(function (resolve, reject) { setTimeout(resolve, 499, 'two')}Promise.race([promise1, promise2]).then(function (value) { console.log(value)}// twoIn the above example, promise2 runs just a millisecond faster than promise1, so it wins the race and triggers the .race() method. This could be useful if you want to use a secondary source if the there is a problem reaching the primary source or it is taking too long.