Adding dates is tricky. Months have different numbers of days, so you can’t rely on just adding 30 days to get an extra month. You also can’t just add a certain number of months because formulas in Salesforce don’t auto increment the year. The solution is modular arithmetic and conditionals.
The goal here was to make a set of fields to send out emails on the first day of each month for 6 months, given a specific month to start with.
What I’m doing here is:
Year: Figuring out the month number, adding one less than the number of months over all, dividing it by 12, and rounding down to add either a 0 or 1 to the year. You have to subtract one from the month because 12/12 = 1 and you don’t want December adding an extra year.
Month: If the resulting month is December, return 12. Otherwise return the month number modulo 12. (12 mod 12 is 0, hence the conditional).
Day: Always returning 01, the first day of the month.
DATE( YEAR( date ) + FLOOR( ( MONTH ( date ) + number_of_months - 1 ) / 12 ), IF( MONTH ( date ) + number_of_months = 12, 12, MOD( MONTH ( date ) + number_of_months, 12 )), 01 )
How to use this: the date variable should be the date field you are starting with. You should replace number_of_months with the number of months you want to add to the original date. If the date is 07/01/2017 I want this to go out on 08/01/2017, I’d set number_of_months to 1. If 09/01/2017, I’d set it to 2, etc.
Note: This only works for the first of each month. If you need it to work on any day of the month, use this more complicated solution to account for months having different lengths.
As I mentioned a few days ago, I’m using Gulp on a new WordPress project. I like to back up my work every night, and since a lot of WordPress config and customization happens in the WordPress editor and widgets, that means backing up the mysql database as well as the code.
Why not use this newfound tool? Let’s do it.
I did some searching and found Gulp WordPress Backup, but it was overkill for what I wanted. But I saw that it used an npm package named mysqldump, for the export, so I grabbed that and started setting up a new task in gulpfile.js:
// add mysqldump as a dependency var mysqlDump =require('mysqldump');// dumpDatabase gulp.task('dumpDatabase', () => { return new Promise((resolve,reject)=>{mysqlDump({host:'localhost',user:'user',password:'pass',database:'wp_database',dest:'backup.sql'},(err)=>{if(err!==null)returnreject(err);});}).catch((err)=>{console.log(err);});});
Next step: Defining the filename. I just wanted to use today’s date because I intend on running this at the end of each work day. Since gulp is all javascript, this is easy:
vartoday=newDate(),dd=today.getDate(),mm=today.getMonth()+1//January is 0! yyyy = today.getFullYear(); if(dd<10) { dd ='0'+dd}if(mm<10){mm='0'+mm}today=mm+'-'+dd+'-'+yyyy;
Add this to the gulp task and you are good to go!
gulp.task('dumpDatabase',()=>{vartoday=newDate(),dd=today.getDate(),mm=today.getMonth()+1//January is 0! yyyy =today.getFullYear();if(dd<10){dd='0'+dd}if(mm<10){mm='0'+mm}today=mm+'-'+dd+'-'+yyyy;returnnewPromise((resolve,reject)=>{mysqlDump({host:'localhost',user:'user',password:'pass',database:'wp_database',dest:'SQLBackups/'+today+'.sql'// Outputs to the folder named SQLBackups and uses today's date as the filename.},(err)=>{if(err!==null)returnreject(err);});}).catch((err)=>{console.log(err);});});
Make sure you add mysqldump to your project’s package.json, or at least run npm install mysqldump before using!
When I updated to macOS High Sierra, a bunch of necessary stuff broke: Jekyll, Homebrew, Node.js, and a bunch of gems. s3_website, the tool I use to deploy my Jekyll site to S3, was one of the gems that just completely disappeared. When I went to reinstall it, I got an error that I didn’t have Java installed. Against my better judgment, I went to the URL listed and installed it. Then I ran s3_website push.
After about 30 seconds, I got an error saying that s3_website doesn’t work with Java 9, which was the most recent version at the link. And also the version you get with brew cask install java. Well, shit.
Exception in thread "main" java.lang.ExceptionInInitializerError at org.jruby.Ruby.newInstance(Ruby.java:266) at s3.website.Ruby$.rubyRuntime$lzycompute(Ruby.scala:4) at s3.website.Ruby$.rubyRuntime(Ruby.scala:4) at s3.website.model.Config$$anonfun$15.apply(Config.scala:229) at s3.website.model.Config$$anonfun$15.apply(Config.scala:227) at scala.util.Try$.apply(Try.scala:192) at s3.website.model.Config$.erbEval(Config.scala:227) at s3.website.model.Site$$anonfun$2.apply(Site.scala:28) at s3.website.model.Site$$anonfun$2.apply(Site.scala:27) at scala.util.Success.flatMap(Try.scala:231) at s3.website.model.Site$.parseConfig(Site.scala:27) at s3.website.model.Site$.loadSite(Site.scala:100) at s3.website.Push$.push(Push.scala:62) at s3.website.Push$.main(Push.scala:40) at s3.website.Push.main(Push.scala) Caused by: java.lang.RuntimeException: unsupported Java version: 9 at org.jruby.RubyInstanceConfig.initGlobalJavaVersion(RubyInstanceConfig.java:1878) at org.jruby.RubyInstanceConfig.(RubyInstanceConfig.java:1585) ... 15 more
After lots of searching, I came across a kind soul on Github suggesting that we use jEnv to define which java environment to use in the directory.
When I first installed jenv, I couldn’t add versions to the tool. I kept getting this error:
ln: /usr/local/opt/jenv/versions/oracle64-9.0.1: No such file or directory
The line-height attribute doesn’t work on span by default. If you need to use line-height on a span, you’ll need to set display:block; on the span element to make it display as a block element (like
While working on the 51 Line Charts for my Opioid Crisis data visualization, I ran into an issue with generating all 51 charts at the same time: The data was either in 51 rows stacked and I couldn’t access the dates effectively, or 306 rows unstacked and I had 6x as many objects as I needed when I did a join.
The solution was to use D3.nest. Nesting allows elements in an array to be grouped into a hierarchical tree structure; think of it like the GROUP BY operator in SQL, except you can have multiple levels of grouping, and the resulting output is a tree rather than a flat table. The levels in the tree are specified by key functions.
When I used the state as a key, it grouped each state’s data together in a tree.
I’ve used Coda by Panic as my IDE of choice for 10 years now, but I think it is starting to fall behind other tools. It isn’t updated often and there aren’t nearly as many community-built packages as other tools have. So I’m giving both Atom and Sublime a try. I’m trying Atom first.
In my first few days of use, here are some things I love:
d3-snippets package – The D3 is super powerful, but unless you use it every day, it is easy to forget the syntax for its huge array of features. I usually need to keep the documentation open in another window. With this package I just need to start typing what I need and I get a list of options with useful snippets.
platformio-ide-terminal package – Yeah, opening terminal.app in another window is easy. But having everything in one place is great.
It is so easy to find and install new packages for Atom. And there are so many!
Git integration – I usually use the command line for git, but I love being able to see which files in the sidebar are new, modified, and staged. Then with the click of a button I can commit and push them.
Easy customization – Within seconds I was able to switch themes and default fonts.
Multi line editing. Protip: On a Mac go to System Preferences > Mission Control and turn off the Control + Shift + Up Arrow and Down Arrow keyboard commands, which you can then use in Atom for multi line selection and editing.
I’m working on a new WordPress theme development project and using Gulp and Sketch for the first time. Here are my first use notes:
Gulp
Toolkit for automating tasks. Tons of packages available for things like minifying JS, compiling Sass, linting, packaging into zip files, pushing content to S3 and external servers, watching and automatically rendering changes in the browser, etc.
Pain to install. Dependencies all the way down.
Everything important goes in gulpfile.js
Here are the tasks I’m using:
gulp styles — Compile, autoprefix and minify Sass files.
gulp scripts — Minify javascript files.
gulp images — Compress and optimize images.
gulp watch — Compile assets when file changes are made, start BrowserSync
gulp — Default task – runs all of the above tasks.
gulp zip — Package theme into zip file for distribution, ignoring node_modules.
Sketch
I love being able to take layers, merge them, and export them as different image formats. This makes exporting background content a breeze.
No longer do I need to toil with eyeballing buttons and trying to figure out their padding, background gradients, and border radius. Code export is a gift from above.
I like their price model. Use the app for life, free updates for a year, resubscribe when you need more updates.
The issue seems to be caused by a change in 3.2 that now reserves the config key theme to specify a gem-based theme for Jekyll. This means that you can’t use the key theme in your config.yml file to specify config settings for your jekyll theme. This was a standard practice for a lot of older Jekyll themes, so I expect this to be a somewhat common problem.
For example, in my config.yml file, I had the following:
# THEME-SPECIFIC CONFIGURATIONtheme:# Metatitle:Chuck Grimmettavatar:avatar.pnggravatar:# Email MD5 hashdescription:"ChuckGrimmett'sblog"# used by search engines
The fix is to change the theme key to something else. I chose template. You not only have to change this in your config.yml file, but you also have to change anywhere that accesses it in your template files. The string you are looking for here is site.theme.* and is usually in your includes and layout files (look for folders called _includes and _layouts).
I changed that section of my config.yml to this:
# THEME-SPECIFIC CONFIGURATIONtemplate:# Metatitle:Chuck Grimmettavatar:avatar.pnggravatar:# Email MD5 hashdescription:"ChuckGrimmett'sblog"# used by search engines
Then I did a global search for site.theme. and replaced it with site.template.
Here is a problem I was faced with at work last week: Individuals who had two different kinds of relationships with an organization had two different contact records stored in two different files in a legacy database. The client wants to collapse those contact records down into one if possible, so we had to do a comparison between then.
Difficulties:
Names were concatenated in one file and stored separately in the other.
Some addresses didn’t match (which is what we were checking in the first place), but even if they did, they were often entered differently between the two files (APT vs #, ST vs St., S vs South).
In one file, all postal codes were stored in one column. In the other file, domestic postal codes were stored in one column and international postal codes were stored in another column.
One file had about 30 duplicates for some reason. This means there were multiple entries in the database, but for some reason they all contained exactly the same information.
First things first: I got the information in a CSV file for comparison. I pulled this into Excel. Thankfully there was a unique ID between the two files that matched, so I was able to quickly deduplicate the first file and get the number of entries to match. Then I sorted the two files in the same order.
Here are the formulas I used for comparisons:
Compare cells on two different sheets and put out Yes if they match, No if they do not: =IF(E2='Sheet 2'!C2,"YES","NO")
Compare the first 5 characters of two cells instead of the whole contents. This is how I solved the whether or not addresses “matched” even if they have slight issues (APT vs #, ST vs St., S vs South). This won’t work for every situation, but I spot checked the cells and didn’t find any issues in my data set. =IF(LEFT(E2,5)=LEFT(F2,5),"YES","NO")
Counting the number of NOs in a particular column: =COUNTIF(G2:G150,"NO")
Count the number of YESes or NOs in a particular row. This will give you a good indicator of whether or not a row matches overall: =COUNTIF(H2:AC2,"NO")=COUNTIF(H2:AD2,"YES")
I’ll admit, unlike the other tutorials where I was able to figure out most of this on my own, I had to mine other examples to figure this out. I primarily followed Mike Bostock’s Pie Chart Update, II, but his commented Arc Tween example was extremely helpful in understanding what d3.interpolate is doing.
First we need to store the beginning angle for each arc. You’ll recall that I’m using two separate arcs, one for the main chart and one for the labels. For about 10 minutes I was trying to figure out why the first update was jumpy but all subsequent ones were smooth. It turns out that we need to store the initial angles for each set of arcs:
g.append("path").attr("d",arc).style("fill",function(d){returncolor(d.data.letter);}).each(function(d){this._current=d;});// store the initial angles;g.append("text").attr("transform",function(d){return"translate("+labelArc.centroid(d)+")";}).text(function(d){returnd.data.letter;}).style("fill","#fff").each(function(d){this._current=d;});// store the initial angles;
Next we need to write two arcTween functions to transition between the two. I followed Mike Bostock’s example for the first one, then adapted it to the label arc, too:
Last we need to include these arcTween() functions into the change() function we wrote before. I commented out the previous updates so you can compare them. The duration is 1/2 a second:
functionchange(){varpie=d3.pie().value(function(d){returnd.presses;})(data);path=d3.select("#pie").selectAll("path").data(pie);//path.attr("d", arc);path.transition().duration(500).attrTween("d",arcTween);// Smooth transition with arcTween//d3.selectAll("text").data(pie).attr("transform", function(d) { return "translate(" + labelArc.centroid(d) + ")"; });d3.selectAll("text").data(pie).transition().duration(500).attrTween("transform",labelarcTween);// Smooth transition with labelarcTween}
Here is is in action. As always, you can view source to see the fully integrated example:
Last week we made a pie chart with D3.js. Today we are going to update it in realtime when buttons are clicked.
Here is the basic pie chart again, slightly modified from the original (I only changed the letters):
The key to making this work is D3’s object constancy. We already baked that into the original design by specifying a key function for the underlying presses count data.
Setting Up
First, we need to copy the pie chart we made last week. Make a few updates: change all the presses in data to 1 and change the letters to A, B, and C.
Next, we need something to click so we can increment the count and update the chart. Three buttons will do nicely:
We ultimately want to call a specific update function when we click each button, so let’s write one. We need to consider what the most critical parts of making the original pie chart were so that we can recreate only the necessary steps:
Defining the value function for d3.pie
Computing the angles based on that data
Putting that information in a path so it can be displayed
Remember that we have two arcs: The main pie and the one holding the labels. We need to update both!
functionchange(){varpie=d3.pie().value(function(d){returnd.presses;})(data);path=d3.select("#pie").selectAll("path").data(pie);// Compute the new anglespath.attr("d",arc);// redrawing the pathd3.selectAll("text").data(pie).attr("transform",function(d){return"translate("+labelArc.centroid(d)+")";});// recomputing the centroid and translating the text accordingly.}
Updating the data and chart on click
Now we need to update the underlying data and the whole chart on click:
This is part of my ongoing effort to relearn D3.js. This short tutorial applies what I’ve learned about data joins, arcs, and labels. It varies slightly from other examples like Mike Bostock’s Pie Chart block because I’m using D3.js version 4 and the API for arcs and pies is different from version 3, which most tutorials are based on. I figured this out through some trial and error. Always read the documentation!
I’m eventually going to use this pie chart as a base to learn how to update charts in real time based on interactions like button pushes or clicks.
Getting Started
Always include the library:
Make a div to hold the chart:
D3 stands for Data-Driven Documents. So what do we always start with when creating something with D3? Data!
Since I’m eventually going to figure out how to update this chart in real time based on button presses, I’m going to start with some dummy data for three easy-to-press buttons: q, w, and e. As always, I log it to the console for quick debugging:
We’ll also need some basics like width, height, and radius since we are dealing with a circle here. Make them variables so your code is reusable later:
varwidth=300,height=300,// Think back to 5th grade. Radius is 1/2 of the diameter. What is the limiting factor on the diameter? Width or height, whichever is smallerradius=Math.min(width,height)/2;
Next we need a color scheme. Be referring to the API, we learn that we should use .scaleOrdinal() for this:
We need to set up the pie based on our data. According to the documentation, d3.pie() computes the necessary angles based on data to generate a pie or doughnut chart, but does not make shapes directly. We need to use an arc generator for that.
Before we create the SVG and join data with shapes, let’s define some arguments for the two arcs we want: The main arc (for the chart) and the arc to hold the labels. We need an inner and outer radius for each. If you change the inner radius to any number greater than 0 on the main arc you’ll get a doughnut.
We always start with an SVG. Select the div we created to hold the chart, append an SVG, give the SVG the attributes defined above, and create a group to hold the arcs. Don’t forget to move the center points, or else the chart will be centered in the upper right corner:
varsvg=d3.select("#pie").append("svg").attr("width",width).attr("height",height).append("g").attr("transform","translate("+width/2+","+height/2+")");// Moving the center point. 1/2 the width and 1/2 the height
Now let’s join the data generated by .pie() with the arcs to generate the necessary groups to hold the upcoming paths. Give them the class “arc”.
Now we can append the paths created by the .arc() functions with the variables we defined above. We’re using the color variable we defined above to get the colors we want for the various arcs:
Once you save, you should see a chart. Now we’re cooking with data!
Labels
Let’s put some labels on it now. We’ll need to append some text tags in each arc, set the position with a transform defined by the labelArc variable we defined earlier, then access the correct letter to add to the label. Then we’ll make it white so it shows up a little better:
I’ve been on a mission to relearn the fundamentals of D3.js from the ground up. This tutorial is a way to apply what I learned about data joins, click events, and selections. Along the way I learned about building arrays.
I also wrote this up as a block for those interested.
Basics
We want to make a 10×10 grid using D3.js. D3’s strength is transforming DOM elements using data. This means we’ll need some data and we’ll want to use SVG and rect elements.
Data
We could write an array of data for the grid by hand, but we wouldn’t learn anything then, would we? Let’s generate one with Javascript.
Picture a grid in your head. It is made up of rows and columns of squares. Since this is ultimately going to be represented by an SVG, let’s think about how an SVG is structured:
What you see here is a basic structure of rows and columns. That means that when we make our data array, we want to make a nested array of rows and cells/columns inside those rows. We’ll need to use iteration to do this. Easy-peasy.
The other question we’ll have when making these arrays is, “What attributes will this grid need?”. Think about how you’d draw a grid: You start in the upper right corner of a piece of paper, draw a 1×1 square, move over the width of 1 square and draw another, and repeat until you get to the end of the row. Then you’d go back to the first square, draw one underneath it, and repeat the process. Here we’ve described positions, widths, and heights. In SVG world these are x, y, width, and height.
Here is the function I’m using to create the underlying data for the upcoming grid. It makes an array that holds 10 other arrays, which each hold 10 values:
functiongridData(){vardata=newArray();varxpos=1;//starting xpos and ypos at 1 so the stroke will show when we make the grid belowvarypos=1;varwidth=50;varheight=50;// iterate for rows for(varrow=0;row<10;row++){data.push(newArray());// iterate for cells/columns inside rowsfor(varcolumn=0;column<10;column++){data[row].push({x:xpos,y:ypos,width:width,height:height})// increment the x position. I.e. move it over by 50 (width variable)xpos+=width;}// reset the x position after a row is completexpos=1;// increment the y position for the next row. Move it down 50 (height variable)ypos+=height;}returndata;}
Making a Grid with D3 Data Joins
We made a cool array above and now we’ll make the data correspond to svg:rect objects to make our grid. First we’ll need to make a div to append everything to (and, of course, don’t forget to include the latest version of D3 in your header):
id="grid">
Now we need to assign our data to a variable so we can access it:
vargridData=gridData();// I like to log the data to the console for quick debuggingconsole.log(gridData);
Next, let’s append an SVG to the div we made and set its width and height attributes:
And finally we make the individual cells/columns. Translating the data is a bit trickier, but the key is understanding that we are doing a selectAll on the rows, which means that any reference to data is to the contents of the single array that is bound to that row. We’ll then use a key function to access the attributes we defined (x, y, width, height):
You’ll note that I added style fill and stroke attributes to make the grid visible.
When we put it all together, here is what we get:
Note: If you are viewing this on your phone, you might want to switch over to a tablet or desktop. I haven’t optimized this example for mobile because that will needlessly complicate it.
Cool, huh? Go ahead and inspect the element and marvel at your find handiwork. Then change the fill, stroke, width, and height attributes and see how it changes.
Adding Click Functions
Let’s have some fun and add click events to the individual cells. I want to have cells turn blue on the first click, orange on the second, grey on the third, and white again on the fourth. Since D3 is data-driven, we’ll need to add some click data to the arrays and then add functions to change it and set colors based on the number of clicks.
//add this to the gridData functionvarclick:0;//add this to the cell/column iteration data.pushclick:click//add this to var column = row.selectAll(".square").on('click',function(d){d.click++;if((d.click)%4==0){d3.select(this).style("fill","#fff");}if((d.click)%4==1){d3.select(this).style("fill","#2C93E8");}if((d.click)%4==2){d3.select(this).style("fill","#F56C4E");}if((d.click)%4==3){d3.select(this).style("fill","#838690");}})
Let’s break down that on('click') function:
When you click on a cell, it increases the click variable (originally set at 0) by 1.
The if statements set the color based on how many times it has been clicked mod 4. This satisfies the UI of only having four states: white, blue, orange, and grey. If you go to your console and call up the data for a certain cell, you’ll see that the full number of clicks is available.
Here it is. Click away!
Randomized click counts
What happens when we randomize click counts when we create the data array?
//add this to the gridData functionvarclick:0;//add this to the cell/column for loop, just above the data.push lineclick=Math.round(Math.random()*100);//add this to var column = row.selectAll(".square").style("fill",function(d){if((d.click)%4==0){return"#fff";}if((d.click)%4==1){return"#2C93E8";}if((d.click)%4==2){return"#F56C4E";}if((d.click)%4==3){return"#838690";}})
Note that Math.random() returns a number between 0 and 1, inclusive. Multiple that by 100 if you want a number between 1 and 100.
It changes when you refresh!
Mouseovers: Even more fun with a bigger grid
What happens when we change the click event to a mouseover event and make a bigger grid? It becomes a lot more fun. I’ll leave the implementation as an exercise to the reader. If you’ve been following along and writing this yourself instead of copying and pasting, you probably already know which variables and events to change:
These are my outputs from Mike Bostock’s Three Little Circles Tutorial, slightly modified so I could understand how each of these items work. This is a tutorial about selections and basic data joins.
We start with three basic SVG circles:
Now let’s select them and make them a little bigger and orange!
This uses a new function: The index of the element within its selection. The index is often useful for positioning elements sequentially. We call it i by convention.
D3.js is a javascript library for manipulating documents based on data. It uses HTML, SVG, and CSS to do so. It emphasizes web standards so that you can use modern browsers without proprietary frameworks.
You can bind data to a DOM (Document Object Model) and apply data-driven transformations to the document.
Example: Generate an HTML table from an array of numbers, then use the same data to make an SVG bar chart.
Selections
D3 makes it a lot easier to modify documents than the W3C DOM API. The W3C method relies on verbose names and manual iteration. D3 employs a declarative approach that operates on arbitrary nodes called selections.
Here is Mike Bostock’s examples for how to change the text color of paragraph elements with the W3C method vs D3 method:
Elements may be selected using a variety of predicates, including containment, attribute values, class and ID.
D3 provides multiple ways to change nodes: Setting attributes and styles, registering event listeners, adding/removing/sorting nodes, and changing HTML or text content.
Direct access to the DOM is possible because each D3 selection is a simple array of nodes.
Dynamic Properties
D3 has similar syntax to jQuery, but styles, attributes, and other properties can be specified as functions of data in D3, not just constants.
Computed properties often refer to bound data. Data is specified as an array of values, and each value is passed as the first argument (d) to selection functions. With the default join-by-index, the first element in the data array is passed to the first node in the selection, the second element to the second node, and so on. For example, if you bind an array of numbers to paragraph elements, you can use these numbers to compute dynamic font sizes:
Once the data has been bound to the document, you can omit the data operator. D3 will retrieve the previously-bound data. This allows you to recompute properties without rebinding.
Enter and Exit
With D3’s enter and exit selections you can create new nodes for incoming data and remove outgoing nodes that are no longer needed.
When data is bound to a selection, each element in the data array is paired with the corresponding node in the selection. If there are fewer nodes than data, the extra data elements form the enter selection, which you can bring to life by using the .enter() selection. Example:
d3.select("body").selectAll("p").data([4,8,15,16,23,42]).enter().append("p").text(function(d){return"I’m number "+d+"!";});
Updating nodes are the result of the data operator. If you forget the enter and exit selections, you will automatically select only the elements for which there exists corresponding data.
A common pattern is to break the initial selection into three parts: Updating nodes to modify, entering the nodes to add, and exiting the nodes to remove. Example:
By handling the three cases (update, enter, exit) separately, you control precisely which operations run on which nodes.
D3 allows you to transform documents based on data. This includes creating and destroying elements.
D3 allows you to change an existing document in response to user interaction, animation over time, or even asynchronous inputs from a third-party. A hybrid approach is also possible, where the document is initially rendered on the server and updated on the client via D3.
Transformation, not Representation
D3 does not introduce a new visual representation. Instead, its graphical marks come from web standards: HTML, SVG, and CSS. If browsers introduce new features tomorrow, you can use them immediately with D3, no update required.
D3 is easy to debug with the browser’s built-in element inspector. The nodes D2 manipulates are the same ones the browser uses natively.
Transitions
D3’s transformation focus extends to animated transitions, too. Transitions interpolate styles and attributes over time. The time between can be controlled with easing functions.
D3’s interpolators support primitives (numbers and numbers within strings like font size, etc) and compound values. They are also extendable.
D3 has no primitive for creating multiple DOM elements. The .append() method can create single elements, but if you want multiple, you need to think in a different way.
Instead of telling D3 how to do something, tell D3 what you want. For example, on the Thinking with Joins page, Mike uses this snippet to tell D3 that the selection “circle” should correspond to data points. This concept is called a data join:
Data points joined to the existing elements produce the update (inner) selection. Leftover unbound data produce the enter (left) selection, which represents missing elements. Any remaining unbound elements produce the exit (right) selection, which represents elements to be removed.
Now let’s explain the svg.selectAll("circle"):
First it returns an empty selection since the SVG container was empty. The parent node of the selection was the SVG container.
The selection is joined to a data array, resulting in three new selections that represent three possible states: enter, update, or exit. Since the selection was empty, the update and exit selections are empty and the enter selection contains a placeholder for each new data point.
The update selection is returned by selection.data and the enter and exit selections hang off the update selection. selection.enter returns the enter selection.
The missing elements are added to the SVG container by calling selection.append on the enter selection. This appends a new circle for each data point in the SVG container.
Thinking with joins means declaring a relationship between a selection (such as a “circle”) and data, then implementing this relationship through the three enter, update, and exit states.
For static visualizations, the enter selection is sufficient. But you can support dynamic visualizations with minor modifications to update and exit.
If a given enter, update, or exit selection happens to be empty, the corresponding code does not operate.
Joins let you target operations to specific states. For example, you can set constant attributes (such as the circle’s radius, defined by the “r” attribute) on enter rather than update. By reselecting elements and minimizing DOM changes, you vastly improve rendering performance!
Similarly, it allows you to target animations to specific states like expanding circles as the come in and contract circles as they go out.
Emmet is a tool I just found that expands your HTML and CSS workflow. It expands HTML from CSS-based abbreviations and quickly selects important parts of the code you are editing.
Here is a list of resources I plan to go through. I should be able to relearn the basics fairly quickly so that I can spend time making charts of my own. I’ll update completed items with check marks as I go through them.
Today I saw that I was getting a bunch of requests for http://cagrimmett.com/blog, which was the landing page for my 2008-2014 blog that I took down last year. That page does not exist now and “blog” is now just a directory on my site generated by Jekyll’s paginator.
I wanted to take those requests and forward them to the landing page of my new blog. The /blog/ requests were all 403 errors, and any direct link to an old post is a 404 error. So I added these two lines to my main .htaccess file to handle the request:
ErrorDocument 403 / ErrorDocument 404 /404.html
This means:
“Take any 403 error and show the user the site’s front page (/)”
“Take any 404 error and show the user the 404 page”
Sometimes you need to put scripts on a specific page in WordPress. Frameworks like Genesis have boxes where you can add header or footer scripts. Most don’t, though. Here is how to load scripts on specific pages in WordPress with the wp_enqueue_scripts hook.
In functions.php in your theme folder, you’ll need to add an action for the wp_enqueue_scripts hook. This will be a function pointing to the script.
I’m using get_stylesheet_directory_uri() to link to the script. This means if your theme’s main style.css is in “example.com/wp_content/themes/twentysixteen/style.css”, your script should be in “example.com/wp_content/themes/twentysixteen/js/script.js”.
Pick one the the scenerios below and add the code to your functions.php file in your theme. Make a backup of it first in case you mess something up.
If you have one of those fancy themes that generates a front page that you edit in the Customizer but it doesn’t have a page ID, but you only want it to display on the front page, don’t fret. WordPress has a is_front_page function:
Letâs say you have a bunch of elements that under certain situations you want to replace with another element. jQueryâs replaceWith() function is perfect for that.
Here is an example of replacing all links with the class replace with a different link. The use case was finding certain buttons that say âApply Nowâ and replacing them with buttons that say âFinish your applicationâ. Since searching for âApply Nowâ wasnât perfect (the text and other links said it, too) I manually put in the replace class so I knew exactly which elements Iâd be selecting.