I Need REST (APIs)

I’ve found a few sites over the last few months that are fast and reliable when all I need is an endpoint of any ol’ data to practice AJAX and dynamic data loading. Several sites will return fake JSON data, however, some of the sample sets can return so much data that the browser can’t handle it. The following sites allow for the four main operations, GET, POST, PATCH and DELETE (or Create, Read, Update, Delete/Destroy).

JSONPlaceHolder – this site is good if you’re trying to simulate a blog with comments. It can take a while for the response to come back but it’s been reliable.

ReqRes – All your basic CRUD operations but the data it returns is smaller. Good for user stores (and Pantone color sets).

Unfortunately those seem to be the only two that are geared toward this need. Two is a lot better than none, though.

When I worked on the Seattle Gun Violence Data Tracker we used data.seattle.gov which is part of a larger civic data project.

I found this amazing resource while searching for “sample REST API”: Public API Repo It doesn’t look like any of the APIs included will let users test all four of the core methods. But, this is the sort of site that will be useful for Python students the next time we get to the BeautifulSoup/data scraping section of class.

Advertisements
I Need REST (APIs)

Variables inside JavaScript Functions

“It doesn’t matter where I declare my variables, right? They just get hoisted….. right?”
~ what this developer had to be thinking right before they committed this code.
Not so fast. Let’s just do a simple test using the developer tools to see whether JavaScript hoists inside functions.

function testy(){
  if(testy===true){
    console.log("It's true! I'm testy!")
  } else { 
    console.log("I'm not testy today")
  }
  var testy = false
}

Before I go showing the answer, what do you think the console shows?

.

.

.

.

.

.

.

.

Screen Shot 2018-09-18 at 9.09.42 PM

 

So it looks like JavaScript does not hoist variable declarations inside of functions. Let’s double check that with a quick change.

function testy(){
  var testy = true
  if(testy===true){
    console.log("It's true! I'm testy!")
  } else {
    console.log("I'm not testy today")
  }
}

 

What happens this time? I won’t keep you in suspense like last time:

Screen Shot 2018-09-18 at 9.12.10 PM

 

And there you have it.

Variables inside JavaScript Functions

But Your Github….

Screen Shot 2018-09-14 at 12.10.57 PM

This is my github contribution chart as of today (github). Of the few recruiters who have looked at my account one of them said “it doesn’t look like you contribute much code”. As I’m heavily back into the job search process I thought I would take a moment to explain “gaps”.

  1. I don’t typically contribute tutorial code. I have occasionally done so. The Harvard CS50 class requires that I have github integration so I can submit assignments. Andrew Ward’s Complete React Training at Udemy requires updates to a github repo as he has us deploy to heroku. But for the most part I figure this is code that is a) not mine and b) readily available from the original tutorial.
  2. I did commit my solutions to the homework that was assigned while I was a teaching assistant at University of Washington for a Python class. These are my original solutions to the assignments which I used as a guide for helping students. I don’t consider them tutorial or code-along-project code.
  3. The large gray chunk in June and July represents tutorial-heavy study time as well as a couple weeks I took off to prepare for my significant other’s birthday (we rented a hall, it was catered and we had out-of-town guests; things needed managing).
  4. With my previous employer my team lead was in charge of squashing commits and merging with master branch. While my unmodified code was credited to my account he most often made subtle changes (and some not so subtle) before merging. As far as git is concerned those are his commits and it was a sticking point between him, our CTO and me.
  5. Most of my code experiments end up on Repl.it or Codepen. I don’t feel the need to also commit that code to version control.

So that’s it in a nutshell.  I do code daily as I’m working to master React and the ecosystem that surround that library, as well as improving my learning in Python. While I am learning a lot and improving every day, it’s not code I’m “proud” of nor does it demonstrate my capabilities, which is what I think git should be used for outside of its professional uses.

But Your Github….

Repairing Doc Martens soles, Pt 1

I didn’t think about making this a blog post before I started, so I “apologize” for not having before photos.

Here’s the story: I purchased a pair of 1461 Smooth shoes from the Doc Marten’s store in Seattle WA in 2016. NB: these are not “Made in England” and are not subject to their “For Life” guarantee, which they discontinued on April 1, 2018 [I wonder why…] These were assembled in Vietnam, though my previous Made in China 1461s (not purchased at a Doc Martens store) fell apart almost immediately and the sole was garbage).

I intended for these to develop some character, wear lines, scuffs, etc. which isn’t something I typically allow for my shoes. But I like Docs that look like they have a story, and I still intended to keep them cleaned (saddle soap) and black (Lincoln polish). It didn’t take long for that to come to an end as I realized one slightly-wet day that the sole had released from the welt and water was getting in. I figured that was more-or-less OK because I have stuff to fix shoes. The internet had some ideas but no one offered ideas that seemed like they actually knew; lots of anecdotal “evidence”. I decided to try my standbys.

What didn’t work: I scrubbed out the seam with an emery board then rubbing alcohol. First I tried Shoe-Goo, which I’ve had good luck with. Nope. I cleaned the opening again and tried E-6000. Still nothing. I even tried PVC cement (because Doc’s soles are reportedly a PVC material) and I might as well have done nothing.

So they became shoes for dry days only. Which means they were forgotten for several months and didn’t get into regular rotation. I’ve worn them for less than 30 total days, and almost all of those days have been dry.

Today I decided I needed to try to repair them. I went back to the internet and the advice was “if you don’t have a hot knife to weld the rubber sole and welt, they’ll never stick together.” Well I am a blacksmith so this is right up my alley. The photo shows all of the equipment I used: a MAPP torch (propane would be fine), a hacksaw blade and my trusty bathroom fan that I use to vent fumes away from me toward the open door.

CAUTION: This process involves burning plastic. There will be lots of smoke and it smells dangerous. You must have good ventilation. Ideally you will have a fan to pull the fumes away from you, and a place like a garage or shed where people can be out of the building while it degasses.

20180902_144750

The process is simple: clean the opening and gently try to pull it open wider. If the seam is weak, now’s the time to figure that out. My sole was detached almost the entire length of the instep. Use your non-dominant hand to open the seam (I put my thumb against the shoe and used my fingers to spread the seam).

Light the torch, heat the blade and insert it in one end of the seam. Let the seam slightly close around the blade. Pull the blade an inch or so along the opening. Remove the blade then pinch the seam closed. Repeat. Do this quickly and fearlessly – a little finger skin is a small price to pay for functional shoes! (Kidding, you do have to work quickly but be safe about it. I don’t think gloves will help here because this requires a fair amount of dexterity). I kept a wood block handy to rest the blade and to scrape off the rubber as it built up.

The end result is not quite a thing of beauty and I haven’t had a chance to wear them. I promised my girlfriend I would throw them away then had a change of heart because that’s super wasteful- look at these things! They look good from above, but the sides are a bit of a mess (the sole did not tear cleanly away from the welt, so that didn’t help the overall aesthetic). However, when I try to pull the seam apart it feels firmly stuck. I will update this when it rains and let you all know how well this worked.

20180902_15042320180902_150453

Repairing Doc Martens soles, Pt 1

Foundations of Programming: Python Class is in the Books

Last night we had project presentations for the Foundations of Python class I TA’d at University of Washington. To a person I was extremely impressed with their projects and the progress they made.

Overall the class was made up of people who had little to no coding experience. Some of these folks had never used their terminal before. Others had experience with R, SQL and GIS programs, but used them to solve specific problems rather than code out programs that were reusable.

I don’t remember all of the projects but these are those that stuck with me:

  • A neuroscientist who used Jupyter Notebooks to track comparative mortality due to Alzheimer’s Disease using CDC data
  • An applied math PhD candidate who plotted the collaborative-ness of various email and document networks in her department
  • One student used BeautifulSoup to scrape articles for information about cheese prices, then made a local data store that the user can update with their own findings. He did not call the data store ‘cheese_cellar’ – missed opportunity there.
  • A security specialist for a financial institution made a suite for determining if credit card numbers had been compromised. He wrote a script to generate fake, semi-randomized 24-character “credit card numbers” and “compromised credit card numbers” like those on the dark web. His final script then compared the two lists and outputted a “compromised” list and a second list of the remaining numbers. The cardholders on the first list would be contacted and security would try to find a common merchant that could be the source of the breach. He said security could use this second list to contact the issuers of those cards and the organizations could collectively trace the origin of the data breach. Very impressive for someone whose previous experience was in BASIC.
  • A project manager automated a task wherein she has to normalize file names every month for her org’s data processing group. Typically this task took three or more hours and now takes seconds. She even accounted for unique files names that didn’t fit the pattern of 95% of the files she has to rename. I referenced Automate the Boring Stuff with Python and she replied “that was my inspo for this project… that and not having to do this by hand anymore”.

My takeaways from the class are several. First I’m impressed with how accessible Python is, not just to write but in the suite of tools that are available. For most students the biggest hurdle was learning how to read HTML so they could figure out which elements to target with BeautifulSoup. I admire the creativity of the folks who weren’t solving a work problem, and I’m awed by the amount of work that the work-problem-solvers were able to automate.

If you’re interested in Python programming, I highly recommend the text for this course, Python Programming for Absolute Beginners. The style is approachable and I didn’t find the pace overwhelming. If you make a Python project, let me know in the comments!

Foundations of Programming: Python Class is in the Books

Notes for the Future: JavaScript Array Methods

This is mostly for me, but you may find it helpful, too. I periodically need a reminder of my JavaScript array methods, and want them in a handy place where I’ll find them.

Make an array:
var constructorArray = new Array();
var regularArray = [];

Test for Array-ness:
console.log(Array.isArray(someArray));

Use these all the time:
myArray.length;
myArray[x]; //where x is the xth position in the array. JavaScript array indices start at zero.
myArray[y] = “thing”; //adds “thing” to myArray at the yth index. If y is not contiguous with the current indexing, “thing” will be added at y and all the unfilled spaces between y and x will be filled with ‘undefined’ values.
delete myArray[x]; //replaces the value at the xth index with “undefined”

For all those ‘do this thing to a string’ whiteboard problems:

myArray.toString();

Will comma separate the items in an array

myArray.join();

By default each item in the string being joined will be separated with a comma. myArray.join(separator=”) will join the items with no characters between them.

Unshift/Push/Shift/Pop:

arrayMethods
Image produced by author.

[Update August 16, 2018:
NB: Array.shift() removes the 0th index and returns it. This mutates the original array and the returned value is whatever myArray[0] was when .shift() was applied. If you are trying to recursively traverse the array you will need to use Array.slice(1) so the function works on the copied array:

EXAMPLE:

This is my solution to a CodeWars problem that is set up thusly:

Write a function called max that takes one argument, an array, and returns the maximum value of that array.
Rules:
You cannot use Math.max (duh!)
You can only use const to declare any variables
You cannot use any loops like for or while
You cannot use any other argument than the one passed to the function
If the array is empty then return -Infinity, just like with Math.max.apply(null, [])
You cannot use any Array.prototype methods like forEach, map, filter, or reduce
function max(arr){
  if(arr.length ===0){
    return-Infinity;
  } elseif(arr.length ===1){
    return arr[0];
  } else{
    if(arr[0]< arr[1]){
      return max(arr.splice(1));
    } elseif(arr[0]> arr[1]){
      return max((arr.splice(1)).concat(arr[0]));
    }
  }
}
max([1,2,3,4,5])  // returns 5
function max(arr){
  if(arr.length ===0){
    return-Infinity;
  }elseif(arr.length ===1){
    return arr[0];
  }else{
    if(arr[0]< arr[1]){
    return max(arr.shift());
    } elseif(arr[0]> arr[1]){
      return max((arr.shift()).concat(arr[0]));
    }
  }
}
max([1,2,3,4,5])  // returns undefined because the shifted value (1, a number type) is being passed into max, which is expecting to work on an array.
END UPDATE ]

Splices:

myArray.splice(2,1,"thing");

at index 2 removes 1 item, inserts “thing” at that index. (Though this is a valid use, myArray[2] = “thing” is probably more performant for the same result in JavaScript).

myArray.splice(2,0,"thing");

At index 2 removes 0 items adds “thing”. If there is already something at index 2, that value’s index is incremented by one and “thing” becomes the value at index 2.

[ UPDATE! Feb 5, 2018:
At work I need to remove an item from an array’s sub-array but there is no guarantee that it will always be loaded at index 2 in the sub-array. Here’s how to remove the known thing regardless of where it lives in the sub-array:

// yields an index number
var removeItemIndex = myArray[‘subArrayName’].indexOf(‘thingToRemove’); 
// use this value as the index to be removed
myArray[‘subArrayName’].splice(removeItemIndex, 1);

END UPDATE ]

REVERSE AN ARRAY:

var myArray = ["Z", "Y", "X", "W"];
myArray.reverse();

Yields [“W”, “X”, “Y”, “Z”].  Use this with .join() and .toString() to reverse those immutable JS strings. This does not leave the original array.

* non-destructive array reversal:

function reverse(array) {
  var tempArray = [];
  var len = array.length; // this is the length of the array being passed in
for (var i = (len -1); i  !== -1; i--) { //start at the 'left' end of the array, work back to the 0-th position and include 0-th index. Checking for i !== 0 will not include the 0-th index. i is negatively iterated with minus minus, in case the rendered font doesn't show that.
tempArray.push(array[i]);
    }
    return tempArray;
};
reverse(myArray);

Don’t forget to call your functions

.SORT():

  • Alphabetic information:
    var myArray = ["Z", "Y", "X", "W"];
    myArray = myArray.sort();

    .sort() is a lexicographic method, which means the method wants to put these items in alphabetic order based on their Unicode code points. .sort() leaves the array in-place for the sort, so no additional arrays are created.

  • Numeric information:
    var myArray = [0, 10, 4, 12, 2, 1, 9];
    function compare(a,b){
    return (a-b);
    }
    myArray = myArray.sort(compare);
    console.log(myArray); // [0,1,2,4,9, 10,12]

    Without doing a compare, .sort puts 10 after 1 because of their Unicode code values.

.concat()  to combine arrays:

myArray = ["A", "B", "C"];
 myOtherArray = [1, 2, 3];
myNewArray = myArray.concat(myOtherArray);
console.log(myNewArray); // ["A", "B", "C", 1, 2, 3]

Slice:
(Do not confuse with splice)
.slice() takes two arguments, which index to start at and which index to stop in front of. .slice() will create a copy of the original array, return the values that were sliced and leaves the original array unchanged. If you only want the slice then use the same array name as the array being sliced.

var myArray = ["A", "B", "C", 1, 2, 3];
myExample = myArray.slice(1,4);
console.log(myExample); // returns ["B", "C", 1]
console.log(myArray); //returns ["A", "B", "C", 1, 2, 3]
myArray = myArray.slice(1,4);
console.log(myArray); // returns ["B", "C", 1]

Slice is also useful as a deep copy of an array in ES5:

var clone = myArray.slice(0)

whereas in ES6 we can do

let clone = [...myArray]

.every()
.every() tests every item in an array for a given criteria. .every() takes a callback and arguments (the array(s) in question). From the MDN docs:

function isBigEnough(element, index, array) {
  return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough);   // false
[12, 54, 18, 130, 44].every(isBigEnough); // true

ES6 gives us .find()

.find() returns the first value that meets the criteria in the function. Example from MDN

var array1 = [5, 12, 8, 130, 44];

var found = array1.find(function(element) {
return element > 10;
});

console.log(found);
// expected output: 12

This is probably not the best way to find multiple items. For a situation like that I would use…

.filter() (ES5 method)

Per MDN: The filter() method creates a new array with all elements that pass the test implemented by the provided function. The original array is left untouched.

let array1 = [5, 12, 8, 130, 44];

const filtered = array1.filter(value => value > 10)

console.log(filtered);
// expected output: [12, 130, 144]

.map() (ES5 method)

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

var array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

.reduce() (ES5 method)

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

 

 

Notes for the Future: JavaScript Array Methods

Notes for the Future, Part 3 – Palindrome Finder (Updated)

[Edit Aug 27, 2018: I decided I would mess around with how many ways I can find palindromes and wrote this repl.it https://repl.it/@kmskelton/play-with-palindromes The code below can stand to have some array methods applied to it, but I’m keeping it for posterity. ]

[Original: May 15, 2017] I’ve heard from several sources that finding palindromes is popular during interviews. I had this challenge as part of the final assessment for my JavaScript course and this is a slightly modified version of what I came up with. This will find the longest palindrome in a string. If there are two equal length palindromes in the string (e.g. “racecar tacocat”) it will return the first. I’ve included notes as I went along.

function paliFinder(inputString) {

  var result = '';

  if (inputString === undefined || inputString.length === 1) {

    return console.log ("result = 'No valid string submitted!'");

  } // handle errors if user tries one letter or simply nothing

  var inputString = inputString.replace(/[^\W_\s]/gi, ''); //remove spaces and punctuation

  var paliArray = inputString.toLowerCase().split(''); //split the modified string on each character and store that as an array

  for (var i = 0; i < paliArray.length; i++) { //loop through once

    var paliMaybe = [];

    var paliMaybeString = '';  // if you're copy/pasting this for your job interview

    var checkArray = []; // I'm gonna make you work for it

    var checkString = ''; // because that's just how I am

    for (var j = i; j < paliArray.length; j++) { // loop through again

      if (paliArray[j] === ' ') {

        break 

      };

      checkArray.push(paliArray[j]); // each letter is added to the end of this array

      checkString = checkArray.join('')

      .toString(); //make the array a string

      paliMaybe.unshift(paliArray[j]); // each letter is added to the front of this array

      paliMaybeString = paliMaybe.join('')

      .toString(); //make the array a string

      if (checkString.length > 1 &&  // don't forget to delete this comment, too

        checkString === paliMaybeString &&

        checkString.length > result.length) {

        result = checkString;

      }

    } 

  }

return console.log(result);

}

paliFinder("tacocat in a racecar")

// tacocat

This is not quite bulletproof, but the only example I’ve found that will break it is something like “A A” with a space between the letters. For some reason it just decides to return nothing.
It’s also not particularly fast with two loops, a push and an unshift. It’s somewhere in the neighborhood of 2n^2 or something crazy.

Notes for the Future, Part 3 – Palindrome Finder (Updated)