Godot 3: How to disable a button and tint its sprite icon a darker color

In this tutorial: disabling buttons and tinting their icons (sprites) a darker color to indicate that they cannot be interacted with by the player.

What we’re making

Here’s my game’s item vault. It displays a grid of buttons, each one representing an inventory “slot” and each button can be used to display an item the player actually owns. There’s an icon and a slot label to help the player understand what each item is (ie: a sword, a robe, a pair of boots, etc.)

This is great for viewing all the items, but sometimes the player wants to fill a specific slot on their character. Here’s what the character page looks like:

When the player goes to select, for example, a “jewelry” item for their character to wear, I want to make it easy to spot which items in the inventory vault are actually jewelry.

To do this, I will write script that figures out which items are not jewelry, disable their buttons, and tint their icons a darker color. The end result should look something like this:

(I could have just hidden all the non-jewelry items, but I think having items “move around” on the player would be confusing. Tinting the non-jewelry items seemed, to me, anyway, like the better user experience.)

Setting it up in script

The initial creation of the inventory button instances takes place in my game’s “vault” scene. Below is a simplified version of my game’s code that (hopefully) demonstrates how the grid of buttons is created and populated with icons and labels. (PS: I have a separate tutorial specific to making a grid of buttons just like this.)

Thematically, the vault represents a shared inventory across all of the player’s characters in my RPG-style game. The shared inventory is represented as an array named global.guildItems.

Each inventory “slot” is represented as an itemButton instance (itemButton is a scene I created, we’ll look at it more closely in a bit).

The first method, _position_vault_buttons(), creates the blank buttons and places them in a grid, the second method, _draw_vault_items(), “populates” them with actual items from the inventory.

This way, we always get X number of buttons, where X is the total capacity of the player’s inventory, and only some of them are used to “hold” the items the player actually owns.

(A lengthier explanation of how I know which item slot to filter by is outside the scope of this tutorial, but it’s done with a global flag set by the heroPage and you can see evidence of it in this code sample below about 6 lines from the end. It’s the one that goes “if (global.guildItems[i].slot != global.browsingForSlot):”)

#vault.gd

func _ready():
  #display inventory size and capacity
  _position_vault_buttons()

func _position_vault_buttons():
  #this method handles the STRUCTURE of the buttons
  #it places the empty buttons in the grid
  #use _draw_vault_items() to put icons and data into buttons
  for i in range(global.vaultSpace):
    var itemButton = preload("res://menus/itemButton.tscn").instance()
    itemButton._set_vault_index(i)
    itemButton.connect("updateSourceButtonArt", self, "_draw_vault_items")
    $centerContainer/grid.add_child(itemButton)
    buttonArray.append(itemButton)
    _draw_vault_items()

func _draw_vault_items():
  #now we pair each physical button with data from global.guildItems array 
  #grab each button from buttonArray and "decorate" it 
  var currentButton = null
  for i in range(buttonArray.size()):
    currentButton = buttonArray[i]
    if (global.guildItems[i]):
      currentButton._set_label(global.guildItems[i].slot)
      currentButton._set_icon(global.guildItems[i].icon)
      currentButton._set_data(global.guildItems[i])
      if (global.currentMenu == "vaultViaHeroPage"):
        if (global.guildItems[i].slot != global.browsingForSlot):
          currentButton._set_disabled() #script I wrote in itemButton.gd 
        else:
          currentButton._clear_label()
          currentButton._clear_icon()
          currentButton._clear_data()

About 4 lines up from the bottom is this line of code:

currentButton._set_disabled()

That _set_disabled() method is a method I wrote on the itemButton’s script, it’s not something built into Godot.

Let’s take a look at the itemButton scene and see how it works.

itemButton scene and script

An itemButton, in my game, is made up of a Button node along with a couple labels and a sprite.

Here is the scene’s structure:

Here is the script that disables the button and dims the sprite over the button:

func _set_disabled():
  $Button.disabled = true
  $Button.modulate = Color(0.5,0.5,0.5,1)
  $Button/sprite_itemIcon.modulate = Color(0.25,0.25,0.25)

The tricky part here, for me, was figuring out how modulate works. The Godot docs are thin on examples and it took some Googling just to figure out that the key word here was “modulate”, not “tint” or “color” or other terms I was initially guessing.

Some things to note about “modulate”:

  • Modulate is a property, so you can set it using “dot” notation.
  • It uses Color, which is built into Godot.
  • set_modulate and get_modulate are the old way of working with modulate (if you see reference to them the guide you’re reading/watching was probably made prior to Godot 3)

There’s a bunch of ways to work with Color, my example is just one of them. Mine is Color(R, G, B, alpha). Here are some more examples of working with Color in Godot.

This method could be expanded to a near-infinite number of uses, my example is just one tiny, specific use case.

References and more reading:

Godot 3: Centering a grid of evenly-spaced buttons on screen

In this tutorial: The scene structure and settings I used in the Godot 3 engine to achieve this amazing centered grid of evenly-spaced buttons. The buttons themselves are all instances of the same scene and are placed in the grid programmatically.

This is my “finished” result (pardon the placeholder assets). It’s a simple hero inventory page for an RPG. The buttons that make up the hero inventory are evenly spaced in a grid, and that grid is centered horizontally on the screen:

This guide will show you the code and the scene structure used to achieve this centered-grid-of-centered-buttons, but it assumes some familiarity with the Godot engine and will skip over some of the basics.

Scene hierarchy and container settings

This “Hero Page” is its own scene. This scene is named heroPage.tscn (and its script is in heroPage.gd). We’ll come back to its script at the end of the tutorial.  For now, we’re working in the scene’s hierarchy.

The parent-most node is a Node2D, and the important bits here for the centered grid of inventory items are:

  • a CenterContainer (which I renamed to centerContainer)
  • a GridContainer (which I renamed to grid)

(You could make this stuff programatically if you prefer but I like to see a certain amount of my UI in the viewport – at least the outlines of containers, where possible.)

I positioned my CenterContainer where I wanted it on the Y axis and gave it a width equal to that of my screen and left the rest alone.

Doesn’t look like much in the viewport yet – just a thin horizontal line.

That’s okay – the buttons themselves will bulk it out.

The next step is to adjust the grid’s settings. I changed the number of columns to 4 and under Custom Constants, I changed Vseparation and Hseparation to 24 (to put some space between each of the buttons).

The button instances

The square buttons are all instances of the same “itemButton” scene (that I made myself). That scene looks like this in the 2D viewport and scene hierarchy:

Unlike the grid or center container, I gave the button’s Control parent a size and a minimum size.

Generating the buttons with script

Finally, the code that adds the buttons to the grid is in the heroPage.gd file itself. This code goes in the _ready() method.

for i in range(heroEquipmentSlots.size()):
   slot = heroEquipmentSlots[i]

   var inventoryBtn = preload("res://menus/itemButton.tscn").instance()
   inventoryBtn._set_label(heroEquipmentSlotNames[i])
  
   #only set icon if the hero actually has an item in this slot
   #otherwise leave it empty
   if (global.selectedHero["equipment"][slot] != null):
      inventoryBtn._set_data(global.selectedHero["equipment"][slot])

   $centerContainer/grid.add_child(inventoryBtn)

I simplified some of the above code from my actual project for readability. The important parts are where it generates an instance of each inventory button and pushes the label and data into that instance, then adds the button to the grid.

The end result

The hero’s eight inventory slots are now in a grid and neatly centered. (I can’t say the same for the rest of the elements on this page yet, but it’s a start!)

Creating an item inventory array in GameMaker Studio 2 from a Google Spreadsheet exported as JSON

In this article: creating a Google spreadsheet of items for my RPG-style GameMaker game, exporting the spreadsheet as JSON, importing the JSON into GameMaker Studio 2, processing the item data into a usable format, and managing the player’s collection of “owned” items.

I’ve been building a hobby project in GameMaker Studio 2 for about a month now. I wanted to add the concept of “items” to my game – stuff like swords, armor, etc. – that grant stats and can be won via quests, managed in an inventory, and assigned to individual heroes. (Typical RPG stuff.)

The game itself might have hundreds or thousands of items (in theory), but the player is likely to have just a small selection of the available items in their inventory. This feature calls for two separate data structures: one to hold all of the game’s items, and one to hold the items the player has in their possession.

Note: I’m pretty new to GameMaker, and I’m documenting my findings as I go for future reference and ease of sharing with friends who are also using GameMaker. There’s quite possibly a better/easier way to do this than the method I’ve cobbled together here. 

Creating the items spreadsheet

For the items themselves, I created a spreadsheet in Google Sheets. The items are arranged in rows, and they have a collection of stats.

Some of them are restricted to certain classes, and Google Sheets lets you restrict choices in a particular field to a predefined list of options so you don’t make typos or introduce inconsistencies where you didn’t want them.

Exporting the data from the spreadsheet

I used Export Sheet Data to export my items as a JSON object. I checked these two settings:

  • Export sheet arrays
  • Export contents as array

Checking these two settings simplifies the structure of the JSON object I’ll be working with inside GameMaker.

Export sheet arrays

With “Export sheet arrays” checked:

[
  {
    "name": "Rusty Broadsword",
    "prestige": 0,

Without “Export sheet arrays” checked:

[
  {
    "Rusty Broadsword": {
      "name": "Rusty Broadsword",
      "prestige": 0,

As you can see, leaving this setting unchecked creates another layer of nesting. I found deeply nested JSON difficult to deal with inside GameMaker, so I wanted to minimize how many “layers” my data set had.

Export contents as array 

With “Export contents as array” checked:

[
  {
    "name": "Rusty Broadsword",
    "prestige": 0,

Without “Export contents as array” checked”:

{
  "items": [
    {
      "name": "Rusty Broadsword",
      "prestige": 0,

With this setting off, you still get all your items in an array but that array is itself a property and it’s contained within an object. This is just more “layers” to drill through in GameMaker and I prefer the simplified data structure.

The end result was this JSON object, which I’ve pasted into a gist:

Bringing the item JSON data into GameMaker Studio 2

My main room has a controller object that I use to set up gameplay globals. In its Create script, I currently just use a flag to see if the init script has run yet (so it doesn’t run every time I re-enter the main room).

For loading the JSON data line by line, I used Jason Lee Elliott’s method he describes on his blog here.

if (!initGameDone) {
  //currency defaults
  global.gold = 100;
  global.diamonds = 10;

  //load all the game items from json
  //http://jasonleeelliott.com/using-json-data/
  var theJsonFile = file_text_open_read("items.json");
  var theData = "";
  while (!file_text_eof(theJsonFile)) {
    theData += file_text_read_string(theJsonFile);
    file_text_readln(theJsonFile);
  }
  file_text_close(theJsonFile);

  var decodedData = json_decode(theData);
  var defaultStuff = ds_map_find_value(decodedData, "default"); 
  //see "default" explanation below 

This is where it started to get weird. theData is an array of objects (makes sense). decodedData is a ds_map made from that array of objects (still making sense). Looking in the debugger, though, with a breakpoint on the line that creates defaultStuff, we can see there’s ds_list in here called “default”:

Weird, I didn’t put that there…  GameMaker did, and it’s documented here. From GameMaker’s documentation:

NOTE: When decoding arrays, there is a map with the key “default” ONLY when an array is the top level structure, and ONLY for that top-level array. Internal lists decode directly to ds_lists without being enclosed in a ds_map.

That’s why defaultStuff is made from finding the “default” value within decodedData.

The next I did was create a global variable to hold all the game’s possible items. This global variable is a ds_map. I wanted it to be a map so that each item in the game could be looked up by its name (I think “Rusty Broadsword” is more memorable and easier to work with than something like an ID number or a position in an array).

  global.allGameItems = ds_map_create();

  for (var i = 0; i < ds_list_size(defaultStuff); i++) {
    var rawItemMap = ds_list_find_value(defaultStuff, i);
    var newKeyName = ds_map_find_value(rawItemMap, "name");
    ds_map_add(global.allGameItems, newKeyName, rawItemMap);
  }

This is just a classic for-loop that looks at each item (represented as a map) in defaultStuff. It grabs the name property out of the map to serve as the key, and uses the item’s map as the value.

Putting items in the player’s inventory

The last step is to actually give a couple items to the player.

The player’s inventory is as ds_list (array) of ds_maps. In this code, item1 and item2 are actual items from the allGameItems ds_map that are found by their name.

  global.playerInventory = ds_list_create();
  var item1 = ds_map_find_value(global.allGameItems, "Rusty Broadsword"); 
  var item2 = ds_map_find_value(global.allGameItems, "Blue Cotton Robe");
  ds_list_add(global.playerInventory, item1);
  ds_list_add(global.playerInventory, item2);

  show_debug_message("player inventory size: " + string(ds_list_size(global.playerInventory)));

  //print what's in the player's inventory
  show_debug_message("PLAYER INVENTORY:");
  for (var i = 0; i < ds_list_size(global.playerInventory); i++) {
    var itemi = ds_list_find_value(global.playerInventory, i); 
    show_debug_message(ds_map_find_value(itemi, "name"));
  }

  initGameDone = true;
}

Since I haven’t yet implemented the player’s inventory screen, I wrote a for-loop to print the name of every item in the player’s inventory to the console. Hopefully this is self-explanatory: it just iterates through the player’s inventory and prints the name property of each item it finds in the inventory.

And there we have it: these items are managed in Google Sheets, exported as JSON, imported into GameMaker, and placed in the player’s inventory by name.

Adapting an extension written for GameMaker Studio 1.4 for use in GameMaker Studio 2.0

In this article: how I adapted an extension written for GameMaker Studio 1.4 (the free version) so that it worked in GameMaker Studio 2 (the new/paid license version).

I wanted to use dicksonlaw583‘s JSOnion extension in GameMaker Studio 2, but the extension was written for GameMaker Studio 1.4. Compiling with the extension in use kept giving me a vague “invalid token” error in 4 different places (luckily, line numbers were included) but no clues as to what token, exactly, was invalid.

It took a lot of trial and error and digging on Google to figure it all out, so I’ve documented what I needed to do here in case it helps someone else.

Importing the Extension

First thing I got confused on was how, exactly, to bring the extension code into GameMaker 2.

The JSOnion instructions say “drag JSOnion.gml into your open project”, but that doesn’t work (or at least it didn’t for me, no matter where I tried to drop).

What I actually had to do is go to the Resources panel and right click on Extensions. Select Create Extension.

Escaping characters

Next, I tried to run my game but the build failed due to a number of “invalid token” errors.

Each error looks like this:

Error : gml_Script__jso_decode_map(84) : invalid token

I was pretty lost here, and the GameMaker docs provided little help.  Searching for “invalid token” comes up with nothing and this list of GML compiler errors offers only a vague hint:

You have an invalid character in your game code, which can happen with foreign language characters or Unicode

Hmm. The extension code looked okay to me…at least, it wasn’t full of bizarre characters and nothing looked weird at the line numbers GameMaker was complaining about.

This particular forum post gave me an important clue: single quotes are considered invalid characters in GML 2! Okay, that was something to go with. I went through the JSOnion.gml code and replaced single quotes with double quotes and, in order to do things like a set of double quotes within double quotes, escaped the interior set of double quotes with a backslash.

I also discovered (through more trial and error) that backslashes used for purposes other than escaping things are also considered invalid characters, so I had to escape those, too.

In summary, to adapt an extension meant for 1.4 to work with 2.0, you have to go into the .gml file and: 

  • Remove usages of single quotes
  • Escape \ and ” characters
    • escaped slash looks like this: “\\”
    • escaped double quotes looks like this: “\””

Note: each time I wanted to test a change I made to JSOnion.gml, I had to go into the JSOnion extension, delete the reference to the file, and re-add the file to get the changes.

Adding macros (constants)

One more thing to do: add the macros.

JSOnion came with a file, constants.txt, that I wasn’t sure how to use. The repo instructions gave a clue: “import constants.txt as macros”, but I think there might’ve been some UI changes since GML 1.4, because I couldn’t figure out how to import this file in the version I’m using.

What I ended up doing was adding the constants manually in the “Macros” section of the extension properties. (See screenshot below).

(These are indeed required, too – if you don’t add the macros and you try to use JSOnion methods, you’ll get errors when trying to read a variable that wasn’t set.)

With the extension code cleaned of “invalid tokens” and the macros in place I can now build.

Was this the right way to do it? I don’t know – I’ve only worked in GameMaker for a few weeks and this was my first attempt at bringing in an extension, so I am far from an “expert” at this point.

Also, I haven’t had a chance to actually use the extension code yet (that’s a subject for another post), but I did get it building so I wanted to share the process in case anyone else is also trying to adapt an old/free extension for the newer/paid version of GameMaker.

OSU eCampus CS361 Software Engineering I review & recap

This post is part of an ongoing series recapping my experience in Oregon State University’s eCampus (online) post-baccalaureate Computer Science degree program. You can learn more about the program here.

Six-word summary: Group work group work group work

In CS361 you’ll get a high level look at “real world” scheduling methodologies (mostly waterfall and agile) and you’ll work in a group with 3-4 other students to meet weekly milestones designing and implementing parts of some other student’s “Vision Statement”.

CS361 Review

You don’t have to spend long on the OSU CS subreddit to realize that virtually no one likes this class. It’s not awful, but I understand the frustrations people voice on various forums around the web.

The heavy reliance on group work was frustrating more often than not and the course materials felt dated or like they were specific to a certain industry, but I didn’t dislike this class as much as most people seem to. I think it helped that I already have design and software development experience and enjoy writing and making diagrams/mockups, so this class played to some of my strengths.

The materials that introduce common planning and scheduling techniques for software projects were a welcome inclusion – I’m glad this stuff is covered somewhere in OSU’s CS program – but I thought they didn’t go nearly in depth enough to prepare students for the realities of working on an agile team. There wasn’t enough story writing, requirements gathering, pointing exercises, or customer involvement.

I thought the weekly homework assignments were a little lackluster. Working in a group is tough even in the best situations – some parts of the homework depended on other parts being done first, and some people’s schedules didn’t seem to allow for them to start the homework early in the week.

The documents we wrote as a group seemed excessively heavy on diagrams and put too much emphasis on satisfying a very specific set of expectations. For example, there’s a lot of emphasis placed on terminology such as “functional requirements” and “functional definitions”, which I had never heard outside of this class or seen used so religiously, but the concepts they represent were familiar. That describes a lot of this class’s materials: heavy focus on overly-specific methods and terms that probably don’t translate to every industry.

Maybe the course’s materials would be improved by taking a step back from strict terminology and definitions and talking instead about how to write good step-by-step documentation, how to write a good bug, how to write a good feature design that someone else can implement from – skills that can be applied to a variety of specific methodologies, since it’s impossible to predict which ones your future company or team might be using. There are so many skills that have nothing to do with programming that programmers still need to develop, and this class could be a good place to start learning them.

Class structure

  • In the first week of the class, everyone in the class writes a 2000 word “Vision Statement” for a software product that solves some lofty real-world problem. Forget about making a simple app to solve a simple problem, your idea for this vision statement should be utterly epic. They are surprisingly strict about the 2000 word count, but you should be able to hit that easily by showing off your design skills and covering every topic imaginable in relation to your app idea. You really can’t write too much, and no topic is too trivial to not write a page about. (I thought I’d covered security pretty well with the half page I wrote on it, but I got got dinged for not writing enough on the topic. I got the feeling the TA had to find something wrong with my document and if it wasn’t that, it’d have been something else.)
  • In the second week of the class, everyone votes on which ideas they think are best.
  • It doesn’t matter what you vote for. Your voting has no bearing on what project you get assigned. But you should vote anyway to help lift decent-sounding projects to the top, so that nobody has to work on the duds.
  • Expect to be assigned to a project you didn’t vote for because you thought it sounded stupid or impossible (or both).
  • You’ll then get grouped with 3-4 classmates based on absolutely no criteria whatsoever, so expect clashing schedules/mismatched interests/time zone incompatibilities. The instructor says this is part of life, and I agree (and every single software team I’ve been on has had an off-shore counterpart on the other side of the globe), but don’t expect your teammates to be so understanding. My group insisted that the only time we could meet was what was usually my bedtime, which sucked for me.
  • You’ll get to know these people very well as you meet 1-2 times a week (probably over a voice chat if your group is keyboard-phobic or generally unavailable at any time of day outside of the specific meeting window)
  • Every week you’ll work with these people to produce a lengthy document in response to a lengthy prompt. It will require diagrams and lots and lots of writing.
  • This assignment will be graded by a TA who might have limited English skills or a general lack of interest in reading 12+ pages of rather dry writing. We lost points on things that were present and the TA missed and we lost points on things that were never part of the requirements in the first place.
  • The last two weeks of the term are spent coding a small portion of the stuff you designed thus far; your group members may or may not participate in this process depending on whether they’re dirtbags or not
  • The final is made up of rather vague questions, but you should review the slides anyway to scoop up whatever points you can here

CS361 Tips

Vision statement tips

The grading requirements on the vision statement draft are really vague, but you can get full credit by writing a ton on every design topic you can think of and meeting the 2000 minimum word requirement.

Some ideas of what to include (beyond what the assignment suggests):

  • What differentiates your app from similar ones – do some market research and write comparisons. Someone’s probably already made a product like the one you’re imagining. What makes yours better? 
  • User profiles – Imagine some hypothetical users for your app and write about them. Are they young? Old? Tech-savvy? Tech-illiterate? How is your app designed to appeal to them and meet their needs?
  • Accessibility features – imagine how your app might work on a screen reader or to someone with limited vision and write about how accessibility concerns are addressed in your app.
  • Security features – I wrote like half a page on security, which wasn’t enough according to my TA. Maybe you can do better!
  • Mockups! I made mine in mockflow

Journal tips

Work on the journal regularly – every other day is a good pace. The class’s instructor looks at these himself (or at least he looked at mine himself and commented on it) and he’s very good at detecting who wrote theirs in one fell swoop the night before it was due.

If you don’t know what to write, here are some ideas I used throughout the course to inspire myself:

  • Draw a comparison between the class’s material and your experiences working in a team – you ought to have some from your previous career or OSU classes
  • Talk about any previous software development experience you have; maybe throw in a bit about how you think CS361’s teachings on topics like agile will help you on future projects you develop
  • Talk about how your group work is going
  • Relate the lecture material to outside reading you’ve done or things you’ve heard
  • Sometimes the lecturer asks questions in the video; respond to those
  • Respond to the weekly learning topics: early in the week, write what you think they mean, then, after you do the lectures and your part of the homework, write again about what you’ve learned about those topics and correct any misinterpretations you had initially

Track your group members’ contributions

Yes, it feels creepy to keep secret notes about who in your group isn’t attending meetings, who turned in their part just hours before it was due, etc., but in the last week you’ll be asked to produce a very long, very detailed document rating each group member on a half-dozen criteria and justifying your rating in writing, so having kept track of this stuff will help you earn full credit on the assignment. I did my group member tracking in a Google Spreadsheet with a column for each week of the class and a row for each group member.

A lot of people in the Slack channel reported getting dinged for not being detailed enough, so keep regular notes and you should have plenty of material for this document and you should be able to write it in very little time. (Mine was 14 pages and included screenshots and data about meeting attendance and how close to the weekly deadline each person submitted their work; I got full credit on the group evaluation.)

Pick a programming language / framework that plays to your group’s strengths

Three people in my group inexplicably voted in favor of a framework they had little to no familiarity with – and majority ruled. I spent 2 weeks giving myself a crash course in JavaFX, coding as I went, which was fine but our development weeks would have gone so much better if the group had just picked something we already knew and could’ve hit the ground running in. The end result: some group members struggled to produce anything at all during the coding weeks.

Here’s what we ended up with: a clickable map of the United States that colors states according to how they voted in the 2016 presidential election and, alternatively, according to how gerrymandered they are.

This screenshot best represents my portion of the work: building the map and hooking it up to real data.

Implementing this much functionality posed plenty of interesting challenges to work through. Things like building a complete map out of individual SVG boundaries, figuring out how to make them clickable, altering their color based on data from the project’s database, and fitting containers within containers to get everything fitting in the application window kept me busy for the two weeks.

For some people in my group this was their first exposure to Git as well, so this project came with a side-helping of Git training. (Note to any future students out there: if you don’t know git yet, start learning it now – don’t wait until you’re in a time crunch of a group project with multiple people counting on you.)

And finally…

Don’t be a dick

Show up to meetings. Do your part and do it early enough so that your group can review it. Don’t disappear during the coding weeks. Be a good team member and make connections on LinkedIn once the class is over.

An educational program like this one is a huge opportunity to network and make friends; you never know who might end up at a great company someday and put in a good word for you. You can gripe about 361 and sandbag for two months, or you can impress a bunch of future industry peers by knocking it out of the park every week.

It’s only 10 weeks – you can do it!

OSU eCampus CS271 Computer Architecture and Assembly Language review & recap

This post is part of an ongoing series recapping my experience in Oregon State University’s eCampus (online) post-baccalaureate Computer Science degree program. You can learn more about the program here.

Six-word summary: Where my 4.0 GPA went to die

CS271 is a pedantic deep-dive into your computer’s inner workings and an opportunity to enjoy coding in a highly restrictive language. There’s special emphasis on going step-by-step through the stack frame and understanding what’s in every register and even some much-appreciated training on “what order to do things in” when building a program.

CS271 Review

CS271 often felt like it was made of two distinct halves that ran in parallel: the first half is made up of the cute little MASM programs you write for the homework that’s due every other week. The other half is the mountains of computer architecture trivia and methods for calculating various things you learn for the bi-weekly exams, such as binary/hex conversions, Hamming codes, memory usage, optimization, recursive output, stack frame changes, the step-by-step changes in registers as a program runs or steps through a loop, and so on.

The class is very well organized. They tell you precisely what to do for the homework and what the output should look like, line by line. Unlike many classes in OSU’s CS program thus far, you won’t need to do a ton of Googling to learn the material – the lectures and the book reading are actually adequate preparation for most of the class’s homework and quiz questions. The workload is consistent. Each week follows the same pattern, and the homework’s complexity ramps up slowly.

However, the homework (in which you write some Assembly language code) is rather light and may give you a false sense of security come quiz and exam time. The true heavy hitters in this class are the self-checks you do after the lectures, the weekly exercises, and the bi-weekly quizzes. Mastering the material found in all of these is essential for surviving the midterm and the final.

Whether 271’s material is interesting is going to depend on your own likes and dislikes. I thought most of it was squarely in the “hey, that’s neat” category, but I thought it focused too much over low-level details that (probably) won’t directly enhance my career in software. (And that’s just like, my opinion, man – I’m sure some people who take 271 find their calling and never resurface from the depths of CPU architecture, binary math, hex addresses, and bit ordering.)

Class structure

  • 10 weeks
  • Multiple briskly-paced weekly lectures
  • An ungraded/untimed “self-check” exercise worksheet for every single lecture – you should actually do these, the quizzes and exams pull from them
  • A weekly exercise quiz with a 6 hour time limit – you get two attempts and they keep the best score, but each attempt has a different batch of questions so it is advised to take it twice to see both question banks
  • 4 bi-weekly tests, 1-hour time limit, each worth 2.5% of your final grade
  • 6 Assembly-language coding projects (homework assignments) total – each one gives you two full weeks to work on it, with the grading rubric released at the start of the 2nd week
  • Proctored midterm, proctored final
  • Steady, even workload
  • Less self-teaching than some OSU classes (still quite a bit of rote memorization and practice, though)
  • NO GROUP PROJECTS!

Tips for CS271

This was my first OSU CS class where I couldn’t quite earn a solid A (I got an A-). It certainly wasn’t for lack of effort or time put in – I think I cleared 20 hours of practice most weeks and I worked on this class’s stuff daily.

There’s a ton of material and the tests are very picky – they’re not multiple choice where half the answers are obviously silly, they’re fill-in-the-blank or multiple choice where all the options seem like they could be right. (The tests are also almost half your final grade. Ouch.)

When I look back on what I could’ve done better and what I would advise future students, these are the things that come to mind.

CS271 tip #1: Get the book, it doesn’t suck!

This is one of the books that’s worth buying. It’s approachable with many  examples to follow and, surprisingly, many quiz questions are lifted line-for-line from the book.

See Assembly Language for x86 Processors on Amazon.com

I liked having a physical book because it freed up screen space during quizzes and while working on homework. I found it helpful to read on paper, practice in a notebook, and really work problems over and over until I had the process down cold. (That’s just my personal preference; I seem to retain more if I read and work on paper.)

CS271 tip #2: Make yourself some worksheets and grade yourself

Speaking of rote memorization and brute-force practice, I highly recommend making yourself some worksheets out of the weekly self-checks and bi-weekly quizzes. Print them out and work through them (over and over) until you can do all of them quickly and perfectly.

This technique was time-consuming but it went a long way to cementing the steps to solving all the various types of CS271 problems. As I mentioned earlier, the homework is borderline useless for the exams. The exams draw their questions almost entirely from the weekly self-checks and bi-weekly quizzes.

The exams tend to layer multiple concepts together into one question and they’re autograded, not graded by a potentially generous TA, so your goal for CS271’s tests should be to become very fast at solving every kind of problem you encounter in the practice materials.

CS271 tip #3: Get a binary/hex calculator

The Casio fx-115ES can do math in binary and hex: addition, subtraction, and conversions between binary/hex and back again.

I had no idea this kind of calculator even existed and the course materials make no mention of it. Frustratingly, I only found out about it through the class’s Slack chat. I was doing conversions by hand like a total chump, which would have cost me dearly on the midterm either in terms of time spent or stupid mistakes or both. The hex and binary questions on the exam were made trivial by having this calculator. I don’t know why the syllabus doesn’t open with “GET THIS CALCULATOR”.

As an alternative to the physical calculator, the course lets you use your operating system’s built-in calculator. (I did this course’s work on my PC but I take tests via ProctorU on Macbook since that’s where my webcam is, so I preferred the physical calculator over having to get familiar with multiple OS calculators.)

CS271 tip #4: Pack that cheat sheet to the density of a neutron star

I made mine in Google Docs, which will let you pick a font size as small as 6 (you have to type it in, it’s not in the dropdown).

One side of my CS271 cheat sheet – the back side was all code examples.

I don’t care for exam cheat sheets. I think allowing cheat sheets drives students to put their efforts into guessing what details should be on the sheet, which sets the student up for an inevitable wave of frustration and disappointment when they realize 2 seconds into the exam that they guessed wrong. Letting students bring a cheat sheet seems to inspire instructors feel free to ask all kinds of minutia-focused questions instead of testing for a more general understanding of the concepts.

But… nobody asked my opinion, and I doubt the cheat sheets are going away any time soon, so my advice here is to pack your sheet as full as you can get it. I think a good cheat sheet for CS271’s midterm and final would be at least 50% code examples, which is what the back side of my sheet was full of.

CS271 tip #5: The extra credit on the homework was generally a waste of time for me

I tried to do the extra credit (of which there are 1-3 points up for grabs on every bi-weekly assignment), but for the most part I found the extra credit opportunities frustrating and almost as time-consuming as the rest of the assignment itself. Your mileage may vary, but I should’ve spent the time on worksheet drills instead.

CS271 tip #6: If I could do one thing differently…

I’d spend more time studying all the nuances of what happens in the system stack while a program runs a loop. Here’s me practicing on a whiteboard, but despite all this preparation I still think this is where I lost points on the exam. I was probably off by 4 on some memory address or miscounted loops somewhere.

And that’s it for CS271! I’m glad I’m done with it; I’ve heard it’s one of the tougher courses and for me, that was definitely true. I worked very hard in this class and I advise all future students to do the same. The tests are no joke and your ability to track and manage tiny details will be tested like never before.

Next up: CS290 – Web Development. See you all next quarter!

Fixing WordPress site’s low mobile score in Google’s PageInsights with W3 Total Cache

In this article: Steps I took to optimize a WordPress-based site for Google’s upcoming mobile search prioritization. It started with a PageSpeed Insights score of 8/100 and ended at 62/100.

Plugins used: W3 Total Cache

Time spent: Several hours of trial and error, but this guide should help you through it much quicker.

Google announced in January that they’re going to take a site’s mobile speed into account for searches beginning July 2018. I’ve always tried to make my WordPress sites mobile-friendly, but it looks like there’s some room for improvement.

One of my biggest (and highest-earning) sites scored just an 8 out of 100 for mobile optimization. Ouch.

(You can test your own site here: https://developers.google.com/speed/pagespeed/insights/ )

What I’ve already done to optimize this WordPress site

I’ve managed this site for a few years and have already put some effort into optimizing it for search and mobile.

The site already scores well for these categories:

  • Avoid landing page redirects
  • Enable compression
  • Minify CSS
  • Minify HTML
  • Minify JavaScript
  • Optimize images
  • Prioritize visible content

Some of those scores are probably due to the site already using a CDN, lazy loading, a good caching plugin, and a good hosting plan. Here’s what the site uses:

However, there’s more work to be done! Here’s what I did to raise my Google Insights mobile score.

Fixing render-blocking JavaScript on above-the-fold content on a WordPress site using W3 Total Cache and a CDN

Let’s look at this render-blocking JS/CSS problem first:

Eliminate render-blocking JavaScript and CSS in above-the-fold content. 

Your page has 8 blocking script resources and 12 blocking CSS resources. This causes a delay in rendering your page.

None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronosly load blocking resources, or inline the critical portions of those resources directly in the HTML.

This message is followed by a list of all the JS and CSS scripts causing the render blocking, which were 8 JavaScript files and 3 CSS files in my site’s case.

These guides were helpful to me while working on this problem:

To fix the blocking JavaScript files I had to do a number of things to configure W3 Total Cache. This part took a couple hours of trial and error and some steps were not covered in the guides I used (or my situation was different from theirs), so I’ve attempted to document the process as I experienced it in this guide.

First, I enabled Minify in the general W3 Total Cache settings. Go to Performance > General Settings > Minify > check the “Enable” box and select the “Manual” radio button.

Next, go to Performance > Minify to work on minify settings as they pertain to JavaScript and CSS. You’ll need the list of blocking files from PageSpeed Insights report. 

Watch out! The file paths shown in the PageSpeed Insights results might be truncated. To get the full path, you have to hover over the truncated path and copy the path from the tool tip

In other words, make sure you are copying a complete path:

https://your-cdn.netdna-ssl.com/wp-includes/js/jquery/jquery.js?ver=1.12.4

and not a path with … in it:

https://your-cdn.netdna-ssl.com/-includes/js/jquery/jquery.js?ver=1.12.4

In Performance > Minify there are a variety of options that apply to all the script in a particular area (before head, after body begins, before end of body). In my case, code in the head tag was already minified, so I set it to “Combine only” (rather than re-minify it). I also needed to keep it blocking, or else my page filled Chrome’s console with “can’t find JQuery!” errors.

Next, under JS file management, add all of the blocking files from the PageSpeed Insights results – be sure to get the full file path, not the truncated version.

Also! If you’re using a CDN, you’ll have to change the domain in the file paths that you paste. 

Instead of this:

https://your-cdn.com/wp-includes/etc

You need to use your website’s actual domain. For each path you paste, change the CDN part to be your site’s domain instead, like this:

https://yourwebsitesrealdomain.com/wp-includes/etc

Or you can remove that part of the url entirely and go with something like:

/wp-includes/etc

…which is what I did for mine:

Note: I needed to set the jquery files to embed in <head> to avoid a slew of console errors when visiting the site. As per the earlier settings, anything embedded in head is going to be blocking. I think some blocking files might be inevitable; the point of these settings is to tease out which files belong where in the load sequence.

Save settings and purge all caches, then test again in PageSpeed Insights.

Woohoo – no JS files blocking loading. I also tested the site manually, and verified that it doesn’t look like garbage and doesn’t fill the console with errors. So far, so good.

Fixing render-blocking CSS with Autoptimize

I initially set up all the CSS file paths in W3 Total Cache but ran into these two cases that I couldn’t figure out how deal with through W3 Total Cache alone:

One blocking css file is from w3tc itself:

https://mywebsite.com/?w3tc_minify=6951f.default.include.89e358.css

And another is from Google Fonts:

https://fonts.googleapis.com/css?family=Open+Sans%3A300%2C400%2C600%2C700%7CMuli%3A300%2C300italic%2C400%2C400italic%2C600%2C600italic%2C700%2C700italic%2C900%2C900italic%7CPlayfair+Display%3A400%2C400italic%2C700%2C700italic&subset=latin%2Clatin-ext

To fix the Google Fonts, I installed the very lightweight plugin Autoptimize and checked these boxes:

I also used Autoptimize to disable Google Fonts. Whether you want to do this is up to you, but I went ahead with it because I am happy with a default system font for this site.

To fix the w3tc minify, I disabled CSS in W3TC and let Autoptimize handle it. I also had to uncheck this setting:

Finally, for the sake of completeness, here’s what my HTML minify settings look like:

At this point, I loaded my site and found it was using serif typefaces on buttons and it wasn’t scaling the hero (header) image correctly. To fix this, I added custom CSS to Autoptimize’s custom CSS section. This CSS gets loaded right away, so the page doesn’t get stuck waiting on the js or css to “fix” certain issues that are visible right away to a visitor.

.button {
   font-family: "Open Sans", sans-serif !important;
}

.header-homepage {
   padding-top: 120px !important;
}

One more thing: I also uploaded a significantly more compressed “hero” banner image jpg to the site (old size: about 350kb, new size: about 110kb).

The reward for all these optimizations:

Note that I still have one render-blocking w3tc js file. For now, I’m going to call this “good enough”, since I don’t know how to fix this last one without breaking some fundamental aspect of the site, so I’m going to move onto the expiry problems and see if I can get the score higher that way.

Fixing “leverage browser caching” with W3 Total Cache

PageSpeed Insights found a few files it thinks could leverage browser caching. These files are all .js files.

I found this guide helpful and accurate at the time of this writing: Leverage Browser Caching with W3 Total Cache

The first step is to enable browser caching in W3 Total Cache’s settings. Go to Performance > General Settings and make sure Browser Cache is enabled.

Then, go to the actual Browser Cache section of the plugin. As per the guide, I ensured these boxes were checked:

  • Set expires header
  • Set cache control header
  • Set entity tag (eTag)
  • Set W3 Total Cache Header – this one was not already checked for me
  • Enable HTTP (gzip) compression

(I re-ran the PageSpeed Insights test at this time just in case that one checkbox was all it took. Alas, there was no change in the results.)

The next thing I did was scroll down a little bit to the CSS & JS section. My “expires header lifetime” was set to 172800, which is way less than the recommended 604800 (2 weeks) the guide recommends. I saved that change, cleared cache, and ran the test again.

Now I have just three files with unsuitable caching times:

Alas, two of the remaining files are out of my hands: they are Google Analytics’s own .js files. After reading this guide to browser caching Google Analytics, I decided not to try to cache the analytics js file myself. Doing so would require manually updating it periodically. Even the guide’s author says they don’t recommend this method. That’s fine by me.

But how about this emoji js file? I don’t use emojis on my site, so I wouldn’t mind removing them and reaping a small page speed boost.

Normally, removing them is as simple as adding these two lines in your site’s functions.php:

remove_action( 'wp_head', 'print_emoji_detection_script', 7 );

remove_action( 'wp_print_styles', 'print_emoji_styles' );

But I’m using a pro theme that gets automatic updates (which will clobber this code if I add it to functions.php), and I don’t want to make a child theme for the express purpose of removing emojis.

So, I did what any good WP user does and installed yet another plugin: Disable Emojis. (Yes, I also canceled Christmas and summer break while I was heartlessly removing emojis from my very srs blog.)

I ran PageSpeed Insights again and….

Woohoo! (It initially came out worse, but network latency has some affect on the score, too. I tried again and got a 62/100).

My report has never looked better:

PSI estimates this page requires 2 render-blocking round trips and ~26 resources (0.4MB) to load. The median page requires 4 render-blocking round trips and ~75 resources (1MB) to load. Fewer round trips and bytes results in faster pages.

Fixing the “flash of unstyled content”

A new problem has been introduced by all this work: now my page looks unstyled for half a second or so while it’s loading.

I used this tool: Critical Path CSS to identify a the “minimum” CSS needed to make the “above the fold” content look good (it’s a huge block, I’m sure a human could produce something more elegant but for now, it’ll do).

I put this CSS into Autoptimize’s “above the fold” CSS section and the flash of unstyled content seems to look better now, though I still see the fonts looking bad before the preferred “open sans” style comes into effect.

Done… for now

At this point, I’ve gotta call it good enough for now. My site’s score went from 8/100 to about 62/100. I still have a one blocking JS file that I don’t know what to do with and two files from Google Analytics with unsuitable cache expiration times.

I’ll update this page when I make further improvements to the site.

How to convert a 4-byte hexadecimal sequence in a little-endian architecture into decimal

Here is my technique for solving the problem of converting a 4-byte hexadecimal sequence in a little-endian architecture into decimal.

This may seem rather niche but it was a surprisingly large part of Week 5 in my CS271 class. The class’s materials and extra help I found around the web seemed to go off on tangents that were interesting but unrelated to solving this kind of problem quickly, and all I really wanted was a simple step-by-step guide I could use on exams.

Therefore, I am sharing my simple 5-step technique for converting hex to decimal in a little-endian architecture here! Hope someone else finds it helpful.

Example problem:

The four-byte sequence 0x86 0x65 0x53 0x82 stored in consecutive memory cells in a little-endian architecture represents ___________ (decimal) when interpreted as a 32-bit signed integer.

From reading this, we know: 

  • it’s little-endian, so we are going to reverse the order of the bits
  • our result will be signed

Step 1: Reverse the bytes

Take the bits in blocks of two and work right to left.

0x86 0x65 0x53 0x82 becomes 0x82536586

Step 2: Look at the most significant bit and determine if there will be a negative result

0x82536586   <-- that's this dude in red here

The most significant bit here contains an 8.

We know that in hex a most-significant bit of 7 or more means we are looking at a negative number. (If this were a positive number, ie: the most significant bit is between 0 and 6, then skip ahead to Step 4.)

Step 3: Since we are working with a negative number, flip the bits (subtract our hex sequence from FFFFFFFF) and add 1

  FFFFFFFF
- 82536586
  7DAC9A79

Add one to the result:

7DAC9A79
      +1
7DAC9A7A

The result is the hex sequence we will use for the next step.

7DAC9A7A

Step 4: Multiply each term by 16 raised to a power

To convert a hex value into a decimal value, we multiply each “position” in the hex sequence by 16 raised to a power. Working from right to left, we know that furthest-right position is 16^0 (so, just a 1). The second-from-right position is 16^1 (so, just a 16). The third-from-right position is 16^2, and so on.

Recall that A = 10, B = 11, C = 12, D = 13, E = 14, and F = 15 when working in hex.

(7*16^7)+(D*16^6)+(A*16^5)+(C*16^4)+(9*16^3)+(A*16^2)+(7*16^1)+A

The result of this long sequence is:

2108463738

Remember that negative sign? Now’s a good time to stick it on.

-2108463738

And there you have it: the result is -2108463738.

Some final notes

  • Be sure to observe whether the problem expects a signed decimal result or an unsigned decimal result. If the problem is asking for unsigned, you can skip the FFFFFFFF subtraction step entirely, even if the most significant bit is 7 or higher.
  • Remember that when working with a signed hexadecimal number, you look at the most significant bit to determine if it’s negative or positive.
    • 0-7 = positive
    • 8-F = negative
  • If you had to do the flipping step, don’t forget to put that negative sign onto your final answer!

OSU eCampus CS325 Analysis of Algorithms review & recap

This post is part of an ongoing series recapping my experience in Oregon State University’s eCampus (online) post-baccalaureate Computer Science degree program. You can learn more about the program here.

Six-word summary: brutally difficult, but it’s over now!

CS325 – it me

In CS325 you’ll study recurrences, asymptotic bounds, probably every major sorting algorithm plus some silly ones, dynamic programming, graph traversal, recursion, linear programs, and more.

CS325 Review

Well, the rumors are true – this class is hard. I’d place it in a tie with CS162 for overall difficulty. But where CS162 tries to kill you with a brutal workload, CS325 tries to kills you with instructional materials that don’t adequately prepare you for the homework or the exams.

The lectures are not sufficient preparation for the homework – you’ll rely on YouTube and Stack Overflow to get through each homework question. The weekly homework assignments are time-consuming and the documents you prepare are long. Mine were anywhere from 5-15 pages of graphs, pseudocode, and written explanations for my work.

If you can take CS325 by itself, you should.

There was a noticeable (and distressing) disconnect between what was on the homework and what was on the exams. I scored 100% on the homework assignments, but failed the midterm. It’s like the homework and exams were from different classes!

A week or so after the midterm was graded it was opened up so students could see which questions they got wrong and dispute wrong answers, if they could prove they had it right. I thought for sure I’d prove the TAs wrong on at least one or two of mine, so I reworked all of my incorrect answers – and reworked and reworked them – until I eventually figured out what subtle thing I missed while taking the test.

I definitely struggled in this class, and for the first time I wondered if I even belonged in this CS program.

Class structure

  • 10 weeks
  • 7 assignments total
  • Group work: weekly graded discussions on Canvas, a 3-person group project the last two weeks of the quarter
  • Proctored midterm (20% of final grade), proctored final (20% of final grade)
  • No homework assignment the week leading into the midterm
  • No homework assignment once the group project at the end begins
  • You can bring a 8.5″ x 11″ sheet of typed notes (size 6 font!) into the midterm and the final with you

Tips for CS325

Take every extra credit opportunity (they’re rarer than you think). There was an extra credit opportunity on the first homework, but there wasn’t another opportunity until the last homework!

Comment early, often, and be helpful in the Canvas discussions. There’s an opportunity for 1 point of extra credit in each of these weekly discussions. I was able to earn it most weeks by doing all of the following:

  • As soon as the discussion thread was available, I “structured” the discussion by creating a series of replies, one for each homework question. In each reply, I posted the contents of the homework question for easy reference. This gave each homework question its own thread for my group mates to use.
  • When I figured something out on the homework, I posted pseudocode or a “how I approached this problem” guide to the Canvas discussion to help others. I spent easily 1-4 hours on creating this type of “tutorial”, every single week.
  • I started the homework right away. On Sunday I did the lectures, on Monday I did question 1, Tuesday I did question 2, etc. By midweek, I had half the homework done and was able to assist with answering questions from group members just starting theirs.

This was a ton of extra work. I see why people blew off the Canvas discussions. But the discussions did two key things for me:

  1. It helped my understanding of the various topics to revisit them and “teach” them to others
  2. The extra credit helped me squeak by with a 92.58% in this class, which got rounded up to a 93% (the cutoff for an A). I needed every. single. point. I could get.

Study recursion – put it on your exam sheet! A lot of the class’s materials (lectures, book reading, and homework) will “gloss over” recursive solutions to problems. They’ll be like, “this is the slow way to do it with recursion, now here’s the better way to do it with <the technique of the week>”.

You might be tricked into thinking the exam will want you to know the fancy technique – you’d be wrong. The midterm will expect you to produce the recursive solutions, which you won’t code for the homework or even look at past the few minutes they get in each lecture. I thought this was unfair of the class, so that’s my tip to future CS325 students: study the recursive solutions. Put them on your “cheat sheet”. Know them inside and out!

The extra credit competition among the final project groups is a poorly-designed zero-sum game that you have almost no chance of winning. Here’s how it works: 60+ groups implement algorithm(s) to solve a given problem in as little time as possible, then post their best running times to a Canvas thread. The assignment won’t tell you what “good” times look like – you’ll figure that out by looking at results that trickle in from the other groups. The winner is whichever group (or groups) has the best performance times in the two different categories.

I think this competition could be made better by awarding extra credit to any (and all) groups that can pass a certain benchmark, since that’s hard enough on its own. My group picked difficult-to-implement but highly performant algorithms and did our work in C++ and we still lost to multiple other groups by a little bit. Unless you’re super dying for that extra credit, I think the winning move here is not to play. Take the time you’d spend optimizing your final project towards an unknown goal and spend it studying for the final instead.

The book sucks. (This is the book.) Okay, maybe the book doesn’t suck, but it doesn’t map nicely to the class material and it won’t walk you through how to solve the kinds of problems you’ll face in the homework. I think the teacher requires this book just for the sake of requiring a book.

You’ll need the power of Google (and YouTube and Stack Overflow) to uncover how-to’s and guides for actually solving problems. I still did the readings every week, just in case something useful turned up, but the book is more like an introduction to the topic, not a guide. I relied almost 100% on external resources to actually learn this class’s material.

There are better videos and walk-throughs for every topic this class covers on YouTube and people’s blogs. Seek them out! There are people who recorded themselves going step by step through real problems pertaining to topics like recurrences and dynamic programming in ways the class-provided lecture videos do not. I owe my A in this class to the generous people of YouTube who took the time to demonstrate these difficult topics.

More than any other class before it, CS325 requires self-teaching and finding help on your own. Whether that experience is worth $1900 is left as an exercise to the reader – there is, of course, the argument that self-teaching is what you’ll do on the job so you might as well get used to it, but there’s also the argument that $1900 ought to buy you at least a little bit of hand-holding.

I’ll be in two classes next quarter: CS271 (Assembly and Architecture) and CS361 (Software Engineering I), so say hi if you’re in either of those with me!

Fix: Font Awesome icons missing with Mesmerize PRO theme and MaxCDN

In this post: missing Font Awesome icons due to missing CDN configuration.

I have a WordPress blog that uses MaxCDN, W3 Total Cache, and the Mesmerize PRO theme by Extend Themes which includes Font Awesome icons.

After installing and activating the theme on my website the Font Awesome icons appeared as boxes:

Missing icon looks like a box
Another missing font awesome icon
Another missing font awesome icon

And I could see these (canceled) errors in the Network tab:

Errors in the Chrome Network tab. fontawesome-webfont status is canceled.
Errors in the Chrome Network tab. fontawesome-webfont status is canceled.

The referrer is

https://cdn1-mycompany.netdna-ssl.com/wp-content/themes/mesmerize-pro/assets/font-awesome/font-awesome.min.css?ver=1.0.221

That referrer, cdn1-mycompany.netdna-ssl.com, isn’t allowed to serve this file. But there’s an easy fix: you can whitelist the CDN itself in the CDN.

The fix: whitelist the CDN itself

In MaxCDN, go to Pull Zones > Security > Whitelist.

You might already have yourdomain.com in here. What you need to add is the domain your CDN files are pulled from.

MAXCDN settings: Pull Zone tab, Security tab, whitelist tab, add cdn1-domain.netdna-ssl.com to whitelist

In my case, that was a domain that took the form of cdn1-mydomain.netdna-ssl.com, but you can find out what yours is by looking in the Network tab while you try to load your site. Look for a red-colored error message and open the Headers.

Anyway, the fix is as easy as adding the domain to this list of whitelisted domains and waiting a few minutes (for me it was about 10 minutes). Reload your website and the Font Awesome icons should now appear.

Note: You will probably need to Purge All Caches, too, once the time has passed to actually see the change in your browser (I use the dropdown in the WP toolbar).

WordPress toolbar with W3 Total Cache Performance section rolled out, Purge All Caches selected

My W3 Total Cache settings

(Just in case it’s useful to someone else trying to debug this problem)

My W3 Total Cache settings are set to upload .css, .tff, .otf, .woff, and .woff2 files.

W3 Total Cache settings for which theme files to upload by extension. css, js, gif, tff, otf, woff, woff2, etc.

Provided again as text so you can copy/paste.

wp-includes file types to upload:

*.css;*.js;*.gif;*.png;*.jpg;*.xml

Theme file types to upload:

*.css;*.js;*.gif;*.png;*.jpg;*.ico;*.tff;*.otf;*.woff;*.woff2

This is a pretty specific configuration issue but hopefully it’ll help someone else out there!