Learnable Programming

http://worrydream.com/LearnableProgramming/

Article by Bret Victor, Sept 2012

How do we get people to understand programming? We change it into something understandable.

The environment differs from the language:

The environment allows users to read the vocabulary, follow the flowsee the statecreate by reactingcreate by abstracting.

The language provides identity and metaphordecompositionrecomposition, and readability.

“In a modern environment, memorizing the minutia of an API should be as relevant as memorizing times tables.” The environment should show what the code is implying, and map out those arguments on the canvas/window, especially if they are visual in nature.

“In order for a learner to understand what the program is actually doing, the program flow must be made visible and tangible.” For loops are great notationally, but while loops offer more visual order to the process. A visual control for the frame-rate/loop-rate is recommended. A visual representation of how the loop runs is also helpful in recognizing the patterns in algorithms.

flow3

“We expect programmers to write code that manipulates variables, without ever seeing the values of those variables. We expect readers to understand code that manipulates variables, without ever seeing the values of the variables. The entire purpose of code is to manipulate data, and we never see the data.” Struggles with state-based functions, such as fill(), are a struggle with not showing the data. If you knew what the default state was, and then how you changed with a function, then you have better understanding of the logical order necessary to execute the program.

victor_1

Other forms of art and creative expression (painting, music, etc) develop ideas by reacting, not planning. Experimentation and the subsequent evaluation is the key task being performed by creatives. Programming should be no different. A graphics library could, for example, autocomplete shapes with actual sizes. If the programmer deems this the correct shape, they can then adjust the size, dimensions or other arguments. [An environment should “encourage the programmer to explore the available functions. A learner who would never think to try typing the “bezier” function, with its unfamiliar name and eight arguments, can now easily stumble upon it and discover what it’s about.”

react5

Understanding the power of variables and functions can be daunting. An environment that teaches abstraction should start with hard coding, and build up the role of the variable: relating on thing to another. This is still creating-by-reacting, as Victor points out, in that the programmer denotes x as the x-position of both a corner of a rectangle and a triangle as a rule established by the two arguments first being hard coded (and then replaced with the same variable). “The learner always gets the experience of interactively controlling the lower-level details, understanding them, developing trust in them, before handing off that control to an abstraction and moving to a higher level of control.”

 

Advertisements

VizTech: OOCSS, DOM Trees

readings 2 Object-Oriented CSS, DOM

Louis Lazaris’s “An Introduction To Object Oriented CSS (OOCSS)”

http://www.smashingmagazine.com/2011/12/an-introduction-to-object-oriented-css-oocss/

Haverbeke, Marijn. Eloquent Javascript. Ch 13 The Document Object Model.

http://eloquentjavascript.net/13_dom.html

The Principles of OOCSS

  • the purpose of OOCSS (object-oriented CSS) is to encourage code reuse and, ultimately, faster and more efficient stylesheets that are easier to add to and maintain.

Separation of Structure from Skin

  • using ID selectors when you could use class selectors is inefficient.

Separation of Containers and Content

  • when we use structural selectors, it limits where the values can apply. Consider identifying classes for each grouping of areas that need common formatting.
  • a .globalwidth class can be set up for many elements of a web page. Now instead of writing new CSS rules, you just need to add class descriptors to your HTML.
    • Benefits include: faster websites (smaller file size and faster download), maintainable stylesheets (cascading easier to recognize)

You Can Still Use IDs

  • IDs can be more helpful for selecting in JavaScript hooks and fragment identifiers

Some Guidelines For Implementation

Ch13: The Document Object Model

DOCUMENT STRUCTURE

  • You can imagine an HTML document as a nested set of boxes. For each box, there is an object, which we can interact with to find out things such as what HTML tag it represents and which boxes and text it contains. This representation is called the Document Object Model, or DOM for short.
  • The global variable document gives us access to these objects. Its documentElement property refers to the object representing the <html> tag. It also provides the properties head and body, which hold the objects for those elements.

TREES

  • We call a data structure a tree when it has a branching structure, has no cycles, and has a single, well-defined “root”.
    • document.documentElement serves as the root
  • Trees are often used to maintain sorted sets of data because elements can usually be found or inserted more efficiently in a sorted tree than in a sorted flat array.
  • Each DOM node object has a nodeType property, which contains a numeric code that identifies the type of node. Regular elements have the value 1, which is also defined as the constant property document.ELEMENT_NODE. Text nodes, representing a section of text in the document, have the value 3 (document.TEXT_NODE). Comments have the value 8 (document.COMMENT_NODE).

THE STANDARD

  • the DOM is a language-neutral interface that can be used to describe other systems that just JavaScript: like HTML, XML, etc.
  • Code that interacts with the DOM is usually long, repetitive, and of poor design.

MOVING THROUGH THE TREE

  • DOM nodes contain a wealth of links to other nearby nodes. The following diagram illustrates these:

  • each of these nodes have a parentNode property. Each of these element nodes has a childNodes property that points out it’s place in an array-like object holding all of it’s siblings.
  • you could use these elements to which functions/if/for() loops to make a search parameter for the document
  • The nodeValue property of a text node refers to the string of text that it represents.

FINDING ELEMENTS

  • getElementsByTagName(“ /*insert element here, like a or p*/)[0]; console.log(link.href);
  • All element nodes have a getElementsByTagName method, which collects all elements with the given tag name that are descendants of a given node and returns an array-like object.
  • to return a specific node, give it an ID attribute and use document.getElementById instead.

<p>My ostrich Gertrude:</p>
<p><img id=”gertrude” src=”img/ostrich.png”></p>


var ostrich = document.getElementById(“gertrude”);
console.log(ostrich.src);

  • similarly, getElementsByClassName, searches contents of element node and retrieves elements that have a given string in their class attribute.

CHANGING THE DOCUMENT

  • the DOM tree can be changed by a number of methods
  • removeChild and appendChild, remove and add children (to end of parent’s list of children).
  • insertBefore inserts a node give as the first argument before the node given as the second argument. document.body.insertBefore(paragraphs[2], paragraphs[0]); array[0), array [1], array[2] becomes array[2], array[0], array[1] — new argument first, old argument second…
  • replaceChild does just that: two arguments , the first replaces the second.

… more to come

VizTech: Web, HTML, CSS, JavaScript, SVG

readings 1 + 2 Web, HTML, CSS, JavaScript, SVG

”HTML Introduction”

http://www.w3schools.com/html/html_intro.asp

A. Murray, Scott. 2013. Interactive Data Visualization. Ch 3 Technology Fundamentals.

http://chimera.labs.oreilly.com/books/1230000000345/ch03.html

WEB

  • The web actually consists of a collection of conversations between web servers and web clients.
  • web clients request, web servers deliver data
  • web servers: Internet-connectd computer running software that makes web documents available by request.
    • Always on, always connected
    • There are remote (not on your device) servers and local servers
  • web browsers/clients: interface for the web server software package
  • Every webpage, in theory, can be identified by its URL (uniform resource locator) or URI (uniform resource identifier)
    • indication of communication protocol (http, https)
    • domain name of resource
    • port number, indicating over which port the connection to the server should be attempted; web browsers will attempt connection over port 80 by default (usually excluded)
    • additional locating info (path of requested file, query parameters, etc)
  • HTTP: Hypertext Transfer Protocol
    • most common protocol for transferring web content from server to client
    • “S” in HTTPS stands for Secure, encrypted transit (like online banking)
  • Order of operations from entering in web address in browser pjo.com/learn/d3
    1. browser defaults protocol HTTP
    2. browser attempts connection to server behind pjo.com, via port 80.
    3. server acknowledges connection and allows request to be made
    4. browser sends request for page that lives at /learn/d3/.
    5. server sends back HTML content for that page.
    6. browser receive HTML and discovers other files needed to assembly and display, including CSS stylesheets, image files, etc. Another connection to same server is needed.
    7. server responds and dispatches other files needed
    8. client browser renders content, first with HTML structure, then apply CSS selectors, and then images, and then JavaScript codes.

HTML

  • Hypertext Markup Language is used to structure content for web browsers. HTML is stored in plain text files with the .html suffix.
    • Current iteration of HTML is HTML5, still referred to HTML
    • “marking up” content means to add structure, specify semantic structure, or adding hierarchy.
    • to mark up, add tags to create elements
    • tags usually occur in pairs and begin and cap the element
    • tags can nest within each other but can not overlap
  • <!DOCTYPE html> must be first in document; standard document type declaration
    • <html> must surround all HTML content in document
    • <head> metadata for document (programmer title, references to external stylesheets and scripts)
    • <title> bookmarking title, displayed in browser tabs
    • <body> primary visible content box
    • <span> & <div> arbitrary span or division of text(inline)/document
  • Attributes: assigned to/qualify elements and their tags
    • often written in the opening tag as <tagname property=“value”> </tagname>
    • Class/ID are universal attributes, can be applied to any tag
    • Class: can group multiple tags together, spaces divide tags
    • ID: unique identifier, cannot begin ID value with number
  • <! – – Comments are displayed like this – – >
  • DOM (Document Object Model): the hierarchical structure of HTML
    • refer to element’s relative relationship in human terms: parent, child, sibling, etc.
  • Developer Tools: allow users to see how browser renders HTML (inspect element on Chrome)
  • Rendering and the Box Model
    • To a browser: EVERYTHINGS A BOX!
    • Each tag is a two-dimensional rectangle, able to be positions and moved and changed.
    • Block-level elements display the full-length of the browser window, and are defaulted stacked top to bottom; inline elements rest within the its parent block.

CSS

  • CSS: Cascading Style Sheets
    • consists of selectors { and properties: and property values; }
    • the sum of which is collectively a CSS rule
  • SELECTORS:
    • multiple selectorA, selectorB, selectorC {
    • descending selectotorsA selectorB {
    • selects all selectorB elements contained in selectorA
    • h1 em (all emphasized elements within an h1 tag pair)
    • .class_selector begins with a period
    • .contains_two.class_selectors (uses periods with no spaces)
  • #ID_selectors
    • div.sidebar (selects div with class “sidebar” but not other elements in that class)
  • PROPERTIES:
  • COMMENTS:
    • /* all comments are surrounded by a slash-asterisk pairing on either end  and can span multiple lines */
  • You can put CSS selectors and properties into the <head> of your document, but separation of hierarchy and appearance in documents is helpful.
  • Inline styles are also possible, <p style=”color: blue; font-size: 48px; font-style: italic;”> but are kind of a hassle</p>
    • if you use separate documents, you must reference the style sheet and location in the <head> <link rel=”stylesheet” href=“style.css”> </head>
  • INHERITANCE: children inherit their parent’s styles
  • CASCADING: styles cascade from the top down, replacing less specific/default rules with ones you specify
  • SPECIFICITY: of a selector, determines which rules are applied over others.

JAVASCRIPT

  • scripting language that makes pages dynamic by manipulating the DOM after a page has already loaded in the browser
  • you can use the CONSOLE in the web developer mode of your browser to test out JS code
  • Variables: var number = 2; var textString = “this is the correct format”; var boolean_1 = true;
  • Arrays: a sequence of values stored in a single variable
    • var array_5s = [5,10,15,20,25];
    • array_5s[2]   //returns 15 because array numbering begins at 0, not 1
    • arrays can hold numbers, strings, booleans, etc.
  • Objects: hold complex sets of data
    • var object_1 = { kind: “abstract”, name: “object 1”, quantity: 1, noteworthy: true};
    • object_1.kind   //returns “abstract”
  • JavaScript Object Notation (JSON) is a syntax optimized for use with JS and AJAX requests
    • Objects display as:
    • {“kind”: “grape”, “color”: “red”, “quantity”: 12, “tasty”: true}
  • GeoJSON can store points in geographical space (typically as longitude/latitude coordinates), but also shapes (such as lines and polygons) and other spatial features. If you have a lot of geodata, it’s worth it to parse it into GeoJSON format for best use with D3.
  • Mathematical operators and comparison operators work normally in JavaScript
  • Control Structures
    • If() only
    • for() now
  • An array organizes lots of data values in one convenient place. Then for() can quickly “loop” through every value in an array and perform some action with it—such as, express the value as a visual form. D3 often manages this looping for us, such as with its magical data() method.
  • Functions: take input and make output
    • var calculateGratuity = function(bill) { return bill * 0.2; };
    • calculateGratuity(38);    // returns 7.60 — a 20% tip!
  • Comments
    • /* works for multiple lines */
    • // works for this line
      but would not comment this line
  • Referencing Scripts

Javascript Gotchas:

  • Dynamic Typing
    • JavaScript (unlike Java) automatically determines the type of variable based on your input. No need to declare a boolean variable, or a float variable. Just a variable is enough!
    • Therefore, variables type can be swapped and switched with no errors.
  • Variable Hoisting
    • JS is run top-to-bottom for the most part; however, JS hoists variables to the top of the function context in which they reside
    • an iteration variable i within a for() loop parameter is created before the for() loop  is read by JS & outside of the for() loop parentheses . This can create conflicting variable names.
  • Function-Level Scope
    • Variable scope: the area of code in which a variable storage is accessible. Not all coding languages have variables accessible for use in the whole document
    • block-level scope indicates variables are only available in between the block of code they reside (in between curly braces). such as, iteration variable i in a for() is only available inside the loop. NOT THE CASE WITH JS.
    • In JavaScript, variables are function-scope. You can keep values contained by wrapping them up in functions.
  • Global Namespace
    • Typing in window in to a web developers CONSOLE displays the global namespace
    • Every variable you add appears in the global namespace and could cause conflicts between similarly named variables—even from other .js files.
    • Solutions: Declare variables only within other functions & Declare a single global object, and attach all of your would-be global variables to that object.

SVG

  • D3 is most useful when used to generate and manipulate visuals as Scalable Vector Graphics (SVG).
    • drawing with HTML is possible but clunky and subject to inconsistencies across browsers.
    • SVG are more reliable, consistent, and faster
  • SVG ELEMENT
    • can be included in HTML document or inserted dynamically into the DOM
    • XML-based, does not run on Internet Explorer versions 8 and earlier
    • create an SVG element (like a canvas), and at minimum specify width and height; SVGs will take up all available room within a block otherwise.
    • height and width specified in pixels or other supported units (pt, in, cm, mm)
  • Simple Shapes
    • SVG coordinate systems begin from top left of bounding box/container
    • <rect x=”0″ y=”0″ width=”500″ height=“50″/>
    • <circle cx=”250″ cy=”25″ r=“25″/> (circles are centered)
    • <ellipse cx=”250″ cy=”25″ rx=”100″ ry=“25″/>
    • <line x1=”0″ y1=”0″ x2=”500″ y2=”50″ stroke=“black”/> (stroke color MUST be included to become visible)
    • <text x=”250″ y=“25″>Easy-peasy</text> (x&y denote start of baseline)
      –>text will inherit CSS-specified font styles of its parent element(s), you can override it with in-line formatting
    • Any visual element that run up against the edge of the SVG will be cropped; consider descenders, especially.
  • STYLING SVG ELEMENTS
    • SVG’s default style is a black fill with no stroke. If you want anything else, you’ll have to apply styles to your elements.
    • You can assign a SVG element a class, and control it with a rule in a CSS stylesheet. Consider beginning CSS rules for SVG elements with svg so that properties of SVG elements that do not translated to CSS properties do not get applied elsewhere in the document by mistake.
    • For example stroke-width and stroke are not CSS-valid properties, but work with SVG properties.
  • LAYERING AND DRAWING ORDER
    • There are no “layers” in SVG and no real concept of depth. SVG does not support CSS’s z-index property, so shapes can be arranged only within the two-dimensional x/y plane. The order in which elements are coded determines their depth order
  • There are two ways to apply transparency: use an RGB color with alpha, or set an opacity value.
    • rgba() expects three values between 0 and 255 for red, green, and blue, plus an alpha (transparency) value between 0.0 and 1.0; with rgba(), transparency is applied to the fill and stroke colors independently
    • <circle cx=”125″ cy=”25″ r=”20″ fill=”rgba(255, 255, 0, 0.75)”stroke=”rgba(255, 0, 0, 0.25)” stroke-width=”10″/>
    • Opacity attribute affects entire shape as one (stroke and fill, etc)
    • <circle cx=”65″ cy=”25″ r=”20″ fill=”rgba(128, 0, 128, 0.75)”stroke=”rgba(0, 255, 0, 0.25)” stroke-width=”10″ opacity=”0.5″/>
  • Notify older browser users (those without SVG or d3 capabilities) to upgrade their browsers to see content
    • Use Modernizr (http://modernizr.com/) to display a non-dynamic model with an explanation to use a different browser.
    • http://js/modernizr.js

          Modernizr.load({
              test: Modernizr.svg && Modernizr.inlinesvg,
              yep : [ ‘js/d3.v3.min.js’,
                         ‘js/script.js’ ]
         });

VizTech: Git and GitHub

assignment 1 Fork, Edit, Commit, Push: GitHub to Local Device and Back

Step-by-step guide

  1. Forking this repo
    • Click on the “Fork” button on the top right while logged in to copy this repo to your account.
  2. Clone repo to your local machine###
    • Using command line, navigate to a desired folder destination using `cd` or `dir` depending on your operating system. Then use `git clone` to clone this repo to your local machine.
    • Again, using command line to navigate into the folder that was just downloaded. Enter the following command “` git remote show origin“`
  3. Make changes to your file###
    • Make changes to ‘hello.txt’ and enter your name where appropriate. You are done!
  4. Stage, commit, and push your changes to Github
    • This step involves three things. First, you “stage” the changes you’ve made locally so it’s ready to be committed. The command is “` git add –all“` where `–all` indicates that you are staging ALL changes you’ve made to all files, as opposed to individual files. Then, use “`git commit -m “Commit message here”“`
    • This means that the changes have been “committed”, and are henceforth tracked. `-m` indicates a message to be included with the commit. It’s good practice to always include a concise, descriptive commit message.
    • Finally, push your committed change from your local machine to Github, using “` git push origin master“`meaning “push changes from your local master branch to the remote destination origin”. We’ll explain what this means later.

In summary…
You’ve just gone through the process of forking from someone else’s Github repo, making your own changes, committing and tracking them, and push them to your own Github repo. We’ll be doing a lot of this throughout the class, so do please get comfortable with it!

Visualization Technologies for the Web: Introduction

ARTG 5330: Visualization Technologies for the Web

From the syllabus: “Throughout the course, you will understand how various parts of the front-end web development environment (HTML, CSS, JavaScript) work with each other, and have the opportunity to explore each area of D3’s functionality—data importing and refinement, DOM manipulation, SVG drawing, interactivity—through in-class exercises and assignments. As your final project, you will be able to explore a dataset of your choice and build a web visualization that communicates your unique insights.”

GIT

Git is a version control systems used in team-development scenarios. Also known as version control or source control, Git features distributed workflow, so that multiple authors can work together on non-linked computers, and thus records and catalogues old-versions of edited documents. It even documents what parts of documents (or code) has been changed.

GITHUB

Github is a web-hosted repository service. It provides a graphical interface for Git functions and hosts it on a cloud.

Workflow: Fork, Clone, Commit, Stage, Push, Pull Request

  • Fork: take master document from repository on GitHub and put it on your GitHub account
  • Clone: copy master doc from cloud onto your local device
  • NOW YOU CAN EDIT THE MASTER DOC: NOW IT’S AN EDITED DOC
  • Commit: Finalize your edited doc on local device
  • Stage: Select edited doc to move into GitHub account
  • Push: Move edited doc from local device to cloud
  • Pull request: propose edited doc to common repository cloud (to make public for team)

TERMINAL

  • a command line interface to a Mac computer’s operating system.
    • used in a majority of the Git operations

HTML

http://www.w3schools.com/html/html_intro.asp

Js_html_css

  • Hyper-Text Markup Language
    • Markup Language = Markup Tags
    • HTML tags define different parts of the document (header, paragraph, list, etc). Tags create hierarchy.
    • Tags almost always come in pairs: <start tag> content <end tag>
    • Tags can also be nested: <start tag><start tag2> content <end tag2> <end tag>… and they very often are.
  • Document Object Model (DOM)
    • HTML documents can be visualized by a DOM tree, which looks like a normal organizational hierarchy chart in any workplace. Tags nested under other tags belong to that initial tag, like children to parents in a family tree.
    • Within the document, each DOM element/tag creates a box. When altering the margins (outside of the information box) and padding (inside the information box), this can affect the outline/stroke of the box (division betwen padding and margins).

CSS

  • Cascading Style Sheet
    • Changes visual elements of different tags within HTML organization
    • format: selector { style domain: style amount;}
      • selectors reference tags, classes, or ids, or combinations
      • style domains reference what’s changing, such as font or background color.
      • style amount is how it’s changing: 2px border, green text color, helvetica font-family.
    • Cascading refers to the way styles are adopted by the parent tags it references as well as all children tags associated with that parent tag.
    • Conflicting Styles? The more specific selector wins out!
      • Specific>Inline/dynamic, ID, Class, Element>Less Specific
      • CSS sheets read top to bottom, so if two selectors rank equal in specificity, then the more recent wins out.

css_priority

  • Cascading Style Sheet is a separate file from HTML documents and needs to be referenced by location in HTML code.