Complete 500 Lines or Less Experienced Programmers Solve Interesting Problems Michael Dibernardo PDF For All Chapters
Complete 500 Lines or Less Experienced Programmers Solve Interesting Problems Michael Dibernardo PDF For All Chapters
com
https://textbookfull.com/product/500-lines-or-less-
experienced-programmers-solve-interesting-problems-michael-
dibernardo/
OR CLICK BUTTON
DOWNLOAD NOW
https://textbookfull.com/product/hypernomics-using-hidden-dimensions-
to-solve-unseen-problems-1st-edition-doug-howarth/
textboxfull.com
https://textbookfull.com/product/how-to-solve-real-world-optimization-
problems-from-theory-to-practice-1st-edition-zak/
textboxfull.com
https://textbookfull.com/product/microwave-and-rf-design-
volume-2-transmission-lines-michael-steer/
textboxfull.com
https://textbookfull.com/product/everything-more-or-less-a-defence-of-
generality-relativism-first-edition-edition-james-studd/
textboxfull.com
https://textbookfull.com/product/cruel-inhuman-or-degrading-treatment-
michael-adler/
textboxfull.com
https://textbookfull.com/product/civil-engineering-solved-
problems-8th-edition-michael-r-lindeburg/
textboxfull.com
Experienced programmers solve interesting problems
500 Lines or Less
Edited by Michael DiBernardo
This work is licensed under the Creative Commons Attribution 3.0 Unported license (CC BY 3.0). You are free:
• to Share—to copy, distribute and transmit the work
• to Remix—to adapt the work
under the following conditions:
• Attribution—you must attribute the work in the manner specified by the author or licensor (but not in any
way that suggests that they endorse you or your use of the work).
with the understanding that:
• Waiver—Any of the above conditions can be waived if you get permission from the copyright holder.
• Public Domain—Where the work or any of its elements is in the public domain under applicable law,
that status is in no way affected by the license.
• Other Rights—In no way are any of the following rights affected by the license:
– Your fair dealing or fair use rights, or other applicable copyright exceptions and limitations;
– The author’s moral rights;
– Rights other persons may have either in the work itself or in how the work is used, such as publicity
or privacy rights.
• Notice—For any reuse or distribution, you must make clear to others the license terms of this work. The
best way to do this is with a link to http://creativecommons.org/licenses/by/3.0/.
To view a copy of this license, visit http://creativecommons.org/licenses/by/3.0/ or send a letter to
Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.
Product and company names mentioned herein may be the trademarks of their respective owners.
While every precaution has been taken in the preparation of this book, the editors and authors assume no
responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.
ISBN: 978-1-329-87127-4
Contents
Introduction ix
by Michael DiBernardo
3 Clustering by Consensus 33
by Dustin J. Mitchell
vi CONTENTS
Introduction
Michael DiBernardo
This is the fourth volume in the Architecture of Open Source Applications series, and the first to not
feature the words “open source applications” anywhere in the title.
The first three volumes in the series were about big problems that big programs have to solve.
For an engineer who is early in their career, it may be a challenge to understand and build upon
programs that are much bigger than a few thousand lines of code, so, while big problems can be
interesting to read about, they can also be challenging to learn from.
500 Lines or Less focuses on the design decisions that programmers make in the small when they
are building something new. The programs you will read about in this book were all written from
scratch for this purpose (although several of them were inspired by larger projects that the authors
had worked on previously).
Before reading each chapter, we encourage you to first think about how you might solve the
problem. What design considerations or constraints do you think the author is going to consider
important? What abstractions do you expect to see? How do you think the problem is going to be
decomposed? Then, when reading the chapter, try to identify what surprised you. It is our hope that
you will learn more by doing this than by simply reading through each chapter from beginning to
end.
Writing a useful program in fewer than 500 lines of source code—without resorting to cheap
tricks—is a challenging exercise in itself; writing one to be read for pedagogical purposes when
neatly rendered in a printed book is even tougher. As such, the editors have occasionally taken
liberties with some of the source formatting when porting it into the book. The original source for
each chapter can be found in the code subdirectory of its project folder.
We hope that the experiences of the authors in this book will help you grow out of your comfort
zone in your own programming practice.
— Michael DiBernardo
Contributors
Michael DiBernardo (editorial): Michael DiBernardo is an engineer and director of delivery at
Wave, and a past PyCon Canada chair. He writes at mikedebo.ca.
Amy Brown (editorial): Amy Brown is a freelance editor based in Toronto. She specializes
in science and academic editing, and working with self-publishing authors. She co-edited the
Architecture of Open Source Applications books with Greg Wilson.
Dethe Elza (Blockcode): Dethe is a geek dad, aesthetic programmer, mentor, and creator of the
Waterbear visual programming tool. He co-hosts the Vancouver Maker Education Salons and wants
to fill the world with robotic origami rabbits.
Malini Das (CI): Malini is a software engineer who is passionate about developing quickly (but
safely!), and solving cross-functional problems. She has worked at Mozilla as a tools engineer and is
currently honing her skills at Twitch.
Dustin J. Mitchell (Cluster): Dustin is an open source software developer and release engineer at
Mozilla. He has worked on projects as varied as a host configuration system in Puppet, a Flask-based
web framework, unit tests for firewall configurations, and a continuous integration framework in
Twisted Python.
Daniel Rocco (Contingent): Daniel loves Python, coffee, craft, stout, object and system design,
bourbon, teaching, trees, and Latin guitar. Thrilled that he gets to write Python for a living, he is
always on the lookout for opportunities to learn from others in the community, and to contribute by
sharing knowledge. He is a frequent speaker at PyAtl on introductory topics, testing, design, and
shiny things; he loves seeing the spark of delight in people’s eyes when someone shares a surprising
or beautiful idea. Daniel lives in Atlanta with a microbiologist and four aspiring rocketeers.
Brandon Rhodes (Contingent): Brandon Rhodes started using Python in the late 1990s, and for
17 years has maintained the PyEphem library for amateur astronomers. He works at Dropbox, has
taught Python programming courses for corporate clients, consulted on projects like the New England
Wildflower Society’s “Go Botany” Django site, and will be the chair of the PyCon conference in
2016 and 2017. Brandon believes that well-written code is a form of literature, that beautifully
formatted code is a work of graphic design, and that correct code is one of the most transparent
forms of thought.
A. Jesse Jiryu Davis (Crawler): Jesse is a staff engineer at MongoDB in New York. He wrote
Motor, the async MongoDB Python driver, and he is the lead developer of the MongoDB C Driver and
a member of the PyMongo team. He contributes to asyncio and Tornado. He writes at emptysqua.re.
Guido van Rossum (Crawler): Guido is the creator of Python, one of the major programming
languages on and off the web. The Python community refers to him as the BDFL (Benevolent
Dictator For Life), a title straight from a Monty Python skit.
Dann Toliver (Dagoba): Dann enjoys building things, like programming languages, databases,
distributed systems, communities of smart friendly humans, and pony castles with his two-year-old.
Taavi Burns (DBDB): As the newest bass (and sometimes tenor) in Countermeasure, Taavi strives
to break the mould. . . sometimes just by ignoring its existence. This is certainly true through the
diversity of workplaces in his career: IBM (doing C and Perl), FreshBooks (all the things), Points.com
(doing Python), and now at PagerDuty (doing Scala). Aside from that—when not gliding along
on his Brompton folding bike—you might find him playing Minecraft with his son or engaging in
parkour (or rock climbing, or other adventures) with his wife. He knits continental.
Leo Zovic: Leo (better known online as inaimathi) is a recovering graphic designer who has
professionally written Scheme, Common Lisp, Erlang, Javascript, Haskell, Clojure, Go, Python,
viii Introduction
PHP and C. He currently blogs about programming, plays board games and works at a Ruby-based
startup in Toronto, Ontario.
Dr. Christian Muise (Flow shop): Dr. Muise is a Research Fellow with the Model-based Embedded
and Robotic Systems group at MIT’s Computer Science and Artificial Intelligence Laboratory. He is
interested in a variety of topics including AI, data-driven projects, mapping, graph theory, and data
visualization, as well as Celtic music, carving, soccer, and coffee.
Yoav Rubin (CircleDB): Yoav is a Senior Software Engineer at Microsoft, and prior to that was
a Research Staff Member and a Master Inventor at IBM Research. He works now in the domain
of data security in the cloud, and in the past his work focused on developing cloud- or web-based
development environments. Yoav holds an MSc in Medical Research in the field of Neuroscience
and BSc in Information Systems Engineering.
Cate Huston (Image filters): Cate is a developer and entrepreneur focused on mobile. She’s lived
and worked in the UK, Australia, Canada, China and the United States, as an engineer at Google, an
Extreme Blue intern at IBM, and a ski instructor. Cate speaks internationally on mobile development,
and her writing has been published on sites as varied as Lifehacker, The Daily Beast, The Eloquent
Woman and Model View Culture. She co-curates Technically Speaking, blogs at Accidentally in
Code and is @catehstn on Twitter.
Allison Kaptur (Interpreter): Allison is an engineer at Dropbox, where she helps maintain one
of the largest networks of Python clients in the world. Before Dropbox, she was a facilitator at the
Recurse Center, a writers’ retreat for programmers in New York. She’s spoken at PyCon North
America about Python internals, and loves weird bugs.
Erick Dransch (Modeller): Erick is a software developer and 2D and 3D computer graphics
enthusiast. He has worked on video games, 3D special effects software, and computer-aided design
tools. If it involves simulating reality, chances are he’d like to learn more about it. You can find him
online at erickdransch.com.
Carl Friedrich Bolz (Object model): Carl is a researcher at King’s College London and is broadly
interested in the implementation and optimization of all kinds of dynamic languages. He is one of
the core authors of PyPy/RPython and has worked on implementations of Prolog, Racket, Smalltalk,
PHP and Ruby.
Marina Samuel (OCR): Marina is an engineer at Mozilla and a current MSc student in Applied
Computing (Artifical Intelligence) at the University of Toronto. She hopes to one day build robots
that will take over the planet.
Dessy Daskalov (Pedometer): Dessy is an engineer by trade, an entrepreneur by passion, and
a developer at heart. She’s currently the CTO and co-founder of Nudge Rewards. When she’s not
busy building product with her team, she can be found teaching others to code, attending or hosting
a Toronto tech event, and online at dessydaskalov.com and @dess_e.
Eunsuk Kang (Same-origin policy): Eunsuk is a PhD candidate and a member of the Software
Design Group at MIT. He received his SM (Master of Science) in Computer Science from MIT
(2010), and a Bachelor of Software Engineering from the University of Waterloo (2007). His research
projects have focused on developing tools and techniques for software modeling and verification,
with applications to security and safety-critical systems.
Santiago Perez (Same-origin policy): Santiago is a PhD student in the Software Design Group at
MIT. He received his SM in Computer Science from MIT (2015), and an undergraduate degree from
ITBA (2011). He used to work at Google, developing frameworks and tools to make engineers more
productive (2012). He currently spends most of his time thinking about design and version control.
Daniel Jackson (Same-origin policy): Daniel is a professor in the Department of Electrical
Engineering and Computer Science at MIT, and leads the Software Design Group in the Computer
Michael DiBernardo ix
Science and Artificial Intelligence Laboratory. He received an MA from Oxford University (1984)
in Physics, and his SM (1988) and PhD (1992) in Computer Science from MIT. He was a software
engineer for Logica UK Ltd. (1984-1986), Assistant Professor of Computer Science at Carnegie
Mellon University (1992-1997), and has been at MIT since 1997. He has broad interests in software
engineering, especially in development methods, design and specification, formal methods, and
safety-critical systems.
Jessica B. Hamrick (Sampler): Jess is a PhD student at UC Berkeley where she studies human
cognition by combining probabilistic models from machine learning with behavioral experiments
from cognitive science. In her spare time, Jess is a core contributor to IPython and Jupyter. She also
holds a BS and MEng in Computer Science from MIT.
Audrey Tang (Spreadsheet): A self-educated programmer and translator, Audrey works with
Apple as an independent contractor on cloud service localization and natural language technologies.
Audrey has previously designed and led the first working Perl 6 implementation, and served in
computer language design committees for Haskell, Perl 5, and Perl 6. Currently Audrey is a full-time
g0v contributor and leads Taiwan’s first e-Rulemaking project.
Leah Hanson (Static analysis): Leah Hanson is a proud alum of Hacker School and loves helping
people learn about Julia. She blogs at blog.leahhanson.us and tweets at @astrieanna.
Ned Batchelder (Template engine): Ned is a software engineer with a long career, currently
working at edX to build open source software to educate the world. He’s the maintainer of coverage.py,
an organizer of Boston Python, and has spoken at many PyCons. He blogs at nedbatchelder.com.
He once had dinner at the White House.
Greg Wilson (Web server): Greg is the founder of Software Carpentry, a crash course in computing
skills for scientists and engineers. He has worked for 30 years in both industry and academia, and is
the author or editor of several books on computing, including the 2008 Jolt Award winner Beautiful
Code and the first two volumes of The Architecture of Open Source Applications. Greg received a
PhD in Computer Science from the University of Edinburgh in 1993.
x Introduction
Acknowledgments
The Architecture of Open Source Applications series would not exist without the hard work of Amy
Brown and Greg Wilson. This particular book would not have been possible without the incredible
efforts of our army of technical reviewers:
Chris Seaton, John Morrissey, and Natalie Black deserve extended thanks for going above and beyond
in their technical reviewing. The quantity and depth of their reviews was instrumental in moving the
book forward at several sticking points.
We are very grateful to PagerDuty for their financial support.
Contributing
If you’d like to report errors or translate the content into other languages, please open an issue at
github.com/aosabook/500lines/ or contact us at [email protected].
xi
[chapter 1]
In block-based programming languages, you write programs by dragging and connecting blocks
that represent parts of the program. Block-based languages differ from conventional programming
languages, in which you type words and symbols.
Learning a programming language can be difficult because they are extremely sensitive to even
the slightest of typos. Most programming languages are case-sensitive, have obscure syntax, and will
refuse to run if you get so much as a semicolon in the wrong place—or worse, leave one out. Further,
most programming languages in use today are based on English and their syntax cannot be localized.
In contrast, a well-done block language can eliminate syntax errors completely. You can still
create a program which does the wrong thing, but you cannot create one with the wrong syntax: the
blocks just won’t fit that way. Block languages are more discoverable: you can see all the constructs
and libraries of the language right in the list of blocks. Further, blocks can be localized into any
human language without changing the meaning of the programming language.
Block-based languages have a long history, with some of the prominent ones being Lego Mind-
storms1 , Alice3D2 , StarLogo3 , and especially Scratch4 . There are several tools for block-based
1 http://www.lego.com/en-us/mindstorms/
2 http://www.alice.org/index.php
3 http://education.mit.edu/projects/starlogo-tng
4 http://scratch.mit.edu/
programming on the web as well: Blockly5 , AppInventor6 , Tynker7 , and many more8 .
The code in this chapter is loosely based on the open-source project Waterbear9 , which is not
a language but a tool for wrapping existing languages with a block-based syntax. Advantages of
such a wrapper include the ones noted above: eliminating syntax errors, visual display of available
components, ease of localization. Additionally, visual code can sometimes be easier to read and
debug, and blocks can be used by pre-typing children. (We could even go further and put icons on
the blocks, either in conjunction with the text names or instead of them, to allow pre-literate children
to write programs, but we don’t go that far in this example.)
The choice of turtle graphics for this language goes back to the Logo language, which was created
specifically to teach programming to children. Several of the block-based languages above include
turtle graphics, and it is a small enough domain to be able to capture in a tightly constrained project
such as this.
If you would like to get a feel for what a block-based-language is like, you can experiment with
the program that is built in this chapter from author’s GitHub repository10 .
Web Applications
In order to make the tool available to the widest possible audience, it is web-native. It’s written in
HTML, CSS, and JavaScript, so it should work in most browsers and platforms.
Modern web browsers are powerful platforms, with a rich set of tools for building great apps. If
something about the implementation became too complex, I took that as a sign that I wasn’t doing it
“the web way” and, where possible, tried to re-think how to better use the browser tools.
An important difference between web applications and traditional desktop or server applications
is the lack of a main() or other entry point. There is no explicit run loop because that is already
built into the browser and implicit on every web page. All our code will be parsed and executed on
load, at which point we can register for events we are interested in for interacting with the user. After
the first run, all further interaction with our code will be through callbacks we set up and register,
whether we register those for events (like mouse movement), timeouts (fired with the periodicity we
specify), or frame handlers (called for each screen redraw, generally 60 frames per second). The
browser does not expose full-featured threads either (only shared-nothing web workers).
Dethe Elza 3
implementations—similar to a library like jQuery but in less than 50 lines of code. file.js is a
similar utility used for loading and saving files and serializing scripts.
These are the remaining files:
• block.js is the abstract representation of a block-based language.
• drag.js implements the key interaction of the language: allowing the user to drag blocks
from a list of available blocks (the “menu”) to assemble them into a program (the “script”).
• menu.js has some helper code and is also responsible for actually running the user’s program.
• turtle.js defines the specifics of our block language (turtle graphics) and initializes its
specific blocks. This is the file that would be replaced in order to create a different block
language.
blocks.jsblocks.js
Each block consists of a few HTML elements, styled with CSS, with some JavaScript event handlers
for dragging-and-dropping and modifying the input argument. The blocks.js file helps to create
and manage these groupings of elements as single objects. When a type of block is added to the
block menu, it is associated with a JavaScript function to implement the language, so each block in
the script has to be able to find its associated function and call it when the script runs.
Blocks have two optional bits of structure. They can have a single numeric parameter (with a
default value), and they can be a container for other blocks. These are hard limits to work with, but
would be relaxed in a larger system. In Waterbear there are also expression blocks which can be
passed in as parameters; multiple parameters of a variety of types are supported. Here in the land of
tight constraints we’ll see what we can do with just one type of parameter.
It’s important to note that there is no real distinction between blocks in the menu and blocks in
the script. Dragging treats them slightly differently based on where they are being dragged from,
and when we run a script it only looks at the blocks in the script area, but they are fundamentally the
same structures, which means we can clone the blocks when dragging from the menu into the script.
The createBlock(name, value, contents) function returns a block as a DOM element
populated with all internal elements, ready to insert into the document. This can be used to create
blocks for the menu, or for restoring script blocks saved in files or localStorage. While it is flexible
this way, it is built specifically for the Blockcode “language” and makes assumptions about it, so
if there is a value it assumes the value represents a numeric argument and creates an input of type
“number”. Since this is a limitation of the Blockcode, this is fine, but if we were to extend the blocks
to support other types of arguments, or more than one argument, the code would have to change.
function blockValue(block){
var input = block.querySelector('input');
return input ? Number(input.value) : null;
}
function blockUnits(block){
if (block.children.length > 1 &&
block.lastChild.nodeType === Node.TEXT_NODE &&
block.lastChild.textContent){
return block.lastChild.textContent.slice(1);
}
}
function blockScript(block){
var script = [block.dataset.name];
var value = blockValue(block);
if (value !== null){
Dethe Elza 5
script.push(blockValue(block));
}
var contents = blockContents(block);
var units = blockUnits(block);
if (contents){script.push(contents.map(blockScript));}
if (units){script.push(units);}
return script.filter(function(notNull){ return notNull !== null; });
}
function runBlocks(blocks){
blocks.forEach(function(block){ trigger('run', block); });
}
drag.jsdrag.js
The purpose of drag.js is to turn static blocks of HTML into a dynamic programming language
by implementing interactions between the menu section of the view and the script section. The
user builds their program by dragging blocks from the menu into the script, and the system runs the
blocks in the script area.
We’re using HTML5 drag-and-drop; the specific JavaScript event handlers it requires are defined
here. (For more information on using HTML5 drag-and-drop, see Eric Bidleman’s article13 .) While
it is nice to have built-in support for drag-and-drop, it does have some oddities and some pretty major
limitations, like not being implemented in any mobile browser at the time of this writing.
We define some variables at the top of the file. When we’re dragging, we’ll need to reference
these from different stages of the dragging callback dance.
Depending on where the drag starts and ends, drop will have different effects:
• If dragging from script to menu, delete dragTarget (remove block from script).
• If dragging from script to script, move dragTarget (move an existing script block).
• If dragging from menu to script, copy dragTarget (insert new block in script).
• If dragging from menu to menu, do nothing.
During the dragStart(evt) handler we start tracking whether the block is being copied from
the menu or moved from (or within) the script. We also grab a list of all the blocks in the script
which are not being dragged, to use later. The evt.dataTransfer.setData call is used for dragging
between the browser and other applications (or the desktop), which we’re not using, but have to call
anyway to work around a bug.
function dragStart(evt){
if (!matches(evt.target, '.block')) return;
if (matches(evt.target, '.menu .block')){
dragType = 'menu';
}else{
dragType = 'script';
13 http://www.html5rocks.com/en/tutorials/dnd/basics/
While we are dragging, the dragenter, dragover, and dragout events give us opportunities to
add visual cues by highlighting valid drop targets, etc. Of these, we only make use of dragover.
function dragOver(evt){
if (!matches(evt.target, '.menu, .menu *, .script, .script *, .content')) {
return;
}
// Necessary. Allows us to drop.
if (evt.preventDefault) { evt.preventDefault(); }
if (dragType === 'menu'){
// See the section on the DataTransfer object.
evt.dataTransfer.dropEffect = 'copy';
}else{
evt.dataTransfer.dropEffect = 'move';
}
return false;
}
When we release the mouse, we get a drop event. This is where the magic happens. We have
to check where we dragged from (set back in dragStart) and where we have dragged to. Then we
either copy the block, move the block, or delete the block as needed. We fire off some custom events
using trigger() (defined in util.js) for our own use in the block logic, so we can refresh the
script when it changes.
function drop(evt){
if (!matches(evt.target, '.menu, .menu *, .script, .script *')) return;
var dropTarget = closest(
evt.target, '.script .container, .script .block, .menu, .script');
var dropType = 'script';
if (matches(dropTarget, '.menu')){ dropType = 'menu'; }
// stops the browser from redirecting.
if (evt.stopPropagation) { evt.stopPropagation(); }
if (dragType === 'script' && dropType === 'menu'){
trigger('blockRemoved', dragTarget.parentElement, dragTarget);
dragTarget.parentElement.removeChild(dragTarget);
}else if (dragType ==='script' && dropType === 'script'){
Dethe Elza 7
if (matches(dropTarget, '.block')){
dropTarget.parentElement.insertBefore(
dragTarget, dropTarget.nextSibling);
}else{
dropTarget.insertBefore(dragTarget, dropTarget.firstChildElement);
}
trigger('blockMoved', dropTarget, dragTarget);
}else if (dragType === 'menu' && dropType === 'script'){
var newNode = dragTarget.cloneNode(true);
newNode.classList.remove('dragging');
if (matches(dropTarget, '.block')){
dropTarget.parentElement.insertBefore(
newNode, dropTarget.nextSibling);
}else{
dropTarget.insertBefore(newNode, dropTarget.firstChildElement);
}
trigger('blockAdded', dropTarget, newNode);
}
}
The dragEnd(evt) is called when we mouse up, but after we handle the drop event. This is
where we can clean up, remove classes from elements, and reset things for the next drag.
function _findAndRemoveClass(klass){
var elem = document.querySelector('.' + klass);
if (elem){ elem.classList.remove(klass); }
}
function dragEnd(evt){
_findAndRemoveClass('dragging');
_findAndRemoveClass('over');
_findAndRemoveClass('next');
}
menu.jsmenu.js
The file menu.js is where blocks are associated with the functions that are called when they run,
and contains the code for actually running the script as the user builds it up. Every time the script is
modified, it is re-run automatically.
“Menu” in this context is not a drop-down (or pop-up) menu, like in most applications, but is the
list of blocks you can choose for your script. This file sets that up, and starts the menu off with a
looping block that is generally useful (and thus not part of the turtle language itself). This is kind of
an odds-and-ends file, for things that may not fit anywhere else.
Having a single file to gather random functions in is useful, especially when an architecture is
under development. My theory of keeping a clean house is to have designated places for clutter, and
that applies to building a program architecture too. One file or module becomes the catch-all for
things that don’t have a clear place to fit in yet. As this file grows it is important to watch for emerging
patterns: several related functions can be spun off into a separate module (or joined together into a
more general function). You don’t want the catch-all to grow indefinitely, but only to be a temporary
holding place until you figure out the right way to organize the code.
When we want to notify the system to run the script during the next frame handler, we call
runSoon() which sets the scriptDirty flag to true. The system calls run() on every frame, but
returns immediately unless scriptDirty is set. When scriptDirty is set, it runs all the script
blocks, and also triggers events to let the specific language handle any tasks it needs before and after
the script is run. This decouples the blocks-as-toolkit from the turtle language to make the blocks
re-usable (or the language pluggable, depending how you look at it).
As part of running the script, we iterate over each block, calling runEach(evt) on it, which sets
a class on the block, then finds and executes its associated function. If we slow things down, you
should be able to watch the code execute as each block highlights to show when it is running.
The requestAnimationFrame method below is provided by the browser for animation. It takes
a function which will be called for the next frame to be rendered by the browser (at 60 frames per
second) after the call is made. How many frames we actually get depends on how fast we can get
work done in that call.
function run(){
if (scriptDirty){
scriptDirty = false;
Block.trigger('beforeRun', script);
var blocks = [].slice.call(
document.querySelectorAll('.script > .block'));
Block.run(blocks);
Block.trigger('afterRun', script);
}else{
Block.trigger('everyFrame', script);
}
requestAnimationFrame(run);
}
requestAnimationFrame(run);
function runEach(evt){
var elem = evt.target;
if (!matches(elem, '.script .block')) return;
if (elem.dataset.name === 'Define block') return;
elem.classList.add('running');
scriptRegistry[elem.dataset.name](elem);
Dethe Elza 9
elem.classList.remove('running');
}
We add blocks to the menu using menuItem(name, fn, value, contents) which takes a
normal block, associates it with a function, and puts in the menu column.
We define repeat(block) here, outside of the turtle language, because it is generally useful in
different languages. If we had blocks for conditionals and reading and writing variables they could
also go here, or into a separate trans-language module, but right now we only have one of these
general-purpose blocks defined.
function repeat(block){
var count = Block.value(block);
var children = Block.contents(block);
for (var i = 0; i < count; i++){
Block.run(children);
}
}
menuItem('Repeat', repeat, 10, []);
turtle.jsturtle.js
turtle.js is the implementation of the turtle block language. It exposes no functions to the rest of
the code, so nothing else can depend on it. This way we can swap out the one file to create a new
block language and know nothing in the core will break.
Turtle programming is a style of graphics programming, first popularized by Logo, where you
have an imaginary turtle carrying a pen walking on the screen. You can tell the turtle to pick up
the pen (stop drawing, but still move), put the pen down (leaving a line everywhere it goes), move
forward a number of steps, or turn a number of degrees. Just those commands, combined with
looping, can create amazingly intricate images.
In this version of turtle graphics we have a few extra blocks. Technically we don’t need both
turn right and turn left because you can have one and get the other with negative numbers.
Likewise move back can be done with move forward and negative numbers. In this case it felt
more balanced to have both.
The image above was formed by putting two loops inside another loop and adding a move
forward and turn right to each loop, then playing with the parameters interactively until I liked
the image that resulted.
The reset() function clears all the state variables to their defaults. If we were to support multiple
turtles, these variables would be encapsulated in an object. We also have a utility, deg2rad(deg),
because we work in degrees in the UI, but we draw in radians. Finally, drawTurtle() draws the
turtle itself. The default turtle is simply a triangle, but you could override this to draw a more
aesthetically-pleasing turtle.
Note that drawTurtle uses the same primitive operations that we define to implement the turtle
drawing. Sometimes you don’t want to reuse code at different abstraction layers, but when the
meaning is clear it can be a big win for code size and performance.
function reset(){
recenter();
direction = deg2rad(90); // facing "up"
visible = true;
pen = true; // when pen is true we draw, otherwise we move without drawing
color = 'black';
}
function drawTurtle(){
var userPen = pen; // save pen state
if (visible){
penUp(); _moveForward(5); penDown();
_turn(-150); _moveForward(12);
Dethe Elza 11
_turn(-120); _moveForward(12);
_turn(-120); _moveForward(12);
_turn(30);
penUp(); _moveForward(-5);
if (userPen){
penDown(); // restore pen state
}
}
}
We have a special block to draw a circle with a given radius at the current mouse position. We
special-case drawCircle because, while you can certainly draw a circle by repeating MOVE 1 RIGHT
1 360 times, controlling the size of the circle is very difficult that way.
function drawCircle(radius){
// Math for this is from http://www.mathopenref.com/polygonradius.html
var userPen = pen; // save pen state
if (visible){
penUp(); _moveForward(-radius); penDown();
_turn(-90);
var steps = Math.min(Math.max(6, Math.floor(radius / 2)), 360);
var theta = 360 / steps;
var side = radius * 2 * Math.sin(Math.PI / steps);
_moveForward(side / 2);
for (var i = 1; i < steps; i++){
_turn(theta); _moveForward(side);
}
_turn(theta); _moveForward(side / 2);
_turn(90);
penUp(); _moveForward(radius); penDown();
if (userPen){
penDown(); // restore pen state
}
}
}
Our main primitive is moveForward, which has to handle some elementary trigonometry and
check whether the pen is up or down.
function _moveForward(distance){
var start = position;
position = {
x: cos(direction) * distance * PIXEL_RATIO + start.x,
y: -sin(direction) * distance * PIXEL_RATIO + start.y
};
if (pen){
ctx.lineStyle = color;
ctx.beginPath();
ctx.moveTo(start.x, start.y);
ctx.lineTo(position.x, position.y);
ctx.stroke();
}
Most of the rest of the turtle commands can be easily defined in terms of what we’ve built above.
When we want a fresh slate, the clear function restores everything back to where we started.
function clear(){
ctx.save();
ctx.fillStyle = 'white';
ctx.fillRect(0,0,WIDTH,HEIGHT);
ctx.restore();
reset();
ctx.moveTo(position.x, position.y);
}
When this script first loads and runs, we use our reset and clear to initialize everything and
draw the turtle.
onResize();
clear();
drawTurtle();
Now we can use the functions above, with the Menu.item function from menu.js, to make blocks
for the user to build scripts from. These are dragged into place to make the user’s programs.
Dethe Elza 13
1.3 Lessons Learned
Why Not Use MVC?
Model-View-Controller (MVC) was a good design choice for Smalltalk programs in the ’80s and it
can work in some variation or other for web apps, but it isn’t the right tool for every problem. All
the state (the “model” in MVC) is captured by the block elements in a block language anyway, so
replicating it into Javascript has little benefit unless there is some other need for the model (if we
were editing shared, distributed code, for instance).
An early version of Waterbear went to great lengths to keep the model in JavaScript and sync it
with the DOM, until I noticed that more than half the code and 90% of the bugs were due to keeping
the model in sync with the DOM. Eliminating the duplication allowed the code to be simpler and
more robust, and with all the state on the DOM elements, many bugs could be found simply by
looking at the DOM in the developer tools. So in this case there is little benefit to building further
separation of MVC than we already have in HTML/CSS/JavaScript.
15
[chapter 2]
Upon the working of the Act, during the first nine months of
its operation, Secretary Gage remarked as follows, in his
annual report dated December 14, 1900:
"The operation of the act of March 14 last with respect to
these two important matters of our finances has well
exemplified its wisdom. Confidence in the purpose and power of
the Government to maintain the gold standard has been greatly
strengthened. The result is that gold flows toward the
Treasury instead of away from it. At the date of this report
the free gold in the Treasury is larger in amount than at any
former period in our history. Including the $150,000,000
reserve, the gold in the Treasury belonging to the Government
amounts to over $242,000,000, while the Treasury holds,
besides, more than $230,000,000, against which certificates
have been issued. That provision of the act which liberalized
the conditions of bank-note issue was also wise and timely.
Under it, … there has been an increase of some $77,000,000 in
bank-note issues. To this fact may be chiefly attributed the
freedom from stress for currency to handle the large harvests
of cotton, wheat, and corn. In this respect the year has been
an exception to the general rule of stringency which for
several years has so plainly marked the autumn season.
{641}
"I, for one, believed, and still believe that the pathway to
prosperity and glory for the country was also the pathway to
success and glory for the Republican party. I thought the two
things inseparable. If, when we made the treaty of peace, we
had adhered to the purpose we declared when we declared war;
if we had dealt with the Philippine Islands as we promised to
deal, have dealt, and expect to deal with Cuba, the country
would have escaped the loss of 6,000 brave soldiers, other
thousands of wrecked and shattered lives, the sickness of many
more, the expenditure of hundreds of millions, and, what is
far worse than all, the trampling under foot of its cherished
ideals. There would have been to-day a noble republic in the
East, sitting docile at our feet, receiving from us
civilization, laws, manners, and giving in turn everything the
gratitude of a free people could give-love, obedience, trade.
The Philippine youth would throng our universities; our
Constitution, our Declaration, the lives of Washington and
Lincoln, the sayings of Jefferson and Franklin would have been
the textbooks of their schools. How our orators and poets
would have delighted to contrast America liberating and
raising up the republic of Asia, with England subduing and
trampling under foot the republic of Africa. Nothing at home
could have withstood the great party and the great President
who had done these things. We should have come from the next
election with a solid North and have carried half the South.
You would at least have been spared the spectacle of great
Republican States rising in revolt against Republican
policies. I do not expect to accomplish anything for liberty
in the Philippine Islands but through the Republican party.
Upon it the fate of these Islands for years to come is to
depend. If that party can not be persuaded, the case is in my
judgment for the present hopeless. …
{642}
James Madison,
Federalist, Number 14.
Seward's Works
Volume 1, page 122.
Seward's Works
Volume 4, page 167.
{644}
"And yet the Senate, the Congress enacted less than two years
ago that the people of Cuba—controlling peaceably no part of
their island, levying no taxes in any orderly or peaceable
way, with no administration of justice, no cabinet—not only of
right ought to be, but were, in fact, a free and independent
State. I did not give my assent to that declaration of fact. I
assented to the doctrine that they of right ought to be. But I
thought the statement of fact much calculated to embarrass the
Government of the United States, if it were bound by that
declaration; and it has been practically disregarded by the
Administration ever since. But the question now is a very
different one. You not only deny that the Filipinos are, but
you deny that they of right ought to be free and independent;
and you recognize Spain as entitled to sell to you the
sovereignty of an island where she was not at the time
occupying a foot of territory, where her soldiers were held
captives by the government of the island, a government to
which you had delivered over a large number of Spanish
prisoners to be held as captives. And yet you come here to-day
and say that they not only are not, but they of right ought
not to be free and independent; and when you are pressed you
answer us by talking about mountains of iron and nuggets of
gold, and trade with China.
"I affirm that you can not get by conquest, and you can not
get by purchase, according to the modern law of nations,
according to the law of nations as accepted and expounded by
the United States, sovereignty over a people, or title to a
territory, of which the power that undertakes to sell it or
the power from whom you undertake to wrest it has not the
actual possession and dominion. … You cannot buy a war. More
than this, you cannot buy a tyrant's claim to subject again an
oppressed people who have achieved their freedom. …
{645}
"7. I would declare that the United States will enforce the
same doctrine as applicable to the Philippines that we
declared as to Mexico and Haiti and the South American
Republics. It is true that the Monroe Doctrine, a doctrine
based largely on our regard for our own interests, is not
applicable either in terms or in principle to a distant
Asiatic territory. But, undoubtedly, having driven out Spain,
we are bound, and have the right, to secure to the people we
have liberated an opportunity, undisturbed and in peace, to
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com