Sunday, January 31, 2016

Day 182: FCC, Deconstructing "Show the Weather" and Redoing "Where Art Thou"

Today I'm going to rebuild my "Show the Weather" app, here's the code I have, a lot of it is from the Udemy course, but with my own key, and I chopped the code up so that I can use it inside JQuery, and then I added the temperature converter and the picture converter (the background picture changes depending on the temperature):

$(document).ready(function() { 
  //The code only runs if navigator is working and the user allows it to run.
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
    /*$("#data").html("latitude: " + position.coords.latitude + "<br>longitude: " + position.coords.longitude);*/
    lat = position.coords.latitude;
    lon = position.coords.longitude;
    url = "http://api.openweathermap.org/data/2.5/weather?" +
"lat=" + lat + "&lon=" + lon +
"&APPID=" + apiKey;
    sendRequest(url);
    function sendRequest(url) {
      var xmlhttp = new XMLHttpRequest();
      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
          var data = JSON.parse(xmlhttp.responseText);
          var weather = {};
          weather.loc = data.name;
          weather.temp = kelvinToFahrenheit(data.main.temp);
          weather.desc = data.weather[0].description;
          update(weather);
          function update(weather) {
            location1 = weather.loc;
            temperature = weather.temp;
            weatherCon = weather.desc;
            $('#newId').html(location1);
            $('#temperature').html(temperature + "&deg;" + "F");
            $('#weatherCon').html(weatherCon);
            setBackground();
          }
        }
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
  }  
    });
  }
  // Button to convert Fahrenheit to Celcius and back
  $("#convert").click(function() {
    toggleFahrenheitAndCelcius(temperature);
  });
  function toggleFahrenheitAndCelcius(temperature) { 
    if (counter === 0) {
    // If the counter is 0, the variable celcius is calculater and output.
    var celcius = Math.round((temperature - 32) * 5/9);
    $('#temperature').html(celcius + "&deg;" + "C");
    counter = counter + 1;  
    }
    else {
    // If the counter is 1, the variable temperature, which has not changed, is output.  It isn't necessary to convert celcius back to fahrenheit, since we already know the value for fahrenheit.
    $('#temperature').html(temperature + "&deg" + "F")
    counter = counter - 1;  
    }
  }
  
  function setBackground() {
    if (temperature > 70) {
      $('#testing').html("the if statement ran");
      $('body').css('background-image', 'url("http://i65.tinypic.com/mvrazd.jpg")');
    }
   if (temperature >= 40 && temperature <= 70) {
      $('body').css('background-image', 'url("http://i68.tinypic.com/14xoyfc.jpg")');
    }
   if (temperature < 40) {
      $('body').css('background-image', 'url("http://i68.tinypic.com/2qaohva.jpg")');
    } 
   
  }
  
});

// Variables
var apiKey = "dfb43772e2aef43ded711dd9faeebb9b";
var temperature;
var weatherCon;
var location1;
var url;
var lat;
var lon;
var counter = 0;

function kelvinToFahrenheit(k){
    return Math.round(k*(9/5)-459.67);

}

See the nesting?  I want to make it so that it's not so nested, that way you can pull a certain piece out and swap it with other code without breaking the whole thing.  That's what I'll be working on today, and after that, I'll work on the CSS.

Also, I'm watching a video called JavaScript: Understanding the Weird Parts.  I went back to "Where Art Thou," and re-did my code after pair programming with a buddy of mine.  To be honest, now that I see my old code and my new code, my old code was not good at all.  The new code actually solves the problem, in the correct manner, here it is:

function where(collection, source) {
  var finalArr = [];
  var count;
  for (var i = 0; i < collection.length; i++) {
    
    count = 0 ;
    
    for (var key in source) {
      //If the object has the property AND the value of the property in the object equals the value of the property in the source, THEN add one to the count, which makes the if statement push the object IF the count equals the amount of keys in source (because ALL the key/value pairs have to match in order for the object to be pushed to the final array).
      if(collection[i].hasOwnProperty(key) && collection[i][key] === source[key])        
      count = count + 1; 
       }
    
    if(count === Object.keys(source).length){ 
        finalArr.push(collection[i]);
        }
    
  }
    return finalArr;
}


where([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 3 });

Here's the question again:




And now I'm going to go back to studying scope some more, so I can rework the weather app.

SUMMARY OF CODING SKILLS

Total Treehouse Points: 5,503

Treehouse Points by Subject Matter (Miscellaneous not included): 
HTML:                                663 
CSS:                                1,599 
Design:                            1,193 
Development Tools:            747 
JavaScript:                      1,239

Treehouse Ranking (%): "You have more total points than 93% of all students."

Treehouse Courses Completed:
How to Make a Website
HTML
CSS Foundations
CSS Layout Techniques
Aesthetic Foundations
Design Foundations
Adobe Photoshop Foundations
Adobe Illustrator Foundations (66% complete, switched focus from web design to web dev)
Console Foundations
Git Basics
Introduction to Programming
JavaScript Basics

Codecademy (& other) Courses Completed:
HTML and CSS (Codecademy) 

Books Read or in Progress:

Completed: "Head First HTML and CSS," by E. Robson & E. Freeman
Completed: "A Smarter Way to Learn JavaScript," by Mark Myers 
Completed: "HTML and CSS," by Jon Duckett
Completed: "JavaScript and JQuery," by Jon Duckett

My Progress on The Odin Project:
1.  Introduction to Web Development                                             100% Complete
2.  Web Development 101                                                               33% Complete 
Note: I switched to FCC for the great online community and better updates/support.

My Progress on Free Code Camp (FCC): 
1. Get Started with Free Code Camp                                                      Complete
2. HTML5 and CSS                                                                                  Complete
3. Responsive Design with Bootstrap                                                       Complete
4. Gear up for Success                                                                           Complete
5. jQuery                                                                                              Complete
6. Basic JavaScript                                                                                 Complete
7. Object Oriented and Functional Programming                                     Complete
8. Basic Algorithm Scripting                                                                   Complete
9. Basic Front End Development Projects                                                Complete

10. JSON API's and Ajax                                                                          Complete
11. Intermediate Algorithm Scripting                                                      Complete

12. Intermediate Front End Development Projects                                   On 2 of 6
13. Claim Your Front End Development Certificate
14. Upper Intermediate Algorithm Scripting
15. Automated Testing and Debugging
16. Advanced Algorithm Scripting
17. AngularJS
18. Git
19. Node.js and Express.js
20. MongoDB
21. Full Stack JavaScript Projects

22. Claim Your Full Stack Development Certificate

After the 800 hours of FCC work above, there are 800 more hours of non-profit coding projects.


Hours Spent Coding Today: 4
Total Hours Coding: 884

Friday, January 29, 2016

Day 181: FCC, "Show the Local Weather"

Today I'm starting on the first of the 6 Intermediate Front End Projects, "Show the Local Weather."  This project requires us to use an API to create a webpage that gives the user the weather at his location.  Here's the user stories we need to complete:



All right, let's get started.  Here's the geolocation code we used in the JSON earlier:

$("#getMessage").on("click", function(){
      // Only change code below this line.  The code below pulls the raw JSON into the message.
      $.getJSON("/json/cats.json", function(json) {    
        $(".message").html(JSON.stringify(json));      
      });

    });

With that code, I can get the coordinates, and then I have to input that into the API somehow.

Ok, so my challenge right now is to get the data from the weather API and somehow work with it.  That's what I'm working on right now.

Well, I finished the challenge, I used a Udemy course for guidance, it helped a lot, but it was written in pure JavaScript, and I wanted to do the design in JQuery, so I had to research a lot anyways.  It also didn't have the converter, so I had to do that as well.  The main thing I took away from it was how to pull the JSON data from the weather API.  That actually has to be done in a certain format or the data just won't come through.  Here's my design:




Pretty cool, huh?  It converts to celsius, and one neat thing was that to convert back, I didn't need to calculate back to fahrenheit (because we already had that value).  I mean I had the formula, but what I did was when I converted from fahrenheit to celsius, I didn't change the original variable, I simply created a new variable, celsius (based on the temperature variable), and when I needed to switch back, I just output the temperature variable, which was still the same.

I had a big problem with the code not functioning properly due to scope issues, so I ended up nesting the code within itself, deeper and deeper, but I'd like to come up with a more modular solution, if possible, so I'm going to rework the code tomorrow.  Another thing is that the background image loads after several seconds, so perhaps there's a way to speed that up (maybe by making the code more modular).  Also, before the data loads, the divs are empty and there is no background at all (just a black background), and that's not very user-friendly, so perhaps I'll give the divs (or create divs) that hold the data a default size tomorrow, and perhaps I'll make a friendlier-looking default background.  Another option is to remove the background image altogether and instead insert a small icon next to the degrees, as that's allowed as well.  An icon would load faster, but since the images will be pulled from elsewhere either way (I'm not hosting locally, I'm linking to tinypic), maybe it will still take a bit to load anyways.  We'll see, but there's a lot of room for improvement here, and also, a lot of room for much more learning.  

This is a GREAT project.

SUMMARY OF CODING SKILLS

Total Treehouse Points: 5,503

Treehouse Points by Subject Matter (Miscellaneous not included): 
HTML:                                663 
CSS:                                1,599 
Design:                            1,193 
Development Tools:            747 
JavaScript:                      1,239

Treehouse Ranking (%): "You have more total points than 93% of all students."

Treehouse Courses Completed:
How to Make a Website
HTML
CSS Foundations
CSS Layout Techniques
Aesthetic Foundations
Design Foundations
Adobe Photoshop Foundations
Adobe Illustrator Foundations (66% complete, switched focus from web design to web dev)
Console Foundations
Git Basics
Introduction to Programming
JavaScript Basics

Codecademy (& other) Courses Completed:
HTML and CSS (Codecademy) 

Books Read or in Progress:

Completed: "Head First HTML and CSS," by E. Robson & E. Freeman
Completed: "A Smarter Way to Learn JavaScript," by Mark Myers 
Completed: "HTML and CSS," by Jon Duckett
Completed: "JavaScript and JQuery," by Jon Duckett

My Progress on The Odin Project:
1.  Introduction to Web Development                                             100% Complete
2.  Web Development 101                                                               33% Complete 
Note: I switched to FCC for the great online community and better updates/support.

My Progress on Free Code Camp (FCC): 
1. Get Started with Free Code Camp                                                      Complete
2. HTML5 and CSS                                                                                  Complete
3. Responsive Design with Bootstrap                                                       Complete
4. Gear up for Success                                                                           Complete
5. jQuery                                                                                              Complete
6. Basic JavaScript                                                                                 Complete
7. Object Oriented and Functional Programming                                     Complete
8. Basic Algorithm Scripting                                                                   Complete
9. Basic Front End Development Projects                                                Complete

10. JSON API's and Ajax                                                                          Complete
11. Intermediate Algorithm Scripting                                                      Complete

12. Intermediate Front End Development Projects                                   On 2 of 6
13. Claim Your Front End Development Certificate
14. Upper Intermediate Algorithm Scripting
15. Automated Testing and Debugging
16. Advanced Algorithm Scripting
17. AngularJS
18. Git
19. Node.js and Express.js
20. MongoDB
21. Full Stack JavaScript Projects

22. Claim Your Full Stack Development Certificate

After the 800 hours of FCC work above, there are 800 more hours of non-profit coding projects.


Hours Spent Coding Today: 10
Total Hours Coding: 880

Wednesday, January 27, 2016

Day 180: FCC, "Arguments Optional," Completed Intermediate JavaScript Algorithms! Started on JSON API's and Ajax!

Today I'm starting with the last Intermediate Algorithm Scripting problem, "Arguments Optional."  This is a very confusing challenge, here it is again:



I actually went to two of FCC's chatrooms and asked for some clarification on the question, and two fellow campers gave me some tips, which I'm wrapping my head around right now.

Here is the gist of the question I posed, so you get a feel for what I was confused about:


Guys, for "Arguments Optional," the last Intermediate JavaScript Algorithm, I'm totally lost. I thought you had to have all the inputs of a function within the parentheses that follow it, but then in this challenge, two of the inputs have parentheses with more inputs following the first set of parentheses following the function, like so:
function add() {
}
add(2)(3);


If I run that, it returns an error. How can we manipulate the items in the two parentheses if they throw errors when they are input like this? To be more specific, how do we work with that item in the second parentheses?  

So then, here's the replies I received:


dooglus 15:23
it wants add(2) to return a function that adds 2 onto whatever argument you pass it

dooglus 15:24
so add(2) returns a function, and add(2)(3) calls that function with 3 as its parameter

dooglus 15:24
it's like (add(2)) (3)
inside the definition of add(), you would check argument.length; if it's 2, you return the sum, and if it's less you return a function: function(x) { return x + arguments[0]; }

dooglus 15:25

ie. a function that adds its argument to the argument that add was called with

That was @dooglus, then another camper, @PenJones offered this advice:


@Adancode the code will take the first function
and apply the second value to the function it is returned,
so in this case you should return a function (because
there is only one argument to the main function) which
adds the first argument (3) to the second argument (2)

@Adancode So if you start with add(3)(5) and that
returns a function it will then do addv2(5) addv2 being

the function you returned

I'm going over the challenge right now, with these tips in mind.  I'm getting closer to solving this.  This is what I have so far:

function add() {
  var originalFirstArgument = arguments[0]; 
  function sumParameters(a, b) {
    return a + b;
  }
  if (arguments.length === 2) {
    sumParameters(arguments[0], arguments[1]);
  }
  // the x below represents the item in the second parentheses, the 3 in the case of add(2)(3)
  if (arguments.length < 2 ) {
    return function(x) { 
      // originalFirstArgument represents the 2, the number in the first pair of parentheses
      return x + originalFirstArgument; //+ arguments[0]; 
    }
  }
  
}


add(2)(3);

Still working on it.  Okay, I figured it out.  Here's my solution:

  var originalFirstArgument = arguments[0]; 
  function sumParameters(a, b) {
    return a + b;
  }
  if (arguments.length === 2 && (typeof arguments[0] === 'number' && typeof arguments[1] === 'number')) {
    return sumParameters(arguments[0], arguments[1]);
  }
  // the x below represents the item in the second parentheses, the 3 in the case of add(2)(3), so if the first argument only has one item in it, and it is a number, then the function(x) runs, which checks if the item in the second pair of parentheses is a number, if it is, it returns x (the item in the second pair of parentheses) added to the variable originalFirstArgument (the item in the first set of parentheses)  This is interesting, I'm going to play around with this to see what neat things I can do with this functionality.
  if (arguments.length < 2 && typeof originalFirstArgument === 'number') {
    return function(x) { 
      // originalFirstArgument represents the 2, the number in the first pair of parentheses
      if ( typeof x === 'number') {
      return x + originalFirstArgument;
      }
    }
  }
  
}


add(2)(3);

This was a really interesting challenge.  I'm going to play around with this functionality for the rest of the afternoon, it's a new concept to me, and it's really cool.  You can chain these things, this will output a 6:

function add() {
  // the variable below saves the 1, the first item in the first set of parentheses
  var firstParentheses = arguments[0]; 
  // the x below represents the item in the second parentheses, the 2 in the case of add(1)(2)(3) 
    return function(x) { 
  // the variable below saves the 2, which is the first item in the second set of parentheses in add(1)(2)(3)
      secondParentheses = arguments[0];
      return function (x) {
  // the code below returns x, which is the third item in the parentheses, added to the first and second items in add(1)(2)(3), which have been saved in the variables above      
        return x + firstParentheses + secondParentheses;
      };
    };
  // this is neat
}


add(1)(2)(3);

Cool!  I'm working on the JSON section now, here's the map:




This section will help me complete the Intermediate Front End Projects, as I'll need to use API's to complete those, something this section goes over.  This code changes the text in the message above the button, it's neat:




That's easy.  I'll save it here.

<script>
  $(document).ready(function() {
    $("#getMessage").on("click", function(){
      // Only change code below this line.
      $(".message").html("Here is the message");
      // Only change code above this line.
    });
  });
</script>


<div class="container-fluid">
  <div class = "row text-center">
    <h2>Cat Photo Finder</h2>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12 well message">
      The message will go here
    </div>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12">
      <button id = "getMessage" class = "btn btn-primary">
        Get Message
      </button>
    </div>
  </div>

</div>

All right, next.  This code pulls the JSON data from the API:




Let's zoom in:



I'm sure I'll be using that later.  Next we inserted code to loop through the JSON data, here it is:

<script>
  $(document).ready(function() {

    $("#getMessage").on("click", function() {
      $.getJSON("/json/cats.json", function(json) {

        var html = "";
        // Only change code below this line.        
        json.forEach(function(val) {

          var keys = Object.keys(val);

          html += "<div class = 'cat'>";

          keys.forEach(function(key) {

          html += "<b>" + key + "</b>: " + val[key] + "<br>";

          });

          html += "</div><br>";

});
        
        // Only change code above this line.

        $(".message").html(html);

      });
    });
  });

</script>

So we called .forEach() with a function inside to loop through the data.  This was itself within the json() {} function.  Some more code, it inserts images of cats into the document:

<script>
  $(document).ready(function() {

    $("#getMessage").on("click", function() {
      $.getJSON("/json/cats.json", function(json) {

        var html = "";

        json.forEach(function(val) {

          html += "<div class = 'cat'>";

          // Only change code below this line.
          
           html += "<img src = '" + val.imageLink + "'>";
          
          // Only change code above this line.

          html += "</div>";

        });

        $(".message").html(html);

      });
    });
  });

</script> 

The html is below:

<div class="container-fluid">
  <div class = "row text-center">
    <h2>Cat Photo Finder</h2>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12 well message">
      The message will go here
    </div>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12">
      <button id = "getMessage" class = "btn btn-primary">
        Get Message
      </button>
    </div>
  </div>

</div>

I saved it in case I want to play with this later.  This next one filters for only certain cat photos in the JSON:




Interesting, here's the code:

<script>
  $(document).ready(function() {

    $("#getMessage").on("click", function() {
      $.getJSON("/json/cats.json", function(json) {

        var html = "";

        // Only change code below this line.
        
        json = json.filter(function(val) {

        return(val.id !== 1);

        });
        
        // Only change code above this line.

        json.forEach(function(val) {

          html += "<div class = 'cat'>"

          html += "<img src = '" + val.imageLink + "'>"

          html += "</div>"

        });

        $(".message").html(html);

      });
    });
  });

</script>

I'm almost done with this section.  JSON contains a bunch of objects, so in manipulating JSON data, I'll get a lot of practice on manipulating objects, which is something I'm looking forward to.  This code allows you to get the user's geolocation data (if they click on the "allow" button in the popup.

<script>
  // Only change code below this line.
  
  if (navigator.geolocation) {

  navigator.geolocation.getCurrentPosition(function(position) {

    $("#data").html("latitude: " + position.coords.latitude + "<br>longitude: " + position.coords.longitude);

  });

}
  
  // Only change code above this line.
</script>
<div id = "data">
  <h4>You are here:</h4>
  
</div>

Every browser has a built in navigator that allows this code to function.  

All right, I'm done with the JSON API's and Ajax section, it's time to start on the Intermediate Front End Projects.  

SUMMARY OF CODING SKILLS

Total Treehouse Points: 5,503

Treehouse Points by Subject Matter (Miscellaneous not included): 
HTML:                                663 
CSS:                                1,599 
Design:                            1,193 
Development Tools:            747 
JavaScript:                      1,239

Treehouse Ranking (%): "You have more total points than 93% of all students."

Treehouse Courses Completed:
How to Make a Website
HTML
CSS Foundations
CSS Layout Techniques
Aesthetic Foundations
Design Foundations
Adobe Photoshop Foundations
Adobe Illustrator Foundations (66% complete, switched focus from web design to web dev)
Console Foundations
Git Basics
Introduction to Programming
JavaScript Basics

Codecademy (& other) Courses Completed:
HTML and CSS (Codecademy) 

Books Read or in Progress:

Completed: "Head First HTML and CSS," by E. Robson & E. Freeman
Completed: "A Smarter Way to Learn JavaScript," by Mark Myers 
Completed: "HTML and CSS," by Jon Duckett
Completed: "JavaScript and JQuery," by Jon Duckett

My Progress on The Odin Project:
1.  Introduction to Web Development                                             100% Complete
2.  Web Development 101                                                               33% Complete 
Note: I switched to FCC for the great online community and better updates/support.

My Progress on Free Code Camp (FCC): 
1. Get Started with Free Code Camp                                                      Complete
2. HTML5 and CSS                                                                                  Complete
3. Responsive Design with Bootstrap                                                       Complete
4. Gear up for Success                                                                           Complete
5. jQuery                                                                                              Complete
6. Basic JavaScript                                                                                 Complete
7. Object Oriented and Functional Programming                                     Complete
8. Basic Algorithm Scripting                                                                   Complete
9. Basic Front End Development Projects                                                Complete

10. JSON API's and Ajax                                                                          Complete
11. Intermediate Algorithm Scripting                                                      Complete

12. Intermediate Front End Development Projects                                   On 1 of 6
13. Claim Your Front End Development Certificate
14. Upper Intermediate Algorithm Scripting
15. Automated Testing and Debugging
16. Advanced Algorithm Scripting
17. AngularJS
18. Git
19. Node.js and Express.js
20. MongoDB
21. Full Stack JavaScript Projects

22. Claim Your Full Stack Development Certificate

After the 800 hours of FCC work above, there are 800 more hours of non-profit coding projects.


Hours Spent Coding Today: 5
Total Hours Coding: 870