<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>http://classes.engineering.wustl.edu/cse330/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Shane</id>
	<title>CSE330 Wiki - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="http://classes.engineering.wustl.edu/cse330/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Shane"/>
	<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Special:Contributions/Shane"/>
	<updated>2026-11-15T18:17:06Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.34.4</generator>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Web_Application_Security,_Part_1&amp;diff=1985</id>
		<title>Web Application Security, Part 1</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Web_Application_Security,_Part_1&amp;diff=1985"/>
		<updated>2015-08-02T18:55:23Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* Git Exposed */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Application-level web security is of increasing concern among web developers.  This article outlines some types of security threats to your web application and how to solve those threats.&lt;br /&gt;
&lt;br /&gt;
This is Part 1 of the Web Application Security article, geared toward the material covered in [[Module 2]].  For material covered in [[Module 3]] (MySQL), see [[Web Application Security, Part 2]].  For material covered in [[Module 6]] (JavaScript), see [[Web Application Security, Part 3]].&lt;br /&gt;
&lt;br /&gt;
== Introduction to Application-Level Web Security ==&lt;br /&gt;
&lt;br /&gt;
Every day, computer hackers around the world penetrate web applications, often for personal profits.  You may find it hard to believe, but '''even high-profile web sites (banks, social media, even computer security companies) are vulnerable to application-level attacks!'''&lt;br /&gt;
&lt;br /&gt;
Not only is it embarrassing to be the programmer who wrote the vulnerable code, but it could also cost you your job.  As a prudent web developer, it is ''imperative'' that you take precautionary measures to make your application difficult to penetrate.  Indeed, most of the time, if your site is well-written, hackers will just move on.&lt;br /&gt;
&lt;br /&gt;
Here's the golden rule: Anything in your site that accepts user input, whether via a form, an AJAX request, a file upload, or even malformed links, can be used as an attack vector.  '''NEVER TRUST USER INPUT!!!'''  This can be summarized in the acronym FIEO, or ''Filter Input, Escape Output''.&lt;br /&gt;
&lt;br /&gt;
=== FIEO in PHP ===&lt;br /&gt;
&lt;br /&gt;
==== Filtering Input ====&lt;br /&gt;
&lt;br /&gt;
&amp;quot;Filter Input&amp;quot; means that you should check that input data is of the format that you are expecting.  For example, if you are expecting a number, you should cast it to a float or an int.  If you are expecting a phone number, you should run it through a regular expression (you will learn regular expressions in module 4).  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;PHP&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
// Cast a number to a float or an int:&lt;br /&gt;
$amount = (float) $_POST['amount'];&lt;br /&gt;
&lt;br /&gt;
// Pass a phone number through a regular expression:&lt;br /&gt;
$phone = preg_match('/\d{3}-\d{3}-\d{4}/', $_POST['phone']) ? $_POST['phone'] : &amp;quot;&amp;quot;;&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Escaping Output ====&lt;br /&gt;
&lt;br /&gt;
&amp;quot;Escape Output&amp;quot; means that you need to nullify, or ''escape'', characters that have special meaning in the markup language of interest.  For example, consider the following string:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
If a&amp;lt;b and b&amp;lt;c then a&amp;lt;c.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Since a less-than sign means the start of a tag in HTML, and '''b''' is a valid tag name, the above string will ''not'' render as you might expect in HTML.  Therefore, we need to ''escape'' our less-than signs by using HTML entities:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
If a&amp;amp;lt;b and b&amp;amp;lt;c then a&amp;amp;lt;c.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The &amp;quot;&amp;amp;lt;&amp;quot; is an '''HTML entity''' that will render as a less-than sign.  (For more information on HTML entities, [http://docs.webplatform.org/wiki/html/entities read this article on the WebPlatform wiki].)&lt;br /&gt;
&lt;br /&gt;
PHP provides a function that, given a string, will convert special characters to their HTML entity equivalents.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;PHP&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
$str = &amp;quot;If a&amp;lt;b and b&amp;lt;c then a&amp;lt;c.&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
// Convert special characters to HTML entities before outputting:&lt;br /&gt;
echo htmlentities($str);&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' ''htmlentities'' escapes a string for use in HTML, but it does ''not'' escape a string for use in other markup languages.  You need to use different methods when escaping strings for other languages.&lt;br /&gt;
&lt;br /&gt;
=== Why Not to Escape Input ===&lt;br /&gt;
&lt;br /&gt;
Filtering your input is important, as shown above.  However, it is bad practice to ''escape'' your input.  For example, don't do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;PHP&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
$message = htmlentites($_POST['amount']); // bad practice&lt;br /&gt;
// then store $message in a database, etc.&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The reason this is bad practice is that it permanently ties that string to its final output format.  For example, what if some time down the road you want to support display of that message in a PDF?  You'd need to go back and remove all the HTML entities again.&lt;br /&gt;
&lt;br /&gt;
This is why you should ''filter'' strings at the input stage but not ''escape'' them until the final output stage.&lt;br /&gt;
&lt;br /&gt;
== Format String Injection ==&lt;br /&gt;
&lt;br /&gt;
If you like using functions like '''printf''' and '''sprintf''', you may find yourself writing&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
printf( &amp;quot;%s&amp;quot;, htmlentities($_GET['username']) ); // good example&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It is tempting to reduce this to&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
printf( htmlentities($_GET['username']) ); // BAD example&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Although the second implementation will work for most usernames, it is '''''not''''' correct!  You are essentially making the client-provided username the ''format string'' for printf.  If the username contains any percentage sign (%), it will be interpreted as the start of a parameter in the format string, causing your script to return errors.  Worse yet, it is known that certain combinations of format parameters will actually reveal system information in the error log.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
The solution is simple: never put dynamic input as the format string.  It should always be static, either hard-coded or from a stable source like a YAML file.  User-supplied input should ''always'' be fed into the string as arguments to sprintf and printf.&lt;br /&gt;
&lt;br /&gt;
If you are outputting only one little string like in the example above, it suffices to use a PHP function like '''print''' or '''echo''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
print htmlentities($_GET['username']); // good example&lt;br /&gt;
echo htmlentities($_GET['username']); // good example&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Server Configurations ==&lt;br /&gt;
&lt;br /&gt;
Sometimes hackers attempt to penetrate your application from the server side rather than the application side.  Server-side security is beyond the realm of this course, but here are some things you should keep in mind.&lt;br /&gt;
&lt;br /&gt;
* Use a highly secure root password, and it should be one that you don't use anywhere else.  Seriously.&lt;br /&gt;
* Use a firewall system to block unnecessary ports from public access.  SSH and Web Server should really be the only ports you need.  You should keep the web serve on port 80, but you have the option of moving SSH to a port other than 22 to make it slightly more secure.&lt;br /&gt;
&lt;br /&gt;
=== Git Exposed ===&lt;br /&gt;
&lt;br /&gt;
Another thing to keep in mind is that by default, Apache serves up ''everything'' in your file tree, only except for Apache-specific configuration files like .htaccess.  This means that if you're not careful, your .git directory can be served, exposing attackers to your raw source code, including things like database passwords! A recent study found that [http://www.jamiembrown.com/blog/one-in-every-600-websites-has-git-exposed/ one in every 600 web sites is making this mistake]. Don't be one of them!&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 2]]&lt;br /&gt;
[[Category:Web Application Security]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Web_Application_Security,_Part_1&amp;diff=1984</id>
		<title>Web Application Security, Part 1</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Web_Application_Security,_Part_1&amp;diff=1984"/>
		<updated>2015-08-02T18:54:08Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* Server Configurations */ Don't expose .git&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Application-level web security is of increasing concern among web developers.  This article outlines some types of security threats to your web application and how to solve those threats.&lt;br /&gt;
&lt;br /&gt;
This is Part 1 of the Web Application Security article, geared toward the material covered in [[Module 2]].  For material covered in [[Module 3]] (MySQL), see [[Web Application Security, Part 2]].  For material covered in [[Module 6]] (JavaScript), see [[Web Application Security, Part 3]].&lt;br /&gt;
&lt;br /&gt;
== Introduction to Application-Level Web Security ==&lt;br /&gt;
&lt;br /&gt;
Every day, computer hackers around the world penetrate web applications, often for personal profits.  You may find it hard to believe, but '''even high-profile web sites (banks, social media, even computer security companies) are vulnerable to application-level attacks!'''&lt;br /&gt;
&lt;br /&gt;
Not only is it embarrassing to be the programmer who wrote the vulnerable code, but it could also cost you your job.  As a prudent web developer, it is ''imperative'' that you take precautionary measures to make your application difficult to penetrate.  Indeed, most of the time, if your site is well-written, hackers will just move on.&lt;br /&gt;
&lt;br /&gt;
Here's the golden rule: Anything in your site that accepts user input, whether via a form, an AJAX request, a file upload, or even malformed links, can be used as an attack vector.  '''NEVER TRUST USER INPUT!!!'''  This can be summarized in the acronym FIEO, or ''Filter Input, Escape Output''.&lt;br /&gt;
&lt;br /&gt;
=== FIEO in PHP ===&lt;br /&gt;
&lt;br /&gt;
==== Filtering Input ====&lt;br /&gt;
&lt;br /&gt;
&amp;quot;Filter Input&amp;quot; means that you should check that input data is of the format that you are expecting.  For example, if you are expecting a number, you should cast it to a float or an int.  If you are expecting a phone number, you should run it through a regular expression (you will learn regular expressions in module 4).  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;PHP&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
// Cast a number to a float or an int:&lt;br /&gt;
$amount = (float) $_POST['amount'];&lt;br /&gt;
&lt;br /&gt;
// Pass a phone number through a regular expression:&lt;br /&gt;
$phone = preg_match('/\d{3}-\d{3}-\d{4}/', $_POST['phone']) ? $_POST['phone'] : &amp;quot;&amp;quot;;&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Escaping Output ====&lt;br /&gt;
&lt;br /&gt;
&amp;quot;Escape Output&amp;quot; means that you need to nullify, or ''escape'', characters that have special meaning in the markup language of interest.  For example, consider the following string:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
If a&amp;lt;b and b&amp;lt;c then a&amp;lt;c.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Since a less-than sign means the start of a tag in HTML, and '''b''' is a valid tag name, the above string will ''not'' render as you might expect in HTML.  Therefore, we need to ''escape'' our less-than signs by using HTML entities:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
If a&amp;amp;lt;b and b&amp;amp;lt;c then a&amp;amp;lt;c.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The &amp;quot;&amp;amp;lt;&amp;quot; is an '''HTML entity''' that will render as a less-than sign.  (For more information on HTML entities, [http://docs.webplatform.org/wiki/html/entities read this article on the WebPlatform wiki].)&lt;br /&gt;
&lt;br /&gt;
PHP provides a function that, given a string, will convert special characters to their HTML entity equivalents.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;PHP&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
$str = &amp;quot;If a&amp;lt;b and b&amp;lt;c then a&amp;lt;c.&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
// Convert special characters to HTML entities before outputting:&lt;br /&gt;
echo htmlentities($str);&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' ''htmlentities'' escapes a string for use in HTML, but it does ''not'' escape a string for use in other markup languages.  You need to use different methods when escaping strings for other languages.&lt;br /&gt;
&lt;br /&gt;
=== Why Not to Escape Input ===&lt;br /&gt;
&lt;br /&gt;
Filtering your input is important, as shown above.  However, it is bad practice to ''escape'' your input.  For example, don't do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;PHP&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
$message = htmlentites($_POST['amount']); // bad practice&lt;br /&gt;
// then store $message in a database, etc.&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The reason this is bad practice is that it permanently ties that string to its final output format.  For example, what if some time down the road you want to support display of that message in a PDF?  You'd need to go back and remove all the HTML entities again.&lt;br /&gt;
&lt;br /&gt;
This is why you should ''filter'' strings at the input stage but not ''escape'' them until the final output stage.&lt;br /&gt;
&lt;br /&gt;
== Format String Injection ==&lt;br /&gt;
&lt;br /&gt;
If you like using functions like '''printf''' and '''sprintf''', you may find yourself writing&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
printf( &amp;quot;%s&amp;quot;, htmlentities($_GET['username']) ); // good example&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It is tempting to reduce this to&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
printf( htmlentities($_GET['username']) ); // BAD example&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Although the second implementation will work for most usernames, it is '''''not''''' correct!  You are essentially making the client-provided username the ''format string'' for printf.  If the username contains any percentage sign (%), it will be interpreted as the start of a parameter in the format string, causing your script to return errors.  Worse yet, it is known that certain combinations of format parameters will actually reveal system information in the error log.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
The solution is simple: never put dynamic input as the format string.  It should always be static, either hard-coded or from a stable source like a YAML file.  User-supplied input should ''always'' be fed into the string as arguments to sprintf and printf.&lt;br /&gt;
&lt;br /&gt;
If you are outputting only one little string like in the example above, it suffices to use a PHP function like '''print''' or '''echo''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
print htmlentities($_GET['username']); // good example&lt;br /&gt;
echo htmlentities($_GET['username']); // good example&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Server Configurations ==&lt;br /&gt;
&lt;br /&gt;
Sometimes hackers attempt to penetrate your application from the server side rather than the application side.  Server-side security is beyond the realm of this course, but here are some things you should keep in mind.&lt;br /&gt;
&lt;br /&gt;
* Use a highly secure root password, and it should be one that you don't use anywhere else.  Seriously.&lt;br /&gt;
* Use a firewall system to block unnecessary ports from public access.  SSH and Web Server should really be the only ports you need.  You should keep the web serve on port 80, but you have the option of moving SSH to a port other than 22 to make it slightly more secure.&lt;br /&gt;
&lt;br /&gt;
=== Git Exposed ===&lt;br /&gt;
&lt;br /&gt;
Another thing to keep in mind is that by default, Apache serves up ''everything'' in your file tree, only except for Apache-specific configuration files like .htaccess.  This means that if you're not careful, your .git directory can be served, exposing attackers to your raw source code, including things like database passwords! A recent study found that [http://www.jamiembrown.com/blog/one-in-every-600-websites-has-git-exposed/ one in every 600 web sites is making this mistake]. Don't be one of them!&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 2]]&lt;br /&gt;
[[Category:Web Application Secur&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=1931</id>
		<title>JavaScript</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=1931"/>
		<updated>2015-07-24T19:35:16Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* Prototypal Inheritance */ Adding note about extending built-in prototypes&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;JavaScript is the most widely used scripting language for implementing client-side functionality in Web applications.  Unlike PHP, JavaScript code is interpreted and executed in a client's web browser (not on the web server).&lt;br /&gt;
&lt;br /&gt;
== JavaScript?  Did you mean Java? ==&lt;br /&gt;
&lt;br /&gt;
'''JavaScript''' is a prototype-based programming language focussed on web interactivity.  It was first introduced in Netscape Navigator, and it in turn gave rise to what is now '''[http://www.ecmascript.org/ ECMAScript]'''.  Originally, JavaScript was called &amp;quot;LiveScript&amp;quot;.  Sun, the developer of Java at the time, wanted a language that would complement its compiled Java language, and so LiveScript was renamed JavaScript.&lt;br /&gt;
&lt;br /&gt;
Beyond that, '''Java and JavaScript are as similar as Ham and Hamster.'''&lt;br /&gt;
&lt;br /&gt;
Java and JavaScript have similar syntax, but the under workings are quite different.  For example, Java requires strict typing, but JavaScript allows for dynamic typing.  Java is object-oriented, but JavaScript is prototype-oriented.  Java is compiled, but JavaScript is interpreted.  Java supports event listeners, but JavaScript makes them a fundamental part of the language.  Java variables are scoped to the innermost method or loop, but JavaScript variables are scoped only to the innermost function.&lt;br /&gt;
&lt;br /&gt;
== JavaScript Language Components ==&lt;br /&gt;
&lt;br /&gt;
This section highlights some features of the JavaScript language that differentiate it from other languages.  For a more comprehensive JavaScript tutorial, the following tutorials are both quality:&lt;br /&gt;
&lt;br /&gt;
* [http://docs.webplatform.org/wiki/javascript WebPlatform]: Great for learning JavaScript for the first time.  Advocates best practices for modern JavaScript development.&lt;br /&gt;
* [http://www.quirksmode.org/js/contents.html QuirksMode]: More advanced than the WebPlatform tutorial, but it thoroughly covers the most powerful aspects of pure JavaScript and gives unparalleled advice on browser compatibility.&lt;br /&gt;
&lt;br /&gt;
Advice: Do '''NOT''' Google for &amp;quot;JavaScript Tutorial&amp;quot;.  The first few hits advocate bad or outdated practices.  Stick with the ones listed here.&lt;br /&gt;
&lt;br /&gt;
=== Variables and Scope ===&lt;br /&gt;
&lt;br /&gt;
To define a variable in JavaScript, use the '''var''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var foo = &amp;quot;bar&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
All variables are objects.  In the case above, the variable '''foo''' is an object of the class '''String'''.&lt;br /&gt;
&lt;br /&gt;
Notice that like PHP, you do not have to explicitly define a type for a variable like '''int''' or '''String'''; this is because JavaScript and PHP are ''dynamically typed languages''.&lt;br /&gt;
&lt;br /&gt;
JavaScript code can access any variable higher in the “function tree”, but not vice-versa.  This is called '''scope'''.  ''All functions create their own scope.''&lt;br /&gt;
&lt;br /&gt;
When you reference a variable, JavaScript will look up through the &amp;quot;function tree&amp;quot; until it finds the variable you asked for.  This means that you could define variables of the same name as global variables inside of functions.  For demonstration of concept:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var a = &amp;quot;hello&amp;quot;;&lt;br /&gt;
var b = &amp;quot;world&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
function sayGoodByeWorld(){&lt;br /&gt;
	var a = &amp;quot;goodbye&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
	alert(a); // goodbye&lt;br /&gt;
	alert(b); // world&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayGoodByeWorld();&lt;br /&gt;
&lt;br /&gt;
alert(a); // hello&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object Literals ===&lt;br /&gt;
&lt;br /&gt;
A very common way of storing and transporting data in JavaScript is by using objects.  You can define an object with certain properties using an '''object literal''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = {&lt;br /&gt;
	color: &amp;quot;red&amp;quot;,&lt;br /&gt;
	flavor: &amp;quot;sweet&amp;quot;,&lt;br /&gt;
	season: &amp;quot;autumn&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(apple.color);  // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
To define a function in JavaScript, use the '''function''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function sayHello(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(); // call the function&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Pass an argument to a function like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function sayHello(name){&lt;br /&gt;
	alert(&amp;quot;Hello, &amp;quot;+name);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(&amp;quot;Todd&amp;quot;); // call the function and pass an argument&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Functions are Objects ====&lt;br /&gt;
&lt;br /&gt;
In JavaScript, functions are objects.  This means that they can be assigned to variables, manipulated on the fly, and even passed as arguments to other functions!  '''''This is an extremely important feature of JavaScript''''' that makes it such a robust language for web development.&lt;br /&gt;
&lt;br /&gt;
You create a function variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayHello = function(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(); // call the function&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Observe that you can make [[#Variables and Scope|scope-dependent]] functions in this way.&lt;br /&gt;
&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=HaPlj796ngQ&lt;br /&gt;
|time=5m45s&lt;br /&gt;
|desc=JavaScript Closures&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
A '''closure''' is a way to separate a certain snippet of JavaScript code from the global scope.  This is useful if you do not want to &amp;quot;muck up&amp;quot; global variables.  Closures are nothing more than anonymous functions that are called as soon as they are created:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
​var a = &amp;quot;hello&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
(​​​​function(){&lt;br /&gt;
	var b = &amp;quot;world&amp;quot;;&lt;br /&gt;
	&lt;br /&gt;
	alert(a); // hello&lt;br /&gt;
	alert(b); // world&lt;br /&gt;
})();&lt;br /&gt;
&lt;br /&gt;
alert(a); // hello&lt;br /&gt;
alert(b);​ // ReferenceError: b is not defined​​​​​​​​​​​​​​​&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Passing Variables to a Closure&lt;br /&gt;
|desc=This example demonstrates how you can &amp;quot;save&amp;quot; previous versions of a variable using closures.  This is possible because of scoping and the fact that function variables can be returned as objects.&lt;br /&gt;
|fiddle_id=YURqa&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Most JavaScript libraries (like jQuery) write all of their code in a closure.  What this means is that except for one or two variable names (jQuery or $), everything associated with the library is completely self-contained.&lt;br /&gt;
&lt;br /&gt;
=== Prototypal Inheritance ===&lt;br /&gt;
&lt;br /&gt;
JavaScript implements '''prototypal inheritance''', as opposed to a language like Java or C++, which implements '''classical inheritance'''.  JavaScript is one of only a handful of languages implementing prototype-based inheritance.&lt;br /&gt;
&lt;br /&gt;
Here's how it works.  Every callable object (function) has a '''prototype'''.  When instances of that object are created, their properties and methods are copied (inherited) from the prototype.  Additionally, changes made to the prototype later in the program are &amp;quot;copied&amp;quot; to every instance.&lt;br /&gt;
&lt;br /&gt;
For example, if you wanted to make a method on all strings that added a “!”, you could modify String’s prototype:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
String.prototype.bang = function(){&lt;br /&gt;
	return this+&amp;quot;!&amp;quot;; // Notice: the context is the instance itself&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(&amp;quot;Hello&amp;quot;.bang()); // alerts Hello!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To &amp;quot;extend&amp;quot; an object, just copy its prototype to a new object.  However, since classical inheritance and prototypal inheritance are different concepts, copying prototypes may have results that you don't expect.  [http://beej.us/blog/data/javascript-prototypes-inheritance/ This article] seems to have a pretty good explanation of how to &amp;quot;inherit&amp;quot; prototypes with example implementations.&lt;br /&gt;
&lt;br /&gt;
==== Extending Built-In Prototypes ====&lt;br /&gt;
&lt;br /&gt;
You should be aware that there is an active debate in the web development community about whether it is good programming style to extend the prototypes of built-in objects like String and Array, such as in the ''String.prototype.bang'' example above.  There are legitimate arguments on both sides.  [http://stackoverflow.com/questions/8859828/javascript-what-dangers-are-in-extending-array-prototype This Stack Overflow post] has good links to some articles discussing this issue.&lt;br /&gt;
&lt;br /&gt;
=== Context ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=0a4r4bm1nQA&lt;br /&gt;
|time=4m32s&lt;br /&gt;
|desc=The ''this'' Variable in JavaScript&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Every function is called on a certain object, which is not necessarily the same object in which it was defined.  This is called '''context'''.&lt;br /&gt;
&lt;br /&gt;
To call a function on an arbitrary context, use either '''call''' or '''apply'''.  ''call'' takes a list of arguments, while ''apply'' takes them all in an array.&lt;br /&gt;
&lt;br /&gt;
To access the current context, use the '''this''' keyword.  Demonstration of concept:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayThisColor = function(){&lt;br /&gt;
	alert(this.color);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
var apple = { color: &amp;quot;red&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
sayThisColor();   // undefined&lt;br /&gt;
sayThisColor.call(apple); // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Events ==&lt;br /&gt;
&lt;br /&gt;
Events are really what make JavaScript such a powerful language for web development.&lt;br /&gt;
&lt;br /&gt;
Rather than being thread based, JavaScript is event based.  Since all JavaScript code runs in a single thread, '''there are no concurrency issues'''.  When an event occurs, JavaScript automatically calls the ''event callback'' as soon as all previous events' callbacks have finished executing.&lt;br /&gt;
&lt;br /&gt;
Code in the form of a '''callback function''' is associated with events via a '''listener'''.  For example, the following JavaScript causes ''sayHello()'' (the callback function) to be run whenever the button with ID &amp;quot;hello&amp;quot; is clicked (the event):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayHello = function(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
document.getElementById(&amp;quot;hello&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, sayHello, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Binding Callbacks to a Button Click&lt;br /&gt;
|fiddle_id=L8c4Z&lt;br /&gt;
|cse330=true&lt;br /&gt;
|desc=In this example, notice how we bind the callback function when the ''DOMContentLoaded'' event fires.  This is because JavaScript requires that the button has been parsed by the browser before it can add event listeners to it.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The '''addEventListener''' method takes three parameters:&lt;br /&gt;
* The event type&lt;br /&gt;
* The callback function&lt;br /&gt;
*: The callback function is passed one parameter: the event object.&lt;br /&gt;
* A boolean representing bubble (false) or capture (true) phase&lt;br /&gt;
*: You usually want Bubble phase.  For more information on event phase, see [[#Event Phase]]&lt;br /&gt;
&lt;br /&gt;
Note that versions of Internet Explorer prior to version 9 required that you use a different, albeit similar, function for assigning event listeners called '''attachEvent'''.  attachEvent takes the same arguments as addEventListener, except you need to put '''on''' before the event type (e.g. &amp;quot;onclick&amp;quot;), and the third argument (phase) is not necessary.&lt;br /&gt;
&lt;br /&gt;
It is perfectly valid to use an '''anonymous function''' as your callback function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;hello&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, function(event){&lt;br /&gt;
	alert(&amp;quot;Hello, World!  Event Type: &amp;quot;+event.type);&lt;br /&gt;
}, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QuirksMode has perhaps the best series of articles about the ins and outs of JavaScript events on the internet: http://www.quirksmode.org/js/contents.html#events&lt;br /&gt;
&lt;br /&gt;
=== The Event Object ===&lt;br /&gt;
&lt;br /&gt;
Callback functions are passed one argument: an ''event object''.  You see above that one property of the event object is ''event.type''.  To see the full list of properties of the event object, you could run the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;my_btn&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, function(event){&lt;br /&gt;
	var strout = &amp;quot;&amp;quot;;&lt;br /&gt;
	for(var i in event){&lt;br /&gt;
		strout += i + &amp;quot;: &amp;quot; + event[i] + &amp;quot;\n&amp;quot;;&lt;br /&gt;
	}&lt;br /&gt;
	console.log(strout);&lt;br /&gt;
}, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some of the most useful properties and methods include:&lt;br /&gt;
* '''event.target''' references the object on which the event occurred.&lt;br /&gt;
* '''event.currentTarget''' references the object whose listener is currently being processed.&lt;br /&gt;
*: ''Note:'' event.target and event.currentTarget might be the same or might be different, depending on whether you are listening for bubbled events.&lt;br /&gt;
* '''event.preventDefault()''' stops the normal result of the event from being executed.  For example, if you listen for a form's ''submit'' event, you can call event.preventDefault() to stop the form from being submitted.&lt;br /&gt;
* '''event.stopPropagation()''' prevents any other event listeners from being executed.  For more detail, read the section on Event Phase below.&lt;br /&gt;
&lt;br /&gt;
For more detail on the event object, see [http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html#interface-Event the W3C specification].&lt;br /&gt;
&lt;br /&gt;
'''Note:''' If your callback function does not take any parameters, it will still run; you just won't have as easy of access to the event object.&lt;br /&gt;
&lt;br /&gt;
=== Event Handlers and Memory Management ===&lt;br /&gt;
&lt;br /&gt;
JavaScript is an automatically garbage-collected language, meaning that memory management is mostly taken care of for you.  However, there are some instances when you need to be careful about creating &amp;quot;zombie&amp;quot; objects.  In JavaScript, this mostly revolves around the idea of event listeners.&lt;br /&gt;
&lt;br /&gt;
I could give an explanatory example, but instead I'll tell you straightaway that '''the moral of the story is that for every &amp;quot;addEventListener&amp;quot;, there should probably be a &amp;quot;removeEventListener&amp;quot;.'''  Here are some good articles to satisfy your hunger for more details on event listeners and JavaScript memory management:&lt;br /&gt;
&lt;br /&gt;
* http://www.vladalexandruionescu.com/2012/08/javascript-memory-leaks.html&lt;br /&gt;
* http://lostechies.com/derickbailey/2012/03/19/backbone-js-and-javascript-garbage-collection/&lt;br /&gt;
* http://stackoverflow.com/questions/5326300/garbage-collection-with-node-js&lt;br /&gt;
&lt;br /&gt;
When you start working with Node.JS in the next module, it's more important than ever to keep good accounting of your event listeners.&lt;br /&gt;
&lt;br /&gt;
=== Event Phase ===&lt;br /&gt;
&lt;br /&gt;
In JavaScript, events occur in two phases: '''Capture Phase''' and '''Bubble Phase'''.  Consider the following HTML document:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&amp;lt;title&amp;gt;Event Test&amp;lt;/title&amp;gt;&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
  &amp;lt;div id=&amp;quot;box&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;button id=&amp;quot;btn&amp;quot;&amp;gt;&lt;br /&gt;
      Hello&lt;br /&gt;
    &amp;lt;/button&amp;gt;&lt;br /&gt;
  &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Suppose the user clicks on the &amp;quot;Hello&amp;quot; button.  Events will be fired in the following order:&lt;br /&gt;
&lt;br /&gt;
# Capture Phase CLICK on the Document&lt;br /&gt;
# Capture Phase CLICK on the Body&lt;br /&gt;
# Capture Phase CLICK on the Div#box&lt;br /&gt;
# Target Phase CLICK on the Button#btn&lt;br /&gt;
# Bubble Phase CLICK on the Div#box&lt;br /&gt;
# Bubble Phase CLICK on the Body&lt;br /&gt;
# Bubble Phase CLICK on the Document&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Using Capture Phase to Enable or Disable a Toolbar&lt;br /&gt;
|fiddle_id=r32Dz&lt;br /&gt;
|desc=We bind an event in the capture phase to the div with ID ''toolbar''.  When ''e.stopPropagation()'' is called, the event does not reach the buttons in the toolbar.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Graphically, here is the order in which an event occurs in three generic nested elements:&lt;br /&gt;
&lt;br /&gt;
[[File:EventPhase.gif]]&lt;br /&gt;
&lt;br /&gt;
Why is this useful?  Suppose you have a control panel (toolbar, etc) that you want to temporarily deactivate.  (For example, Bold/Italic/Underline buttons on a graphic text editor that currently has no content.)  You could keep bubble phase event listeners on your buttons, but prevent those events from occurring by stopping the event in the capture phase on the parent element before the event reaches your buttons!  Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var disableToolbarFunc = function(e){&lt;br /&gt;
	e.stopPropogation();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// To disable toolbar:&lt;br /&gt;
document.getElementById(&amp;quot;box&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, disableToolbarFunc, true);&lt;br /&gt;
&lt;br /&gt;
// To re-enable toolbar:&lt;br /&gt;
document.getElementById(&amp;quot;box&amp;quot;).removeEventListener(&amp;quot;click&amp;quot;, disableToolbarFunc, true);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Word of caution:''' Like many great things in web development, capture phase does not work in versions of Internet Explorer prior to version 9.  There is no elegant substitution for older versions of Internet Explorer.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' When the event reaches the innermost element, there is no distinction between capture phase and bubble phase.  The order in which event handlers were added to the element determines the order in which those callbacks are evaluated.&lt;br /&gt;
&lt;br /&gt;
== Document Object Model ==&lt;br /&gt;
&lt;br /&gt;
The '''Document Object Model (DOM)'''  is what enables JavaScript to manipulate the content of your web page.&lt;br /&gt;
&lt;br /&gt;
=== Nodes and Traversing the DOM ===&lt;br /&gt;
&lt;br /&gt;
Each element on your page, whether it is a &amp;lt;nowiki&amp;gt;&amp;lt;p&amp;gt;, &amp;lt;img/&amp;gt;&amp;lt;/nowiki&amp;gt;, a string of text, or even an attribute, is called a '''node'''.&lt;br /&gt;
&lt;br /&gt;
Every node, except for the document itself, has exactly one parent.  A single node may have multiple children.&lt;br /&gt;
&lt;br /&gt;
Consider the following HTML code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;ul id=&amp;quot;my-list&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;fruits&amp;quot;&amp;gt;Apples&amp;lt;/li&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;citrus&amp;quot;&amp;gt;Oranges and &amp;lt;strong&amp;gt;Lemons&amp;lt;/strong&amp;gt;&amp;lt;/li&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;berries&amp;quot;&amp;gt;Cherries&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ul&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, the ul with ID &amp;quot;my-list&amp;quot; has three child '''element nodes''' (the three li's) as well as four child '''text nodes''' (the whitespace counts as a text node) and a child '''attribute node'''.  The second LI has one child '''text node''' as well as one child '''element node''' and one child '''attribute node'''.&lt;br /&gt;
&lt;br /&gt;
The DOM can be traversed in JavaScript.  First, let's look at an example.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
e = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;citrus&amp;quot;)[0].lastChild.nodeName;&lt;br /&gt;
alert(e);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Currently Selected Radio Button&lt;br /&gt;
|fiddle_id=SHcng&lt;br /&gt;
|desc=In pure JavaScript, in order to determine the currently selected radio button, it is necessary to iterate over an array of pointers to all possible radio buttons, and stop when you find one that is &amp;quot;checked&amp;quot;.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The above snippet gets the element with class name '''citrus''' that is a child of the element with ID '''my-list''' (the second LI in the example above), and alerts the type of its second child node (which in this case is '''STRONG''').&lt;br /&gt;
&lt;br /&gt;
Some common methods for traversing the DOM include:&lt;br /&gt;
&lt;br /&gt;
* Node.parentNode&lt;br /&gt;
* Node.childNodes - returns an array of nodes&lt;br /&gt;
* Node.firstChild - same as Node.childNodes[0]&lt;br /&gt;
* Node.lastChild - same as Node.childNodes[Node.childNodes.length-1]&lt;br /&gt;
* Node.previousSibling&lt;br /&gt;
* Node.nextSibling&lt;br /&gt;
&lt;br /&gt;
You can also search for child (including all descendants) using one of the following methods:&lt;br /&gt;
&lt;br /&gt;
* Node.getElementsByTagName(&amp;quot;tag-name&amp;quot;) - returns an array of element nodes having the tag name '''tag-name''' that are descendants of Node&lt;br /&gt;
* Node.getElementById(&amp;quot;id&amp;quot;) - returns a single node having the ID '''id''' that is a descendant of Node&lt;br /&gt;
* Node.getElementsByName(&amp;quot;what-name&amp;quot;) - returns an array of element nodes having their '''name''' attribute set to '''what-name'''.  Useful for radio buttons and other form elements.&lt;br /&gt;
* Node.getElementsByClassName(&amp;quot;class&amp;quot;) - returns an array of nodes having the class '''class'''&lt;br /&gt;
*: '''Note:''' As of October 2012, 82% of the browser market supports Node.getElementsByClassName ([http://caniuse.com/getelementsbyclassname more info]).  In order to support the other 18%, you need to either add your own getElementsByClassName to Node's prototype or use a JavaScript library like jQuery or MooTools.&lt;br /&gt;
&lt;br /&gt;
It is common in JavaScript to have long statements like the one in the example above, where you call methods on several objects in sequence.&lt;br /&gt;
&lt;br /&gt;
=== Creating, Moving, and Removing Nodes ===&lt;br /&gt;
&lt;br /&gt;
You will frequently find yourself wanting to modify the DOM.  JavaScript provides methods that help you do this.&lt;br /&gt;
&lt;br /&gt;
Consider the same HTML as above.  If you wanted to add another element to the list, you could use this code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var newLi = document.createElement(&amp;quot;li&amp;quot;);  // creates a node with the tag name li&lt;br /&gt;
newLi.appendChild(document.createTextNode(&amp;quot;Broccoli&amp;quot;));&lt;br /&gt;
newLi.setAttribute(&amp;quot;class&amp;quot;, &amp;quot;veggies&amp;quot;);&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).appendChild(newLi);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to remove the apples from the list, you could do:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;fruits&amp;quot;)[0];&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).removeChild(apple);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to move the apples to the end of the list, you could do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;fruits&amp;quot;)[0];&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).appendChild(apple);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that '''Node.append()''' both removes a node from its previous location ''and'' appends it to its new location, which is always going to be as the last child of the parent node.&lt;br /&gt;
&lt;br /&gt;
In summary, here are the methods to know from this section:&lt;br /&gt;
&lt;br /&gt;
* Node.append(otherNode) - removes otherNode from its current location in the DOM (if applicable) and then adds it as the last child of Node&lt;br /&gt;
* Node.removeChild(otherNode) - removes otherNode, a child of Node, from the DOM&lt;br /&gt;
* document.createElement(&amp;quot;tag-name&amp;quot;) - create a new node with the tag name &amp;quot;tag-name&amp;quot;&lt;br /&gt;
* document.createTextNode(&amp;quot;text&amp;quot;) - create a node containing only the string '''text'''&lt;br /&gt;
* Node.setAttribute(&amp;quot;attribute&amp;quot;, &amp;quot;value&amp;quot;) - sets the attribute node of name &amp;quot;attribute&amp;quot; to &amp;quot;value&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=== DOM Shortcuts ===&lt;br /&gt;
&lt;br /&gt;
In the above sections, we have been creating, reading, modifying, and deleting Nodes.  This is the most &amp;quot;correct&amp;quot; way to change the content of a web page from inside JavaScript.&lt;br /&gt;
&lt;br /&gt;
This section documents a few shortcuts that are not as &amp;quot;pure&amp;quot; as using Nodes but can be less confusing and cumbersome.&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Displaying Information&lt;br /&gt;
|fiddle_id=Q3BPZ&lt;br /&gt;
|desc=This example shows how to use some of the shortcut methods for using JavaScript to display information on the page.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
==== textContent ====&lt;br /&gt;
&lt;br /&gt;
Using textContent to display information is probably the easiest method out there.  For example, the following code overwrites whatever is in the element with ID &amp;quot;holder&amp;quot; with the string &amp;quot;Hello World&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).textContent = &amp;quot;Hello World&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to instead append the text, simply use '''+=''' instead of '''=''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).textContent += &amp;quot; -  Later, he said Hello World  - &amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that textContent displays strings literally; that is, it does not allow for HTML.  Setting the textContent property also removes any HTML that may have already been in that element.&lt;br /&gt;
&lt;br /&gt;
==== innerHTML ====&lt;br /&gt;
&lt;br /&gt;
If you need to use HTML in your output but don't want to use the method described earlier in this section, a straightforward strategy is to use the innerHTML property of an element. For example, the following code would add a paragraph saying &amp;quot;Hello World&amp;quot; to the element with ID &amp;quot;holder&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).innerHTML += &amp;quot;&amp;lt;p&amp;gt;Hello World&amp;lt;/p&amp;gt;&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Important:''' You need to be careful to prevent XSS-type attacks if you display information using innerHTML.  For example, be sure to escape a user-supplied string before appending it to innerHTML.&lt;br /&gt;
&lt;br /&gt;
=== JavaScript Inspectors ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=PKzrmbN-pMg&lt;br /&gt;
|time=4m13s&lt;br /&gt;
|desc=Using Firebug, WebKit Inspector, and IE Developer Tools&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Various browsers and browser plugins give you, the developer, tools to debug your code, inspect the DOM, and much more.  Using these tools is essential for an efficient workflow.&lt;br /&gt;
&lt;br /&gt;
* '''Firebug'''.  Firebug is a plugin for Firefox that is a toolkit full of web developer tools, one of which is a DOM inspector.  To inspect the DOM of a web page, simply open the Firebug window while viewing the web page.&lt;br /&gt;
* '''WebKit Inspector'''.  The WebKit Inspector, which is available in both Chrome and Safari, enables you to see the DOM tree and relationships between elements.  However, its DOM inspection tools are not as robust as those of Firebug.&lt;br /&gt;
* '''Opera Dragonfly'''.  The web browser Opera comes with a web developer toolkit similar to the WebKit Inspector called Dragonfly.  It is important that you test your sites in Opera, because although Opera has only a small fraction of the desktop browser market, it is second only to WebKit on the mobile market.  Opera also has extremely strong CSS support, so it is good for testing for bugs in your CSS.&lt;br /&gt;
&lt;br /&gt;
All of the above-mentioned tools enable you to look at the DOM of your web page and find what properties and methods are associated with each node.  This is helpful because if you have JavaScript that manipulates HTML elements, you cannot tell which properties are associated with which elements by looking at the source code alone.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 6]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=1927</id>
		<title>Node.JS</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=1927"/>
		<updated>2015-07-10T08:11:17Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* Node.JS Security */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;AJAX is a useful technology for web applications that need to pull periodic updates from your server.  But what do you do when you have thousands of clients all requesting data that changes real-time?  A PHP+AJAX approach would choke.  It is situations like these that Node.JS comes to the rescue.&lt;br /&gt;
&lt;br /&gt;
== Non-Blocking I/O ==&lt;br /&gt;
&lt;br /&gt;
You dabbled in the concept of non-blocking I/O when you implemented AJAX in the previous JavaScript module.  Node.JS uses this execution model at its core.&lt;br /&gt;
&lt;br /&gt;
The core idea is the use of '''''anonymous functions''''' as ''callbacks'' for processing the results of intensive operations.  Consider the pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
var data = database.query(&amp;quot;select * from news&amp;quot;);&lt;br /&gt;
print data[0].title;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above pseudo-code queries a database, saves the result of the query in a variable named ''data'', and then prints out the first title in ''data''.  The problem arises when multiple clients all want to access the server at the same time.  ''In a blocking I/O model, a client needs to wait until all other clients are finished before it can start its process.''  With intensive operations and thousands of clients, this can easily crash your server!&lt;br /&gt;
&lt;br /&gt;
The solution is to use ''non-blocking I/O''.  Consider this revised pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Non-Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
database.query(&amp;quot;select * from news&amp;quot;, function(data){&lt;br /&gt;
	print data[0].title;&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The revised pseudo-code achieves the same end result as the first version.  However, ''it allows other clients to perform tasks while this process is waiting for the database to be queried!''  The code occurs in two parts: first, we start the query.  Second, ''when the query is complete'', our '''anonymous callback function''' is executed.  In Node.JS, callback functions are usually passed one or more parameters.&lt;br /&gt;
&lt;br /&gt;
Better yet, with non-blocking I/O, you have no concurrency issues, because everything runs in just one thread.  Nifty!&lt;br /&gt;
&lt;br /&gt;
== Installing Node.JS ==&lt;br /&gt;
&lt;br /&gt;
You can get Node.JS from yum or apt-get, but the versions are going to be out dated.  Remember that Node.JS is a rapidly changing language, so a version of Node from last year is going to be drastically different than a version of Node today.&lt;br /&gt;
&lt;br /&gt;
The unofficial instructions for installing Node.JS can be found here: https://gist.github.com/isaacs/579814&lt;br /&gt;
&lt;br /&gt;
There are several choices, but my favorite is probably ''use-nave-no-shell.sh''.&lt;br /&gt;
&lt;br /&gt;
The instructions at the above link have a couple bugs.  If you run this sequence of commands, Node and NPM will install correctly:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ mkdir ~/.nave&lt;br /&gt;
$ cd ~/.nave&lt;br /&gt;
$ wget http://github.com/isaacs/nave/raw/master/nave.sh&lt;br /&gt;
$ sudo ln -s $PWD/nave.sh /usr/local/bin/nave&lt;br /&gt;
$ chmod a+x nave.sh&lt;br /&gt;
$ sudo chown -R $USER:$USER /usr/local&lt;br /&gt;
$ nave usemain stable&lt;br /&gt;
$ curl -L https://www.npmjs.org/install.sh | sh&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Your First Node.JS Application: Hello World ==&lt;br /&gt;
&lt;br /&gt;
Let's try running the example application given on the front page of nodejs.org:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var http = require('http');&lt;br /&gt;
http.createServer(function (req, res) {&lt;br /&gt;
	res.writeHead(200, {&lt;br /&gt;
		'Content-Type': 'text/plain'&lt;br /&gt;
	});&lt;br /&gt;
	res.end('Hello World\n');&lt;br /&gt;
}).listen(1337);&lt;br /&gt;
console.log('Server running at http://localhost:1337/');&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Paste the example into a file named `hello.js`, and then run it by calling `node hello.js`.  You should now be able to see your Hello World by visiting your server at port 1337!  (Press ^C to stop the application.)  '''Note:''' If you're running the code from your EC2 instance, you will need to open port 1337.&lt;br /&gt;
&lt;br /&gt;
Let's walk through each line in the above example.&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;code&amp;gt;var http = require('http');&amp;lt;/code&amp;gt; enables us to use Node's built-in HTTP server.  We've been spoiled that languages like PHP automatically load all of the libraries that we need.  However, '''''most functionality in Node.JS is NOT loaded by default.'''''  When you want to use any non-fundamental feature of Node, you need to ''require'' it into a variable, as this example does with the HTTP package.  You should be familiar with this concept when you needed to use ArrayList and other specialty packages in Java in CSE 132.&lt;br /&gt;
* &amp;lt;code&amp;gt;http.createServer(function (req, res) { ... }).listen(1337);&amp;lt;/code&amp;gt; uses the HTTP server API to listen for HTTP connections on port 1337.  The anonymous callback function will be called whenever a connection is made.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.writeHead(200, { 'Content-Type': 'text/plain' });&amp;lt;/code&amp;gt; specifies the Content-Type header to be &amp;quot;text/plain&amp;quot;.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.end('Hello World\n');&amp;lt;/code&amp;gt; writes &amp;quot;Hello World&amp;quot; to the response.&lt;br /&gt;
&lt;br /&gt;
Note the use of non-blocking I/O, even in this one little example.  ''Whenever a connection is made, the callback function will be called and passed parameters associated with that connection.''&lt;br /&gt;
&lt;br /&gt;
== A Static Fileserver Using Node.JS ==&lt;br /&gt;
&lt;br /&gt;
Node.JS does not automatically serve up static files in the way that an Apache/PHP does.  We need to either use an extension that handles this for us, like Express, or we need to write our own code to make a simple static fileserver.  The latter option is really not all that difficult, and it gives good insight into how a static fileserver works.&lt;br /&gt;
&lt;br /&gt;
=== Installing Packages ===&lt;br /&gt;
&lt;br /&gt;
In order for the example code below to work, you need to install the ''mime'' package.  To do this, '''cd to the working directory where you will save your Node.JS JavaScript file''' and run:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;$ npm install mime&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''npm'' is the package manager for Node.JS.  Unlike all of the package managers we've used up to this point, ''npm'' installs dependencies locally, ''not'' globally.  This means that you can have two different projects using different versions of the same package.  ''npm'' will create a ''node_modules'' directory in the CWD and will install the packages into it.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' When using npm to install local dependencies, '''''do not use sudo'''''.  It will screw up your file permissions.&lt;br /&gt;
&lt;br /&gt;
=== Static Fileserver Code ===&lt;br /&gt;
&lt;br /&gt;
The following code will make an HTTP server on port 3456 that serves up all static files in &amp;lt;STATIC DIRECTORY NAME&amp;gt; relative to app.js.&lt;br /&gt;
&lt;br /&gt;
'''Make an attempt to understand this code.'''  It's important that you are comfortable with the non-blocking nature, as well as how we handle file I/O. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Require the functionality we need to use:&lt;br /&gt;
var http = require('http'),&lt;br /&gt;
	url = require('url'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	mime = require('mime'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	fs = require('fs');&lt;br /&gt;
&lt;br /&gt;
// Make a simple fileserver for all of our static content.&lt;br /&gt;
// Everything underneath &amp;lt;STATIC DIRECTORY NAME&amp;gt; will be served.&lt;br /&gt;
var app = http.createServer(function(req, resp){&lt;br /&gt;
	var filename = path.join(__dirname, &amp;quot;&amp;lt;STATIC DIRECTORY NAME&amp;gt;&amp;quot;, url.parse(req.url).pathname);&lt;br /&gt;
	(fs.exists || path.exists)(filename, function(exists){&lt;br /&gt;
		if (exists) {&lt;br /&gt;
			fs.readFile(filename, function(err, data){&lt;br /&gt;
				if (err) {&lt;br /&gt;
					// File exists but is not readable (permissions issue?)&lt;br /&gt;
					resp.writeHead(500, {&lt;br /&gt;
						&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
					});&lt;br /&gt;
					resp.write(&amp;quot;Internal server error: could not read file&amp;quot;);&lt;br /&gt;
					resp.end();&lt;br /&gt;
					return;&lt;br /&gt;
				}&lt;br /&gt;
				&lt;br /&gt;
				// File exists and is readable&lt;br /&gt;
				var mimetype = mime.lookup(filename);&lt;br /&gt;
				resp.writeHead(200, {&lt;br /&gt;
					&amp;quot;Content-Type&amp;quot;: mimetype&lt;br /&gt;
				});&lt;br /&gt;
				resp.write(data);&lt;br /&gt;
				resp.end();&lt;br /&gt;
				return;&lt;br /&gt;
			});&lt;br /&gt;
		}else{&lt;br /&gt;
			// File does not exist&lt;br /&gt;
			resp.writeHead(404, {&lt;br /&gt;
				&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
			});&lt;br /&gt;
			resp.write(&amp;quot;Requested file not found: &amp;quot;+filename);&lt;br /&gt;
			resp.end();&lt;br /&gt;
			return;&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
app.listen(3456);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Port 3456 ===&lt;br /&gt;
&lt;br /&gt;
We are running our server on port 3456 as opposed to the default web server port, which of course is 80.  We therefore need to open our Node.JS application like this:&lt;br /&gt;
&lt;br /&gt;
http://ec2-xx-xx-xx-xx.compute-1.amazonaws.com:3456/path.extension&lt;br /&gt;
&lt;br /&gt;
However, this won't work on the first time.  ''Why?'' (Try to figure this out on your own before reading the next paragraph.)&lt;br /&gt;
&lt;br /&gt;
We need to open port 3456 on our Amazon EC2 instance.  Remember when you opened port 80 way back in Module 2?  We need to do the same sort of procedure again now.&lt;br /&gt;
&lt;br /&gt;
# Log into your EC2 management console&lt;br /&gt;
# Go to &amp;quot;Security Groups&amp;quot;&lt;br /&gt;
# Select your security group from Module 2&lt;br /&gt;
# Under &amp;quot;Inbound&amp;quot;, create a custom TCP rule for port 3456, and apply your changes.&lt;br /&gt;
&lt;br /&gt;
== Node.JS Security ==&lt;br /&gt;
&lt;br /&gt;
Just because we're writing in JavaScript doesn't mean that we can forget about the security practices you've been learning in the last three months of CSE 330.  XSS is still a problem, as is the use of ''eval'', CSRF attacks, and so on.&lt;br /&gt;
&lt;br /&gt;
The two links below have good information about security vulnerabilities specific to Node.JS that you should think about when crafting your application.&lt;br /&gt;
&lt;br /&gt;
# Book from PragProg ($24, 2015): https://pragprog.com/book/kdnodesec/secure-your-node-js-web-application&lt;br /&gt;
# Slideshow from a Switzerland Conference on Application Security (2012): http://www.slideshare.net/ASF-WS/asfws-2012-nodejs-security-old-vulnerabilities-in-new-dresses-par-sven-vetsch&lt;br /&gt;
&lt;br /&gt;
== Node.JS Conventions ==&lt;br /&gt;
&lt;br /&gt;
There ought to be a standard way to save metadata about your app, right?  Well, ''npm'' introduces a straightforward way to do this in the form of a ''package.json'' file.&lt;br /&gt;
&lt;br /&gt;
To make your ''npm'' file with a step-by-step prompt, run in your project root directory:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm init&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One nifty feature of ''package.json'' is the way it automatically handles dependencies.  For example, you can put the following lines in your ''package.json'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
  &amp;quot;dependencies&amp;quot;: {&lt;br /&gt;
    &amp;quot;mime&amp;quot;: &amp;quot;~1.2.11&amp;quot;,&lt;br /&gt;
    &amp;quot;socket.io&amp;quot;: &amp;quot;~0.9.16&amp;quot;,&lt;br /&gt;
  },&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then, back on the command line, when you run&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm install&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
it automatically installs the dependencies for you!  No more headaches of trying to figure out which modules you need to install; all that information is saved for you in your code base.&lt;br /&gt;
&lt;br /&gt;
'''Tip:''' Once you set up your ''package.json'' file, you can automatically add a dependency to it by using the ''--save'' argument on ''npm install'': &amp;lt;code&amp;gt;npm install --save socket.io&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 7]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=1926</id>
		<title>Node.JS</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=1926"/>
		<updated>2015-07-10T08:10:58Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* Node.JS Security */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;AJAX is a useful technology for web applications that need to pull periodic updates from your server.  But what do you do when you have thousands of clients all requesting data that changes real-time?  A PHP+AJAX approach would choke.  It is situations like these that Node.JS comes to the rescue.&lt;br /&gt;
&lt;br /&gt;
== Non-Blocking I/O ==&lt;br /&gt;
&lt;br /&gt;
You dabbled in the concept of non-blocking I/O when you implemented AJAX in the previous JavaScript module.  Node.JS uses this execution model at its core.&lt;br /&gt;
&lt;br /&gt;
The core idea is the use of '''''anonymous functions''''' as ''callbacks'' for processing the results of intensive operations.  Consider the pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
var data = database.query(&amp;quot;select * from news&amp;quot;);&lt;br /&gt;
print data[0].title;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above pseudo-code queries a database, saves the result of the query in a variable named ''data'', and then prints out the first title in ''data''.  The problem arises when multiple clients all want to access the server at the same time.  ''In a blocking I/O model, a client needs to wait until all other clients are finished before it can start its process.''  With intensive operations and thousands of clients, this can easily crash your server!&lt;br /&gt;
&lt;br /&gt;
The solution is to use ''non-blocking I/O''.  Consider this revised pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Non-Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
database.query(&amp;quot;select * from news&amp;quot;, function(data){&lt;br /&gt;
	print data[0].title;&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The revised pseudo-code achieves the same end result as the first version.  However, ''it allows other clients to perform tasks while this process is waiting for the database to be queried!''  The code occurs in two parts: first, we start the query.  Second, ''when the query is complete'', our '''anonymous callback function''' is executed.  In Node.JS, callback functions are usually passed one or more parameters.&lt;br /&gt;
&lt;br /&gt;
Better yet, with non-blocking I/O, you have no concurrency issues, because everything runs in just one thread.  Nifty!&lt;br /&gt;
&lt;br /&gt;
== Installing Node.JS ==&lt;br /&gt;
&lt;br /&gt;
You can get Node.JS from yum or apt-get, but the versions are going to be out dated.  Remember that Node.JS is a rapidly changing language, so a version of Node from last year is going to be drastically different than a version of Node today.&lt;br /&gt;
&lt;br /&gt;
The unofficial instructions for installing Node.JS can be found here: https://gist.github.com/isaacs/579814&lt;br /&gt;
&lt;br /&gt;
There are several choices, but my favorite is probably ''use-nave-no-shell.sh''.&lt;br /&gt;
&lt;br /&gt;
The instructions at the above link have a couple bugs.  If you run this sequence of commands, Node and NPM will install correctly:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ mkdir ~/.nave&lt;br /&gt;
$ cd ~/.nave&lt;br /&gt;
$ wget http://github.com/isaacs/nave/raw/master/nave.sh&lt;br /&gt;
$ sudo ln -s $PWD/nave.sh /usr/local/bin/nave&lt;br /&gt;
$ chmod a+x nave.sh&lt;br /&gt;
$ sudo chown -R $USER:$USER /usr/local&lt;br /&gt;
$ nave usemain stable&lt;br /&gt;
$ curl -L https://www.npmjs.org/install.sh | sh&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Your First Node.JS Application: Hello World ==&lt;br /&gt;
&lt;br /&gt;
Let's try running the example application given on the front page of nodejs.org:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var http = require('http');&lt;br /&gt;
http.createServer(function (req, res) {&lt;br /&gt;
	res.writeHead(200, {&lt;br /&gt;
		'Content-Type': 'text/plain'&lt;br /&gt;
	});&lt;br /&gt;
	res.end('Hello World\n');&lt;br /&gt;
}).listen(1337);&lt;br /&gt;
console.log('Server running at http://localhost:1337/');&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Paste the example into a file named `hello.js`, and then run it by calling `node hello.js`.  You should now be able to see your Hello World by visiting your server at port 1337!  (Press ^C to stop the application.)  '''Note:''' If you're running the code from your EC2 instance, you will need to open port 1337.&lt;br /&gt;
&lt;br /&gt;
Let's walk through each line in the above example.&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;code&amp;gt;var http = require('http');&amp;lt;/code&amp;gt; enables us to use Node's built-in HTTP server.  We've been spoiled that languages like PHP automatically load all of the libraries that we need.  However, '''''most functionality in Node.JS is NOT loaded by default.'''''  When you want to use any non-fundamental feature of Node, you need to ''require'' it into a variable, as this example does with the HTTP package.  You should be familiar with this concept when you needed to use ArrayList and other specialty packages in Java in CSE 132.&lt;br /&gt;
* &amp;lt;code&amp;gt;http.createServer(function (req, res) { ... }).listen(1337);&amp;lt;/code&amp;gt; uses the HTTP server API to listen for HTTP connections on port 1337.  The anonymous callback function will be called whenever a connection is made.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.writeHead(200, { 'Content-Type': 'text/plain' });&amp;lt;/code&amp;gt; specifies the Content-Type header to be &amp;quot;text/plain&amp;quot;.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.end('Hello World\n');&amp;lt;/code&amp;gt; writes &amp;quot;Hello World&amp;quot; to the response.&lt;br /&gt;
&lt;br /&gt;
Note the use of non-blocking I/O, even in this one little example.  ''Whenever a connection is made, the callback function will be called and passed parameters associated with that connection.''&lt;br /&gt;
&lt;br /&gt;
== A Static Fileserver Using Node.JS ==&lt;br /&gt;
&lt;br /&gt;
Node.JS does not automatically serve up static files in the way that an Apache/PHP does.  We need to either use an extension that handles this for us, like Express, or we need to write our own code to make a simple static fileserver.  The latter option is really not all that difficult, and it gives good insight into how a static fileserver works.&lt;br /&gt;
&lt;br /&gt;
=== Installing Packages ===&lt;br /&gt;
&lt;br /&gt;
In order for the example code below to work, you need to install the ''mime'' package.  To do this, '''cd to the working directory where you will save your Node.JS JavaScript file''' and run:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;$ npm install mime&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''npm'' is the package manager for Node.JS.  Unlike all of the package managers we've used up to this point, ''npm'' installs dependencies locally, ''not'' globally.  This means that you can have two different projects using different versions of the same package.  ''npm'' will create a ''node_modules'' directory in the CWD and will install the packages into it.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' When using npm to install local dependencies, '''''do not use sudo'''''.  It will screw up your file permissions.&lt;br /&gt;
&lt;br /&gt;
=== Static Fileserver Code ===&lt;br /&gt;
&lt;br /&gt;
The following code will make an HTTP server on port 3456 that serves up all static files in &amp;lt;STATIC DIRECTORY NAME&amp;gt; relative to app.js.&lt;br /&gt;
&lt;br /&gt;
'''Make an attempt to understand this code.'''  It's important that you are comfortable with the non-blocking nature, as well as how we handle file I/O. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Require the functionality we need to use:&lt;br /&gt;
var http = require('http'),&lt;br /&gt;
	url = require('url'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	mime = require('mime'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	fs = require('fs');&lt;br /&gt;
&lt;br /&gt;
// Make a simple fileserver for all of our static content.&lt;br /&gt;
// Everything underneath &amp;lt;STATIC DIRECTORY NAME&amp;gt; will be served.&lt;br /&gt;
var app = http.createServer(function(req, resp){&lt;br /&gt;
	var filename = path.join(__dirname, &amp;quot;&amp;lt;STATIC DIRECTORY NAME&amp;gt;&amp;quot;, url.parse(req.url).pathname);&lt;br /&gt;
	(fs.exists || path.exists)(filename, function(exists){&lt;br /&gt;
		if (exists) {&lt;br /&gt;
			fs.readFile(filename, function(err, data){&lt;br /&gt;
				if (err) {&lt;br /&gt;
					// File exists but is not readable (permissions issue?)&lt;br /&gt;
					resp.writeHead(500, {&lt;br /&gt;
						&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
					});&lt;br /&gt;
					resp.write(&amp;quot;Internal server error: could not read file&amp;quot;);&lt;br /&gt;
					resp.end();&lt;br /&gt;
					return;&lt;br /&gt;
				}&lt;br /&gt;
				&lt;br /&gt;
				// File exists and is readable&lt;br /&gt;
				var mimetype = mime.lookup(filename);&lt;br /&gt;
				resp.writeHead(200, {&lt;br /&gt;
					&amp;quot;Content-Type&amp;quot;: mimetype&lt;br /&gt;
				});&lt;br /&gt;
				resp.write(data);&lt;br /&gt;
				resp.end();&lt;br /&gt;
				return;&lt;br /&gt;
			});&lt;br /&gt;
		}else{&lt;br /&gt;
			// File does not exist&lt;br /&gt;
			resp.writeHead(404, {&lt;br /&gt;
				&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
			});&lt;br /&gt;
			resp.write(&amp;quot;Requested file not found: &amp;quot;+filename);&lt;br /&gt;
			resp.end();&lt;br /&gt;
			return;&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
app.listen(3456);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Port 3456 ===&lt;br /&gt;
&lt;br /&gt;
We are running our server on port 3456 as opposed to the default web server port, which of course is 80.  We therefore need to open our Node.JS application like this:&lt;br /&gt;
&lt;br /&gt;
http://ec2-xx-xx-xx-xx.compute-1.amazonaws.com:3456/path.extension&lt;br /&gt;
&lt;br /&gt;
However, this won't work on the first time.  ''Why?'' (Try to figure this out on your own before reading the next paragraph.)&lt;br /&gt;
&lt;br /&gt;
We need to open port 3456 on our Amazon EC2 instance.  Remember when you opened port 80 way back in Module 2?  We need to do the same sort of procedure again now.&lt;br /&gt;
&lt;br /&gt;
# Log into your EC2 management console&lt;br /&gt;
# Go to &amp;quot;Security Groups&amp;quot;&lt;br /&gt;
# Select your security group from Module 2&lt;br /&gt;
# Under &amp;quot;Inbound&amp;quot;, create a custom TCP rule for port 3456, and apply your changes.&lt;br /&gt;
&lt;br /&gt;
== Node.JS Security ==&lt;br /&gt;
&lt;br /&gt;
Just because we're writing in JavaScript doesn't mean that we can forget about the security practices you've been learning in the last three months of CSE 330.  XSS is still a problem, as is the use of ''eval'', CSRF attacks, and so on.&lt;br /&gt;
&lt;br /&gt;
The two links below have good information about security vulnerabilities specific to Node.JS that you should think about when crafting your application.&lt;br /&gt;
&lt;br /&gt;
1. Book from PragProg ($24, 2015): https://pragprog.com/book/kdnodesec/secure-your-node-js-web-application&lt;br /&gt;
2. Slideshow from a Switzerland Conference on Application Security (2012): http://www.slideshare.net/ASF-WS/asfws-2012-nodejs-security-old-vulnerabilities-in-new-dresses-par-sven-vetsch&lt;br /&gt;
&lt;br /&gt;
== Node.JS Conventions ==&lt;br /&gt;
&lt;br /&gt;
There ought to be a standard way to save metadata about your app, right?  Well, ''npm'' introduces a straightforward way to do this in the form of a ''package.json'' file.&lt;br /&gt;
&lt;br /&gt;
To make your ''npm'' file with a step-by-step prompt, run in your project root directory:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm init&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One nifty feature of ''package.json'' is the way it automatically handles dependencies.  For example, you can put the following lines in your ''package.json'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
  &amp;quot;dependencies&amp;quot;: {&lt;br /&gt;
    &amp;quot;mime&amp;quot;: &amp;quot;~1.2.11&amp;quot;,&lt;br /&gt;
    &amp;quot;socket.io&amp;quot;: &amp;quot;~0.9.16&amp;quot;,&lt;br /&gt;
  },&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then, back on the command line, when you run&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm install&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
it automatically installs the dependencies for you!  No more headaches of trying to figure out which modules you need to install; all that information is saved for you in your code base.&lt;br /&gt;
&lt;br /&gt;
'''Tip:''' Once you set up your ''package.json'' file, you can automatically add a dependency to it by using the ''--save'' argument on ''npm install'': &amp;lt;code&amp;gt;npm install --save socket.io&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 7]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Pong_Game&amp;diff=1869</id>
		<title>Pong Game</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Pong_Game&amp;diff=1869"/>
		<updated>2015-02-20T04:10:57Z</updated>

		<summary type="html">&lt;p&gt;Shane: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This article documents ''pong-game.js'', a pre-built JavaScript file that helps you implement your pong game.&lt;br /&gt;
&lt;br /&gt;
== Setup ==&lt;br /&gt;
&lt;br /&gt;
First thing first: set up a static file server running Node.JS.  We will need it in order to serve up our HTML and JavaScript content.&lt;br /&gt;
&lt;br /&gt;
=== File 1: pong-game.js ===&lt;br /&gt;
&lt;br /&gt;
The first file you can save in your ''static'' directory will be ''pong-game.js'', which you can download from here: http://classes.engineering.wustl.edu/cse330/content/pong-game.js&lt;br /&gt;
&lt;br /&gt;
We created the ''pong-game.js'' file for you to save you time and so that you can focus on the Node.JS and Socket.IO aspects of this module.  This file contains the core Pong engine, but it does ''not'' establish communication between users of any kind.&lt;br /&gt;
&lt;br /&gt;
=== File 2: client.js ===&lt;br /&gt;
&lt;br /&gt;
You should create an additional file, ''client.js'', which you include into ''client.html'' and which contains the client-side logic for your Pong game.  It should load after ''pong-game.js''.  You will be saving all of you client-side code in this file.&lt;br /&gt;
&lt;br /&gt;
=== File 3: client.html ===&lt;br /&gt;
&lt;br /&gt;
The third file you can save in your ''static'' directory should be an HTML file created from your favorite [[HTML and CSS#Quick and Easy Page Layout|Quick and Easy Page Layout]].  You need to add the following CSS rules:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;css&amp;quot;&amp;gt;&lt;br /&gt;
#gameContainer{&lt;br /&gt;
	margin: 0 auto;&lt;br /&gt;
	width: 960px;&lt;br /&gt;
	height: 500px;&lt;br /&gt;
}&lt;br /&gt;
#controls{&lt;br /&gt;
	height: 20px;&lt;br /&gt;
	text-align: center;&lt;br /&gt;
}&lt;br /&gt;
#game{&lt;br /&gt;
	width: 960px;&lt;br /&gt;
	height: 480px;&lt;br /&gt;
	border: 1px solid black;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Add the following HTML inside your ''main'' div; this is what will contain the Pong game canvas:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;div id=&amp;quot;gameContainer&amp;quot; style=&amp;quot;display:none;&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;div id=&amp;quot;game&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You also need to require ''pong-game.js'' and ''client.js''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;script src=&amp;quot;pong-game.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;script src=&amp;quot;client.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Connecting to Socket.IO ===&lt;br /&gt;
&lt;br /&gt;
Now that you have your static fileserver running that serves up your three files (''pong-game.js'', ''client.html'', and ''client.js''), we need to connect everything with Socket.IO.&lt;br /&gt;
&lt;br /&gt;
Set up a static fileserver by following the instructions in [[Node.JS|the Node.JS guide]].  When finished, add the following lines:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var io = socketio.listen(app);&lt;br /&gt;
io.sockets.on(&amp;quot;connection&amp;quot;, function(socket){&lt;br /&gt;
	// This closure runs when a new Socket.IO connection is established.&lt;br /&gt;
	&lt;br /&gt;
	// Listen for client messaging server:&lt;br /&gt;
	socket.on(&amp;quot;message&amp;quot;, function(content){&lt;br /&gt;
		// do stuff&lt;br /&gt;
	});&lt;br /&gt;
	&lt;br /&gt;
	// Send a message from the server to the client:&lt;br /&gt;
	socket.emit(&amp;quot;message&amp;quot;, {some:&amp;quot;data&amp;quot;});&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Don't forget to require socket.io at the top of your file!&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
socketio = require(&amp;quot;socket.io&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You also need to make sure to install ''socket.io'' from npm.&lt;br /&gt;
&lt;br /&gt;
Inside of the ''io.listen'' callback function is where most of your server-side code will go.&lt;br /&gt;
&lt;br /&gt;
On the client side, you need to include the Socket.IO library (put this above ''pong-game.js'' and ''client.js''):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&amp;lt;script src=&amp;quot;/socket.io/socket.io.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And finally, you need to connect your client to the Socket.IO server (put this in ''client.js''):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;var socket = io.connect(window.location.origin);&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
But enough of us giving you all the code!  It's time for you to start being creative.&lt;br /&gt;
&lt;br /&gt;
== The API ==&lt;br /&gt;
&lt;br /&gt;
For the remainder of this module, your work will be in three files:&lt;br /&gt;
&lt;br /&gt;
* app.js (or whatever you called your Node.JS file)&lt;br /&gt;
* client.html&lt;br /&gt;
* client.js&lt;br /&gt;
&lt;br /&gt;
What you need to do is to build a system that enables two players who are both viewing ''client.html'' to choose each other (e.g., from a lobby) and play a game of Pong.&lt;br /&gt;
&lt;br /&gt;
You should be wondering, &amp;quot;how do I interact with the Pong game?&amp;quot;  The public interface is as follows.&lt;br /&gt;
&lt;br /&gt;
=== Methods ===&lt;br /&gt;
&lt;br /&gt;
* '''pong.init()'''&lt;br /&gt;
*: Initialize the game client.&lt;br /&gt;
* '''pong.resetBall([x, y])'''&lt;br /&gt;
*: Arbitrarily set the position of the ball.  Defaults to the center if no arguments are given.  Cancels all animations currently acting on the ball.&lt;br /&gt;
* '''pong.launch(angle, direction)'''&lt;br /&gt;
*: Launch the ball ''from its current position'' in the specified ''angle'' (-89 to +89) and direction (-1 for left or 1 for right).&lt;br /&gt;
* '''pong.updateOpponentPaddle(position)'''&lt;br /&gt;
*: Set the position of the opponent paddle to ''position''.  (Hint: the ''position'' value should have been generated by the opponent's '''paddlemove''' event)&lt;br /&gt;
* '''pong.pauseOrResumeGame()'''&lt;br /&gt;
*: Set the game in a paused state, or remove the game from a paused state.&lt;br /&gt;
* '''pong.ready()'''&lt;br /&gt;
*: Returns true if the game is not in a &amp;quot;paused&amp;quot; state.&lt;br /&gt;
* '''pong.setScore(score)'''&lt;br /&gt;
*: Display score on the game canvas.  ''score'' is an object literal containing two fields: left and right.&lt;br /&gt;
&lt;br /&gt;
=== Events ===&lt;br /&gt;
&lt;br /&gt;
All events for the pong game are fired on the window.&lt;br /&gt;
&lt;br /&gt;
* '''paddlemove'''&lt;br /&gt;
*: The player's paddle has moved.&lt;br /&gt;
*: This event will fire only after the paddle has moved 15 pixels or more.&lt;br /&gt;
** '''event.detail.position'''&lt;br /&gt;
**: The new y coordinate of the paddle.&lt;br /&gt;
* '''paddlehit-left'''&lt;br /&gt;
*: The ball has hit the left side of the screen.&lt;br /&gt;
** '''event.detail.hit'''&lt;br /&gt;
**: True if the ball hit the player's paddle; false otherwise.&lt;br /&gt;
** '''event.detail.angle'''&lt;br /&gt;
**: If the ball was reflected, the new angle of the ball's rightward movement.&lt;br /&gt;
** '''event.detail.position'''&lt;br /&gt;
**: The position at which the ball hit the left side.&lt;br /&gt;
&lt;br /&gt;
=== Problems with Our Interface ===&lt;br /&gt;
&lt;br /&gt;
There are at least two major problematic issues with our API:&lt;br /&gt;
&lt;br /&gt;
* We are firing events on the window.  We should have taken the time to make our Pong class implement the EventTarget interface directly.&lt;br /&gt;
* We are putting more trust in the client than we should, because the client can fake any angle and position upon the '''paddlehit-left''' event and manipulate the game in his or her favor.  The trajectory should be computed on the Node.JS side.&lt;br /&gt;
&lt;br /&gt;
Just be aware of the above issues as you complete this lab.  You won't be required to fix them, although if you do (and if you recompile your modified code with Lime) you may be a candidate for extra credit.&lt;br /&gt;
&lt;br /&gt;
=== Enabling a Player to Pause ===&lt;br /&gt;
&lt;br /&gt;
''You do not need to implement pausing for the purposes of Module 7.  If you do, you can earn 5 points of creative portion.''&lt;br /&gt;
&lt;br /&gt;
Implementing a game pause is more difficult for a network game than it is for a game that runs on just one computer: you need to make sure that the game is in a state such that you won't run into any race conditions, etc.&lt;br /&gt;
&lt;br /&gt;
One situation during a Pong game when it makes sense to enable a user to pause the game is after a user has lost a round.  Since the game at that point in time is waiting for the player to launch the next ball, we shouldn't have any race conditions.&lt;br /&gt;
&lt;br /&gt;
If you implement pausing, the '''pong.pauseOrResumeGame()''' and '''pong.ready()''' functions will come in handy.&lt;br /&gt;
&lt;br /&gt;
== Examples ==&lt;br /&gt;
&lt;br /&gt;
=== Starting a Pong Game ===&lt;br /&gt;
&lt;br /&gt;
Once two players have formed a pair, one of them needs to initialize the game with a certain angle and direction for the ball.  Here is how you might go about doing this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// generate an initial angle between -60 degrees and +60 degrees:&lt;br /&gt;
var initAngle = -60 + 120*Math.random();&lt;br /&gt;
&lt;br /&gt;
// randomly choose the initial direction of the ball:&lt;br /&gt;
var initDirection = Math.random() &amp;lt; 0.5 ? -1 : 1;&lt;br /&gt;
&lt;br /&gt;
// show the game canvas:&lt;br /&gt;
document.getElementById(&amp;quot;gameContainer&amp;quot;).style.display = &amp;quot;block&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
// initialize the game canvas:&lt;br /&gt;
pong.init();&lt;br /&gt;
&lt;br /&gt;
// move the ball to the center:&lt;br /&gt;
pong.resetBall();&lt;br /&gt;
&lt;br /&gt;
// set the ball into motion:&lt;br /&gt;
pong.launch(initAngle, initDirection);&lt;br /&gt;
&lt;br /&gt;
// tell the server about the ball's initial angle and direction.  For example:&lt;br /&gt;
socket.emit(&amp;quot;launch&amp;quot;, {&lt;br /&gt;
	angle: initAngle,&lt;br /&gt;
	direction: initDirection&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== When a Player Reflects the Ball ===&lt;br /&gt;
&lt;br /&gt;
When the ball hits a player's side, the '''paddlehit-left''' event fires on the window.  Here is how you might listen for this event in your ''client.js'' and transmit this information over your socket:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
window.addEventListener(&amp;quot;paddlehit-left&amp;quot;, function(e){&lt;br /&gt;
	// e.detail.hit will be true if the client hit the ball with his/her paddle.&lt;br /&gt;
	if (e.detail.hit) {&lt;br /&gt;
		console.log(&amp;quot;HIT PADDLE.  New angle: %f&amp;quot;, e.detail.angle); // log a message to the console&lt;br /&gt;
		&lt;br /&gt;
		// Tell our opponent via Socket.IO about the ball's new angle and position:&lt;br /&gt;
		socket.emit(&amp;quot;reflect&amp;quot;, {&lt;br /&gt;
			angle: e.detail.angle,&lt;br /&gt;
			position: e.detail.position&lt;br /&gt;
		});&lt;br /&gt;
		&lt;br /&gt;
		// Note: The game automatically launches the ball and determines the angle based on the ball's position relative to the paddle position.  We therefore do not need to call pong.launch() in here (but our opponent will, as shown below).&lt;br /&gt;
	}else{&lt;br /&gt;
		console.log(&amp;quot;MISSED PADDLE&amp;quot;);&lt;br /&gt;
		&lt;br /&gt;
		// in here, we will update the score, check for victory condition, launch a new ball (perhaps after a timeout), etc.&lt;br /&gt;
	}&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is what you might have in ''app.js'' inside of your Socket.IO callback function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Listen for the &amp;quot;reflect&amp;quot; message from the client&lt;br /&gt;
socket.on(&amp;quot;reflect&amp;quot;, function(data){&lt;br /&gt;
	// Tell our opponent about the reflection.&lt;br /&gt;
	// Note: In this sample implementation, we store the opponent in `socket.opponent`.&lt;br /&gt;
	// You might use a different mechanism for storing the opponent's socket.&lt;br /&gt;
	socket.opponent.emit(&amp;quot;reflect&amp;quot;, data);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, here is what you might have on the opponent's end (hint: this is also in ''client.js''):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Listen for the &amp;quot;reflect&amp;quot; message from the server&lt;br /&gt;
socket.on(&amp;quot;reflect&amp;quot;, function(data){&lt;br /&gt;
	// In order to make up for any network lag, immediately move the ball to its correct position:&lt;br /&gt;
	pong.resetBall(960, data.position);&lt;br /&gt;
	&lt;br /&gt;
	// Finally, launch the ball on our local game client:&lt;br /&gt;
	pong.launch(data.angle, -1);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Flow Chart ==&lt;br /&gt;
&lt;br /&gt;
If you are a visual learner, this flow chart of the logic you need to build for the pong game might be useful.&lt;br /&gt;
&lt;br /&gt;
[[File:Module 7 Flow Chart.png]]&lt;br /&gt;
&lt;br /&gt;
== How We Built pong-game.js ==&lt;br /&gt;
&lt;br /&gt;
If you are curious, we used the [http://www.limejs.com/ LimeJS] framework as the backbone of ''pong-game.js''.  You can find the pre-compiled source code for the Pong game here:&lt;br /&gt;
&lt;br /&gt;
* http://classes.engineering.wustl.edu/cse330/content/pong.js&lt;br /&gt;
* http://classes.engineering.wustl.edu/cse330/content/ball.js&lt;br /&gt;
&lt;br /&gt;
We then used the [https://developers.google.com/closure/compiler/ Google Closure Compiler] to compile all of the libraries you need into the one modular JavaScript file.&lt;br /&gt;
&lt;br /&gt;
Just to be clear, ''for the purposes of Module 7, you do not need to bother with either LimeJS or Google Closure.''&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 7]]&lt;br /&gt;
[[Category:Former Content]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Web_Application_Security,_Part_2&amp;diff=1866</id>
		<title>Web Application Security, Part 2</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Web_Application_Security,_Part_2&amp;diff=1866"/>
		<updated>2015-02-14T03:27:21Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* Abuse of Functionality */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This is Part 2 of the Web Application Security article, geared toward the material covered in [[Module 3]].  For material covered in [[Module 2]] (HTML, CSS, and PHP), see [[Web Application Security, Part 1]]. For material covered in [[Module 6]] (JavaScript), see [[Web Application Security, Part 3]].&lt;br /&gt;
&lt;br /&gt;
== Password Security ==&lt;br /&gt;
&lt;br /&gt;
Let's assume for a moment that despite all of your efforts in the other fronts of web security, an attacker was still able to extract information from your database.  If you store your passwords as plain text, not only will the attacker be able to log in as whomever he chooses, but the attacker will ''also'' likely be able to log in as the users of your site on different sites (since many users employ the same password on several different web sites).&lt;br /&gt;
&lt;br /&gt;
=== Encryption ===&lt;br /&gt;
&lt;br /&gt;
The types of encryption and encryption algorithms is a whole class to itself.&lt;br /&gt;
&lt;br /&gt;
In CSE330 and future web application development, you should always use '''one-way encryption''' to encrypt your passwords.  What this means is that you feed a string of text (a password) to an encryption function, and that encryption function returns another string of text that is a ''digest'' of the password.  It is impossible to mathematically convert a digest back to its associated password, but encrypting the same password will always yield the same digest.&lt;br /&gt;
&lt;br /&gt;
One-way encryption algorithms can also be ''salted''.  What this means is that the string to be encrypted is modified by a ''salt'' before the encryption occurs.  The same salt and the same password will always yield the same digest.  Using a salted hashing algorithm is preferable to a non-salted hashing algorithm for passwords because although digests cannot be reversed, non-salted digests can be looked up in a rainbow table.&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
So, the solution is to store salted, one-way-encrypted passwords in your database.  PHP provides the [http://php.net/crypt crypt()] function to do this for you.&lt;br /&gt;
&lt;br /&gt;
How does it work?  ''crypt()'' is an automagical function that both generates a random salt and tests for password integrity.  Let's look at a few examples.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
&lt;br /&gt;
echo crypt(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
/*&lt;br /&gt;
 * The above line prints, for example:   $1$WQvMDFgI$5.mVOS7V2Q/aB78Mxl13Q1&lt;br /&gt;
 * This line is of the format:   $1$random-salt$crypted-password&lt;br /&gt;
 */&lt;br /&gt;
&lt;br /&gt;
echo crypt(&amp;quot;Hello World&amp;quot;, '$1$WQvMDFgI$5.mVOS7V2Q/aB78Mxl13Q1');&lt;br /&gt;
/*&lt;br /&gt;
 * The above line prints:   $1$WQvMDFgI$5.mVOS7V2Q/aB78Mxl13Q1&lt;br /&gt;
 * This is the same as the salt-hash string we passed as the second argument.&lt;br /&gt;
 */&lt;br /&gt;
&lt;br /&gt;
echo crypt(&amp;quot;Goodbye World&amp;quot;, '$1$WQvMDFgI$5.mVOS7V2Q/aB78Mxl13Q1');&lt;br /&gt;
/*&lt;br /&gt;
 * The above line prints:   $1$WQvMDFgI$1REUkR026Ttck17Sfzp.V/&lt;br /&gt;
 * Note that this is NOT the same as when we pass the real password to crypt.&lt;br /&gt;
 */&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As you can see form the above example, '''crypt() generates a string that contains ''both'' a random salt ''and'' the hashed password.'''  You can store the constant-length value in a CHAR field in your database, and then have just one field for both the password and the salt.&lt;br /&gt;
&lt;br /&gt;
=== Example ===&lt;br /&gt;
&lt;br /&gt;
Here is an example of what you might do on your login page.  '''''Note:'' This example assumes that you salted the user's password already and stored it in the database.'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
// This is a *good* example of how you can implement password-based user authentication in your web application.&lt;br /&gt;
&lt;br /&gt;
require 'database.php';&lt;br /&gt;
&lt;br /&gt;
// Use a prepared statement&lt;br /&gt;
$stmt = $mysqli-&amp;gt;prepare(&amp;quot;SELECT COUNT(*), id, crypted_password FROM users WHERE username=?&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
// Bind the parameter&lt;br /&gt;
$stmt-&amp;gt;bind_param('s', $user);&lt;br /&gt;
$user = $_POST['username'];&lt;br /&gt;
$stmt-&amp;gt;execute();&lt;br /&gt;
&lt;br /&gt;
// Bind the results&lt;br /&gt;
$stmt-&amp;gt;bind_result($cnt, $user_id, $pwd_hash);&lt;br /&gt;
$stmt-&amp;gt;fetch();&lt;br /&gt;
&lt;br /&gt;
$pwd_guess = $_POST['password'];&lt;br /&gt;
// Compare the submitted password to the actual password hash&lt;br /&gt;
if( $cnt == 1 &amp;amp;&amp;amp; crypt($pwd_guess, $pwd_hash)==$pwd_hash){&lt;br /&gt;
	// Login succeeded!&lt;br /&gt;
	$_SESSION['user_id'] = $user_id;&lt;br /&gt;
	// Redirect to your target page&lt;br /&gt;
}else{&lt;br /&gt;
	// Login failed; redirect back to the login screen&lt;br /&gt;
}&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' You may sometimes see functions like vanilla [http://php.net/md5 md5()] used to encrypt passwords.  md5() does indeed perform one-way encryption, but it does so without a salt.  '''THIS IS BAD PRACTICE''', because unsalted md5 hashes can be trivially reversed using a rainbow table.  (Just Google for &amp;quot;md5 decrypter&amp;quot;.)  Using a salt prevents the effective use of a rainbow table.&lt;br /&gt;
&lt;br /&gt;
=== OpenID ===&lt;br /&gt;
&lt;br /&gt;
One other solution that will solve ''all'' issues related to password security is to not have passwords at all.  This can be achieved using [[wikipedia:OpenID|OpenID]], which allows end users to use their accounts from other sites (e.g. Google, Yahoo, and Twitter) to authenticate on your site.  Not only does this make your life easier in the security realm, but it also eliminates the need for password recovery, etc.&lt;br /&gt;
&lt;br /&gt;
There are many PHP libraries available for OpenID authentication; one such library is the creatively named [http://pear.php.net/package/OpenID OpenID], which you can install using [[PHP#PEAR|PEAR]].  You will need to install some other packages first, some from yum (if using RHEL) and some from pear.  (If you don't install them, PEAR will yell at you.)  These are the commands you need to run in order to install the correct packages (make sure you understand what they do before running them):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ sudo yum install php-mbstring php-bcmath   # not necessary on Debian&lt;br /&gt;
$ sudo apachectl graceful   # restart Apache&lt;br /&gt;
$ sudo pear install Crypt_DiffieHellman-0.2.6 Validate-0.8.5 Services_Yadis-0.5.1 OpenID-0.3.3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here's an example implementation that uses the PEAR package.&lt;br /&gt;
&lt;br /&gt;
'''Login Page:'''&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;form action=&amp;quot;process_openid.php&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;input id=&amp;quot;start&amp;quot; name=&amp;quot;start&amp;quot; type=&amp;quot;hidden&amp;quot; value=&amp;quot;true&amp;quot; /&amp;gt;&lt;br /&gt;
	&amp;lt;fieldset&amp;gt;&lt;br /&gt;
		&amp;lt;legend&amp;gt;Sign in using OpenID&amp;lt;/legend&amp;gt;&lt;br /&gt;
		&amp;lt;div id=&amp;quot;openid_choice&amp;quot;&amp;gt;&lt;br /&gt;
			&amp;lt;p&amp;gt;Please select your account provider:&amp;lt;/p&amp;gt;&lt;br /&gt;
			&amp;lt;select name=&amp;quot;identifier&amp;quot;&amp;gt;&lt;br /&gt;
				&amp;lt;option value=&amp;quot;https://www.google.com/accounts/o8/id&amp;quot;&amp;gt;Google&amp;lt;/option&amp;gt;&lt;br /&gt;
				&amp;lt;option value=&amp;quot;http://yahoo.com/&amp;quot;&amp;gt;Yahoo&amp;lt;/option&amp;gt;&lt;br /&gt;
			&amp;lt;/select&amp;gt;&lt;br /&gt;
		&amp;lt;/div&amp;gt;&lt;br /&gt;
		&amp;lt;p&amp;gt;&lt;br /&gt;
			&amp;lt;input type=&amp;quot;submit&amp;quot; value=&amp;quot;Sign In&amp;quot;/&amp;gt;&lt;br /&gt;
		&amp;lt;/p&amp;gt;&lt;br /&gt;
	&amp;lt;/fieldset&amp;gt;&lt;br /&gt;
&amp;lt;/form&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''process_openid.php:'''&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
require_once 'OpenID/RelyingParty.php';&lt;br /&gt;
require_once 'OpenID/Message.php';&lt;br /&gt;
require_once 'Net/URL2.php';&lt;br /&gt;
&lt;br /&gt;
session_start();&lt;br /&gt;
&lt;br /&gt;
$realm = &amp;quot;http://www.yoursite.com/&amp;quot;;&lt;br /&gt;
$returnTo = $realm . &amp;quot;path/to/process_openid.php&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
$identifier = @$_POST['identifier'] ?: @$_SESSION['identifier'] ?: null; // note: the @ signs suppress &amp;quot;undefined&amp;quot; notices&lt;br /&gt;
&lt;br /&gt;
$o = new OpenID_RelyingParty($returnTo, $realm, $identifier);&lt;br /&gt;
&lt;br /&gt;
// Part 1: We are processing a login request before visiting the OpenID provider&lt;br /&gt;
if(@$_POST['start']) {&lt;br /&gt;
	$authRequest = $o-&amp;gt;prepare();&lt;br /&gt;
	$url = $authRequest-&amp;gt;getAuthorizeURL();&lt;br /&gt;
	&lt;br /&gt;
	header(&amp;quot;Location: &amp;quot;.$url);&lt;br /&gt;
	exit;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// Part 2: The user is returning to our site after visiting the OpenID provider's site&lt;br /&gt;
else {&lt;br /&gt;
	$usid = @$_SESSION['identifier'] ?: null;&lt;br /&gt;
	unset($_SESSION['identifier']);&lt;br /&gt;
&lt;br /&gt;
	$queryString = count($_POST) ? file_get_contents('php://input') : $_SERVER['QUERY_STRING'];&lt;br /&gt;
	&lt;br /&gt;
	$message = new OpenID_Message($queryString, OpenID_Message::FORMAT_HTTP);&lt;br /&gt;
&lt;br /&gt;
	$result = $o-&amp;gt;verify(new Net_URL2($returnTo . '?' . $queryString), $message);&lt;br /&gt;
	&lt;br /&gt;
	if($result-&amp;gt;success()){&lt;br /&gt;
		// Login Success!&lt;br /&gt;
		&lt;br /&gt;
		// Get the OpenID identifier, which is unique to every OpenID user (i.e. you can use it in your database to&lt;br /&gt;
		// keep track of people between logins), and save it in the session:&lt;br /&gt;
		$_SESSION[&amp;quot;openid.identity&amp;quot;] = $message-&amp;gt;get(&amp;quot;openid.identity&amp;quot;);&lt;br /&gt;
		&lt;br /&gt;
		// Now redirect to the target page for logged-in users&lt;br /&gt;
	}else{&lt;br /&gt;
		// Login Failed.  You can redirect back to the login page or whatever&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:'''  OpenID is by nature a secure form of authentication for a web application; the fact that government agencies like the GSA use OpenID helps attest to this.  However, OpenID remains vulnerable to man-in-the-middle, content-spoofing attacks.  If you are writing a high-profile application using OpenID, it is therefore recommended that you establish an SSL (https) connection to your OpenID providers to help prevent phishing.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' You may use OpenID for modules 4 and higher, but you must implement your own authentication system for module 3.&lt;br /&gt;
&lt;br /&gt;
=== Real-Life Examples ===&lt;br /&gt;
&lt;br /&gt;
Here is a constantly-updated list of sites that do not use proper password security: http://plaintextoffenders.com/&lt;br /&gt;
&lt;br /&gt;
== Cross-Site Request Forgery ==&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=3IOKaIRg8V4&lt;br /&gt;
|time=3m45s&lt;br /&gt;
|desc=Cross Site Request Forgeries&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
A cross-site request forgery (CSRF, pronounced ''sea-surf'') involves a victim, who is logged in to the targeted site, visiting an attacker’s site.  The attacker has code on his site that forces the victim to unwittingly perform actions on the targeted site.&lt;br /&gt;
&lt;br /&gt;
For example, suppose Mother Goose visited Dr. Evil's blog.  Dr. Evil had the following tag embedded in his bloc:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&amp;lt;img src=&amp;quot;http://www.bank.com/transfer.php?dest=dr-evil&amp;amp;amp;amount=5000&amp;quot; /&amp;gt;&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This would cause Mother Goose to authorize a $5000 transfer to Dr. Evil, completely without Mother Goose's knowledge!&lt;br /&gt;
&lt;br /&gt;
Worse yet, Dr. Evil could just send an e-mail to Mother Goose with this image tag.  All Mother Goose would need to do to be attacked is open the e-mail!  (Now you know why sometimes your e-mail client turns off images from suspicious sources.)&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
The first precautionary measure is to always use POST requests (as opposed to GET requests) for actions that change something on your server.  This will fend off all except the most hard-core CSRF attacks.&lt;br /&gt;
&lt;br /&gt;
However, fully preventing CSRF attacks is not difficult.  To do this, you can use a '''CSRF token'''.  A CSRF token is a known string of text that is submitted in all of the forms on your site.  If the string is not what you expect, then you can assume that the request was forged.&lt;br /&gt;
&lt;br /&gt;
For example, consider this form:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;form action=&amp;quot;transfer.php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;dest&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;input type=&amp;quot;number&amp;quot; name=&amp;quot;amount&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;input type=&amp;quot;submit&amp;quot; value=&amp;quot;Transfer&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;/form&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We can easily add a hidden CSRF token field like so (as well as making the form POST rather than GET):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;form action=&amp;quot;transfer.php&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;dest&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;input type=&amp;quot;number&amp;quot; name=&amp;quot;amount&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;token&amp;quot; value=&amp;quot;&amp;lt;?php echo $_SESSION['token'];?&amp;gt;&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;input type=&amp;quot;submit&amp;quot; value=&amp;quot;Transfer&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;/form&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''This assumes that &amp;lt;code&amp;gt;$_SESSION['token']&amp;lt;/code&amp;gt; contains an alphanumeric string that was randomly generated upon session creation.'''  For example, you could add this line ''beneath beneath where the user successfully authenticates'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
$_SESSION['token'] = substr(md5(rand()), 0, 10); // generate a 10-character random string&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We can now test for validity of the CSRF token on the server side (in transfer.php):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
$destination_username = $_POST['dest'];&lt;br /&gt;
$amount = $_POST['amount'];&lt;br /&gt;
if($_SESSION['token'] !== $_POST['token']){&lt;br /&gt;
	die(&amp;quot;Request forgery detected&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
$mysqli-&amp;gt;query(/* perform transfer */);&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now, if Mother Goose were to view a page containing the malicious &amp;lt;img/&amp;gt; tag, the transfer would not take place.&lt;br /&gt;
&lt;br /&gt;
=== Real-Life Examples ===&lt;br /&gt;
&lt;br /&gt;
* [http://www.zdnet.com/no-data-breach-in-first-weibo-attack-2062301014/ Weibo, June 2011]&lt;br /&gt;
* [http://www.huffingtonpost.com/huff-wires/20110601/us-tec-google-hacking-attack/ Gmail, June 2011]&lt;br /&gt;
* [http://www.pcworld.com/businesscenter/article/228609/hackers_steal_hotmail_messages_thanks_to_web_flaw.html Hotmail, May 2011]&lt;br /&gt;
* [http://www.theregister.co.uk/2010/05/19/facebook_private_data_leak/ Facebook, May 2010]&lt;br /&gt;
&lt;br /&gt;
== SQL Injection ==&lt;br /&gt;
&lt;br /&gt;
[[File:Exploits of a mom.png]]&lt;br /&gt;
&lt;br /&gt;
SQL injection occurs when an attacker submits specially-crafted input into your server, which is then included in an SQL query.  The input modifies the query to perform additional actions on the database or to access unwanted information.&lt;br /&gt;
&lt;br /&gt;
For instance, suppose you had the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
require 'database.php';&lt;br /&gt;
&lt;br /&gt;
/* DISCLAIMER: THIS CODE IS BAD IN MANY MORE WAYS THAN JUST&lt;br /&gt;
BEING VULNERABLE TO SQL INJECTION! IT IS FOR DEMONSTRATION OF&lt;br /&gt;
CONCEPT ONLY. DO NOT USE THIS CODE IN YOUR OWN PROJECTS! */&lt;br /&gt;
&lt;br /&gt;
$res = $mysqli-&amp;gt;query(&amp;quot;SELECT id FROM users WHERE username='&amp;quot;.$_POST['username'].&amp;quot;' AND password='&amp;quot;.$_POST['password'].&amp;quot;'&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
if( $res-&amp;gt;num_rows==1 ){&lt;br /&gt;
    $row = $res-&amp;gt;fetch_assoc();&lt;br /&gt;
    $_SESSION['user_id'] = $row[&amp;quot;id&amp;quot;];&lt;br /&gt;
}else{&lt;br /&gt;
    echo &amp;quot;Login failed.&amp;quot;;&lt;br /&gt;
    exit;&lt;br /&gt;
}&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This code is vulnerable to SQL injection.  For example, suppose the attacker used the following string of text for his username:&lt;br /&gt;
&lt;br /&gt;
 mother-goose' --&lt;br /&gt;
&lt;br /&gt;
Here's what the resulting query would look like:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;mysql&amp;quot;&amp;gt;&lt;br /&gt;
SELECT id FROM users WHERE username='mother-goose' --' AND password=''&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Since &amp;lt;code&amp;gt;--&amp;lt;/code&amp;gt; is the start of a comment in SQL, when MySQL interprets this query, it will ''completely ignore'' the password-checking part of the query!  Dr. Evil can log in using anyone's username and steal all of their money!&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
If you write your queries manually (as in the example above), you need to use &amp;lt;code&amp;gt;$mysqli-&amp;gt;real_escape_string()&amp;lt;/code&amp;gt; to sanitize your input:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
$safe_username = $mysqli-&amp;gt;real_escape_string($_POST['username']);&lt;br /&gt;
// ...&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, the better solution is to use prepared queries.  For more information on prepared queries, see [[PHP and MySQL]].&lt;br /&gt;
&lt;br /&gt;
'''IMPORTANT:''' If you correctly use the sample code in the PHP and MySQL guide above, you are already safe from SQL injection attacks.&lt;br /&gt;
&lt;br /&gt;
=== Real-Life Examples ===&lt;br /&gt;
&lt;br /&gt;
* [http://www.zdnet.com/unknowns-hack-european-space-agency-4010026071/ European Space Agency, May 2012]&lt;br /&gt;
* [http://www.dutchnews.nl/news/archives/2012/04/new_online_medical_records_sca.php Dutch Department Stores, April 2012]&lt;br /&gt;
* [http://www.msnbc.msn.com/id/46735808/ns/technology_and_science-security/ Ancestry.com, March 2012]&lt;br /&gt;
* [http://www.scmagazine.com.au/News/292592,allphones-hacked-staff-passwords-exposed.aspx Allphones (Australian Telecommunications Retailer), March 2012]&lt;br /&gt;
* [http://www.abc4.com/content/news/slc/story/More-fallout-Salt-Lake-City-police-website-hacked/PiSspE768UiioitJ3K4gyQ.cspx Salt Lake City Police Department, February 2012]&lt;br /&gt;
&lt;br /&gt;
== Abuse of Functionality ==&lt;br /&gt;
&lt;br /&gt;
''Abuse of Functionality'' is a general term that refers to when an attacker exploits vulnerabilities in the logic of your application.&lt;br /&gt;
&lt;br /&gt;
For example, suppose you were a banking site, and you had the following code to perform a transaction:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
require 'database.php';&lt;br /&gt;
&lt;br /&gt;
$amount = (double) $_POST['amount'];&lt;br /&gt;
$destination_username = $mysqli-&amp;gt;real_escape_string($_POST['destination']);&lt;br /&gt;
&lt;br /&gt;
$mysqli-&amp;gt;autocommit(false); // start transaction&lt;br /&gt;
$mysqli-&amp;gt;query(&amp;quot;UPDATE users SET balance=balance-&amp;quot;.$amount.&amp;quot;&lt;br /&gt;
	WHERE id=&amp;quot;.$_SESSION['user_id']);&lt;br /&gt;
$mysqli-&amp;gt;query(&amp;quot;UPDATE users SET balance=balance+&amp;quot;.$amount.&amp;quot;&lt;br /&gt;
	WHERE username='&amp;quot;.$destination_username.&amp;quot;'&amp;quot;);&lt;br /&gt;
$mysqli-&amp;gt;commit(); // commit transaction&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It may not be obvious, but if you don't filter your input, it is trivial for an attacker to ''insert a negative number'' into the &amp;quot;amount&amp;quot; field and transfer money from anyone's account to his account!  The solution here is to simply filter amount for what you expect (in this case, a positive number that is not greater than the user's current balance).&lt;br /&gt;
&lt;br /&gt;
=== Filtering on the Client Side is Never Enough ===&lt;br /&gt;
&lt;br /&gt;
Suppose you have an e-mail field in a form in HTML, and you use some JavaScript function (or HTML5) to check it for form as an e-mail address:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;email&amp;quot; onchange=&amp;quot;checkEmail(this);&amp;quot; /&amp;gt; &amp;lt;!-- HTML versions ≤ XHTML 1.0 --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;input type=&amp;quot;email&amp;quot; name=&amp;quot;email&amp;quot; /&amp;gt; &amp;lt;!-- HTML versions ≥ 5 --&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
With this filter in place, any layperson using your form is now required to submit an e-mail address in that field.  ''However'', it is trivial for an attacker to bypass this client-side filtering (e.g., by using web developer tools like Firebug) and still submit non-email text to your server.  This is why '''IT IS ESSENTIAL THAT YOU FILTER INPUT ON THE SERVER SIDE!  Any sort of filtering on the client side are just bells and whistles for the end user.'''&lt;br /&gt;
&lt;br /&gt;
=== Information Leakage ===&lt;br /&gt;
&lt;br /&gt;
''Information Leakage'' is a noteworthy type of ''Abuse of Functionality'' attack that involves unprivileged users accessing privileged information.  In fact, Information Leakage accounts for a significant percentage of all recorded web application vulnerabilities (second only to Cross-Site Scripting).&lt;br /&gt;
&lt;br /&gt;
The concept is relatively simple.  Suppose you have an administration page that loads an image containing a graph of all activity on your site:&lt;br /&gt;
&lt;br /&gt;
'''admin.php'''&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
if($_SESSION['admin']) echo '&amp;lt;img src=&amp;quot;stats.php?day=2012-08-19&amp;quot; alt=&amp;quot;Stats for 2012-08-19&amp;quot; /&amp;gt;';&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''stats.php'''&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
// query the database, and save the results in $result&lt;br /&gt;
&lt;br /&gt;
$im = new PNGraph();&lt;br /&gt;
$im-&amp;gt;takeData($result);&lt;br /&gt;
&lt;br /&gt;
header(&amp;quot;Content-Type: image/png&amp;quot;);&lt;br /&gt;
print $im-&amp;gt;toString();&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice how you check for admin credentials in ''admin.php''.  However, you forgot to do this in ''stats.php'' itself.  An attacker could simply load ''stats.php'' directly to see all of the sensitive admin-only information!&lt;br /&gt;
&lt;br /&gt;
==== Solution ====&lt;br /&gt;
&lt;br /&gt;
Information Leakage is an attack that requires the developer to see the big picture and really keep track of what's going on in his or her application.  As a rule of thumb, ''whenever'' you query the database to access sensitive information, check the permissions of the user first.&lt;br /&gt;
&lt;br /&gt;
=== A Note about Frameworks ===&lt;br /&gt;
&lt;br /&gt;
Web frameworks are designed to make web development more agile, but they in turn have security weaknesses of their own.  For instance, the infamous ''mass-assignment vulnerability'' in Ruby on Rails-type MVC frameworks is an abuse of functionality vulnerability that enables attackers to save arbitrary information in your database (!).&lt;br /&gt;
&lt;br /&gt;
The important thing to know is that '''if you use a web framework, be familiar with the security considerations with that framework'''.  Most of the time, frameworks will have articles on their web sites that discuss these concerns.  (If your framework doesn't have a guide like this, you should probably be using a different framework!)&lt;br /&gt;
&lt;br /&gt;
=== Real-Life Examples ===&lt;br /&gt;
&lt;br /&gt;
* [http://gizmodo.com/some-guy-figured-out-how-to-delete-every-photo-on-faceb-1685491356 Facebook, February 2015 (bypassing authorization on REST API calls)]&lt;br /&gt;
* [http://www.whitec0de.com/new-hotmail-exploit-can-get-any-hotmail-email-account-hacked-for-just-20/ Hotmail, April 2012 (parameter manipulation)]&lt;br /&gt;
* [http://www.theregister.co.uk/2012/04/18/toshiba_slapped_by_ico/ Toshiba, April 2012 (parameter manipulation / information leakage)]&lt;br /&gt;
* [http://www.zdnet.com/blog/security/3-million-bank-accounts-hacked-in-iran/11577 Iranian Banks, April 2012 (information leakage)]&lt;br /&gt;
* [http://www.zdnet.com/blog/security/hacker-steals-chinese-government-defense-contracts/11386 Chinese Department of Defense, April 2012 (information leakage)]&lt;br /&gt;
* [http://articles.chicagotribune.com/2012-04-04/news/sns-rt-us-usa-hackers-utahbre83404g-20120404_1_data-security-breach-cyber-attack-hackers Utah Medicaid, April 2012]&lt;br /&gt;
&lt;br /&gt;
== CAPTCHA Abuse ==&lt;br /&gt;
&lt;br /&gt;
CAPTCHAs are a great way to stop robots from submitting forms in your web application.  However, depending on how you implement CAPTCHAs, it might be possible for a hacker to bypass the CAPTCHA on your site.&lt;br /&gt;
&lt;br /&gt;
For example, suppose you are making a home-grown CAPTCHA system for your application.  You have a table '''CaptchaTable''' with the following fields: '''id''' and '''value'''.  Your form looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;form action=&amp;quot;signup.php&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;strong&amp;gt;Subscribe to our newsletter&amp;lt;/strong&amp;gt;&lt;br /&gt;
	&amp;lt;input type=&amp;quot;email&amp;quot; name=&amp;quot;email&amp;quot; placeholder=&amp;quot;Enter Your Email Here&amp;quot; /&amp;gt;&lt;br /&gt;
	&amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;captcha_value&amp;quot; placeholder=&amp;quot;Type what you see in the CAPTCHA below.&amp;quot; /&amp;gt;&lt;br /&gt;
	&amp;lt;img src=&amp;quot;captcha.php?id=12345&amp;quot; /&amp;gt;&lt;br /&gt;
	&amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;captcha_id&amp;quot; value=&amp;quot;12345&amp;quot; /&amp;gt;&lt;br /&gt;
	&amp;lt;input type=&amp;quot;submit&amp;quot; value=&amp;quot;Sign Up&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;/form&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here's what the code on ''signup.php'' might look like:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
$email = $_POST[&amp;quot;email&amp;quot;];&lt;br /&gt;
$captcha_id = (int) $_POST[&amp;quot;captcha_id&amp;quot;];&lt;br /&gt;
$captcha_value = $_POST[&amp;quot;captcha_value&amp;quot;];&lt;br /&gt;
&lt;br /&gt;
// check CAPTCHA&lt;br /&gt;
&lt;br /&gt;
$captcha_stmt = $mysqli-&amp;gt;prepare(&amp;quot;select count(*) as match from CaptchaTable where id=? and value=?&amp;quot;);&lt;br /&gt;
$captcha_stmt-&amp;gt;bind_param(&amp;quot;is&amp;quot;, $captcha_id, $captcha_value);&lt;br /&gt;
$captcha_stmt-&amp;gt;execute();&lt;br /&gt;
$captcha_row = (int) $captcha_stmt-&amp;gt;fetch_assoc();&lt;br /&gt;
$captcha_stmt-&amp;gt;close();&lt;br /&gt;
&lt;br /&gt;
if ($captcha_row[&amp;quot;match&amp;quot;] == 0){&lt;br /&gt;
	http_response_code(403);&lt;br /&gt;
	echo &amp;quot;Invalid CAPTCHA&amp;quot;;&lt;br /&gt;
	exit;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// continue with signup procedure down here&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The issue here is that a hacker can simply solve one CAPTCHA and then send that CAPTCHA ID and Value over and over again!&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
If you already have a home-grown CAPTCHA system, the best solution here would be to simply issue another query to the database that deletes a CAPTCHA id-value pair as soon as it is submitted in a form.&lt;br /&gt;
&lt;br /&gt;
If you haven't yet implemented your CAPTCHA system, you might want to consider a third-party solution like [http://www.google.com/recaptcha reCAPTCHA].&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 3]]&lt;br /&gt;
[[Category:Web Application Security]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=1856</id>
		<title>JavaScript</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=1856"/>
		<updated>2015-01-09T10:24:56Z</updated>

		<summary type="html">&lt;p&gt;Shane: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;JavaScript is the most widely used scripting language for implementing client-side functionality in Web applications.  Unlike PHP, JavaScript code is interpreted and executed in a client's web browser (not on the web server).&lt;br /&gt;
&lt;br /&gt;
== JavaScript?  Did you mean Java? ==&lt;br /&gt;
&lt;br /&gt;
'''JavaScript''' is a prototype-based programming language focussed on web interactivity.  It was first introduced in Netscape Navigator, and it in turn gave rise to what is now '''[http://www.ecmascript.org/ ECMAScript]'''.  Originally, JavaScript was called &amp;quot;LiveScript&amp;quot;.  Sun, the developer of Java at the time, wanted a language that would complement its compiled Java language, and so LiveScript was renamed JavaScript.&lt;br /&gt;
&lt;br /&gt;
Beyond that, '''Java and JavaScript are as similar as Ham and Hamster.'''&lt;br /&gt;
&lt;br /&gt;
Java and JavaScript have similar syntax, but the under workings are quite different.  For example, Java requires strict typing, but JavaScript allows for dynamic typing.  Java is object-oriented, but JavaScript is prototype-oriented.  Java is compiled, but JavaScript is interpreted.  Java supports event listeners, but JavaScript makes them a fundamental part of the language.  Java variables are scoped to the innermost method or loop, but JavaScript variables are scoped only to the innermost function.&lt;br /&gt;
&lt;br /&gt;
== JavaScript Language Components ==&lt;br /&gt;
&lt;br /&gt;
This section highlights some features of the JavaScript language that differentiate it from other languages.  For a more comprehensive JavaScript tutorial, the following tutorials are both quality:&lt;br /&gt;
&lt;br /&gt;
* [http://docs.webplatform.org/wiki/javascript WebPlatform]: Great for learning JavaScript for the first time.  Advocates best practices for modern JavaScript development.&lt;br /&gt;
* [http://www.quirksmode.org/js/contents.html QuirksMode]: More advanced than the WebPlatform tutorial, but it thoroughly covers the most powerful aspects of pure JavaScript and gives unparalleled advice on browser compatibility.&lt;br /&gt;
&lt;br /&gt;
Advice: Do '''NOT''' Google for &amp;quot;JavaScript Tutorial&amp;quot;.  The first few hits advocate bad or outdated practices.  Stick with the ones listed here.&lt;br /&gt;
&lt;br /&gt;
=== Variables and Scope ===&lt;br /&gt;
&lt;br /&gt;
To define a variable in JavaScript, use the '''var''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var foo = &amp;quot;bar&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
All variables are objects.  In the case above, the variable '''foo''' is an object of the class '''String'''.&lt;br /&gt;
&lt;br /&gt;
Notice that like PHP, you do not have to explicitly define a type for a variable like '''int''' or '''String'''; this is because JavaScript and PHP are ''dynamically typed languages''.&lt;br /&gt;
&lt;br /&gt;
JavaScript code can access any variable higher in the “function tree”, but not vice-versa.  This is called '''scope'''.  ''All functions create their own scope.''&lt;br /&gt;
&lt;br /&gt;
When you reference a variable, JavaScript will look up through the &amp;quot;function tree&amp;quot; until it finds the variable you asked for.  This means that you could define variables of the same name as global variables inside of functions.  For demonstration of concept:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var a = &amp;quot;hello&amp;quot;;&lt;br /&gt;
var b = &amp;quot;world&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
function sayGoodByeWorld(){&lt;br /&gt;
	var a = &amp;quot;goodbye&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
	alert(a); // goodbye&lt;br /&gt;
	alert(b); // world&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayGoodByeWorld();&lt;br /&gt;
&lt;br /&gt;
alert(a); // hello&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object Literals ===&lt;br /&gt;
&lt;br /&gt;
A very common way of storing and transporting data in JavaScript is by using objects.  You can define an object with certain properties using an '''object literal''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = {&lt;br /&gt;
	color: &amp;quot;red&amp;quot;,&lt;br /&gt;
	flavor: &amp;quot;sweet&amp;quot;,&lt;br /&gt;
	season: &amp;quot;autumn&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(apple.color);  // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
To define a function in JavaScript, use the '''function''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function sayHello(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(); // call the function&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Pass an argument to a function like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function sayHello(name){&lt;br /&gt;
	alert(&amp;quot;Hello, &amp;quot;+name);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(&amp;quot;Todd&amp;quot;); // call the function and pass an argument&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Functions are Objects ====&lt;br /&gt;
&lt;br /&gt;
In JavaScript, functions are objects.  This means that they can be assigned to variables, manipulated on the fly, and even passed as arguments to other functions!  '''''This is an extremely important feature of JavaScript''''' that makes it such a robust language for web development.&lt;br /&gt;
&lt;br /&gt;
You create a function variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayHello = function(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(); // call the function&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Observe that you can make [[#Variables and Scope|scope-dependent]] functions in this way.&lt;br /&gt;
&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=HaPlj796ngQ&lt;br /&gt;
|time=5m45s&lt;br /&gt;
|desc=JavaScript Closures&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
A '''closure''' is a way to separate a certain snippet of JavaScript code from the global scope.  This is useful if you do not want to &amp;quot;muck up&amp;quot; global variables.  Closures are nothing more than anonymous functions that are called as soon as they are created:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
​var a = &amp;quot;hello&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
(​​​​function(){&lt;br /&gt;
	var b = &amp;quot;world&amp;quot;;&lt;br /&gt;
	&lt;br /&gt;
	alert(a); // hello&lt;br /&gt;
	alert(b); // world&lt;br /&gt;
})();&lt;br /&gt;
&lt;br /&gt;
alert(a); // hello&lt;br /&gt;
alert(b);​ // ReferenceError: b is not defined​​​​​​​​​​​​​​​&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Passing Variables to a Closure&lt;br /&gt;
|desc=This example demonstrates how you can &amp;quot;save&amp;quot; previous versions of a variable using closures.  This is possible because of scoping and the fact that function variables can be returned as objects.&lt;br /&gt;
|fiddle_id=YURqa&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Most JavaScript libraries (like jQuery) write all of their code in a closure.  What this means is that except for one or two variable names (jQuery or $), everything associated with the library is completely self-contained.&lt;br /&gt;
&lt;br /&gt;
=== Prototypal Inheritance ===&lt;br /&gt;
&lt;br /&gt;
JavaScript implements '''prototypal inheritance''', as opposed to a language like Java or C++, which implements '''classical inheritance'''.  JavaScript is one of only a handful of languages implementing prototype-based inheritance.&lt;br /&gt;
&lt;br /&gt;
Here's how it works.  Every callable object (function) has a '''prototype'''.  When instances of that object are created, their properties and methods are copied (inherited) from the prototype.  Additionally, changes made to the prototype later in the program are &amp;quot;copied&amp;quot; to every instance.&lt;br /&gt;
&lt;br /&gt;
For example, if you wanted to make a method on all strings that added a “!”, you could modify String’s prototype:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
String.prototype.bang = function(){&lt;br /&gt;
	return this+&amp;quot;!&amp;quot;; // Notice: the context is the instance itself&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(&amp;quot;Hello&amp;quot;.bang()); // alerts Hello!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To &amp;quot;extend&amp;quot; an object, just copy its prototype to a new object.  However, since classical inheritance and prototypal inheritance are different concepts, copying prototypes may have results that you don't expect.  [http://beej.us/blog/data/javascript-prototypes-inheritance/ This article] seems to have a pretty good explanation with example implementations.&lt;br /&gt;
&lt;br /&gt;
=== Context ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=0a4r4bm1nQA&lt;br /&gt;
|time=4m32s&lt;br /&gt;
|desc=The ''this'' Variable in JavaScript&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Every function is called on a certain object, which is not necessarily the same object in which it was defined.  This is called '''context'''.&lt;br /&gt;
&lt;br /&gt;
To call a function on an arbitrary context, use either '''call''' or '''apply'''.  ''call'' takes a list of arguments, while ''apply'' takes them all in an array.&lt;br /&gt;
&lt;br /&gt;
To access the current context, use the '''this''' keyword.  Demonstration of concept:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayThisColor = function(){&lt;br /&gt;
	alert(this.color);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
var apple = { color: &amp;quot;red&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
sayThisColor();   // undefined&lt;br /&gt;
sayThisColor.call(apple); // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Events ==&lt;br /&gt;
&lt;br /&gt;
Events are really what make JavaScript such a powerful language for web development.&lt;br /&gt;
&lt;br /&gt;
Rather than being thread based, JavaScript is event based.  Since all JavaScript code runs in a single thread, '''there are no concurrency issues'''.  When an event occurs, JavaScript automatically calls the ''event callback'' as soon as all previous events' callbacks have finished executing.&lt;br /&gt;
&lt;br /&gt;
Code in the form of a '''callback function''' is associated with events via a '''listener'''.  For example, the following JavaScript causes ''sayHello()'' (the callback function) to be run whenever the button with ID &amp;quot;hello&amp;quot; is clicked (the event):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayHello = function(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
document.getElementById(&amp;quot;hello&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, sayHello, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Binding Callbacks to a Button Click&lt;br /&gt;
|fiddle_id=L8c4Z&lt;br /&gt;
|cse330=true&lt;br /&gt;
|desc=In this example, notice how we bind the callback function when the ''DOMContentLoaded'' event fires.  This is because JavaScript requires that the button has been parsed by the browser before it can add event listeners to it.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The '''addEventListener''' method takes three parameters:&lt;br /&gt;
* The event type&lt;br /&gt;
* The callback function&lt;br /&gt;
*: The callback function is passed one parameter: the event object.&lt;br /&gt;
* A boolean representing bubble (false) or capture (true) phase&lt;br /&gt;
*: You usually want Bubble phase.  For more information on event phase, see [[#Event Phase]]&lt;br /&gt;
&lt;br /&gt;
Note that versions of Internet Explorer prior to version 9 required that you use a different, albeit similar, function for assigning event listeners called '''attachEvent'''.  attachEvent takes the same arguments as addEventListener, except you need to put '''on''' before the event type (e.g. &amp;quot;onclick&amp;quot;), and the third argument (phase) is not necessary.&lt;br /&gt;
&lt;br /&gt;
It is perfectly valid to use an '''anonymous function''' as your callback function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;hello&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, function(event){&lt;br /&gt;
	alert(&amp;quot;Hello, World!  Event Type: &amp;quot;+event.type);&lt;br /&gt;
}, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QuirksMode has perhaps the best series of articles about the ins and outs of JavaScript events on the internet: http://www.quirksmode.org/js/contents.html#events&lt;br /&gt;
&lt;br /&gt;
=== The Event Object ===&lt;br /&gt;
&lt;br /&gt;
Callback functions are passed one argument: an ''event object''.  You see above that one property of the event object is ''event.type''.  To see the full list of properties of the event object, you could run the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;my_btn&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, function(event){&lt;br /&gt;
	var strout = &amp;quot;&amp;quot;;&lt;br /&gt;
	for(var i in event){&lt;br /&gt;
		strout += i + &amp;quot;: &amp;quot; + event[i] + &amp;quot;\n&amp;quot;;&lt;br /&gt;
	}&lt;br /&gt;
	console.log(strout);&lt;br /&gt;
}, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some of the most useful properties and methods include:&lt;br /&gt;
* '''event.target''' references the object on which the event occurred.&lt;br /&gt;
* '''event.currentTarget''' references the object whose listener is currently being processed.&lt;br /&gt;
*: ''Note:'' event.target and event.currentTarget might be the same or might be different, depending on whether you are listening for bubbled events.&lt;br /&gt;
* '''event.preventDefault()''' stops the normal result of the event from being executed.  For example, if you listen for a form's ''submit'' event, you can call event.preventDefault() to stop the form from being submitted.&lt;br /&gt;
* '''event.stopPropagation()''' prevents any other event listeners from being executed.  For more detail, read the section on Event Phase below.&lt;br /&gt;
&lt;br /&gt;
For more detail on the event object, see [http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html#interface-Event the W3C specification].&lt;br /&gt;
&lt;br /&gt;
'''Note:''' If your callback function does not take any parameters, it will still run; you just won't have as easy of access to the event object.&lt;br /&gt;
&lt;br /&gt;
=== Event Handlers and Memory Management ===&lt;br /&gt;
&lt;br /&gt;
JavaScript is an automatically garbage-collected language, meaning that memory management is mostly taken care of for you.  However, there are some instances when you need to be careful about creating &amp;quot;zombie&amp;quot; objects.  In JavaScript, this mostly revolves around the idea of event listeners.&lt;br /&gt;
&lt;br /&gt;
I could give an explanatory example, but instead I'll tell you straightaway that '''the moral of the story is that for every &amp;quot;addEventListener&amp;quot;, there should probably be a &amp;quot;removeEventListener&amp;quot;.'''  Here are some good articles to satisfy your hunger for more details on event listeners and JavaScript memory management:&lt;br /&gt;
&lt;br /&gt;
* http://www.vladalexandruionescu.com/2012/08/javascript-memory-leaks.html&lt;br /&gt;
* http://lostechies.com/derickbailey/2012/03/19/backbone-js-and-javascript-garbage-collection/&lt;br /&gt;
* http://stackoverflow.com/questions/5326300/garbage-collection-with-node-js&lt;br /&gt;
&lt;br /&gt;
When you start working with Node.JS in the next module, it's more important than ever to keep good accounting of your event listeners.&lt;br /&gt;
&lt;br /&gt;
=== Event Phase ===&lt;br /&gt;
&lt;br /&gt;
In JavaScript, events occur in two phases: '''Capture Phase''' and '''Bubble Phase'''.  Consider the following HTML document:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&amp;lt;title&amp;gt;Event Test&amp;lt;/title&amp;gt;&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
  &amp;lt;div id=&amp;quot;box&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;button id=&amp;quot;btn&amp;quot;&amp;gt;&lt;br /&gt;
      Hello&lt;br /&gt;
    &amp;lt;/button&amp;gt;&lt;br /&gt;
  &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Suppose the user clicks on the &amp;quot;Hello&amp;quot; button.  Events will be fired in the following order:&lt;br /&gt;
&lt;br /&gt;
# Capture Phase CLICK on the Document&lt;br /&gt;
# Capture Phase CLICK on the Body&lt;br /&gt;
# Capture Phase CLICK on the Div#box&lt;br /&gt;
# Target Phase CLICK on the Button#btn&lt;br /&gt;
# Bubble Phase CLICK on the Div#box&lt;br /&gt;
# Bubble Phase CLICK on the Body&lt;br /&gt;
# Bubble Phase CLICK on the Document&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Using Capture Phase to Enable or Disable a Toolbar&lt;br /&gt;
|fiddle_id=r32Dz&lt;br /&gt;
|desc=We bind an event in the capture phase to the div with ID ''toolbar''.  When ''e.stopPropagation()'' is called, the event does not reach the buttons in the toolbar.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Graphically, here is the order in which an event occurs in three generic nested elements:&lt;br /&gt;
&lt;br /&gt;
[[File:EventPhase.gif]]&lt;br /&gt;
&lt;br /&gt;
Why is this useful?  Suppose you have a control panel (toolbar, etc) that you want to temporarily deactivate.  (For example, Bold/Italic/Underline buttons on a graphic text editor that currently has no content.)  You could keep bubble phase event listeners on your buttons, but prevent those events from occurring by stopping the event in the capture phase on the parent element before the event reaches your buttons!  Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var disableToolbarFunc = function(e){&lt;br /&gt;
	e.stopPropogation();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// To disable toolbar:&lt;br /&gt;
document.getElementById(&amp;quot;box&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, disableToolbarFunc, true);&lt;br /&gt;
&lt;br /&gt;
// To re-enable toolbar:&lt;br /&gt;
document.getElementById(&amp;quot;box&amp;quot;).removeEventListener(&amp;quot;click&amp;quot;, disableToolbarFunc, true);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Word of caution:''' Like many great things in web development, capture phase does not work in versions of Internet Explorer prior to version 9.  There is no elegant substitution for older versions of Internet Explorer.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' When the event reaches the innermost element, there is no distinction between capture phase and bubble phase.  The order in which event handlers were added to the element determines the order in which those callbacks are evaluated.&lt;br /&gt;
&lt;br /&gt;
== Document Object Model ==&lt;br /&gt;
&lt;br /&gt;
The '''Document Object Model (DOM)'''  is what enables JavaScript to manipulate the content of your web page.&lt;br /&gt;
&lt;br /&gt;
=== Nodes and Traversing the DOM ===&lt;br /&gt;
&lt;br /&gt;
Each element on your page, whether it is a &amp;lt;nowiki&amp;gt;&amp;lt;p&amp;gt;, &amp;lt;img/&amp;gt;&amp;lt;/nowiki&amp;gt;, a string of text, or even an attribute, is called a '''node'''.&lt;br /&gt;
&lt;br /&gt;
Every node, except for the document itself, has exactly one parent.  A single node may have multiple children.&lt;br /&gt;
&lt;br /&gt;
Consider the following HTML code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;ul id=&amp;quot;my-list&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;fruits&amp;quot;&amp;gt;Apples&amp;lt;/li&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;citrus&amp;quot;&amp;gt;Oranges and &amp;lt;strong&amp;gt;Lemons&amp;lt;/strong&amp;gt;&amp;lt;/li&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;berries&amp;quot;&amp;gt;Cherries&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ul&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, the ul with ID &amp;quot;my-list&amp;quot; has three child '''element nodes''' (the three li's) as well as four child '''text nodes''' (the whitespace counts as a text node) and a child '''attribute node'''.  The second LI has one child '''text node''' as well as one child '''element node''' and one child '''attribute node'''.&lt;br /&gt;
&lt;br /&gt;
The DOM can be traversed in JavaScript.  First, let's look at an example.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
e = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;citrus&amp;quot;)[0].lastChild.nodeName;&lt;br /&gt;
alert(e);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Currently Selected Radio Button&lt;br /&gt;
|fiddle_id=SHcng&lt;br /&gt;
|desc=In pure JavaScript, in order to determine the currently selected radio button, it is necessary to iterate over an array of pointers to all possible radio buttons, and stop when you find one that is &amp;quot;checked&amp;quot;.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The above snippet gets the element with class name '''citrus''' that is a child of the element with ID '''my-list''' (the second LI in the example above), and alerts the type of its second child node (which in this case is '''STRONG''').&lt;br /&gt;
&lt;br /&gt;
Some common methods for traversing the DOM include:&lt;br /&gt;
&lt;br /&gt;
* Node.parentNode&lt;br /&gt;
* Node.childNodes - returns an array of nodes&lt;br /&gt;
* Node.firstChild - same as Node.childNodes[0]&lt;br /&gt;
* Node.lastChild - same as Node.childNodes[Node.childNodes.length-1]&lt;br /&gt;
* Node.previousSibling&lt;br /&gt;
* Node.nextSibling&lt;br /&gt;
&lt;br /&gt;
You can also search for child (including all descendants) using one of the following methods:&lt;br /&gt;
&lt;br /&gt;
* Node.getElementsByTagName(&amp;quot;tag-name&amp;quot;) - returns an array of element nodes having the tag name '''tag-name''' that are descendants of Node&lt;br /&gt;
* Node.getElementById(&amp;quot;id&amp;quot;) - returns a single node having the ID '''id''' that is a descendant of Node&lt;br /&gt;
* Node.getElementsByName(&amp;quot;what-name&amp;quot;) - returns an array of element nodes having their '''name''' attribute set to '''what-name'''.  Useful for radio buttons and other form elements.&lt;br /&gt;
* Node.getElementsByClassName(&amp;quot;class&amp;quot;) - returns an array of nodes having the class '''class'''&lt;br /&gt;
*: '''Note:''' As of October 2012, 82% of the browser market supports Node.getElementsByClassName ([http://caniuse.com/getelementsbyclassname more info]).  In order to support the other 18%, you need to either add your own getElementsByClassName to Node's prototype or use a JavaScript library like jQuery or MooTools.&lt;br /&gt;
&lt;br /&gt;
It is common in JavaScript to have long statements like the one in the example above, where you call methods on several objects in sequence.&lt;br /&gt;
&lt;br /&gt;
=== Creating, Moving, and Removing Nodes ===&lt;br /&gt;
&lt;br /&gt;
You will frequently find yourself wanting to modify the DOM.  JavaScript provides methods that help you do this.&lt;br /&gt;
&lt;br /&gt;
Consider the same HTML as above.  If you wanted to add another element to the list, you could use this code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var newLi = document.createElement(&amp;quot;li&amp;quot;);  // creates a node with the tag name li&lt;br /&gt;
newLi.appendChild(document.createTextNode(&amp;quot;Broccoli&amp;quot;));&lt;br /&gt;
newLi.setAttribute(&amp;quot;class&amp;quot;, &amp;quot;veggies&amp;quot;);&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).appendChild(newLi);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to remove the apples from the list, you could do:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;fruits&amp;quot;)[0];&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).removeChild(apple);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to move the apples to the end of the list, you could do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;fruits&amp;quot;)[0];&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).appendChild(apple);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that '''Node.append()''' both removes a node from its previous location ''and'' appends it to its new location, which is always going to be as the last child of the parent node.&lt;br /&gt;
&lt;br /&gt;
In summary, here are the methods to know from this section:&lt;br /&gt;
&lt;br /&gt;
* Node.append(otherNode) - removes otherNode from its current location in the DOM (if applicable) and then adds it as the last child of Node&lt;br /&gt;
* Node.removeChild(otherNode) - removes otherNode, a child of Node, from the DOM&lt;br /&gt;
* document.createElement(&amp;quot;tag-name&amp;quot;) - create a new node with the tag name &amp;quot;tag-name&amp;quot;&lt;br /&gt;
* document.createTextNode(&amp;quot;text&amp;quot;) - create a node containing only the string '''text'''&lt;br /&gt;
* Node.setAttribute(&amp;quot;attribute&amp;quot;, &amp;quot;value&amp;quot;) - sets the attribute node of name &amp;quot;attribute&amp;quot; to &amp;quot;value&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=== DOM Shortcuts ===&lt;br /&gt;
&lt;br /&gt;
In the above sections, we have been creating, reading, modifying, and deleting Nodes.  This is the most &amp;quot;correct&amp;quot; way to change the content of a web page from inside JavaScript.&lt;br /&gt;
&lt;br /&gt;
This section documents a few shortcuts that are not as &amp;quot;pure&amp;quot; as using Nodes but can be less confusing and cumbersome.&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Displaying Information&lt;br /&gt;
|fiddle_id=Q3BPZ&lt;br /&gt;
|desc=This example shows how to use some of the shortcut methods for using JavaScript to display information on the page.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
==== textContent ====&lt;br /&gt;
&lt;br /&gt;
Using textContent to display information is probably the easiest method out there.  For example, the following code overwrites whatever is in the element with ID &amp;quot;holder&amp;quot; with the string &amp;quot;Hello World&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).textContent = &amp;quot;Hello World&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to instead append the text, simply use '''+=''' instead of '''=''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).textContent += &amp;quot; -  Later, he said Hello World  - &amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that textContent displays strings literally; that is, it does not allow for HTML.  Setting the textContent property also removes any HTML that may have already been in that element.&lt;br /&gt;
&lt;br /&gt;
==== innerHTML ====&lt;br /&gt;
&lt;br /&gt;
If you need to use HTML in your output but don't want to use the method described earlier in this section, a straightforward strategy is to use the innerHTML property of an element. For example, the following code would add a paragraph saying &amp;quot;Hello World&amp;quot; to the element with ID &amp;quot;holder&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).innerHTML += &amp;quot;&amp;lt;p&amp;gt;Hello World&amp;lt;/p&amp;gt;&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Important:''' You need to be careful to prevent XSS-type attacks if you display information using innerHTML.  For example, be sure to escape a user-supplied string before appending it to innerHTML.&lt;br /&gt;
&lt;br /&gt;
=== JavaScript Inspectors ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=PKzrmbN-pMg&lt;br /&gt;
|time=4m13s&lt;br /&gt;
|desc=Using Firebug, WebKit Inspector, and IE Developer Tools&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Various browsers and browser plugins give you, the developer, tools to debug your code, inspect the DOM, and much more.  Using these tools is essential for an efficient workflow.&lt;br /&gt;
&lt;br /&gt;
* '''Firebug'''.  Firebug is a plugin for Firefox that is a toolkit full of web developer tools, one of which is a DOM inspector.  To inspect the DOM of a web page, simply open the Firebug window while viewing the web page.&lt;br /&gt;
* '''WebKit Inspector'''.  The WebKit Inspector, which is available in both Chrome and Safari, enables you to see the DOM tree and relationships between elements.  However, its DOM inspection tools are not as robust as those of Firebug.&lt;br /&gt;
* '''Opera Dragonfly'''.  The web browser Opera comes with a web developer toolkit similar to the WebKit Inspector called Dragonfly.  It is important that you test your sites in Opera, because although Opera has only a small fraction of the desktop browser market, it is second only to WebKit on the mobile market.  Opera also has extremely strong CSS support, so it is good for testing for bugs in your CSS.&lt;br /&gt;
&lt;br /&gt;
All of the above-mentioned tools enable you to look at the DOM of your web page and find what properties and methods are associated with each node.  This is helpful because if you have JavaScript that manipulates HTML elements, you cannot tell which properties are associated with which elements by looking at the source code alone.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 6]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=1855</id>
		<title>JavaScript</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=1855"/>
		<updated>2015-01-09T09:34:45Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* Event Handlers and Memory Management */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;JavaScript is the most widely used scripting language for implementing client-side functionality in Web applications.  Unlike PHP, JavaScript code is interpreted and executed in a client's web browser (not on the web server).&lt;br /&gt;
&lt;br /&gt;
== JavaScript?  Did you mean Java? ==&lt;br /&gt;
&lt;br /&gt;
'''JavaScript''' is a prototype-based programming language focussed on web interactivity.  It was first introduced in Netscape Navigator, and it in turn gave rise to what is now '''[http://www.ecmascript.org/ ECMAScript]'''.  Originally, JavaScript was called &amp;quot;LiveScript&amp;quot;.  Sun, the developer of Java at the time, wanted a language that would complement its compiled Java language, and so LiveScript was renamed JavaScript.&lt;br /&gt;
&lt;br /&gt;
Beyond that, '''Java and JavaScript are as similar as Ham and Hamster.'''&lt;br /&gt;
&lt;br /&gt;
Java and JavaScript have similar syntax, but the under workings are quite different.  For example, Java requires strict typing, but JavaScript allows for dynamic typing.  Java is object-oriented, but JavaScript is prototype-oriented.  Java is compiled, but JavaScript is interpreted.  Java supports event listeners, but JavaScript makes them a fundamental part of the language.  Java variables are scoped to the innermost method or loop, but JavaScript variables are scoped only to the innermost function.&lt;br /&gt;
&lt;br /&gt;
== JavaScript Language Components ==&lt;br /&gt;
&lt;br /&gt;
This section highlights some features of the JavaScript language that differentiate it from other languages.  For a more comprehensive JavaScript tutorial, the following tutorials are both quality:&lt;br /&gt;
&lt;br /&gt;
* [http://docs.webplatform.org/wiki/javascript WebPlatform]: Great for learning JavaScript for the first time.  Advocates best practices for modern JavaScript development.&lt;br /&gt;
* [http://www.quirksmode.org/js/contents.html QuirksMode]: More advanced than the WebPlatform tutorial, but it thoroughly covers the most powerful aspects of pure JavaScript and gives unparalleled advice on browser compatibility.&lt;br /&gt;
&lt;br /&gt;
Advice: Do '''NOT''' Google for &amp;quot;JavaScript Tutorial&amp;quot;.  The first few hits advocate bad or outdated practices.  Stick with the ones listed here.&lt;br /&gt;
&lt;br /&gt;
=== Variables and Scope ===&lt;br /&gt;
&lt;br /&gt;
To define a variable in JavaScript, use the '''var''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var foo = &amp;quot;bar&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
All variables are objects.  In the case above, the variable '''foo''' is an object of the class '''String'''.&lt;br /&gt;
&lt;br /&gt;
Notice that like PHP, you do not have to explicitly define a type for a variable like '''int''' or '''String'''; this is because JavaScript and PHP are ''dynamically typed languages''.&lt;br /&gt;
&lt;br /&gt;
JavaScript code can access any variable higher in the “function tree”, but not vice-versa.  This is called '''scope'''.  ''All functions create their own scope.''&lt;br /&gt;
&lt;br /&gt;
When you reference a variable, JavaScript will look up through the &amp;quot;function tree&amp;quot; until it finds the variable you asked for.  This means that you could define variables of the same name as global variables inside of functions.  For demonstration of concept:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var a = &amp;quot;hello&amp;quot;;&lt;br /&gt;
var b = &amp;quot;world&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
function sayGoodByeWorld(){&lt;br /&gt;
	var a = &amp;quot;goodbye&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
	alert(a); // goodbye&lt;br /&gt;
	alert(b); // world&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayGoodByeWorld();&lt;br /&gt;
&lt;br /&gt;
alert(a); // hello&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object Literals ===&lt;br /&gt;
&lt;br /&gt;
A very common way of storing and transporting data in JavaScript is by using objects.  You can define an object with certain properties using an '''object literal''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = {&lt;br /&gt;
	color: &amp;quot;red&amp;quot;,&lt;br /&gt;
	flavor: &amp;quot;sweet&amp;quot;,&lt;br /&gt;
	season: &amp;quot;autumn&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(apple.color);  // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
To define a function in JavaScript, use the '''function''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function sayHello(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(); // call the function&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Pass an argument to a function like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function sayHello(name){&lt;br /&gt;
	alert(&amp;quot;Hello, &amp;quot;+name);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(&amp;quot;Todd&amp;quot;); // call the function and pass an argument&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Functions are Objects ====&lt;br /&gt;
&lt;br /&gt;
In JavaScript, functions are objects.  This means that they can be assigned to variables, manipulated on the fly, and even passed as arguments to other functions!  '''''This is an extremely important feature of JavaScript''''' that makes it such a robust language for web development.&lt;br /&gt;
&lt;br /&gt;
You create a function variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayHello = function(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(); // call the function&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Observe that you can make [[#Variables and Scope|scope-dependent]] functions in this way.&lt;br /&gt;
&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=HaPlj796ngQ&lt;br /&gt;
|time=5m45s&lt;br /&gt;
|desc=JavaScript Closures&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
A '''closure''' is a way to separate a certain snippet of JavaScript code from the global scope.  This is useful if you do not want to &amp;quot;muck up&amp;quot; global variables.  Closures are nothing more than anonymous functions that are called as soon as they are created:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
​var a = &amp;quot;hello&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
(​​​​function(){&lt;br /&gt;
	var b = &amp;quot;world&amp;quot;;&lt;br /&gt;
	&lt;br /&gt;
	alert(a); // hello&lt;br /&gt;
	alert(b); // world&lt;br /&gt;
})();&lt;br /&gt;
&lt;br /&gt;
alert(a); // hello&lt;br /&gt;
alert(b);​ // ReferenceError: b is not defined​​​​​​​​​​​​​​​&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Passing Variables to a Closure&lt;br /&gt;
|desc=This example demonstrates how you can &amp;quot;save&amp;quot; previous versions of a variable using closures.  This is possible because of scoping and the fact that function variables can be returned as objects.&lt;br /&gt;
|fiddle_id=YURqa&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Most JavaScript libraries (like jQuery) write all of their code in a closure.  What this means is that except for one or two variable names (jQuery or $), everything associated with the library is completely self-contained.&lt;br /&gt;
&lt;br /&gt;
=== Prototypal Inheritance ===&lt;br /&gt;
&lt;br /&gt;
JavaScript implements '''prototypal inheritance''', as opposed to a language like Java or C++, which implements '''classical inheritance'''.  JavaScript is one of only a handful of languages implementing prototype-based inheritance.&lt;br /&gt;
&lt;br /&gt;
Here's how it works.  Every callable object (function) has a '''prototype'''.  When instances of that object are created, their properties and methods are copied (inherited) from the prototype.  Additionally, changes made to the prototype later in the program are &amp;quot;copied&amp;quot; to every instance.&lt;br /&gt;
&lt;br /&gt;
For example, if you wanted to make a method on all strings that added a “!”, you could modify String’s prototype:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
String.prototype.bang = function(){&lt;br /&gt;
	return this+&amp;quot;!&amp;quot;; // Notice: the context is the instance itself&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(&amp;quot;Hello&amp;quot;.bang()); // alerts Hello!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To &amp;quot;extend&amp;quot; an object, just copy its prototype to a new object.  However, since classical inheritance and prototypal inheritance are different concepts, copying prototypes may have results that you don't expect.  [http://beej.us/blog/data/javascript-prototypes-inheritance/ This article] seems to have a pretty good explanation with example implementations.&lt;br /&gt;
&lt;br /&gt;
=== Context ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=0a4r4bm1nQA&lt;br /&gt;
|time=4m32s&lt;br /&gt;
|desc=The ''this'' Variable in JavaScript&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Every function is called on a certain object, which is not necessarily the same object in which it was defined.  This is called '''context'''.&lt;br /&gt;
&lt;br /&gt;
To call a function on an arbitrary context, use either '''call''' or '''apply'''.  ''call'' takes a list of arguments, while ''apply'' takes them all in an array.&lt;br /&gt;
&lt;br /&gt;
To access the current context, use the '''this''' keyword.  Demonstration of concept:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayThisColor = function(){&lt;br /&gt;
	alert(this.color);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
var apple = { color: &amp;quot;red&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
sayThisColor();   // undefined&lt;br /&gt;
sayThisColor.call(apple); // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Events ==&lt;br /&gt;
&lt;br /&gt;
Events are really what make JavaScript such a powerful language for web development.&lt;br /&gt;
&lt;br /&gt;
Rather than being thread based, JavaScript is event based.  Since all JavaScript code runs in a single thread, '''there are no concurrency issues'''.  When an event occurs, JavaScript automatically calls the ''event callback'' as soon as all previous events' callbacks have finished executing.&lt;br /&gt;
&lt;br /&gt;
Code in the form of a '''callback function''' is associated with events via a '''listener'''.  For example, the following JavaScript causes ''sayHello()'' (the callback function) to be run whenever the button with ID &amp;quot;hello&amp;quot; is clicked (the event):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayHello = function(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
document.getElementById(&amp;quot;hello&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, sayHello, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Binding Callbacks to a Button Click&lt;br /&gt;
|fiddle_id=L8c4Z&lt;br /&gt;
|cse330=true&lt;br /&gt;
|desc=In this example, notice how we bind the callback function when the ''DOMContentLoaded'' event fires.  This is because JavaScript requires that the button has been parsed by the browser before it can add event listeners to it.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The '''addEventListener''' method takes three parameters:&lt;br /&gt;
* The event type&lt;br /&gt;
* The callback function&lt;br /&gt;
*: The callback function is passed one parameter: the event object.&lt;br /&gt;
* A boolean representing bubble (false) or capture (true) phase&lt;br /&gt;
*: You usually want Bubble phase.  For more information on event phase, see [[#Event Phase]]&lt;br /&gt;
&lt;br /&gt;
Note that versions of Internet Explorer prior to version 9 required that you use a different, albeit similar, function for assigning event listeners called '''attachEvent'''.  attachEvent takes the same arguments as addEventListener, except you need to put '''on''' before the event type (e.g. &amp;quot;onclick&amp;quot;), and the third argument (phase) is not necessary.&lt;br /&gt;
&lt;br /&gt;
It is perfectly valid to use an '''anonymous function''' as your callback function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;hello&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, function(event){&lt;br /&gt;
	alert(&amp;quot;Hello, World!  Event Type: &amp;quot;+event.type);&lt;br /&gt;
}, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QuirksMode has perhaps the best series of articles about the ins and outs of JavaScript events on the internet: http://www.quirksmode.org/js/contents.html#events&lt;br /&gt;
&lt;br /&gt;
=== The Event Object ===&lt;br /&gt;
&lt;br /&gt;
Callback functions are passed one argument: an ''event object''.  You see above that one property of the event object is ''event.type''.  To see the full list of properties of the event object, you could run the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;my_btn&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, function(event){&lt;br /&gt;
	var strout = &amp;quot;&amp;quot;;&lt;br /&gt;
	for(var i in event){&lt;br /&gt;
		strout += i + &amp;quot;: &amp;quot; + event[i] + &amp;quot;\n&amp;quot;;&lt;br /&gt;
	}&lt;br /&gt;
	console.log(strout);&lt;br /&gt;
}, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some of the most useful properties and methods include:&lt;br /&gt;
* '''event.target''' references the object on which the event occurred.&lt;br /&gt;
* '''event.currentTarget''' references the object whose listener is currently being processed.&lt;br /&gt;
*: ''Note:'' event.target and event.currentTarget might be the same or might be different, depending on whether you are listening for bubbled events.&lt;br /&gt;
* '''event.preventDefault()''' stops the normal result of the event from being executed.  For example, if you listen for a form's ''submit'' event, you can call event.preventDefault() to stop the form from being submitted.&lt;br /&gt;
* '''event.stopPropagation()''' prevents any other event listeners from being executed.  For more detail, read the section on Event Phase below.&lt;br /&gt;
&lt;br /&gt;
For more detail on the event object, see [http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html#interface-Event the W3C specification].&lt;br /&gt;
&lt;br /&gt;
'''Note:''' If your callback function does not take any parameters, it will still run; you just won't have as easy of access to the event object.&lt;br /&gt;
&lt;br /&gt;
=== Event Handlers and Memory Management ===&lt;br /&gt;
&lt;br /&gt;
JavaScript is an automatically garbage-collected language, meaning that memory management is mostly taken care of for you.  However, there are some instances when you need to be careful about creating &amp;quot;zombie&amp;quot; objects.  In JavaScript, this mostly revolves around the idea of event listeners.&lt;br /&gt;
&lt;br /&gt;
I could give an explanatory example, but instead I'll tell you straightaway that '''the moral of the story is that for every &amp;quot;addEventListener&amp;quot;, there should probably be a &amp;quot;removeEventListener&amp;quot;.'''  Here are some good articles to satisfy your hunger for more details on event listeners and JavaScript memory management:&lt;br /&gt;
&lt;br /&gt;
* http://www.vladalexandruionescu.com/2012/08/javascript-memory-leaks.html&lt;br /&gt;
* http://lostechies.com/derickbailey/2012/03/19/backbone-js-and-javascript-garbage-collection/&lt;br /&gt;
&lt;br /&gt;
When you start working with Node.JS in the next module, it's more important than ever to keep good accounting of your event listeners.&lt;br /&gt;
&lt;br /&gt;
=== Event Phase ===&lt;br /&gt;
&lt;br /&gt;
In JavaScript, events occur in two phases: '''Capture Phase''' and '''Bubble Phase'''.  Consider the following HTML document:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&amp;lt;title&amp;gt;Event Test&amp;lt;/title&amp;gt;&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
  &amp;lt;div id=&amp;quot;box&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;button id=&amp;quot;btn&amp;quot;&amp;gt;&lt;br /&gt;
      Hello&lt;br /&gt;
    &amp;lt;/button&amp;gt;&lt;br /&gt;
  &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Suppose the user clicks on the &amp;quot;Hello&amp;quot; button.  Events will be fired in the following order:&lt;br /&gt;
&lt;br /&gt;
# Capture Phase CLICK on the Document&lt;br /&gt;
# Capture Phase CLICK on the Body&lt;br /&gt;
# Capture Phase CLICK on the Div#box&lt;br /&gt;
# Target Phase CLICK on the Button#btn&lt;br /&gt;
# Bubble Phase CLICK on the Div#box&lt;br /&gt;
# Bubble Phase CLICK on the Body&lt;br /&gt;
# Bubble Phase CLICK on the Document&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Using Capture Phase to Enable or Disable a Toolbar&lt;br /&gt;
|fiddle_id=r32Dz&lt;br /&gt;
|desc=We bind an event in the capture phase to the div with ID ''toolbar''.  When ''e.stopPropagation()'' is called, the event does not reach the buttons in the toolbar.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Graphically, here is the order in which an event occurs in three generic nested elements:&lt;br /&gt;
&lt;br /&gt;
[[File:EventPhase.gif]]&lt;br /&gt;
&lt;br /&gt;
Why is this useful?  Suppose you have a control panel (toolbar, etc) that you want to temporarily deactivate.  (For example, Bold/Italic/Underline buttons on a graphic text editor that currently has no content.)  You could keep bubble phase event listeners on your buttons, but prevent those events from occurring by stopping the event in the capture phase on the parent element before the event reaches your buttons!  Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var disableToolbarFunc = function(e){&lt;br /&gt;
	e.stopPropogation();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// To disable toolbar:&lt;br /&gt;
document.getElementById(&amp;quot;box&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, disableToolbarFunc, true);&lt;br /&gt;
&lt;br /&gt;
// To re-enable toolbar:&lt;br /&gt;
document.getElementById(&amp;quot;box&amp;quot;).removeEventListener(&amp;quot;click&amp;quot;, disableToolbarFunc, true);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Word of caution:''' Like many great things in web development, capture phase does not work in versions of Internet Explorer prior to version 9.  There is no elegant substitution for older versions of Internet Explorer.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' When the event reaches the innermost element, there is no distinction between capture phase and bubble phase.  The order in which event handlers were added to the element determines the order in which those callbacks are evaluated.&lt;br /&gt;
&lt;br /&gt;
== Document Object Model ==&lt;br /&gt;
&lt;br /&gt;
The '''Document Object Model (DOM)'''  is what enables JavaScript to manipulate the content of your web page.&lt;br /&gt;
&lt;br /&gt;
=== Nodes and Traversing the DOM ===&lt;br /&gt;
&lt;br /&gt;
Each element on your page, whether it is a &amp;lt;nowiki&amp;gt;&amp;lt;p&amp;gt;, &amp;lt;img/&amp;gt;&amp;lt;/nowiki&amp;gt;, a string of text, or even an attribute, is called a '''node'''.&lt;br /&gt;
&lt;br /&gt;
Every node, except for the document itself, has exactly one parent.  A single node may have multiple children.&lt;br /&gt;
&lt;br /&gt;
Consider the following HTML code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;ul id=&amp;quot;my-list&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;fruits&amp;quot;&amp;gt;Apples&amp;lt;/li&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;citrus&amp;quot;&amp;gt;Oranges and &amp;lt;strong&amp;gt;Lemons&amp;lt;/strong&amp;gt;&amp;lt;/li&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;berries&amp;quot;&amp;gt;Cherries&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ul&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, the ul with ID &amp;quot;my-list&amp;quot; has three child '''element nodes''' (the three li's) as well as four child '''text nodes''' (the whitespace counts as a text node) and a child '''attribute node'''.  The second LI has one child '''text node''' as well as one child '''element node''' and one child '''attribute node'''.&lt;br /&gt;
&lt;br /&gt;
The DOM can be traversed in JavaScript.  First, let's look at an example.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
e = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;citrus&amp;quot;)[0].lastChild.nodeName;&lt;br /&gt;
alert(e);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Currently Selected Radio Button&lt;br /&gt;
|fiddle_id=SHcng&lt;br /&gt;
|desc=In pure JavaScript, in order to determine the currently selected radio button, it is necessary to iterate over an array of pointers to all possible radio buttons, and stop when you find one that is &amp;quot;checked&amp;quot;.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The above snippet gets the element with class name '''citrus''' that is a child of the element with ID '''my-list''' (the second LI in the example above), and alerts the type of its second child node (which in this case is '''STRONG''').&lt;br /&gt;
&lt;br /&gt;
Some common methods for traversing the DOM include:&lt;br /&gt;
&lt;br /&gt;
* Node.parentNode&lt;br /&gt;
* Node.childNodes - returns an array of nodes&lt;br /&gt;
* Node.firstChild - same as Node.childNodes[0]&lt;br /&gt;
* Node.lastChild - same as Node.childNodes[Node.childNodes.length-1]&lt;br /&gt;
* Node.previousSibling&lt;br /&gt;
* Node.nextSibling&lt;br /&gt;
&lt;br /&gt;
You can also search for child (including all descendants) using one of the following methods:&lt;br /&gt;
&lt;br /&gt;
* Node.getElementsByTagName(&amp;quot;tag-name&amp;quot;) - returns an array of element nodes having the tag name '''tag-name''' that are descendants of Node&lt;br /&gt;
* Node.getElementById(&amp;quot;id&amp;quot;) - returns a single node having the ID '''id''' that is a descendant of Node&lt;br /&gt;
* Node.getElementsByName(&amp;quot;what-name&amp;quot;) - returns an array of element nodes having their '''name''' attribute set to '''what-name'''.  Useful for radio buttons and other form elements.&lt;br /&gt;
* Node.getElementsByClassName(&amp;quot;class&amp;quot;) - returns an array of nodes having the class '''class'''&lt;br /&gt;
*: '''Note:''' As of October 2012, 82% of the browser market supports Node.getElementsByClassName ([http://caniuse.com/getelementsbyclassname more info]).  In order to support the other 18%, you need to either add your own getElementsByClassName to Node's prototype or use a JavaScript library like jQuery or MooTools.&lt;br /&gt;
&lt;br /&gt;
It is common in JavaScript to have long statements like the one in the example above, where you call methods on several objects in sequence.&lt;br /&gt;
&lt;br /&gt;
=== Creating, Moving, and Removing Nodes ===&lt;br /&gt;
&lt;br /&gt;
You will frequently find yourself wanting to modify the DOM.  JavaScript provides methods that help you do this.&lt;br /&gt;
&lt;br /&gt;
Consider the same HTML as above.  If you wanted to add another element to the list, you could use this code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var newLi = document.createElement(&amp;quot;li&amp;quot;);  // creates a node with the tag name li&lt;br /&gt;
newLi.appendChild(document.createTextNode(&amp;quot;Broccoli&amp;quot;));&lt;br /&gt;
newLi.setAttribute(&amp;quot;class&amp;quot;, &amp;quot;veggies&amp;quot;);&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).appendChild(newLi);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to remove the apples from the list, you could do:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;fruits&amp;quot;)[0];&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).removeChild(apple);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to move the apples to the end of the list, you could do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;fruits&amp;quot;)[0];&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).appendChild(apple);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that '''Node.append()''' both removes a node from its previous location ''and'' appends it to its new location, which is always going to be as the last child of the parent node.&lt;br /&gt;
&lt;br /&gt;
In summary, here are the methods to know from this section:&lt;br /&gt;
&lt;br /&gt;
* Node.append(otherNode) - removes otherNode from its current location in the DOM (if applicable) and then adds it as the last child of Node&lt;br /&gt;
* Node.removeChild(otherNode) - removes otherNode, a child of Node, from the DOM&lt;br /&gt;
* document.createElement(&amp;quot;tag-name&amp;quot;) - create a new node with the tag name &amp;quot;tag-name&amp;quot;&lt;br /&gt;
* document.createTextNode(&amp;quot;text&amp;quot;) - create a node containing only the string '''text'''&lt;br /&gt;
* Node.setAttribute(&amp;quot;attribute&amp;quot;, &amp;quot;value&amp;quot;) - sets the attribute node of name &amp;quot;attribute&amp;quot; to &amp;quot;value&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=== DOM Shortcuts ===&lt;br /&gt;
&lt;br /&gt;
In the above sections, we have been creating, reading, modifying, and deleting Nodes.  This is the most &amp;quot;correct&amp;quot; way to change the content of a web page from inside JavaScript.&lt;br /&gt;
&lt;br /&gt;
This section documents a few shortcuts that are not as &amp;quot;pure&amp;quot; as using Nodes but can be less confusing and cumbersome.&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Displaying Information&lt;br /&gt;
|fiddle_id=Q3BPZ&lt;br /&gt;
|desc=This example shows how to use some of the shortcut methods for using JavaScript to display information on the page.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
==== textContent ====&lt;br /&gt;
&lt;br /&gt;
Using textContent to display information is probably the easiest method out there.  For example, the following code overwrites whatever is in the element with ID &amp;quot;holder&amp;quot; with the string &amp;quot;Hello World&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).textContent = &amp;quot;Hello World&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to instead append the text, simply use '''+=''' instead of '''=''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).textContent += &amp;quot; -  Later, he said Hello World  - &amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that textContent displays strings literally; that is, it does not allow for HTML.  Setting the textContent property also removes any HTML that may have already been in that element.&lt;br /&gt;
&lt;br /&gt;
==== innerHTML ====&lt;br /&gt;
&lt;br /&gt;
If you need to use HTML in your output but don't want to use the method described earlier in this section, a straightforward strategy is to use the innerHTML property of an element. For example, the following code would add a paragraph saying &amp;quot;Hello World&amp;quot; to the element with ID &amp;quot;holder&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).innerHTML += &amp;quot;&amp;lt;p&amp;gt;Hello World&amp;lt;/p&amp;gt;&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Important:''' You need to be careful to prevent XSS-type attacks if you display information using innerHTML.  For example, be sure to escape a user-supplied string before appending it to innerHTML.&lt;br /&gt;
&lt;br /&gt;
=== JavaScript Inspectors ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=PKzrmbN-pMg&lt;br /&gt;
|time=4m13s&lt;br /&gt;
|desc=Using Firebug, WebKit Inspector, and IE Developer Tools&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Various browsers and browser plugins give you, the developer, tools to debug your code, inspect the DOM, and much more.  Using these tools is essential for an efficient workflow.&lt;br /&gt;
&lt;br /&gt;
* '''Firebug'''.  Firebug is a plugin for Firefox that is a toolkit full of web developer tools, one of which is a DOM inspector.  To inspect the DOM of a web page, simply open the Firebug window while viewing the web page.&lt;br /&gt;
* '''WebKit Inspector'''.  The WebKit Inspector, which is available in both Chrome and Safari, enables you to see the DOM tree and relationships between elements.  However, its DOM inspection tools are not as robust as those of Firebug.&lt;br /&gt;
* '''Opera Dragonfly'''.  The web browser Opera comes with a web developer toolkit similar to the WebKit Inspector called Dragonfly.  It is important that you test your sites in Opera, because although Opera has only a small fraction of the desktop browser market, it is second only to WebKit on the mobile market.  Opera also has extremely strong CSS support, so it is good for testing for bugs in your CSS.&lt;br /&gt;
&lt;br /&gt;
All of the above-mentioned tools enable you to look at the DOM of your web page and find what properties and methods are associated with each node.  This is helpful because if you have JavaScript that manipulates HTML elements, you cannot tell which properties are associated with which elements by looking at the source code alone.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 6]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=1854</id>
		<title>JavaScript</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=1854"/>
		<updated>2015-01-09T09:32:10Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* Event Handlers and Memory Management */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;JavaScript is the most widely used scripting language for implementing client-side functionality in Web applications.  Unlike PHP, JavaScript code is interpreted and executed in a client's web browser (not on the web server).&lt;br /&gt;
&lt;br /&gt;
== JavaScript?  Did you mean Java? ==&lt;br /&gt;
&lt;br /&gt;
'''JavaScript''' is a prototype-based programming language focussed on web interactivity.  It was first introduced in Netscape Navigator, and it in turn gave rise to what is now '''[http://www.ecmascript.org/ ECMAScript]'''.  Originally, JavaScript was called &amp;quot;LiveScript&amp;quot;.  Sun, the developer of Java at the time, wanted a language that would complement its compiled Java language, and so LiveScript was renamed JavaScript.&lt;br /&gt;
&lt;br /&gt;
Beyond that, '''Java and JavaScript are as similar as Ham and Hamster.'''&lt;br /&gt;
&lt;br /&gt;
Java and JavaScript have similar syntax, but the under workings are quite different.  For example, Java requires strict typing, but JavaScript allows for dynamic typing.  Java is object-oriented, but JavaScript is prototype-oriented.  Java is compiled, but JavaScript is interpreted.  Java supports event listeners, but JavaScript makes them a fundamental part of the language.  Java variables are scoped to the innermost method or loop, but JavaScript variables are scoped only to the innermost function.&lt;br /&gt;
&lt;br /&gt;
== JavaScript Language Components ==&lt;br /&gt;
&lt;br /&gt;
This section highlights some features of the JavaScript language that differentiate it from other languages.  For a more comprehensive JavaScript tutorial, the following tutorials are both quality:&lt;br /&gt;
&lt;br /&gt;
* [http://docs.webplatform.org/wiki/javascript WebPlatform]: Great for learning JavaScript for the first time.  Advocates best practices for modern JavaScript development.&lt;br /&gt;
* [http://www.quirksmode.org/js/contents.html QuirksMode]: More advanced than the WebPlatform tutorial, but it thoroughly covers the most powerful aspects of pure JavaScript and gives unparalleled advice on browser compatibility.&lt;br /&gt;
&lt;br /&gt;
Advice: Do '''NOT''' Google for &amp;quot;JavaScript Tutorial&amp;quot;.  The first few hits advocate bad or outdated practices.  Stick with the ones listed here.&lt;br /&gt;
&lt;br /&gt;
=== Variables and Scope ===&lt;br /&gt;
&lt;br /&gt;
To define a variable in JavaScript, use the '''var''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var foo = &amp;quot;bar&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
All variables are objects.  In the case above, the variable '''foo''' is an object of the class '''String'''.&lt;br /&gt;
&lt;br /&gt;
Notice that like PHP, you do not have to explicitly define a type for a variable like '''int''' or '''String'''; this is because JavaScript and PHP are ''dynamically typed languages''.&lt;br /&gt;
&lt;br /&gt;
JavaScript code can access any variable higher in the “function tree”, but not vice-versa.  This is called '''scope'''.  ''All functions create their own scope.''&lt;br /&gt;
&lt;br /&gt;
When you reference a variable, JavaScript will look up through the &amp;quot;function tree&amp;quot; until it finds the variable you asked for.  This means that you could define variables of the same name as global variables inside of functions.  For demonstration of concept:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var a = &amp;quot;hello&amp;quot;;&lt;br /&gt;
var b = &amp;quot;world&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
function sayGoodByeWorld(){&lt;br /&gt;
	var a = &amp;quot;goodbye&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
	alert(a); // goodbye&lt;br /&gt;
	alert(b); // world&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayGoodByeWorld();&lt;br /&gt;
&lt;br /&gt;
alert(a); // hello&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object Literals ===&lt;br /&gt;
&lt;br /&gt;
A very common way of storing and transporting data in JavaScript is by using objects.  You can define an object with certain properties using an '''object literal''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = {&lt;br /&gt;
	color: &amp;quot;red&amp;quot;,&lt;br /&gt;
	flavor: &amp;quot;sweet&amp;quot;,&lt;br /&gt;
	season: &amp;quot;autumn&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(apple.color);  // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
To define a function in JavaScript, use the '''function''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function sayHello(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(); // call the function&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Pass an argument to a function like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function sayHello(name){&lt;br /&gt;
	alert(&amp;quot;Hello, &amp;quot;+name);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(&amp;quot;Todd&amp;quot;); // call the function and pass an argument&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Functions are Objects ====&lt;br /&gt;
&lt;br /&gt;
In JavaScript, functions are objects.  This means that they can be assigned to variables, manipulated on the fly, and even passed as arguments to other functions!  '''''This is an extremely important feature of JavaScript''''' that makes it such a robust language for web development.&lt;br /&gt;
&lt;br /&gt;
You create a function variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayHello = function(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(); // call the function&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Observe that you can make [[#Variables and Scope|scope-dependent]] functions in this way.&lt;br /&gt;
&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=HaPlj796ngQ&lt;br /&gt;
|time=5m45s&lt;br /&gt;
|desc=JavaScript Closures&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
A '''closure''' is a way to separate a certain snippet of JavaScript code from the global scope.  This is useful if you do not want to &amp;quot;muck up&amp;quot; global variables.  Closures are nothing more than anonymous functions that are called as soon as they are created:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
​var a = &amp;quot;hello&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
(​​​​function(){&lt;br /&gt;
	var b = &amp;quot;world&amp;quot;;&lt;br /&gt;
	&lt;br /&gt;
	alert(a); // hello&lt;br /&gt;
	alert(b); // world&lt;br /&gt;
})();&lt;br /&gt;
&lt;br /&gt;
alert(a); // hello&lt;br /&gt;
alert(b);​ // ReferenceError: b is not defined​​​​​​​​​​​​​​​&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Passing Variables to a Closure&lt;br /&gt;
|desc=This example demonstrates how you can &amp;quot;save&amp;quot; previous versions of a variable using closures.  This is possible because of scoping and the fact that function variables can be returned as objects.&lt;br /&gt;
|fiddle_id=YURqa&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Most JavaScript libraries (like jQuery) write all of their code in a closure.  What this means is that except for one or two variable names (jQuery or $), everything associated with the library is completely self-contained.&lt;br /&gt;
&lt;br /&gt;
=== Prototypal Inheritance ===&lt;br /&gt;
&lt;br /&gt;
JavaScript implements '''prototypal inheritance''', as opposed to a language like Java or C++, which implements '''classical inheritance'''.  JavaScript is one of only a handful of languages implementing prototype-based inheritance.&lt;br /&gt;
&lt;br /&gt;
Here's how it works.  Every callable object (function) has a '''prototype'''.  When instances of that object are created, their properties and methods are copied (inherited) from the prototype.  Additionally, changes made to the prototype later in the program are &amp;quot;copied&amp;quot; to every instance.&lt;br /&gt;
&lt;br /&gt;
For example, if you wanted to make a method on all strings that added a “!”, you could modify String’s prototype:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
String.prototype.bang = function(){&lt;br /&gt;
	return this+&amp;quot;!&amp;quot;; // Notice: the context is the instance itself&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(&amp;quot;Hello&amp;quot;.bang()); // alerts Hello!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To &amp;quot;extend&amp;quot; an object, just copy its prototype to a new object.  However, since classical inheritance and prototypal inheritance are different concepts, copying prototypes may have results that you don't expect.  [http://beej.us/blog/data/javascript-prototypes-inheritance/ This article] seems to have a pretty good explanation with example implementations.&lt;br /&gt;
&lt;br /&gt;
=== Context ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=0a4r4bm1nQA&lt;br /&gt;
|time=4m32s&lt;br /&gt;
|desc=The ''this'' Variable in JavaScript&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Every function is called on a certain object, which is not necessarily the same object in which it was defined.  This is called '''context'''.&lt;br /&gt;
&lt;br /&gt;
To call a function on an arbitrary context, use either '''call''' or '''apply'''.  ''call'' takes a list of arguments, while ''apply'' takes them all in an array.&lt;br /&gt;
&lt;br /&gt;
To access the current context, use the '''this''' keyword.  Demonstration of concept:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayThisColor = function(){&lt;br /&gt;
	alert(this.color);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
var apple = { color: &amp;quot;red&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
sayThisColor();   // undefined&lt;br /&gt;
sayThisColor.call(apple); // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Events ==&lt;br /&gt;
&lt;br /&gt;
Events are really what make JavaScript such a powerful language for web development.&lt;br /&gt;
&lt;br /&gt;
Rather than being thread based, JavaScript is event based.  Since all JavaScript code runs in a single thread, '''there are no concurrency issues'''.  When an event occurs, JavaScript automatically calls the ''event callback'' as soon as all previous events' callbacks have finished executing.&lt;br /&gt;
&lt;br /&gt;
Code in the form of a '''callback function''' is associated with events via a '''listener'''.  For example, the following JavaScript causes ''sayHello()'' (the callback function) to be run whenever the button with ID &amp;quot;hello&amp;quot; is clicked (the event):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayHello = function(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
document.getElementById(&amp;quot;hello&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, sayHello, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Binding Callbacks to a Button Click&lt;br /&gt;
|fiddle_id=L8c4Z&lt;br /&gt;
|cse330=true&lt;br /&gt;
|desc=In this example, notice how we bind the callback function when the ''DOMContentLoaded'' event fires.  This is because JavaScript requires that the button has been parsed by the browser before it can add event listeners to it.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The '''addEventListener''' method takes three parameters:&lt;br /&gt;
* The event type&lt;br /&gt;
* The callback function&lt;br /&gt;
*: The callback function is passed one parameter: the event object.&lt;br /&gt;
* A boolean representing bubble (false) or capture (true) phase&lt;br /&gt;
*: You usually want Bubble phase.  For more information on event phase, see [[#Event Phase]]&lt;br /&gt;
&lt;br /&gt;
Note that versions of Internet Explorer prior to version 9 required that you use a different, albeit similar, function for assigning event listeners called '''attachEvent'''.  attachEvent takes the same arguments as addEventListener, except you need to put '''on''' before the event type (e.g. &amp;quot;onclick&amp;quot;), and the third argument (phase) is not necessary.&lt;br /&gt;
&lt;br /&gt;
It is perfectly valid to use an '''anonymous function''' as your callback function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;hello&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, function(event){&lt;br /&gt;
	alert(&amp;quot;Hello, World!  Event Type: &amp;quot;+event.type);&lt;br /&gt;
}, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QuirksMode has perhaps the best series of articles about the ins and outs of JavaScript events on the internet: http://www.quirksmode.org/js/contents.html#events&lt;br /&gt;
&lt;br /&gt;
=== The Event Object ===&lt;br /&gt;
&lt;br /&gt;
Callback functions are passed one argument: an ''event object''.  You see above that one property of the event object is ''event.type''.  To see the full list of properties of the event object, you could run the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;my_btn&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, function(event){&lt;br /&gt;
	var strout = &amp;quot;&amp;quot;;&lt;br /&gt;
	for(var i in event){&lt;br /&gt;
		strout += i + &amp;quot;: &amp;quot; + event[i] + &amp;quot;\n&amp;quot;;&lt;br /&gt;
	}&lt;br /&gt;
	console.log(strout);&lt;br /&gt;
}, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some of the most useful properties and methods include:&lt;br /&gt;
* '''event.target''' references the object on which the event occurred.&lt;br /&gt;
* '''event.currentTarget''' references the object whose listener is currently being processed.&lt;br /&gt;
*: ''Note:'' event.target and event.currentTarget might be the same or might be different, depending on whether you are listening for bubbled events.&lt;br /&gt;
* '''event.preventDefault()''' stops the normal result of the event from being executed.  For example, if you listen for a form's ''submit'' event, you can call event.preventDefault() to stop the form from being submitted.&lt;br /&gt;
* '''event.stopPropagation()''' prevents any other event listeners from being executed.  For more detail, read the section on Event Phase below.&lt;br /&gt;
&lt;br /&gt;
For more detail on the event object, see [http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html#interface-Event the W3C specification].&lt;br /&gt;
&lt;br /&gt;
'''Note:''' If your callback function does not take any parameters, it will still run; you just won't have as easy of access to the event object.&lt;br /&gt;
&lt;br /&gt;
=== Event Handlers and Memory Management ===&lt;br /&gt;
&lt;br /&gt;
JavaScript is an automatically garbage-collected language, meaning that memory management is mostly taken care of for you.  However, there are some instances when you need to be careful about creating &amp;quot;zombie&amp;quot; objects.  In JavaScript, this mostly revolves around the idea of event listeners.&lt;br /&gt;
&lt;br /&gt;
I could give an explanatory example, but instead I'll tell you straightaway that '''the moral of the story is that for every &amp;quot;addEventListener&amp;quot;, there should probably be a &amp;quot;removeEventListener&amp;quot;.'''  For more details on memory leaks in JavaScript, read this article: http://www.vladalexandruionescu.com/2012/08/javascript-memory-leaks.html&lt;br /&gt;
&lt;br /&gt;
When you start working with Node.JS in the next module, it's more important than ever to keep good accounting of your event listeners.&lt;br /&gt;
&lt;br /&gt;
=== Event Phase ===&lt;br /&gt;
&lt;br /&gt;
In JavaScript, events occur in two phases: '''Capture Phase''' and '''Bubble Phase'''.  Consider the following HTML document:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&amp;lt;title&amp;gt;Event Test&amp;lt;/title&amp;gt;&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
  &amp;lt;div id=&amp;quot;box&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;button id=&amp;quot;btn&amp;quot;&amp;gt;&lt;br /&gt;
      Hello&lt;br /&gt;
    &amp;lt;/button&amp;gt;&lt;br /&gt;
  &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Suppose the user clicks on the &amp;quot;Hello&amp;quot; button.  Events will be fired in the following order:&lt;br /&gt;
&lt;br /&gt;
# Capture Phase CLICK on the Document&lt;br /&gt;
# Capture Phase CLICK on the Body&lt;br /&gt;
# Capture Phase CLICK on the Div#box&lt;br /&gt;
# Target Phase CLICK on the Button#btn&lt;br /&gt;
# Bubble Phase CLICK on the Div#box&lt;br /&gt;
# Bubble Phase CLICK on the Body&lt;br /&gt;
# Bubble Phase CLICK on the Document&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Using Capture Phase to Enable or Disable a Toolbar&lt;br /&gt;
|fiddle_id=r32Dz&lt;br /&gt;
|desc=We bind an event in the capture phase to the div with ID ''toolbar''.  When ''e.stopPropagation()'' is called, the event does not reach the buttons in the toolbar.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Graphically, here is the order in which an event occurs in three generic nested elements:&lt;br /&gt;
&lt;br /&gt;
[[File:EventPhase.gif]]&lt;br /&gt;
&lt;br /&gt;
Why is this useful?  Suppose you have a control panel (toolbar, etc) that you want to temporarily deactivate.  (For example, Bold/Italic/Underline buttons on a graphic text editor that currently has no content.)  You could keep bubble phase event listeners on your buttons, but prevent those events from occurring by stopping the event in the capture phase on the parent element before the event reaches your buttons!  Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var disableToolbarFunc = function(e){&lt;br /&gt;
	e.stopPropogation();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// To disable toolbar:&lt;br /&gt;
document.getElementById(&amp;quot;box&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, disableToolbarFunc, true);&lt;br /&gt;
&lt;br /&gt;
// To re-enable toolbar:&lt;br /&gt;
document.getElementById(&amp;quot;box&amp;quot;).removeEventListener(&amp;quot;click&amp;quot;, disableToolbarFunc, true);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Word of caution:''' Like many great things in web development, capture phase does not work in versions of Internet Explorer prior to version 9.  There is no elegant substitution for older versions of Internet Explorer.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' When the event reaches the innermost element, there is no distinction between capture phase and bubble phase.  The order in which event handlers were added to the element determines the order in which those callbacks are evaluated.&lt;br /&gt;
&lt;br /&gt;
== Document Object Model ==&lt;br /&gt;
&lt;br /&gt;
The '''Document Object Model (DOM)'''  is what enables JavaScript to manipulate the content of your web page.&lt;br /&gt;
&lt;br /&gt;
=== Nodes and Traversing the DOM ===&lt;br /&gt;
&lt;br /&gt;
Each element on your page, whether it is a &amp;lt;nowiki&amp;gt;&amp;lt;p&amp;gt;, &amp;lt;img/&amp;gt;&amp;lt;/nowiki&amp;gt;, a string of text, or even an attribute, is called a '''node'''.&lt;br /&gt;
&lt;br /&gt;
Every node, except for the document itself, has exactly one parent.  A single node may have multiple children.&lt;br /&gt;
&lt;br /&gt;
Consider the following HTML code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;ul id=&amp;quot;my-list&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;fruits&amp;quot;&amp;gt;Apples&amp;lt;/li&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;citrus&amp;quot;&amp;gt;Oranges and &amp;lt;strong&amp;gt;Lemons&amp;lt;/strong&amp;gt;&amp;lt;/li&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;berries&amp;quot;&amp;gt;Cherries&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ul&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, the ul with ID &amp;quot;my-list&amp;quot; has three child '''element nodes''' (the three li's) as well as four child '''text nodes''' (the whitespace counts as a text node) and a child '''attribute node'''.  The second LI has one child '''text node''' as well as one child '''element node''' and one child '''attribute node'''.&lt;br /&gt;
&lt;br /&gt;
The DOM can be traversed in JavaScript.  First, let's look at an example.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
e = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;citrus&amp;quot;)[0].lastChild.nodeName;&lt;br /&gt;
alert(e);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Currently Selected Radio Button&lt;br /&gt;
|fiddle_id=SHcng&lt;br /&gt;
|desc=In pure JavaScript, in order to determine the currently selected radio button, it is necessary to iterate over an array of pointers to all possible radio buttons, and stop when you find one that is &amp;quot;checked&amp;quot;.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The above snippet gets the element with class name '''citrus''' that is a child of the element with ID '''my-list''' (the second LI in the example above), and alerts the type of its second child node (which in this case is '''STRONG''').&lt;br /&gt;
&lt;br /&gt;
Some common methods for traversing the DOM include:&lt;br /&gt;
&lt;br /&gt;
* Node.parentNode&lt;br /&gt;
* Node.childNodes - returns an array of nodes&lt;br /&gt;
* Node.firstChild - same as Node.childNodes[0]&lt;br /&gt;
* Node.lastChild - same as Node.childNodes[Node.childNodes.length-1]&lt;br /&gt;
* Node.previousSibling&lt;br /&gt;
* Node.nextSibling&lt;br /&gt;
&lt;br /&gt;
You can also search for child (including all descendants) using one of the following methods:&lt;br /&gt;
&lt;br /&gt;
* Node.getElementsByTagName(&amp;quot;tag-name&amp;quot;) - returns an array of element nodes having the tag name '''tag-name''' that are descendants of Node&lt;br /&gt;
* Node.getElementById(&amp;quot;id&amp;quot;) - returns a single node having the ID '''id''' that is a descendant of Node&lt;br /&gt;
* Node.getElementsByName(&amp;quot;what-name&amp;quot;) - returns an array of element nodes having their '''name''' attribute set to '''what-name'''.  Useful for radio buttons and other form elements.&lt;br /&gt;
* Node.getElementsByClassName(&amp;quot;class&amp;quot;) - returns an array of nodes having the class '''class'''&lt;br /&gt;
*: '''Note:''' As of October 2012, 82% of the browser market supports Node.getElementsByClassName ([http://caniuse.com/getelementsbyclassname more info]).  In order to support the other 18%, you need to either add your own getElementsByClassName to Node's prototype or use a JavaScript library like jQuery or MooTools.&lt;br /&gt;
&lt;br /&gt;
It is common in JavaScript to have long statements like the one in the example above, where you call methods on several objects in sequence.&lt;br /&gt;
&lt;br /&gt;
=== Creating, Moving, and Removing Nodes ===&lt;br /&gt;
&lt;br /&gt;
You will frequently find yourself wanting to modify the DOM.  JavaScript provides methods that help you do this.&lt;br /&gt;
&lt;br /&gt;
Consider the same HTML as above.  If you wanted to add another element to the list, you could use this code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var newLi = document.createElement(&amp;quot;li&amp;quot;);  // creates a node with the tag name li&lt;br /&gt;
newLi.appendChild(document.createTextNode(&amp;quot;Broccoli&amp;quot;));&lt;br /&gt;
newLi.setAttribute(&amp;quot;class&amp;quot;, &amp;quot;veggies&amp;quot;);&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).appendChild(newLi);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to remove the apples from the list, you could do:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;fruits&amp;quot;)[0];&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).removeChild(apple);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to move the apples to the end of the list, you could do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;fruits&amp;quot;)[0];&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).appendChild(apple);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that '''Node.append()''' both removes a node from its previous location ''and'' appends it to its new location, which is always going to be as the last child of the parent node.&lt;br /&gt;
&lt;br /&gt;
In summary, here are the methods to know from this section:&lt;br /&gt;
&lt;br /&gt;
* Node.append(otherNode) - removes otherNode from its current location in the DOM (if applicable) and then adds it as the last child of Node&lt;br /&gt;
* Node.removeChild(otherNode) - removes otherNode, a child of Node, from the DOM&lt;br /&gt;
* document.createElement(&amp;quot;tag-name&amp;quot;) - create a new node with the tag name &amp;quot;tag-name&amp;quot;&lt;br /&gt;
* document.createTextNode(&amp;quot;text&amp;quot;) - create a node containing only the string '''text'''&lt;br /&gt;
* Node.setAttribute(&amp;quot;attribute&amp;quot;, &amp;quot;value&amp;quot;) - sets the attribute node of name &amp;quot;attribute&amp;quot; to &amp;quot;value&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=== DOM Shortcuts ===&lt;br /&gt;
&lt;br /&gt;
In the above sections, we have been creating, reading, modifying, and deleting Nodes.  This is the most &amp;quot;correct&amp;quot; way to change the content of a web page from inside JavaScript.&lt;br /&gt;
&lt;br /&gt;
This section documents a few shortcuts that are not as &amp;quot;pure&amp;quot; as using Nodes but can be less confusing and cumbersome.&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Displaying Information&lt;br /&gt;
|fiddle_id=Q3BPZ&lt;br /&gt;
|desc=This example shows how to use some of the shortcut methods for using JavaScript to display information on the page.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
==== textContent ====&lt;br /&gt;
&lt;br /&gt;
Using textContent to display information is probably the easiest method out there.  For example, the following code overwrites whatever is in the element with ID &amp;quot;holder&amp;quot; with the string &amp;quot;Hello World&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).textContent = &amp;quot;Hello World&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to instead append the text, simply use '''+=''' instead of '''=''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).textContent += &amp;quot; -  Later, he said Hello World  - &amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that textContent displays strings literally; that is, it does not allow for HTML.  Setting the textContent property also removes any HTML that may have already been in that element.&lt;br /&gt;
&lt;br /&gt;
==== innerHTML ====&lt;br /&gt;
&lt;br /&gt;
If you need to use HTML in your output but don't want to use the method described earlier in this section, a straightforward strategy is to use the innerHTML property of an element. For example, the following code would add a paragraph saying &amp;quot;Hello World&amp;quot; to the element with ID &amp;quot;holder&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).innerHTML += &amp;quot;&amp;lt;p&amp;gt;Hello World&amp;lt;/p&amp;gt;&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Important:''' You need to be careful to prevent XSS-type attacks if you display information using innerHTML.  For example, be sure to escape a user-supplied string before appending it to innerHTML.&lt;br /&gt;
&lt;br /&gt;
=== JavaScript Inspectors ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=PKzrmbN-pMg&lt;br /&gt;
|time=4m13s&lt;br /&gt;
|desc=Using Firebug, WebKit Inspector, and IE Developer Tools&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Various browsers and browser plugins give you, the developer, tools to debug your code, inspect the DOM, and much more.  Using these tools is essential for an efficient workflow.&lt;br /&gt;
&lt;br /&gt;
* '''Firebug'''.  Firebug is a plugin for Firefox that is a toolkit full of web developer tools, one of which is a DOM inspector.  To inspect the DOM of a web page, simply open the Firebug window while viewing the web page.&lt;br /&gt;
* '''WebKit Inspector'''.  The WebKit Inspector, which is available in both Chrome and Safari, enables you to see the DOM tree and relationships between elements.  However, its DOM inspection tools are not as robust as those of Firebug.&lt;br /&gt;
* '''Opera Dragonfly'''.  The web browser Opera comes with a web developer toolkit similar to the WebKit Inspector called Dragonfly.  It is important that you test your sites in Opera, because although Opera has only a small fraction of the desktop browser market, it is second only to WebKit on the mobile market.  Opera also has extremely strong CSS support, so it is good for testing for bugs in your CSS.&lt;br /&gt;
&lt;br /&gt;
All of the above-mentioned tools enable you to look at the DOM of your web page and find what properties and methods are associated with each node.  This is helpful because if you have JavaScript that manipulates HTML elements, you cannot tell which properties are associated with which elements by looking at the source code alone.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 6]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=1853</id>
		<title>JavaScript</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=1853"/>
		<updated>2015-01-09T09:21:23Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* Event Handlers and Memory Management */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;JavaScript is the most widely used scripting language for implementing client-side functionality in Web applications.  Unlike PHP, JavaScript code is interpreted and executed in a client's web browser (not on the web server).&lt;br /&gt;
&lt;br /&gt;
== JavaScript?  Did you mean Java? ==&lt;br /&gt;
&lt;br /&gt;
'''JavaScript''' is a prototype-based programming language focussed on web interactivity.  It was first introduced in Netscape Navigator, and it in turn gave rise to what is now '''[http://www.ecmascript.org/ ECMAScript]'''.  Originally, JavaScript was called &amp;quot;LiveScript&amp;quot;.  Sun, the developer of Java at the time, wanted a language that would complement its compiled Java language, and so LiveScript was renamed JavaScript.&lt;br /&gt;
&lt;br /&gt;
Beyond that, '''Java and JavaScript are as similar as Ham and Hamster.'''&lt;br /&gt;
&lt;br /&gt;
Java and JavaScript have similar syntax, but the under workings are quite different.  For example, Java requires strict typing, but JavaScript allows for dynamic typing.  Java is object-oriented, but JavaScript is prototype-oriented.  Java is compiled, but JavaScript is interpreted.  Java supports event listeners, but JavaScript makes them a fundamental part of the language.  Java variables are scoped to the innermost method or loop, but JavaScript variables are scoped only to the innermost function.&lt;br /&gt;
&lt;br /&gt;
== JavaScript Language Components ==&lt;br /&gt;
&lt;br /&gt;
This section highlights some features of the JavaScript language that differentiate it from other languages.  For a more comprehensive JavaScript tutorial, the following tutorials are both quality:&lt;br /&gt;
&lt;br /&gt;
* [http://docs.webplatform.org/wiki/javascript WebPlatform]: Great for learning JavaScript for the first time.  Advocates best practices for modern JavaScript development.&lt;br /&gt;
* [http://www.quirksmode.org/js/contents.html QuirksMode]: More advanced than the WebPlatform tutorial, but it thoroughly covers the most powerful aspects of pure JavaScript and gives unparalleled advice on browser compatibility.&lt;br /&gt;
&lt;br /&gt;
Advice: Do '''NOT''' Google for &amp;quot;JavaScript Tutorial&amp;quot;.  The first few hits advocate bad or outdated practices.  Stick with the ones listed here.&lt;br /&gt;
&lt;br /&gt;
=== Variables and Scope ===&lt;br /&gt;
&lt;br /&gt;
To define a variable in JavaScript, use the '''var''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var foo = &amp;quot;bar&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
All variables are objects.  In the case above, the variable '''foo''' is an object of the class '''String'''.&lt;br /&gt;
&lt;br /&gt;
Notice that like PHP, you do not have to explicitly define a type for a variable like '''int''' or '''String'''; this is because JavaScript and PHP are ''dynamically typed languages''.&lt;br /&gt;
&lt;br /&gt;
JavaScript code can access any variable higher in the “function tree”, but not vice-versa.  This is called '''scope'''.  ''All functions create their own scope.''&lt;br /&gt;
&lt;br /&gt;
When you reference a variable, JavaScript will look up through the &amp;quot;function tree&amp;quot; until it finds the variable you asked for.  This means that you could define variables of the same name as global variables inside of functions.  For demonstration of concept:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var a = &amp;quot;hello&amp;quot;;&lt;br /&gt;
var b = &amp;quot;world&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
function sayGoodByeWorld(){&lt;br /&gt;
	var a = &amp;quot;goodbye&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
	alert(a); // goodbye&lt;br /&gt;
	alert(b); // world&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayGoodByeWorld();&lt;br /&gt;
&lt;br /&gt;
alert(a); // hello&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object Literals ===&lt;br /&gt;
&lt;br /&gt;
A very common way of storing and transporting data in JavaScript is by using objects.  You can define an object with certain properties using an '''object literal''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = {&lt;br /&gt;
	color: &amp;quot;red&amp;quot;,&lt;br /&gt;
	flavor: &amp;quot;sweet&amp;quot;,&lt;br /&gt;
	season: &amp;quot;autumn&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(apple.color);  // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
To define a function in JavaScript, use the '''function''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function sayHello(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(); // call the function&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Pass an argument to a function like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function sayHello(name){&lt;br /&gt;
	alert(&amp;quot;Hello, &amp;quot;+name);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(&amp;quot;Todd&amp;quot;); // call the function and pass an argument&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Functions are Objects ====&lt;br /&gt;
&lt;br /&gt;
In JavaScript, functions are objects.  This means that they can be assigned to variables, manipulated on the fly, and even passed as arguments to other functions!  '''''This is an extremely important feature of JavaScript''''' that makes it such a robust language for web development.&lt;br /&gt;
&lt;br /&gt;
You create a function variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayHello = function(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(); // call the function&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Observe that you can make [[#Variables and Scope|scope-dependent]] functions in this way.&lt;br /&gt;
&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=HaPlj796ngQ&lt;br /&gt;
|time=5m45s&lt;br /&gt;
|desc=JavaScript Closures&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
A '''closure''' is a way to separate a certain snippet of JavaScript code from the global scope.  This is useful if you do not want to &amp;quot;muck up&amp;quot; global variables.  Closures are nothing more than anonymous functions that are called as soon as they are created:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
​var a = &amp;quot;hello&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
(​​​​function(){&lt;br /&gt;
	var b = &amp;quot;world&amp;quot;;&lt;br /&gt;
	&lt;br /&gt;
	alert(a); // hello&lt;br /&gt;
	alert(b); // world&lt;br /&gt;
})();&lt;br /&gt;
&lt;br /&gt;
alert(a); // hello&lt;br /&gt;
alert(b);​ // ReferenceError: b is not defined​​​​​​​​​​​​​​​&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Passing Variables to a Closure&lt;br /&gt;
|desc=This example demonstrates how you can &amp;quot;save&amp;quot; previous versions of a variable using closures.  This is possible because of scoping and the fact that function variables can be returned as objects.&lt;br /&gt;
|fiddle_id=YURqa&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Most JavaScript libraries (like jQuery) write all of their code in a closure.  What this means is that except for one or two variable names (jQuery or $), everything associated with the library is completely self-contained.&lt;br /&gt;
&lt;br /&gt;
=== Prototypal Inheritance ===&lt;br /&gt;
&lt;br /&gt;
JavaScript implements '''prototypal inheritance''', as opposed to a language like Java or C++, which implements '''classical inheritance'''.  JavaScript is one of only a handful of languages implementing prototype-based inheritance.&lt;br /&gt;
&lt;br /&gt;
Here's how it works.  Every callable object (function) has a '''prototype'''.  When instances of that object are created, their properties and methods are copied (inherited) from the prototype.  Additionally, changes made to the prototype later in the program are &amp;quot;copied&amp;quot; to every instance.&lt;br /&gt;
&lt;br /&gt;
For example, if you wanted to make a method on all strings that added a “!”, you could modify String’s prototype:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
String.prototype.bang = function(){&lt;br /&gt;
	return this+&amp;quot;!&amp;quot;; // Notice: the context is the instance itself&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(&amp;quot;Hello&amp;quot;.bang()); // alerts Hello!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To &amp;quot;extend&amp;quot; an object, just copy its prototype to a new object.  However, since classical inheritance and prototypal inheritance are different concepts, copying prototypes may have results that you don't expect.  [http://beej.us/blog/data/javascript-prototypes-inheritance/ This article] seems to have a pretty good explanation with example implementations.&lt;br /&gt;
&lt;br /&gt;
=== Context ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=0a4r4bm1nQA&lt;br /&gt;
|time=4m32s&lt;br /&gt;
|desc=The ''this'' Variable in JavaScript&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Every function is called on a certain object, which is not necessarily the same object in which it was defined.  This is called '''context'''.&lt;br /&gt;
&lt;br /&gt;
To call a function on an arbitrary context, use either '''call''' or '''apply'''.  ''call'' takes a list of arguments, while ''apply'' takes them all in an array.&lt;br /&gt;
&lt;br /&gt;
To access the current context, use the '''this''' keyword.  Demonstration of concept:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayThisColor = function(){&lt;br /&gt;
	alert(this.color);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
var apple = { color: &amp;quot;red&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
sayThisColor();   // undefined&lt;br /&gt;
sayThisColor.call(apple); // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Events ==&lt;br /&gt;
&lt;br /&gt;
Events are really what make JavaScript such a powerful language for web development.&lt;br /&gt;
&lt;br /&gt;
Rather than being thread based, JavaScript is event based.  Since all JavaScript code runs in a single thread, '''there are no concurrency issues'''.  When an event occurs, JavaScript automatically calls the ''event callback'' as soon as all previous events' callbacks have finished executing.&lt;br /&gt;
&lt;br /&gt;
Code in the form of a '''callback function''' is associated with events via a '''listener'''.  For example, the following JavaScript causes ''sayHello()'' (the callback function) to be run whenever the button with ID &amp;quot;hello&amp;quot; is clicked (the event):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayHello = function(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
document.getElementById(&amp;quot;hello&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, sayHello, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Binding Callbacks to a Button Click&lt;br /&gt;
|fiddle_id=L8c4Z&lt;br /&gt;
|cse330=true&lt;br /&gt;
|desc=In this example, notice how we bind the callback function when the ''DOMContentLoaded'' event fires.  This is because JavaScript requires that the button has been parsed by the browser before it can add event listeners to it.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The '''addEventListener''' method takes three parameters:&lt;br /&gt;
* The event type&lt;br /&gt;
* The callback function&lt;br /&gt;
*: The callback function is passed one parameter: the event object.&lt;br /&gt;
* A boolean representing bubble (false) or capture (true) phase&lt;br /&gt;
*: You usually want Bubble phase.  For more information on event phase, see [[#Event Phase]]&lt;br /&gt;
&lt;br /&gt;
Note that versions of Internet Explorer prior to version 9 required that you use a different, albeit similar, function for assigning event listeners called '''attachEvent'''.  attachEvent takes the same arguments as addEventListener, except you need to put '''on''' before the event type (e.g. &amp;quot;onclick&amp;quot;), and the third argument (phase) is not necessary.&lt;br /&gt;
&lt;br /&gt;
It is perfectly valid to use an '''anonymous function''' as your callback function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;hello&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, function(event){&lt;br /&gt;
	alert(&amp;quot;Hello, World!  Event Type: &amp;quot;+event.type);&lt;br /&gt;
}, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QuirksMode has perhaps the best series of articles about the ins and outs of JavaScript events on the internet: http://www.quirksmode.org/js/contents.html#events&lt;br /&gt;
&lt;br /&gt;
=== The Event Object ===&lt;br /&gt;
&lt;br /&gt;
Callback functions are passed one argument: an ''event object''.  You see above that one property of the event object is ''event.type''.  To see the full list of properties of the event object, you could run the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;my_btn&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, function(event){&lt;br /&gt;
	var strout = &amp;quot;&amp;quot;;&lt;br /&gt;
	for(var i in event){&lt;br /&gt;
		strout += i + &amp;quot;: &amp;quot; + event[i] + &amp;quot;\n&amp;quot;;&lt;br /&gt;
	}&lt;br /&gt;
	console.log(strout);&lt;br /&gt;
}, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some of the most useful properties and methods include:&lt;br /&gt;
* '''event.target''' references the object on which the event occurred.&lt;br /&gt;
* '''event.currentTarget''' references the object whose listener is currently being processed.&lt;br /&gt;
*: ''Note:'' event.target and event.currentTarget might be the same or might be different, depending on whether you are listening for bubbled events.&lt;br /&gt;
* '''event.preventDefault()''' stops the normal result of the event from being executed.  For example, if you listen for a form's ''submit'' event, you can call event.preventDefault() to stop the form from being submitted.&lt;br /&gt;
* '''event.stopPropagation()''' prevents any other event listeners from being executed.  For more detail, read the section on Event Phase below.&lt;br /&gt;
&lt;br /&gt;
For more detail on the event object, see [http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html#interface-Event the W3C specification].&lt;br /&gt;
&lt;br /&gt;
'''Note:''' If your callback function does not take any parameters, it will still run; you just won't have as easy of access to the event object.&lt;br /&gt;
&lt;br /&gt;
=== Event Handlers and Memory Management ===&lt;br /&gt;
&lt;br /&gt;
JavaScript is an automatically garbage-collected language, meaning that memory management is mostly taken care of for you.  However, there are some instances when you need to be careful about creating &amp;quot;zombie&amp;quot; objects.  One common &amp;quot;gotcha&amp;quot; instance of this is in event listeners.&lt;br /&gt;
&lt;br /&gt;
For example, consider the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Declare an object&lt;br /&gt;
var myObject = {&lt;br /&gt;
	fn: function(event) {&lt;br /&gt;
		alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
// Make a property of that object listen for some event&lt;br /&gt;
document.getElementById(&amp;quot;my-div&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, myObject.fn, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, myObject will ''not'' be garbage collected, even if it goes out of scope, so long as its property ''fn'' is a listener for an event on the div.  In order to release myObject from memory, you need o do the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// If we want myObject to be garbage collected when it leaves scope, we need to remove the event listener.&lt;br /&gt;
document.getElementById(&amp;quot;my-div&amp;quot;).removeEventListener(&amp;quot;click&amp;quot;, myObject.fn, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The moral of the story is that for every &amp;quot;addEventListener&amp;quot;, there should probably be a &amp;quot;removeEventListener&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
For more information on memory leaks in JavaScript, read this article: http://www.vladalexandruionescu.com/2012/08/javascript-memory-leaks.html&lt;br /&gt;
&lt;br /&gt;
=== Event Phase ===&lt;br /&gt;
&lt;br /&gt;
In JavaScript, events occur in two phases: '''Capture Phase''' and '''Bubble Phase'''.  Consider the following HTML document:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&amp;lt;title&amp;gt;Event Test&amp;lt;/title&amp;gt;&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
  &amp;lt;div id=&amp;quot;box&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;button id=&amp;quot;btn&amp;quot;&amp;gt;&lt;br /&gt;
      Hello&lt;br /&gt;
    &amp;lt;/button&amp;gt;&lt;br /&gt;
  &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Suppose the user clicks on the &amp;quot;Hello&amp;quot; button.  Events will be fired in the following order:&lt;br /&gt;
&lt;br /&gt;
# Capture Phase CLICK on the Document&lt;br /&gt;
# Capture Phase CLICK on the Body&lt;br /&gt;
# Capture Phase CLICK on the Div#box&lt;br /&gt;
# Target Phase CLICK on the Button#btn&lt;br /&gt;
# Bubble Phase CLICK on the Div#box&lt;br /&gt;
# Bubble Phase CLICK on the Body&lt;br /&gt;
# Bubble Phase CLICK on the Document&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Using Capture Phase to Enable or Disable a Toolbar&lt;br /&gt;
|fiddle_id=r32Dz&lt;br /&gt;
|desc=We bind an event in the capture phase to the div with ID ''toolbar''.  When ''e.stopPropagation()'' is called, the event does not reach the buttons in the toolbar.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Graphically, here is the order in which an event occurs in three generic nested elements:&lt;br /&gt;
&lt;br /&gt;
[[File:EventPhase.gif]]&lt;br /&gt;
&lt;br /&gt;
Why is this useful?  Suppose you have a control panel (toolbar, etc) that you want to temporarily deactivate.  (For example, Bold/Italic/Underline buttons on a graphic text editor that currently has no content.)  You could keep bubble phase event listeners on your buttons, but prevent those events from occurring by stopping the event in the capture phase on the parent element before the event reaches your buttons!  Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var disableToolbarFunc = function(e){&lt;br /&gt;
	e.stopPropogation();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// To disable toolbar:&lt;br /&gt;
document.getElementById(&amp;quot;box&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, disableToolbarFunc, true);&lt;br /&gt;
&lt;br /&gt;
// To re-enable toolbar:&lt;br /&gt;
document.getElementById(&amp;quot;box&amp;quot;).removeEventListener(&amp;quot;click&amp;quot;, disableToolbarFunc, true);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Word of caution:''' Like many great things in web development, capture phase does not work in versions of Internet Explorer prior to version 9.  There is no elegant substitution for older versions of Internet Explorer.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' When the event reaches the innermost element, there is no distinction between capture phase and bubble phase.  The order in which event handlers were added to the element determines the order in which those callbacks are evaluated.&lt;br /&gt;
&lt;br /&gt;
== Document Object Model ==&lt;br /&gt;
&lt;br /&gt;
The '''Document Object Model (DOM)'''  is what enables JavaScript to manipulate the content of your web page.&lt;br /&gt;
&lt;br /&gt;
=== Nodes and Traversing the DOM ===&lt;br /&gt;
&lt;br /&gt;
Each element on your page, whether it is a &amp;lt;nowiki&amp;gt;&amp;lt;p&amp;gt;, &amp;lt;img/&amp;gt;&amp;lt;/nowiki&amp;gt;, a string of text, or even an attribute, is called a '''node'''.&lt;br /&gt;
&lt;br /&gt;
Every node, except for the document itself, has exactly one parent.  A single node may have multiple children.&lt;br /&gt;
&lt;br /&gt;
Consider the following HTML code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;ul id=&amp;quot;my-list&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;fruits&amp;quot;&amp;gt;Apples&amp;lt;/li&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;citrus&amp;quot;&amp;gt;Oranges and &amp;lt;strong&amp;gt;Lemons&amp;lt;/strong&amp;gt;&amp;lt;/li&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;berries&amp;quot;&amp;gt;Cherries&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ul&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, the ul with ID &amp;quot;my-list&amp;quot; has three child '''element nodes''' (the three li's) as well as four child '''text nodes''' (the whitespace counts as a text node) and a child '''attribute node'''.  The second LI has one child '''text node''' as well as one child '''element node''' and one child '''attribute node'''.&lt;br /&gt;
&lt;br /&gt;
The DOM can be traversed in JavaScript.  First, let's look at an example.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
e = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;citrus&amp;quot;)[0].lastChild.nodeName;&lt;br /&gt;
alert(e);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Currently Selected Radio Button&lt;br /&gt;
|fiddle_id=SHcng&lt;br /&gt;
|desc=In pure JavaScript, in order to determine the currently selected radio button, it is necessary to iterate over an array of pointers to all possible radio buttons, and stop when you find one that is &amp;quot;checked&amp;quot;.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The above snippet gets the element with class name '''citrus''' that is a child of the element with ID '''my-list''' (the second LI in the example above), and alerts the type of its second child node (which in this case is '''STRONG''').&lt;br /&gt;
&lt;br /&gt;
Some common methods for traversing the DOM include:&lt;br /&gt;
&lt;br /&gt;
* Node.parentNode&lt;br /&gt;
* Node.childNodes - returns an array of nodes&lt;br /&gt;
* Node.firstChild - same as Node.childNodes[0]&lt;br /&gt;
* Node.lastChild - same as Node.childNodes[Node.childNodes.length-1]&lt;br /&gt;
* Node.previousSibling&lt;br /&gt;
* Node.nextSibling&lt;br /&gt;
&lt;br /&gt;
You can also search for child (including all descendants) using one of the following methods:&lt;br /&gt;
&lt;br /&gt;
* Node.getElementsByTagName(&amp;quot;tag-name&amp;quot;) - returns an array of element nodes having the tag name '''tag-name''' that are descendants of Node&lt;br /&gt;
* Node.getElementById(&amp;quot;id&amp;quot;) - returns a single node having the ID '''id''' that is a descendant of Node&lt;br /&gt;
* Node.getElementsByName(&amp;quot;what-name&amp;quot;) - returns an array of element nodes having their '''name''' attribute set to '''what-name'''.  Useful for radio buttons and other form elements.&lt;br /&gt;
* Node.getElementsByClassName(&amp;quot;class&amp;quot;) - returns an array of nodes having the class '''class'''&lt;br /&gt;
*: '''Note:''' As of October 2012, 82% of the browser market supports Node.getElementsByClassName ([http://caniuse.com/getelementsbyclassname more info]).  In order to support the other 18%, you need to either add your own getElementsByClassName to Node's prototype or use a JavaScript library like jQuery or MooTools.&lt;br /&gt;
&lt;br /&gt;
It is common in JavaScript to have long statements like the one in the example above, where you call methods on several objects in sequence.&lt;br /&gt;
&lt;br /&gt;
=== Creating, Moving, and Removing Nodes ===&lt;br /&gt;
&lt;br /&gt;
You will frequently find yourself wanting to modify the DOM.  JavaScript provides methods that help you do this.&lt;br /&gt;
&lt;br /&gt;
Consider the same HTML as above.  If you wanted to add another element to the list, you could use this code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var newLi = document.createElement(&amp;quot;li&amp;quot;);  // creates a node with the tag name li&lt;br /&gt;
newLi.appendChild(document.createTextNode(&amp;quot;Broccoli&amp;quot;));&lt;br /&gt;
newLi.setAttribute(&amp;quot;class&amp;quot;, &amp;quot;veggies&amp;quot;);&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).appendChild(newLi);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to remove the apples from the list, you could do:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;fruits&amp;quot;)[0];&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).removeChild(apple);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to move the apples to the end of the list, you could do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;fruits&amp;quot;)[0];&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).appendChild(apple);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that '''Node.append()''' both removes a node from its previous location ''and'' appends it to its new location, which is always going to be as the last child of the parent node.&lt;br /&gt;
&lt;br /&gt;
In summary, here are the methods to know from this section:&lt;br /&gt;
&lt;br /&gt;
* Node.append(otherNode) - removes otherNode from its current location in the DOM (if applicable) and then adds it as the last child of Node&lt;br /&gt;
* Node.removeChild(otherNode) - removes otherNode, a child of Node, from the DOM&lt;br /&gt;
* document.createElement(&amp;quot;tag-name&amp;quot;) - create a new node with the tag name &amp;quot;tag-name&amp;quot;&lt;br /&gt;
* document.createTextNode(&amp;quot;text&amp;quot;) - create a node containing only the string '''text'''&lt;br /&gt;
* Node.setAttribute(&amp;quot;attribute&amp;quot;, &amp;quot;value&amp;quot;) - sets the attribute node of name &amp;quot;attribute&amp;quot; to &amp;quot;value&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=== DOM Shortcuts ===&lt;br /&gt;
&lt;br /&gt;
In the above sections, we have been creating, reading, modifying, and deleting Nodes.  This is the most &amp;quot;correct&amp;quot; way to change the content of a web page from inside JavaScript.&lt;br /&gt;
&lt;br /&gt;
This section documents a few shortcuts that are not as &amp;quot;pure&amp;quot; as using Nodes but can be less confusing and cumbersome.&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Displaying Information&lt;br /&gt;
|fiddle_id=Q3BPZ&lt;br /&gt;
|desc=This example shows how to use some of the shortcut methods for using JavaScript to display information on the page.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
==== textContent ====&lt;br /&gt;
&lt;br /&gt;
Using textContent to display information is probably the easiest method out there.  For example, the following code overwrites whatever is in the element with ID &amp;quot;holder&amp;quot; with the string &amp;quot;Hello World&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).textContent = &amp;quot;Hello World&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to instead append the text, simply use '''+=''' instead of '''=''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).textContent += &amp;quot; -  Later, he said Hello World  - &amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that textContent displays strings literally; that is, it does not allow for HTML.  Setting the textContent property also removes any HTML that may have already been in that element.&lt;br /&gt;
&lt;br /&gt;
==== innerHTML ====&lt;br /&gt;
&lt;br /&gt;
If you need to use HTML in your output but don't want to use the method described earlier in this section, a straightforward strategy is to use the innerHTML property of an element. For example, the following code would add a paragraph saying &amp;quot;Hello World&amp;quot; to the element with ID &amp;quot;holder&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).innerHTML += &amp;quot;&amp;lt;p&amp;gt;Hello World&amp;lt;/p&amp;gt;&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Important:''' You need to be careful to prevent XSS-type attacks if you display information using innerHTML.  For example, be sure to escape a user-supplied string before appending it to innerHTML.&lt;br /&gt;
&lt;br /&gt;
=== JavaScript Inspectors ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=PKzrmbN-pMg&lt;br /&gt;
|time=4m13s&lt;br /&gt;
|desc=Using Firebug, WebKit Inspector, and IE Developer Tools&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Various browsers and browser plugins give you, the developer, tools to debug your code, inspect the DOM, and much more.  Using these tools is essential for an efficient workflow.&lt;br /&gt;
&lt;br /&gt;
* '''Firebug'''.  Firebug is a plugin for Firefox that is a toolkit full of web developer tools, one of which is a DOM inspector.  To inspect the DOM of a web page, simply open the Firebug window while viewing the web page.&lt;br /&gt;
* '''WebKit Inspector'''.  The WebKit Inspector, which is available in both Chrome and Safari, enables you to see the DOM tree and relationships between elements.  However, its DOM inspection tools are not as robust as those of Firebug.&lt;br /&gt;
* '''Opera Dragonfly'''.  The web browser Opera comes with a web developer toolkit similar to the WebKit Inspector called Dragonfly.  It is important that you test your sites in Opera, because although Opera has only a small fraction of the desktop browser market, it is second only to WebKit on the mobile market.  Opera also has extremely strong CSS support, so it is good for testing for bugs in your CSS.&lt;br /&gt;
&lt;br /&gt;
All of the above-mentioned tools enable you to look at the DOM of your web page and find what properties and methods are associated with each node.  This is helpful because if you have JavaScript that manipulates HTML elements, you cannot tell which properties are associated with which elements by looking at the source code alone.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 6]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Getting_MEAN&amp;diff=1852</id>
		<title>Getting MEAN</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Getting_MEAN&amp;diff=1852"/>
		<updated>2015-01-07T12:28:34Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* What did all that mean? */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Installation=&lt;br /&gt;
To install MEAN, make sure you already have all of the following components installed and configured correctly.&lt;br /&gt;
&amp;lt;br/&amp;gt;&lt;br /&gt;
'''1. Node.js''' (should come with npm) &amp;lt;br/&amp;gt;&lt;br /&gt;
To find out if you have node and npm, try checking their versions (may not be the same):&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
node --version&lt;br /&gt;
v0.10.25&lt;br /&gt;
npm --version&lt;br /&gt;
1.3.24&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
IF you don't have node.js, install it [http://nodejs.org/ here].&lt;br /&gt;
&lt;br /&gt;
'''2. Bower'''&lt;br /&gt;
&lt;br /&gt;
Bower is a web application manager used by MEAN. To install bower, type the following command in your terminal: &lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;npm install -g bower&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''3. MongoDB'''&lt;br /&gt;
To install MongoDB, follow the instructions for your OS [http://docs.mongodb.org/manual/installation/ here].&lt;br /&gt;
&lt;br /&gt;
'''4. Grunt'''&lt;br /&gt;
To install Grunt type the following command:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;npm install -g grunt-cli&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''5. and finally, MEAN'''&lt;br /&gt;
In your terminal, type:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt; &amp;gt; sudo npm install -g mean-cli &amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* MEAN stack documentations are available [http://mean.io/#!/docs here]. They'll help you to get familiar with the file structure and idioms.&lt;br /&gt;
&lt;br /&gt;
== What did all that mean? ==&lt;br /&gt;
&lt;br /&gt;
You just installed four different command line tools.  Here's what they all do.&lt;br /&gt;
&lt;br /&gt;
* '''npm''' is the package manager for Node.JS.  It installs libraries for use by your Node.JS applications.  The configuration file for ''npm'' (the list of packages for ''npm'' to install) is ''package.json''.&lt;br /&gt;
* '''bower''' is a package manager for front-end libraries.  Rather than manually downloading your jQuery, Bootstrap, Angular, and other front-end JavaScript and CSS (and remembering to update them when a new version of one of those libraries comes out), ''bower'' installs them for you.  The configuration file for ''bower'' (the list of packages for ''bower'' to install) is ''bower.json''.&lt;br /&gt;
* '''grunt''' is a build tool designed for JavaScript.  It's like ''make'' or ''ant'', but for JavaScript.  The configuration file for ''grunt'' (the list of commands to run when building your project) is ''Gruntfile.js'' (a name inspired by the ''Makefile'' for ''make'', the dominant C and C++ build tool).&lt;br /&gt;
* '''mean''' is a utility designed to help you carry out routine tasks associated with developing for the MEAN stack.&lt;br /&gt;
&lt;br /&gt;
Don't be confused by the fact that you use ''npm'' to install ''bower'', ''grunt'', and ''mean''.  The people who made ''bower'', ''grunt'', and ''mean'' just all decided to use ''npm'' as the place to publish their projects, probably because the executables themselves are written in Node.JS.  They could just as well have chosen ''apt-get'' or ''yum'' or any of the other package managers you've been using in this class.&lt;br /&gt;
&lt;br /&gt;
=Running the Default App =&lt;br /&gt;
* Init and run an app. &lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
&amp;gt; mean init myApp // create your first app&lt;br /&gt;
&amp;gt; cd myApp &lt;br /&gt;
&amp;gt; npm install // Install dependencies&lt;br /&gt;
&amp;gt; grunt // Launch mean&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Make sure MongoDB is connected and running (if you run into problems, refer to the section on MongoDB)&lt;br /&gt;
&lt;br /&gt;
* Go ahead and explore features of the default Article app (such as logging in, adding/deleting articles).&lt;br /&gt;
&lt;br /&gt;
=Generating a Package =&lt;br /&gt;
* By now you should know what a package is in MEAN. If you don't, read [http://learn.mean.io/#mean-io-packages this].&lt;br /&gt;
&lt;br /&gt;
* Try creating a package named myPackage by typing: &lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
&amp;gt; mean package myPackage&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Locate it inside the packages folder:&lt;br /&gt;
* Compare the structure of myPackage folder to that of the default app. Make sure you see both '''public''' and  '''server''' folders and their subfolders.&lt;br /&gt;
* Restart your app, make sure you can see a link to the newly created package.&lt;br /&gt;
&lt;br /&gt;
=A Closer Look at the App =&lt;br /&gt;
Take a look at the directory where you app resides, you will see two folders '''public''' and  '''server''', which contain code for the client side and server side respectively.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Models ==&lt;br /&gt;
&lt;br /&gt;
Open up article.js in /server/models&lt;br /&gt;
&lt;br /&gt;
MEAN is MVC on the client side and the server side.  Since the model is tied to the backend to MongoDB, you will only see the models folder on the server side, which is normal. &lt;br /&gt;
The models are mongoose models that's why we need to require mongoose (what the following line does):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var mongoose = require('mongoose'), Schema = mongoose.Schema;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The following part then defines the schema:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var ArticleSchema = new Schema({&lt;br /&gt;
    created: {&lt;br /&gt;
        type: Date,&lt;br /&gt;
        default: Date.now&lt;br /&gt;
    },&lt;br /&gt;
    title: {&lt;br /&gt;
        type: String,&lt;br /&gt;
        default: '',&lt;br /&gt;
        trim: true&lt;br /&gt;
    },&lt;br /&gt;
    content: {&lt;br /&gt;
        type: String,&lt;br /&gt;
        default: '',&lt;br /&gt;
        trim: true&lt;br /&gt;
    },&lt;br /&gt;
    user: {&lt;br /&gt;
        type: Schema.ObjectId,&lt;br /&gt;
        ref: 'User'&lt;br /&gt;
    }&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The next part is validations, or criteria an object needs to pass before it can be saved to the DB. &lt;br /&gt;
The following code is to make sure that an article has a title:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
ArticleSchema.path('title').validate(function(title) {&lt;br /&gt;
    return title.length;&lt;br /&gt;
}, 'Title cannot be blank');&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, Mongoose allows us to define methods to our data objects as well. &lt;br /&gt;
These are called statics. From the Mongoose doc: Schemas not only define the structure of your document and casting of properties, they also define document instance methods, static Model methods, compound indexes and document lifecycle hooks called middleware.&lt;br /&gt;
The following code defines a method called load for the article schema:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
ArticleSchema.statics.load = function(id, cb) {&lt;br /&gt;
    this.findOne({&lt;br /&gt;
        _id: id&lt;br /&gt;
    }).populate('user', 'name username').exec(cb);&lt;br /&gt;
};&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you have trouble understanding what the code does, review the Mongoose [http://mongoosejs.com/docs/index.html quick start] guide.&lt;br /&gt;
&lt;br /&gt;
=== Models Practice === &lt;br /&gt;
Define a schema for a model named '''Phone''', name it phone.js and save it in the corresponding folder in 'myPackage' (hint: /packages/myPackage/server/models/)&lt;br /&gt;
A product needs to have the following fields with specific types. Here is an example of a Phone object can be stored in the MongoDB:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
    {&lt;br /&gt;
        &amp;quot;age&amp;quot;: 0, &lt;br /&gt;
        &amp;quot;id&amp;quot;: &amp;quot;motorola-xoom-with-wi-fi&amp;quot;, &lt;br /&gt;
        &amp;quot;imageUrl&amp;quot;: &amp;quot;img/phones/motorola-xoom-with-wi-fi.0.jpg&amp;quot;, &lt;br /&gt;
        &amp;quot;name&amp;quot;: &amp;quot;Motorola XOOM\u2122 with Wi-Fi&amp;quot;, &lt;br /&gt;
        &amp;quot;snippet&amp;quot;: &amp;quot;The Next, Next Generation\r\n\r\nExperience the future with Motorola XOOM wi.. d by Android 3.0 (Honeycomb).&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is taken from phones.json used by the AngularJS tutorial. If you have gone through the tutorial, you should have realized that instead of using a DB, json files were used to simplify the tutorial.&lt;br /&gt;
Find phones.json in /app/phones in the angular tutorial folder and try importing its content to MongoDB so you can use them in your current MEAN package.&lt;br /&gt;
&amp;lt;br/&amp;gt; Here is how (assuming mongod is running):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
&amp;gt; mongo --shell // connect to mongo shell &lt;br /&gt;
&amp;gt; use mean-dev // switches to database used by mean.&lt;br /&gt;
&amp;gt; mongoimport --db mean-dev --collection phones --type json --file ''&amp;lt;path to phones.json&amp;gt;'' --jsonArray // imports json file to the DB&lt;br /&gt;
&amp;gt; show collections // check to see if phones are added to your database&lt;br /&gt;
&amp;gt; coll = db.phones // to see the content of the file&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Controllers ==&lt;br /&gt;
&lt;br /&gt;
You'll find a controllers folder on both the server side and the client (public) side.  &lt;br /&gt;
* The client side controllers are part of the Angular MVC scheme that contains client side logic and may issue requests to the server.&lt;br /&gt;
* The server side controllers deal with the models and requests from the client side.&lt;br /&gt;
&lt;br /&gt;
'''Server side:'''&lt;br /&gt;
&lt;br /&gt;
* Find articles.js in the controllers folder. Try to understand what each part does. &lt;br /&gt;
&lt;br /&gt;
'''Client side:''' open up articles.js in /articles/public/controllers&lt;br /&gt;
Compare the functions defined in ArticlesController, can you find the server side implementation of corresponding functions? &lt;br /&gt;
&lt;br /&gt;
Here is a diagram to help you understand how this works:&lt;br /&gt;
&lt;br /&gt;
[[File:Mean.png]]&lt;br /&gt;
&lt;br /&gt;
== Views &amp;amp; Routing ==&lt;br /&gt;
Even though typically views are implemented and used for the client end, routing happens on both ends.&lt;br /&gt;
&lt;br /&gt;
* Find articles.js in /server/routes&lt;br /&gt;
You'll see that it requires the articles controller and its methods for querying the database.&lt;br /&gt;
&lt;br /&gt;
The first section requires the articles controller, which defines different methods &lt;br /&gt;
&lt;br /&gt;
For example, code below tells the server to use a method named &amp;quot;all&amp;quot; in the articles controller when the url is pointed to /articles:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;   &lt;br /&gt;
app.route('/articles')&lt;br /&gt;
      .get(articles.all)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Go to http://localhost:3000/articles, what do you see? Does it make sense?&lt;br /&gt;
&lt;br /&gt;
Let's switch to the public folder where the views reside.  Go to articles/public/views, open up list.html: &amp;lt;br/&amp;gt;&lt;br /&gt;
The first line tells the framework that  ArticlesController is responsible for this particular view and when this view is loaded, use find() to initiate data binding.&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;section data-ng-controller=&amp;quot;ArticlesController&amp;quot; data-ng-init=&amp;quot;find()&amp;quot;&amp;gt; &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Feel free to take a look at what find() does. Make sure you understand that what find() does is actually done by the backend, where a corresponding find() is written (as mentioned above).&lt;br /&gt;
Hopefully you have a better understanding of how these technologies all work together now.&lt;br /&gt;
&lt;br /&gt;
Review the AngularJS section if you have any questions regarding the view data binding.&lt;br /&gt;
&lt;br /&gt;
The view files in articles/views only defines the code for displaying the articles, where does the navigation bar gets defined.&lt;br /&gt;
The answer is in /public/system. &lt;br /&gt;
*The .html files in public/system/views provide a container/layout for the application. &lt;br /&gt;
For example, header.html includes the menu bar (displayed on the top of the page):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;div class=&amp;quot;left pull-left&amp;quot;&amp;gt;&lt;br /&gt;
     &amp;lt;ul class=&amp;quot;navbar-nav nav&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;li data-ng-repeat=&amp;quot;item in menus.main&amp;quot; ui-route=&amp;quot;/{{item.link}}&amp;quot; ng-class=&amp;quot;{active: $uiRoute}&amp;quot;&amp;gt;&lt;br /&gt;
            &amp;lt;a mean-token=&amp;quot;item.link&amp;quot; ui-sref='{{item.link}}'&amp;gt;{{item.title}}&amp;lt;/a&amp;gt;&lt;br /&gt;
        &amp;lt;/li&amp;gt;&lt;br /&gt;
   &amp;lt;/ul&amp;gt;&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Try changing &amp;lt;nowiki&amp;gt;{{item.title}} &amp;lt;/nowiki&amp;gt; inside the &amp;lt;a&amp;gt; &amp;lt;/a&amp;gt;tags to &amp;quot;my articles&amp;quot; see what happens to the page.&lt;br /&gt;
* The ui-sref is &amp;quot;href&amp;quot; in ui-route, an AngularJS plugin, try changing &amp;lt;nowiki&amp;gt;{{item.link}}&amp;lt;/nowiki&amp;gt; to #!/myarticles, &lt;br /&gt;
* What happens to the application now? When you click on &amp;quot;my articles&amp;quot;?&lt;br /&gt;
&lt;br /&gt;
The page to articles is no longer served!&lt;br /&gt;
&lt;br /&gt;
But how does the framework know which page to serve given a certain url?  The file responsible for this (called routing in web development) is in public/articles/routes&lt;br /&gt;
&lt;br /&gt;
open up articles.js in this folder and find the line that specifies the routing scheme for /articles:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            .state('all articles', {&lt;br /&gt;
                url: '/articles',&lt;br /&gt;
                templateUrl: 'public/articles/views/list.html',&lt;br /&gt;
                resolve: {&lt;br /&gt;
                    loggedin: checkLoggedin&lt;br /&gt;
                }&lt;br /&gt;
            }&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is ui-route's way of telling the server what to serve the page specified by the templateUrl when it sees &amp;quot;localhost:3000/#!/phones&amp;quot;. &lt;br /&gt;
The #! is a hash prefix used for MEAN to make ajax calls so make sure to include it when coding your views.&lt;br /&gt;
Now try changing the url to &amp;quot;/myarticles&amp;quot;, save and go back to your app, click on &amp;quot;my articles&amp;quot; now, what happens?&lt;br /&gt;
&lt;br /&gt;
*This is important if you want to customize your navigation bar and links. Just remember that each url needs an entry in the route file, in the format of the example above.&lt;br /&gt;
&lt;br /&gt;
= Practice = &lt;br /&gt;
&lt;br /&gt;
Can you implement a view in your myPackage to display all phones injected in the DB? &lt;br /&gt;
Hint: myPackage has the same file structure as the default app.&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Getting_MEAN&amp;diff=1851</id>
		<title>Getting MEAN</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Getting_MEAN&amp;diff=1851"/>
		<updated>2015-01-07T12:26:41Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* What did all that mean? */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Installation=&lt;br /&gt;
To install MEAN, make sure you already have all of the following components installed and configured correctly.&lt;br /&gt;
&amp;lt;br/&amp;gt;&lt;br /&gt;
'''1. Node.js''' (should come with npm) &amp;lt;br/&amp;gt;&lt;br /&gt;
To find out if you have node and npm, try checking their versions (may not be the same):&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
node --version&lt;br /&gt;
v0.10.25&lt;br /&gt;
npm --version&lt;br /&gt;
1.3.24&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
IF you don't have node.js, install it [http://nodejs.org/ here].&lt;br /&gt;
&lt;br /&gt;
'''2. Bower'''&lt;br /&gt;
&lt;br /&gt;
Bower is a web application manager used by MEAN. To install bower, type the following command in your terminal: &lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;npm install -g bower&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''3. MongoDB'''&lt;br /&gt;
To install MongoDB, follow the instructions for your OS [http://docs.mongodb.org/manual/installation/ here].&lt;br /&gt;
&lt;br /&gt;
'''4. Grunt'''&lt;br /&gt;
To install Grunt type the following command:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;npm install -g grunt-cli&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''5. and finally, MEAN'''&lt;br /&gt;
In your terminal, type:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt; &amp;gt; sudo npm install -g mean-cli &amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* MEAN stack documentations are available [http://mean.io/#!/docs here]. They'll help you to get familiar with the file structure and idioms.&lt;br /&gt;
&lt;br /&gt;
== What did all that mean? ==&lt;br /&gt;
&lt;br /&gt;
You just installed four different command line tools.  Here's what they all do.&lt;br /&gt;
&lt;br /&gt;
* '''npm''' is the package manager for Node.JS.  It installs libraries for use by your Node.JS applications.  The configuration file for ''npm'' (the list of packages for ''npm'' to install) is ''package.json''.&lt;br /&gt;
* '''bower''' is a package manager for front-end libraries.  Rather than manually downloading your jQuery, Bootstrap, Angular, and other front-end JavaScript and CSS (and remembering to update them when a new version of one of those libraries comes out), ''bower'' installs them for you.  The configuration file for ''bower'' (the list of packages for ''bower'' to install) is ''bower.json''.&lt;br /&gt;
* '''grunt''' is a build tool designed for JavaScript.  It's like ''make'' or ''ant'', but for JavaScript.  The configuration file for ''grunt'' (the list of commands to run when building your project) is ''Gruntfile.js''.&lt;br /&gt;
* '''mean''' is a utility designed to help you carry out routine tasks associated with developing for the MEAN stack.&lt;br /&gt;
&lt;br /&gt;
Don't be confused by the fact that you use ''npm'' to install ''bower'', ''grunt'', and ''mean''.  The people who made ''bower'', ''grunt'', and ''mean'' just all decided to use ''npm'' as the place to publish their projects, probably because the executables themselves are written in Node.JS.  They could just as well have chosen ''apt-get'' or ''yum'' or any of the other package managers you've been using in this class.&lt;br /&gt;
&lt;br /&gt;
=Running the Default App =&lt;br /&gt;
* Init and run an app. &lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
&amp;gt; mean init myApp // create your first app&lt;br /&gt;
&amp;gt; cd myApp &lt;br /&gt;
&amp;gt; npm install // Install dependencies&lt;br /&gt;
&amp;gt; grunt // Launch mean&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Make sure MongoDB is connected and running (if you run into problems, refer to the section on MongoDB)&lt;br /&gt;
&lt;br /&gt;
* Go ahead and explore features of the default Article app (such as logging in, adding/deleting articles).&lt;br /&gt;
&lt;br /&gt;
=Generating a Package =&lt;br /&gt;
* By now you should know what a package is in MEAN. If you don't, read [http://learn.mean.io/#mean-io-packages this].&lt;br /&gt;
&lt;br /&gt;
* Try creating a package named myPackage by typing: &lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
&amp;gt; mean package myPackage&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Locate it inside the packages folder:&lt;br /&gt;
* Compare the structure of myPackage folder to that of the default app. Make sure you see both '''public''' and  '''server''' folders and their subfolders.&lt;br /&gt;
* Restart your app, make sure you can see a link to the newly created package.&lt;br /&gt;
&lt;br /&gt;
=A Closer Look at the App =&lt;br /&gt;
Take a look at the directory where you app resides, you will see two folders '''public''' and  '''server''', which contain code for the client side and server side respectively.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Models ==&lt;br /&gt;
&lt;br /&gt;
Open up article.js in /server/models&lt;br /&gt;
&lt;br /&gt;
MEAN is MVC on the client side and the server side.  Since the model is tied to the backend to MongoDB, you will only see the models folder on the server side, which is normal. &lt;br /&gt;
The models are mongoose models that's why we need to require mongoose (what the following line does):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var mongoose = require('mongoose'), Schema = mongoose.Schema;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The following part then defines the schema:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var ArticleSchema = new Schema({&lt;br /&gt;
    created: {&lt;br /&gt;
        type: Date,&lt;br /&gt;
        default: Date.now&lt;br /&gt;
    },&lt;br /&gt;
    title: {&lt;br /&gt;
        type: String,&lt;br /&gt;
        default: '',&lt;br /&gt;
        trim: true&lt;br /&gt;
    },&lt;br /&gt;
    content: {&lt;br /&gt;
        type: String,&lt;br /&gt;
        default: '',&lt;br /&gt;
        trim: true&lt;br /&gt;
    },&lt;br /&gt;
    user: {&lt;br /&gt;
        type: Schema.ObjectId,&lt;br /&gt;
        ref: 'User'&lt;br /&gt;
    }&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The next part is validations, or criteria an object needs to pass before it can be saved to the DB. &lt;br /&gt;
The following code is to make sure that an article has a title:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
ArticleSchema.path('title').validate(function(title) {&lt;br /&gt;
    return title.length;&lt;br /&gt;
}, 'Title cannot be blank');&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, Mongoose allows us to define methods to our data objects as well. &lt;br /&gt;
These are called statics. From the Mongoose doc: Schemas not only define the structure of your document and casting of properties, they also define document instance methods, static Model methods, compound indexes and document lifecycle hooks called middleware.&lt;br /&gt;
The following code defines a method called load for the article schema:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
ArticleSchema.statics.load = function(id, cb) {&lt;br /&gt;
    this.findOne({&lt;br /&gt;
        _id: id&lt;br /&gt;
    }).populate('user', 'name username').exec(cb);&lt;br /&gt;
};&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you have trouble understanding what the code does, review the Mongoose [http://mongoosejs.com/docs/index.html quick start] guide.&lt;br /&gt;
&lt;br /&gt;
=== Models Practice === &lt;br /&gt;
Define a schema for a model named '''Phone''', name it phone.js and save it in the corresponding folder in 'myPackage' (hint: /packages/myPackage/server/models/)&lt;br /&gt;
A product needs to have the following fields with specific types. Here is an example of a Phone object can be stored in the MongoDB:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
    {&lt;br /&gt;
        &amp;quot;age&amp;quot;: 0, &lt;br /&gt;
        &amp;quot;id&amp;quot;: &amp;quot;motorola-xoom-with-wi-fi&amp;quot;, &lt;br /&gt;
        &amp;quot;imageUrl&amp;quot;: &amp;quot;img/phones/motorola-xoom-with-wi-fi.0.jpg&amp;quot;, &lt;br /&gt;
        &amp;quot;name&amp;quot;: &amp;quot;Motorola XOOM\u2122 with Wi-Fi&amp;quot;, &lt;br /&gt;
        &amp;quot;snippet&amp;quot;: &amp;quot;The Next, Next Generation\r\n\r\nExperience the future with Motorola XOOM wi.. d by Android 3.0 (Honeycomb).&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is taken from phones.json used by the AngularJS tutorial. If you have gone through the tutorial, you should have realized that instead of using a DB, json files were used to simplify the tutorial.&lt;br /&gt;
Find phones.json in /app/phones in the angular tutorial folder and try importing its content to MongoDB so you can use them in your current MEAN package.&lt;br /&gt;
&amp;lt;br/&amp;gt; Here is how (assuming mongod is running):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
&amp;gt; mongo --shell // connect to mongo shell &lt;br /&gt;
&amp;gt; use mean-dev // switches to database used by mean.&lt;br /&gt;
&amp;gt; mongoimport --db mean-dev --collection phones --type json --file ''&amp;lt;path to phones.json&amp;gt;'' --jsonArray // imports json file to the DB&lt;br /&gt;
&amp;gt; show collections // check to see if phones are added to your database&lt;br /&gt;
&amp;gt; coll = db.phones // to see the content of the file&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Controllers ==&lt;br /&gt;
&lt;br /&gt;
You'll find a controllers folder on both the server side and the client (public) side.  &lt;br /&gt;
* The client side controllers are part of the Angular MVC scheme that contains client side logic and may issue requests to the server.&lt;br /&gt;
* The server side controllers deal with the models and requests from the client side.&lt;br /&gt;
&lt;br /&gt;
'''Server side:'''&lt;br /&gt;
&lt;br /&gt;
* Find articles.js in the controllers folder. Try to understand what each part does. &lt;br /&gt;
&lt;br /&gt;
'''Client side:''' open up articles.js in /articles/public/controllers&lt;br /&gt;
Compare the functions defined in ArticlesController, can you find the server side implementation of corresponding functions? &lt;br /&gt;
&lt;br /&gt;
Here is a diagram to help you understand how this works:&lt;br /&gt;
&lt;br /&gt;
[[File:Mean.png]]&lt;br /&gt;
&lt;br /&gt;
== Views &amp;amp; Routing ==&lt;br /&gt;
Even though typically views are implemented and used for the client end, routing happens on both ends.&lt;br /&gt;
&lt;br /&gt;
* Find articles.js in /server/routes&lt;br /&gt;
You'll see that it requires the articles controller and its methods for querying the database.&lt;br /&gt;
&lt;br /&gt;
The first section requires the articles controller, which defines different methods &lt;br /&gt;
&lt;br /&gt;
For example, code below tells the server to use a method named &amp;quot;all&amp;quot; in the articles controller when the url is pointed to /articles:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;   &lt;br /&gt;
app.route('/articles')&lt;br /&gt;
      .get(articles.all)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Go to http://localhost:3000/articles, what do you see? Does it make sense?&lt;br /&gt;
&lt;br /&gt;
Let's switch to the public folder where the views reside.  Go to articles/public/views, open up list.html: &amp;lt;br/&amp;gt;&lt;br /&gt;
The first line tells the framework that  ArticlesController is responsible for this particular view and when this view is loaded, use find() to initiate data binding.&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;section data-ng-controller=&amp;quot;ArticlesController&amp;quot; data-ng-init=&amp;quot;find()&amp;quot;&amp;gt; &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Feel free to take a look at what find() does. Make sure you understand that what find() does is actually done by the backend, where a corresponding find() is written (as mentioned above).&lt;br /&gt;
Hopefully you have a better understanding of how these technologies all work together now.&lt;br /&gt;
&lt;br /&gt;
Review the AngularJS section if you have any questions regarding the view data binding.&lt;br /&gt;
&lt;br /&gt;
The view files in articles/views only defines the code for displaying the articles, where does the navigation bar gets defined.&lt;br /&gt;
The answer is in /public/system. &lt;br /&gt;
*The .html files in public/system/views provide a container/layout for the application. &lt;br /&gt;
For example, header.html includes the menu bar (displayed on the top of the page):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;div class=&amp;quot;left pull-left&amp;quot;&amp;gt;&lt;br /&gt;
     &amp;lt;ul class=&amp;quot;navbar-nav nav&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;li data-ng-repeat=&amp;quot;item in menus.main&amp;quot; ui-route=&amp;quot;/{{item.link}}&amp;quot; ng-class=&amp;quot;{active: $uiRoute}&amp;quot;&amp;gt;&lt;br /&gt;
            &amp;lt;a mean-token=&amp;quot;item.link&amp;quot; ui-sref='{{item.link}}'&amp;gt;{{item.title}}&amp;lt;/a&amp;gt;&lt;br /&gt;
        &amp;lt;/li&amp;gt;&lt;br /&gt;
   &amp;lt;/ul&amp;gt;&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Try changing &amp;lt;nowiki&amp;gt;{{item.title}} &amp;lt;/nowiki&amp;gt; inside the &amp;lt;a&amp;gt; &amp;lt;/a&amp;gt;tags to &amp;quot;my articles&amp;quot; see what happens to the page.&lt;br /&gt;
* The ui-sref is &amp;quot;href&amp;quot; in ui-route, an AngularJS plugin, try changing &amp;lt;nowiki&amp;gt;{{item.link}}&amp;lt;/nowiki&amp;gt; to #!/myarticles, &lt;br /&gt;
* What happens to the application now? When you click on &amp;quot;my articles&amp;quot;?&lt;br /&gt;
&lt;br /&gt;
The page to articles is no longer served!&lt;br /&gt;
&lt;br /&gt;
But how does the framework know which page to serve given a certain url?  The file responsible for this (called routing in web development) is in public/articles/routes&lt;br /&gt;
&lt;br /&gt;
open up articles.js in this folder and find the line that specifies the routing scheme for /articles:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            .state('all articles', {&lt;br /&gt;
                url: '/articles',&lt;br /&gt;
                templateUrl: 'public/articles/views/list.html',&lt;br /&gt;
                resolve: {&lt;br /&gt;
                    loggedin: checkLoggedin&lt;br /&gt;
                }&lt;br /&gt;
            }&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is ui-route's way of telling the server what to serve the page specified by the templateUrl when it sees &amp;quot;localhost:3000/#!/phones&amp;quot;. &lt;br /&gt;
The #! is a hash prefix used for MEAN to make ajax calls so make sure to include it when coding your views.&lt;br /&gt;
Now try changing the url to &amp;quot;/myarticles&amp;quot;, save and go back to your app, click on &amp;quot;my articles&amp;quot; now, what happens?&lt;br /&gt;
&lt;br /&gt;
*This is important if you want to customize your navigation bar and links. Just remember that each url needs an entry in the route file, in the format of the example above.&lt;br /&gt;
&lt;br /&gt;
= Practice = &lt;br /&gt;
&lt;br /&gt;
Can you implement a view in your myPackage to display all phones injected in the DB? &lt;br /&gt;
Hint: myPackage has the same file structure as the default app.&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Getting_MEAN&amp;diff=1850</id>
		<title>Getting MEAN</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Getting_MEAN&amp;diff=1850"/>
		<updated>2015-01-07T12:21:55Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* What did all that mean? */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Installation=&lt;br /&gt;
To install MEAN, make sure you already have all of the following components installed and configured correctly.&lt;br /&gt;
&amp;lt;br/&amp;gt;&lt;br /&gt;
'''1. Node.js''' (should come with npm) &amp;lt;br/&amp;gt;&lt;br /&gt;
To find out if you have node and npm, try checking their versions (may not be the same):&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
node --version&lt;br /&gt;
v0.10.25&lt;br /&gt;
npm --version&lt;br /&gt;
1.3.24&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
IF you don't have node.js, install it [http://nodejs.org/ here].&lt;br /&gt;
&lt;br /&gt;
'''2. Bower'''&lt;br /&gt;
&lt;br /&gt;
Bower is a web application manager used by MEAN. To install bower, type the following command in your terminal: &lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;npm install -g bower&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''3. MongoDB'''&lt;br /&gt;
To install MongoDB, follow the instructions for your OS [http://docs.mongodb.org/manual/installation/ here].&lt;br /&gt;
&lt;br /&gt;
'''4. Grunt'''&lt;br /&gt;
To install Grunt type the following command:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;npm install -g grunt-cli&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''5. and finally, MEAN'''&lt;br /&gt;
In your terminal, type:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt; &amp;gt; sudo npm install -g mean-cli &amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* MEAN stack documentations are available [http://mean.io/#!/docs here]. They'll help you to get familiar with the file structure and idioms.&lt;br /&gt;
&lt;br /&gt;
== What did all that mean? ==&lt;br /&gt;
&lt;br /&gt;
You just used three different command line tools.  Here's what they all do.&lt;br /&gt;
&lt;br /&gt;
* '''npm''' is the package manager for Node.JS.  It installs libraries for use by your Node.JS applications.  The configuration file for ''npm'' (the list of packages for ''npm'' to install) is ''package.json''.&lt;br /&gt;
* '''bower''' is a package manager for front-end libraries.  Rather than manually downloading your jQuery, Bootstrap, Angular, and other front-end JavaScript and CSS (and remembering to update them when a new version of one of those libraries comes out), ''bower'' installs them for you.  The configuration file for ''bower'' (the list of packages for ''bower'' to install) is ''bower.json''.&lt;br /&gt;
* '''grunt''' is a build tool designed for JavaScript.  It's like ''make'' or ''ant'', but for JavaScript.  The configuration file for ''grunt'' (the list of commands to run when building your project) is ''Gruntfile.js''.&lt;br /&gt;
&lt;br /&gt;
Don't be confused by the fact that you use ''npm'' to install ''bower'' and ''grunt''.  The people who made ''bower'' and ''grunt'' just both decided to use ''npm'' as the place to publish their projects, probably because the executables themselves are written in Node.JS.  They could just as well have chosen ''apt-get'' or ''yum'' or any of the other package managers you've been using in this class.&lt;br /&gt;
&lt;br /&gt;
=Running the Default App =&lt;br /&gt;
* Init and run an app. &lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
&amp;gt; mean init myApp // create your first app&lt;br /&gt;
&amp;gt; cd myApp &lt;br /&gt;
&amp;gt; npm install // Install dependencies&lt;br /&gt;
&amp;gt; grunt // Launch mean&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Make sure MongoDB is connected and running (if you run into problems, refer to the section on MongoDB)&lt;br /&gt;
&lt;br /&gt;
* Go ahead and explore features of the default Article app (such as logging in, adding/deleting articles).&lt;br /&gt;
&lt;br /&gt;
=Generating a Package =&lt;br /&gt;
* By now you should know what a package is in MEAN. If you don't, read [http://learn.mean.io/#mean-io-packages this].&lt;br /&gt;
&lt;br /&gt;
* Try creating a package named myPackage by typing: &lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
&amp;gt; mean package myPackage&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Locate it inside the packages folder:&lt;br /&gt;
* Compare the structure of myPackage folder to that of the default app. Make sure you see both '''public''' and  '''server''' folders and their subfolders.&lt;br /&gt;
* Restart your app, make sure you can see a link to the newly created package.&lt;br /&gt;
&lt;br /&gt;
=A Closer Look at the App =&lt;br /&gt;
Take a look at the directory where you app resides, you will see two folders '''public''' and  '''server''', which contain code for the client side and server side respectively.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Models ==&lt;br /&gt;
&lt;br /&gt;
Open up article.js in /server/models&lt;br /&gt;
&lt;br /&gt;
MEAN is MVC on the client side and the server side.  Since the model is tied to the backend to MongoDB, you will only see the models folder on the server side, which is normal. &lt;br /&gt;
The models are mongoose models that's why we need to require mongoose (what the following line does):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var mongoose = require('mongoose'), Schema = mongoose.Schema;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The following part then defines the schema:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var ArticleSchema = new Schema({&lt;br /&gt;
    created: {&lt;br /&gt;
        type: Date,&lt;br /&gt;
        default: Date.now&lt;br /&gt;
    },&lt;br /&gt;
    title: {&lt;br /&gt;
        type: String,&lt;br /&gt;
        default: '',&lt;br /&gt;
        trim: true&lt;br /&gt;
    },&lt;br /&gt;
    content: {&lt;br /&gt;
        type: String,&lt;br /&gt;
        default: '',&lt;br /&gt;
        trim: true&lt;br /&gt;
    },&lt;br /&gt;
    user: {&lt;br /&gt;
        type: Schema.ObjectId,&lt;br /&gt;
        ref: 'User'&lt;br /&gt;
    }&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The next part is validations, or criteria an object needs to pass before it can be saved to the DB. &lt;br /&gt;
The following code is to make sure that an article has a title:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
ArticleSchema.path('title').validate(function(title) {&lt;br /&gt;
    return title.length;&lt;br /&gt;
}, 'Title cannot be blank');&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, Mongoose allows us to define methods to our data objects as well. &lt;br /&gt;
These are called statics. From the Mongoose doc: Schemas not only define the structure of your document and casting of properties, they also define document instance methods, static Model methods, compound indexes and document lifecycle hooks called middleware.&lt;br /&gt;
The following code defines a method called load for the article schema:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
ArticleSchema.statics.load = function(id, cb) {&lt;br /&gt;
    this.findOne({&lt;br /&gt;
        _id: id&lt;br /&gt;
    }).populate('user', 'name username').exec(cb);&lt;br /&gt;
};&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you have trouble understanding what the code does, review the Mongoose [http://mongoosejs.com/docs/index.html quick start] guide.&lt;br /&gt;
&lt;br /&gt;
=== Models Practice === &lt;br /&gt;
Define a schema for a model named '''Phone''', name it phone.js and save it in the corresponding folder in 'myPackage' (hint: /packages/myPackage/server/models/)&lt;br /&gt;
A product needs to have the following fields with specific types. Here is an example of a Phone object can be stored in the MongoDB:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
    {&lt;br /&gt;
        &amp;quot;age&amp;quot;: 0, &lt;br /&gt;
        &amp;quot;id&amp;quot;: &amp;quot;motorola-xoom-with-wi-fi&amp;quot;, &lt;br /&gt;
        &amp;quot;imageUrl&amp;quot;: &amp;quot;img/phones/motorola-xoom-with-wi-fi.0.jpg&amp;quot;, &lt;br /&gt;
        &amp;quot;name&amp;quot;: &amp;quot;Motorola XOOM\u2122 with Wi-Fi&amp;quot;, &lt;br /&gt;
        &amp;quot;snippet&amp;quot;: &amp;quot;The Next, Next Generation\r\n\r\nExperience the future with Motorola XOOM wi.. d by Android 3.0 (Honeycomb).&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is taken from phones.json used by the AngularJS tutorial. If you have gone through the tutorial, you should have realized that instead of using a DB, json files were used to simplify the tutorial.&lt;br /&gt;
Find phones.json in /app/phones in the angular tutorial folder and try importing its content to MongoDB so you can use them in your current MEAN package.&lt;br /&gt;
&amp;lt;br/&amp;gt; Here is how (assuming mongod is running):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
&amp;gt; mongo --shell // connect to mongo shell &lt;br /&gt;
&amp;gt; use mean-dev // switches to database used by mean.&lt;br /&gt;
&amp;gt; mongoimport --db mean-dev --collection phones --type json --file ''&amp;lt;path to phones.json&amp;gt;'' --jsonArray // imports json file to the DB&lt;br /&gt;
&amp;gt; show collections // check to see if phones are added to your database&lt;br /&gt;
&amp;gt; coll = db.phones // to see the content of the file&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Controllers ==&lt;br /&gt;
&lt;br /&gt;
You'll find a controllers folder on both the server side and the client (public) side.  &lt;br /&gt;
* The client side controllers are part of the Angular MVC scheme that contains client side logic and may issue requests to the server.&lt;br /&gt;
* The server side controllers deal with the models and requests from the client side.&lt;br /&gt;
&lt;br /&gt;
'''Server side:'''&lt;br /&gt;
&lt;br /&gt;
* Find articles.js in the controllers folder. Try to understand what each part does. &lt;br /&gt;
&lt;br /&gt;
'''Client side:''' open up articles.js in /articles/public/controllers&lt;br /&gt;
Compare the functions defined in ArticlesController, can you find the server side implementation of corresponding functions? &lt;br /&gt;
&lt;br /&gt;
Here is a diagram to help you understand how this works:&lt;br /&gt;
&lt;br /&gt;
[[File:Mean.png]]&lt;br /&gt;
&lt;br /&gt;
== Views &amp;amp; Routing ==&lt;br /&gt;
Even though typically views are implemented and used for the client end, routing happens on both ends.&lt;br /&gt;
&lt;br /&gt;
* Find articles.js in /server/routes&lt;br /&gt;
You'll see that it requires the articles controller and its methods for querying the database.&lt;br /&gt;
&lt;br /&gt;
The first section requires the articles controller, which defines different methods &lt;br /&gt;
&lt;br /&gt;
For example, code below tells the server to use a method named &amp;quot;all&amp;quot; in the articles controller when the url is pointed to /articles:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;   &lt;br /&gt;
app.route('/articles')&lt;br /&gt;
      .get(articles.all)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Go to http://localhost:3000/articles, what do you see? Does it make sense?&lt;br /&gt;
&lt;br /&gt;
Let's switch to the public folder where the views reside.  Go to articles/public/views, open up list.html: &amp;lt;br/&amp;gt;&lt;br /&gt;
The first line tells the framework that  ArticlesController is responsible for this particular view and when this view is loaded, use find() to initiate data binding.&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;section data-ng-controller=&amp;quot;ArticlesController&amp;quot; data-ng-init=&amp;quot;find()&amp;quot;&amp;gt; &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Feel free to take a look at what find() does. Make sure you understand that what find() does is actually done by the backend, where a corresponding find() is written (as mentioned above).&lt;br /&gt;
Hopefully you have a better understanding of how these technologies all work together now.&lt;br /&gt;
&lt;br /&gt;
Review the AngularJS section if you have any questions regarding the view data binding.&lt;br /&gt;
&lt;br /&gt;
The view files in articles/views only defines the code for displaying the articles, where does the navigation bar gets defined.&lt;br /&gt;
The answer is in /public/system. &lt;br /&gt;
*The .html files in public/system/views provide a container/layout for the application. &lt;br /&gt;
For example, header.html includes the menu bar (displayed on the top of the page):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;div class=&amp;quot;left pull-left&amp;quot;&amp;gt;&lt;br /&gt;
     &amp;lt;ul class=&amp;quot;navbar-nav nav&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;li data-ng-repeat=&amp;quot;item in menus.main&amp;quot; ui-route=&amp;quot;/{{item.link}}&amp;quot; ng-class=&amp;quot;{active: $uiRoute}&amp;quot;&amp;gt;&lt;br /&gt;
            &amp;lt;a mean-token=&amp;quot;item.link&amp;quot; ui-sref='{{item.link}}'&amp;gt;{{item.title}}&amp;lt;/a&amp;gt;&lt;br /&gt;
        &amp;lt;/li&amp;gt;&lt;br /&gt;
   &amp;lt;/ul&amp;gt;&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Try changing &amp;lt;nowiki&amp;gt;{{item.title}} &amp;lt;/nowiki&amp;gt; inside the &amp;lt;a&amp;gt; &amp;lt;/a&amp;gt;tags to &amp;quot;my articles&amp;quot; see what happens to the page.&lt;br /&gt;
* The ui-sref is &amp;quot;href&amp;quot; in ui-route, an AngularJS plugin, try changing &amp;lt;nowiki&amp;gt;{{item.link}}&amp;lt;/nowiki&amp;gt; to #!/myarticles, &lt;br /&gt;
* What happens to the application now? When you click on &amp;quot;my articles&amp;quot;?&lt;br /&gt;
&lt;br /&gt;
The page to articles is no longer served!&lt;br /&gt;
&lt;br /&gt;
But how does the framework know which page to serve given a certain url?  The file responsible for this (called routing in web development) is in public/articles/routes&lt;br /&gt;
&lt;br /&gt;
open up articles.js in this folder and find the line that specifies the routing scheme for /articles:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            .state('all articles', {&lt;br /&gt;
                url: '/articles',&lt;br /&gt;
                templateUrl: 'public/articles/views/list.html',&lt;br /&gt;
                resolve: {&lt;br /&gt;
                    loggedin: checkLoggedin&lt;br /&gt;
                }&lt;br /&gt;
            }&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is ui-route's way of telling the server what to serve the page specified by the templateUrl when it sees &amp;quot;localhost:3000/#!/phones&amp;quot;. &lt;br /&gt;
The #! is a hash prefix used for MEAN to make ajax calls so make sure to include it when coding your views.&lt;br /&gt;
Now try changing the url to &amp;quot;/myarticles&amp;quot;, save and go back to your app, click on &amp;quot;my articles&amp;quot; now, what happens?&lt;br /&gt;
&lt;br /&gt;
*This is important if you want to customize your navigation bar and links. Just remember that each url needs an entry in the route file, in the format of the example above.&lt;br /&gt;
&lt;br /&gt;
= Practice = &lt;br /&gt;
&lt;br /&gt;
Can you implement a view in your myPackage to display all phones injected in the DB? &lt;br /&gt;
Hint: myPackage has the same file structure as the default app.&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Getting_MEAN&amp;diff=1849</id>
		<title>Getting MEAN</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Getting_MEAN&amp;diff=1849"/>
		<updated>2015-01-07T12:18:44Z</updated>

		<summary type="html">&lt;p&gt;Shane: Adding explanation of npm, bower, and grunt.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Installation=&lt;br /&gt;
To install MEAN, make sure you already have all of the following components installed and configured correctly.&lt;br /&gt;
&amp;lt;br/&amp;gt;&lt;br /&gt;
'''1. Node.js''' (should come with npm) &amp;lt;br/&amp;gt;&lt;br /&gt;
To find out if you have node and npm, try checking their versions (may not be the same):&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
node --version&lt;br /&gt;
v0.10.25&lt;br /&gt;
npm --version&lt;br /&gt;
1.3.24&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
IF you don't have node.js, install it [http://nodejs.org/ here].&lt;br /&gt;
&lt;br /&gt;
'''2. Bower'''&lt;br /&gt;
&lt;br /&gt;
Bower is a web application manager used by MEAN. To install bower, type the following command in your terminal: &lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;npm install -g bower&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''3. MongoDB'''&lt;br /&gt;
To install MongoDB, follow the instructions for your OS [http://docs.mongodb.org/manual/installation/ here].&lt;br /&gt;
&lt;br /&gt;
'''4. Grunt'''&lt;br /&gt;
To install Grunt type the following command:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;npm install -g grunt-cli&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''5. and finally, MEAN'''&lt;br /&gt;
In your terminal, type:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt; &amp;gt; sudo npm install -g mean-cli &amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* MEAN stack documentations are available [http://mean.io/#!/docs here]. They'll help you to get familiar with the file structure and idioms.&lt;br /&gt;
&lt;br /&gt;
== What did all that mean? ==&lt;br /&gt;
&lt;br /&gt;
You just used three different command line tools.  Here's what they all do.&lt;br /&gt;
&lt;br /&gt;
* '''npm''' is the package manager for Node.JS.  It installs libraries for use by your Node.JS applications.  The configuration file for ''npm'' (the list of packages for ''npm'' to install) is ''package.json''.&lt;br /&gt;
* '''bower''' is a package manager for front-end libraries.  Rather than manually downloading your jQuery, Bootstrap, Angular, and other front-end JavaScript and CSS (and remembering to update them when a new version of one of those libraries comes out), ''bower'' installs them for you.  The configuration file for ''bower'' (the list of packages for ''bower'' to install) is ''bower.json''.&lt;br /&gt;
* '''grunt''' is a build tool designed for JavaScript.  It's like ''make'' or ''ant'', but for JavaScript.  The configuration file for ''grunt'' (the list of commands to run when building your project) is ''Gruntfile.js''.&lt;br /&gt;
&lt;br /&gt;
=Running the Default App =&lt;br /&gt;
* Init and run an app. &lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
&amp;gt; mean init myApp // create your first app&lt;br /&gt;
&amp;gt; cd myApp &lt;br /&gt;
&amp;gt; npm install // Install dependencies&lt;br /&gt;
&amp;gt; grunt // Launch mean&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Make sure MongoDB is connected and running (if you run into problems, refer to the section on MongoDB)&lt;br /&gt;
&lt;br /&gt;
* Go ahead and explore features of the default Article app (such as logging in, adding/deleting articles).&lt;br /&gt;
&lt;br /&gt;
=Generating a Package =&lt;br /&gt;
* By now you should know what a package is in MEAN. If you don't, read [http://learn.mean.io/#mean-io-packages this].&lt;br /&gt;
&lt;br /&gt;
* Try creating a package named myPackage by typing: &lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
&amp;gt; mean package myPackage&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Locate it inside the packages folder:&lt;br /&gt;
* Compare the structure of myPackage folder to that of the default app. Make sure you see both '''public''' and  '''server''' folders and their subfolders.&lt;br /&gt;
* Restart your app, make sure you can see a link to the newly created package.&lt;br /&gt;
&lt;br /&gt;
=A Closer Look at the App =&lt;br /&gt;
Take a look at the directory where you app resides, you will see two folders '''public''' and  '''server''', which contain code for the client side and server side respectively.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Models ==&lt;br /&gt;
&lt;br /&gt;
Open up article.js in /server/models&lt;br /&gt;
&lt;br /&gt;
MEAN is MVC on the client side and the server side.  Since the model is tied to the backend to MongoDB, you will only see the models folder on the server side, which is normal. &lt;br /&gt;
The models are mongoose models that's why we need to require mongoose (what the following line does):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var mongoose = require('mongoose'), Schema = mongoose.Schema;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The following part then defines the schema:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var ArticleSchema = new Schema({&lt;br /&gt;
    created: {&lt;br /&gt;
        type: Date,&lt;br /&gt;
        default: Date.now&lt;br /&gt;
    },&lt;br /&gt;
    title: {&lt;br /&gt;
        type: String,&lt;br /&gt;
        default: '',&lt;br /&gt;
        trim: true&lt;br /&gt;
    },&lt;br /&gt;
    content: {&lt;br /&gt;
        type: String,&lt;br /&gt;
        default: '',&lt;br /&gt;
        trim: true&lt;br /&gt;
    },&lt;br /&gt;
    user: {&lt;br /&gt;
        type: Schema.ObjectId,&lt;br /&gt;
        ref: 'User'&lt;br /&gt;
    }&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The next part is validations, or criteria an object needs to pass before it can be saved to the DB. &lt;br /&gt;
The following code is to make sure that an article has a title:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
ArticleSchema.path('title').validate(function(title) {&lt;br /&gt;
    return title.length;&lt;br /&gt;
}, 'Title cannot be blank');&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, Mongoose allows us to define methods to our data objects as well. &lt;br /&gt;
These are called statics. From the Mongoose doc: Schemas not only define the structure of your document and casting of properties, they also define document instance methods, static Model methods, compound indexes and document lifecycle hooks called middleware.&lt;br /&gt;
The following code defines a method called load for the article schema:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
ArticleSchema.statics.load = function(id, cb) {&lt;br /&gt;
    this.findOne({&lt;br /&gt;
        _id: id&lt;br /&gt;
    }).populate('user', 'name username').exec(cb);&lt;br /&gt;
};&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you have trouble understanding what the code does, review the Mongoose [http://mongoosejs.com/docs/index.html quick start] guide.&lt;br /&gt;
&lt;br /&gt;
=== Models Practice === &lt;br /&gt;
Define a schema for a model named '''Phone''', name it phone.js and save it in the corresponding folder in 'myPackage' (hint: /packages/myPackage/server/models/)&lt;br /&gt;
A product needs to have the following fields with specific types. Here is an example of a Phone object can be stored in the MongoDB:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
    {&lt;br /&gt;
        &amp;quot;age&amp;quot;: 0, &lt;br /&gt;
        &amp;quot;id&amp;quot;: &amp;quot;motorola-xoom-with-wi-fi&amp;quot;, &lt;br /&gt;
        &amp;quot;imageUrl&amp;quot;: &amp;quot;img/phones/motorola-xoom-with-wi-fi.0.jpg&amp;quot;, &lt;br /&gt;
        &amp;quot;name&amp;quot;: &amp;quot;Motorola XOOM\u2122 with Wi-Fi&amp;quot;, &lt;br /&gt;
        &amp;quot;snippet&amp;quot;: &amp;quot;The Next, Next Generation\r\n\r\nExperience the future with Motorola XOOM wi.. d by Android 3.0 (Honeycomb).&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is taken from phones.json used by the AngularJS tutorial. If you have gone through the tutorial, you should have realized that instead of using a DB, json files were used to simplify the tutorial.&lt;br /&gt;
Find phones.json in /app/phones in the angular tutorial folder and try importing its content to MongoDB so you can use them in your current MEAN package.&lt;br /&gt;
&amp;lt;br/&amp;gt; Here is how (assuming mongod is running):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
&amp;gt; mongo --shell // connect to mongo shell &lt;br /&gt;
&amp;gt; use mean-dev // switches to database used by mean.&lt;br /&gt;
&amp;gt; mongoimport --db mean-dev --collection phones --type json --file ''&amp;lt;path to phones.json&amp;gt;'' --jsonArray // imports json file to the DB&lt;br /&gt;
&amp;gt; show collections // check to see if phones are added to your database&lt;br /&gt;
&amp;gt; coll = db.phones // to see the content of the file&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Controllers ==&lt;br /&gt;
&lt;br /&gt;
You'll find a controllers folder on both the server side and the client (public) side.  &lt;br /&gt;
* The client side controllers are part of the Angular MVC scheme that contains client side logic and may issue requests to the server.&lt;br /&gt;
* The server side controllers deal with the models and requests from the client side.&lt;br /&gt;
&lt;br /&gt;
'''Server side:'''&lt;br /&gt;
&lt;br /&gt;
* Find articles.js in the controllers folder. Try to understand what each part does. &lt;br /&gt;
&lt;br /&gt;
'''Client side:''' open up articles.js in /articles/public/controllers&lt;br /&gt;
Compare the functions defined in ArticlesController, can you find the server side implementation of corresponding functions? &lt;br /&gt;
&lt;br /&gt;
Here is a diagram to help you understand how this works:&lt;br /&gt;
&lt;br /&gt;
[[File:Mean.png]]&lt;br /&gt;
&lt;br /&gt;
== Views &amp;amp; Routing ==&lt;br /&gt;
Even though typically views are implemented and used for the client end, routing happens on both ends.&lt;br /&gt;
&lt;br /&gt;
* Find articles.js in /server/routes&lt;br /&gt;
You'll see that it requires the articles controller and its methods for querying the database.&lt;br /&gt;
&lt;br /&gt;
The first section requires the articles controller, which defines different methods &lt;br /&gt;
&lt;br /&gt;
For example, code below tells the server to use a method named &amp;quot;all&amp;quot; in the articles controller when the url is pointed to /articles:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;   &lt;br /&gt;
app.route('/articles')&lt;br /&gt;
      .get(articles.all)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Go to http://localhost:3000/articles, what do you see? Does it make sense?&lt;br /&gt;
&lt;br /&gt;
Let's switch to the public folder where the views reside.  Go to articles/public/views, open up list.html: &amp;lt;br/&amp;gt;&lt;br /&gt;
The first line tells the framework that  ArticlesController is responsible for this particular view and when this view is loaded, use find() to initiate data binding.&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;section data-ng-controller=&amp;quot;ArticlesController&amp;quot; data-ng-init=&amp;quot;find()&amp;quot;&amp;gt; &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Feel free to take a look at what find() does. Make sure you understand that what find() does is actually done by the backend, where a corresponding find() is written (as mentioned above).&lt;br /&gt;
Hopefully you have a better understanding of how these technologies all work together now.&lt;br /&gt;
&lt;br /&gt;
Review the AngularJS section if you have any questions regarding the view data binding.&lt;br /&gt;
&lt;br /&gt;
The view files in articles/views only defines the code for displaying the articles, where does the navigation bar gets defined.&lt;br /&gt;
The answer is in /public/system. &lt;br /&gt;
*The .html files in public/system/views provide a container/layout for the application. &lt;br /&gt;
For example, header.html includes the menu bar (displayed on the top of the page):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;div class=&amp;quot;left pull-left&amp;quot;&amp;gt;&lt;br /&gt;
     &amp;lt;ul class=&amp;quot;navbar-nav nav&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;li data-ng-repeat=&amp;quot;item in menus.main&amp;quot; ui-route=&amp;quot;/{{item.link}}&amp;quot; ng-class=&amp;quot;{active: $uiRoute}&amp;quot;&amp;gt;&lt;br /&gt;
            &amp;lt;a mean-token=&amp;quot;item.link&amp;quot; ui-sref='{{item.link}}'&amp;gt;{{item.title}}&amp;lt;/a&amp;gt;&lt;br /&gt;
        &amp;lt;/li&amp;gt;&lt;br /&gt;
   &amp;lt;/ul&amp;gt;&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Try changing &amp;lt;nowiki&amp;gt;{{item.title}} &amp;lt;/nowiki&amp;gt; inside the &amp;lt;a&amp;gt; &amp;lt;/a&amp;gt;tags to &amp;quot;my articles&amp;quot; see what happens to the page.&lt;br /&gt;
* The ui-sref is &amp;quot;href&amp;quot; in ui-route, an AngularJS plugin, try changing &amp;lt;nowiki&amp;gt;{{item.link}}&amp;lt;/nowiki&amp;gt; to #!/myarticles, &lt;br /&gt;
* What happens to the application now? When you click on &amp;quot;my articles&amp;quot;?&lt;br /&gt;
&lt;br /&gt;
The page to articles is no longer served!&lt;br /&gt;
&lt;br /&gt;
But how does the framework know which page to serve given a certain url?  The file responsible for this (called routing in web development) is in public/articles/routes&lt;br /&gt;
&lt;br /&gt;
open up articles.js in this folder and find the line that specifies the routing scheme for /articles:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
            .state('all articles', {&lt;br /&gt;
                url: '/articles',&lt;br /&gt;
                templateUrl: 'public/articles/views/list.html',&lt;br /&gt;
                resolve: {&lt;br /&gt;
                    loggedin: checkLoggedin&lt;br /&gt;
                }&lt;br /&gt;
            }&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is ui-route's way of telling the server what to serve the page specified by the templateUrl when it sees &amp;quot;localhost:3000/#!/phones&amp;quot;. &lt;br /&gt;
The #! is a hash prefix used for MEAN to make ajax calls so make sure to include it when coding your views.&lt;br /&gt;
Now try changing the url to &amp;quot;/myarticles&amp;quot;, save and go back to your app, click on &amp;quot;my articles&amp;quot; now, what happens?&lt;br /&gt;
&lt;br /&gt;
*This is important if you want to customize your navigation bar and links. Just remember that each url needs an entry in the route file, in the format of the example above.&lt;br /&gt;
&lt;br /&gt;
= Practice = &lt;br /&gt;
&lt;br /&gt;
Can you implement a view in your myPackage to display all phones injected in the DB? &lt;br /&gt;
Hint: myPackage has the same file structure as the default app.&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=1826</id>
		<title>Node.JS</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=1826"/>
		<updated>2014-11-03T18:29:49Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* Installing Node.JS */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;AJAX is a useful technology for web applications that need to pull periodic updates from your server.  But what do you do when you have thousands of clients all requesting data that changes real-time?  A PHP+AJAX approach would choke.  It is situations like these that Node.JS comes to the rescue.&lt;br /&gt;
&lt;br /&gt;
== Non-Blocking I/O ==&lt;br /&gt;
&lt;br /&gt;
You dabbled in the concept of non-blocking I/O when you implemented AJAX in the previous JavaScript module.  Node.JS uses this execution model at its core.&lt;br /&gt;
&lt;br /&gt;
The core idea is the use of '''''anonymous functions''''' as ''callbacks'' for processing the results of intensive operations.  Consider the pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
var data = database.query(&amp;quot;select * from news&amp;quot;);&lt;br /&gt;
print data[0].title;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above pseudo-code queries a database, saves the result of the query in a variable named ''data'', and then prints out the first title in ''data''.  The problem arises when multiple clients all want to access the server at the same time.  ''In a blocking I/O model, a client needs to wait until all other clients are finished before it can start its process.''  With intensive operations and thousands of clients, this can easily crash your server!&lt;br /&gt;
&lt;br /&gt;
The solution is to use ''non-blocking I/O''.  Consider this revised pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Non-Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
database.query(&amp;quot;select * from news&amp;quot;, function(data){&lt;br /&gt;
	print data[0].title;&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The revised pseudo-code achieves the same end result as the first version.  However, ''it allows other clients to perform tasks while this process is waiting for the database to be queried!''  The code occurs in two parts: first, we start the query.  Second, ''when the query is complete'', our '''anonymous callback function''' is executed.  In Node.JS, callback functions are usually passed one or more parameters.&lt;br /&gt;
&lt;br /&gt;
Better yet, with non-blocking I/O, you have no concurrency issues, because everything runs in just one thread.  Nifty!&lt;br /&gt;
&lt;br /&gt;
== Installing Node.JS ==&lt;br /&gt;
&lt;br /&gt;
You can get Node.JS from yum or apt-get, but the versions are going to be out dated.  Remember that Node.JS is a rapidly changing language, so a version of Node from last year is going to be drastically different than a version of Node today.&lt;br /&gt;
&lt;br /&gt;
The unofficial instructions for installing Node.JS can be found here: https://gist.github.com/isaacs/579814&lt;br /&gt;
&lt;br /&gt;
There are several choices, but my favorite is probably ''use-nave-no-shell.sh''.&lt;br /&gt;
&lt;br /&gt;
The instructions at the above link have a couple bugs.  If you run this sequence of commands, Node and NPM will install correctly:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ mkdir ~/.nave&lt;br /&gt;
$ cd ~/.nave&lt;br /&gt;
$ wget http://github.com/isaacs/nave/raw/master/nave.sh&lt;br /&gt;
$ sudo ln -s $PWD/nave.sh /usr/local/bin/nave&lt;br /&gt;
$ chmod a+x nave.sh&lt;br /&gt;
$ sudo chown -R $USER:$USER /usr/local&lt;br /&gt;
$ nave usemain stable&lt;br /&gt;
$ curl https://www.npmjs.org/install.sh | sh&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Your First Node.JS Application: Hello World ==&lt;br /&gt;
&lt;br /&gt;
Let's try running the example application given on the front page of nodejs.org:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var http = require('http');&lt;br /&gt;
http.createServer(function (req, res) {&lt;br /&gt;
	res.writeHead(200, {&lt;br /&gt;
		'Content-Type': 'text/plain'&lt;br /&gt;
	});&lt;br /&gt;
	res.end('Hello World\n');&lt;br /&gt;
}).listen(1337);&lt;br /&gt;
console.log('Server running at http://localhost:1337/');&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Paste the example into a file named `hello.js`, and then run it by calling `node hello.js`.  You should now be able to see your Hello World by visiting your server at port 1337!  (Press ^C to stop the application.)  '''Note:''' If you're running the code from your EC2 instance, you will need to open port 1337.&lt;br /&gt;
&lt;br /&gt;
Let's walk through each line in the above example.&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;code&amp;gt;var http = require('http');&amp;lt;/code&amp;gt; enables us to use Node's built-in HTTP server.  We've been spoiled that languages like PHP automatically load all of the libraries that we need.  However, '''''most functionality in Node.JS is NOT loaded by default.'''''  When you want to use any non-fundamental feature of Node, you need to ''require'' it into a variable, as this example does with the HTTP package.  You should be familiar with this concept when you needed to use ArrayList and other specialty packages in Java in CSE 132.&lt;br /&gt;
* &amp;lt;code&amp;gt;http.createServer(function (req, res) { ... }).listen(1337);&amp;lt;/code&amp;gt; uses the HTTP server API to listen for HTTP connections on port 1337.  The anonymous callback function will be called whenever a connection is made.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.writeHead(200, { 'Content-Type': 'text/plain' });&amp;lt;/code&amp;gt; specifies the Content-Type header to be &amp;quot;text/plain&amp;quot;.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.end('Hello World\n');&amp;lt;/code&amp;gt; writes &amp;quot;Hello World&amp;quot; to the response.&lt;br /&gt;
&lt;br /&gt;
Note the use of non-blocking I/O, even in this one little example.  ''Whenever a connection is made, the callback function will be called and passed parameters associated with that connection.''&lt;br /&gt;
&lt;br /&gt;
== A Static Fileserver Using Node.JS ==&lt;br /&gt;
&lt;br /&gt;
Node.JS does not automatically serve up static files in the way that an Apache/PHP does.  We need to either use an extension that handles this for us, like Express, or we need to write our own code to make a simple static fileserver.  The latter option is really not all that difficult, and it gives good insight into how a static fileserver works.&lt;br /&gt;
&lt;br /&gt;
=== Installing Packages ===&lt;br /&gt;
&lt;br /&gt;
In order for the example code below to work, you need to install the ''mime'' package.  To do this, '''cd to the working directory where you will save your Node.JS JavaScript file''' and run:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;$ npm install mime&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''npm'' is the package manager for Node.JS.  Unlike all of the package managers we've used up to this point, ''npm'' installs dependencies locally, ''not'' globally.  This means that you can have two different projects using different versions of the same package.  ''npm'' will create a ''node_modules'' directory in the CWD and will install the packages into it.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' When using npm to install local dependencies, '''''do not use sudo'''''.  It will screw up your file permissions.&lt;br /&gt;
&lt;br /&gt;
=== Static Fileserver Code ===&lt;br /&gt;
&lt;br /&gt;
The following code will make an HTTP server on port 3456 that serves up all static files in &amp;lt;STATIC DIRECTORY NAME&amp;gt; relative to app.js.&lt;br /&gt;
&lt;br /&gt;
'''Make an attempt to understand this code.'''  It's important that you are comfortable with the non-blocking nature, as well as how we handle file I/O.  There may be quiz questions about this code.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Require the functionality we need to use:&lt;br /&gt;
var http = require('http'),&lt;br /&gt;
	url = require('url'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	mime = require('mime'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	fs = require('fs');&lt;br /&gt;
&lt;br /&gt;
// Make a simple fileserver for all of our static content.&lt;br /&gt;
// Everything underneath &amp;lt;STATIC DIRECTORY NAME&amp;gt; will be served.&lt;br /&gt;
var app = http.createServer(function(req, resp){&lt;br /&gt;
	var filename = path.join(__dirname, &amp;quot;&amp;lt;STATIC DIRECTORY NAME&amp;gt;&amp;quot;, url.parse(req.url).pathname);&lt;br /&gt;
	(fs.exists || path.exists)(filename, function(exists){&lt;br /&gt;
		if (exists) {&lt;br /&gt;
			fs.readFile(filename, function(err, data){&lt;br /&gt;
				if (err) {&lt;br /&gt;
					// File exists but is not readable (permissions issue?)&lt;br /&gt;
					resp.writeHead(500, {&lt;br /&gt;
						&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
					});&lt;br /&gt;
					resp.write(&amp;quot;Internal server error: could not read file&amp;quot;);&lt;br /&gt;
					resp.end();&lt;br /&gt;
					return;&lt;br /&gt;
				}&lt;br /&gt;
				&lt;br /&gt;
				// File exists and is readable&lt;br /&gt;
				var mimetype = mime.lookup(filename);&lt;br /&gt;
				resp.writeHead(200, {&lt;br /&gt;
					&amp;quot;Content-Type&amp;quot;: mimetype&lt;br /&gt;
				});&lt;br /&gt;
				resp.write(data);&lt;br /&gt;
				resp.end();&lt;br /&gt;
				return;&lt;br /&gt;
			});&lt;br /&gt;
		}else{&lt;br /&gt;
			// File does not exist&lt;br /&gt;
			resp.writeHead(404, {&lt;br /&gt;
				&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
			});&lt;br /&gt;
			resp.write(&amp;quot;Requested file not found: &amp;quot;+filename);&lt;br /&gt;
			resp.end();&lt;br /&gt;
			return;&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
app.listen(3456);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Port 3456 ===&lt;br /&gt;
&lt;br /&gt;
We are running our server on port 3456 as opposed to the default web server port, which of course is 80.  We therefore need to open our Node.JS application like this:&lt;br /&gt;
&lt;br /&gt;
http://ec2-xx-xx-xx-xx.compute-1.amazonaws.com:3456/path.extension&lt;br /&gt;
&lt;br /&gt;
However, this won't work on the first time.  ''Why?'' (Try to figure this out on your own before reading the next paragraph.)&lt;br /&gt;
&lt;br /&gt;
We need to open port 3456 on our Amazon EC2 instance.  Remember when you opened port 80 way back in Module 2?  We need to do the same sort of procedure again now.&lt;br /&gt;
&lt;br /&gt;
# Log into your EC2 management console&lt;br /&gt;
# Go to &amp;quot;Security Groups&amp;quot;&lt;br /&gt;
# Select your security group from Module 2&lt;br /&gt;
# Under &amp;quot;Inbound&amp;quot;, create a custom TCP rule for port 3456, and apply your changes.&lt;br /&gt;
&lt;br /&gt;
== Node.JS Security ==&lt;br /&gt;
&lt;br /&gt;
Just because we're writing in JavaScript doesn't mean that we can forget about the security practices you've been learning in the last three months of CSE 330.  XSS is still a problem, as is the use of ''eval'', CSRF attacks, and so on.&lt;br /&gt;
&lt;br /&gt;
Here is a good slideshow introducing Node.JS as well as some security vulnerabilities to look out for: http://www.slideshare.net/ASF-WS/asfws-2012-nodejs-security-old-vulnerabilities-in-new-dresses-par-sven-vetsch&lt;br /&gt;
&lt;br /&gt;
== Node.JS Conventions ==&lt;br /&gt;
&lt;br /&gt;
There ought to be a standard way to save metadata about your app, right?  Well, ''npm'' introduces a straightforward way to do this in the form of a ''package.json'' file.&lt;br /&gt;
&lt;br /&gt;
To make your ''npm'' file with a step-by-step prompt, run in your project root directory:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm init&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One nifty feature of ''package.json'' is the way it automatically handles dependencies.  For example, you can put the following lines in your ''package.json'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
  &amp;quot;dependencies&amp;quot;: {&lt;br /&gt;
    &amp;quot;mime&amp;quot;: &amp;quot;~1.2.11&amp;quot;,&lt;br /&gt;
    &amp;quot;socket.io&amp;quot;: &amp;quot;~0.9.16&amp;quot;,&lt;br /&gt;
  },&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then, back on the command line, when you run&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm install&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
it automatically installs the dependencies for you!  No more headaches of trying to figure out which modules you need to install; all that information is saved for you in your code base.&lt;br /&gt;
&lt;br /&gt;
'''Tip:''' Once you set up your ''package.json'' file, you can automatically add a dependency to it by using the ''--save'' argument on ''npm install'': &amp;lt;code&amp;gt;npm install --save socket.io&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 7]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Socket.IO&amp;diff=1825</id>
		<title>Socket.IO</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Socket.IO&amp;diff=1825"/>
		<updated>2014-11-03T17:55:53Z</updated>

		<summary type="html">&lt;p&gt;Shane: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;AJAX is useful when one-way communication is satisfactory for your web application.  However, what happens when you need two-way communication, like a chat client or multiplayer game?  AJAX isn't the tool for the job.  This is where '''Socket.IO''' comes in.&lt;br /&gt;
&lt;br /&gt;
Built to work natively with Node.JS, Socket.IO enables asynchronous, two-way communication between the server and the client.  This means that the server can send messages to the client without the client having to ask first, as is the case with AJAX.  As you learn Socket.IO, Non-Blocking I/O will become your best friend!&lt;br /&gt;
&lt;br /&gt;
== Installing Socket.IO ==&lt;br /&gt;
&lt;br /&gt;
Before you install Socket.IO, you need to install [[Node.JS]] and NPM, which is often installed automatically when you install Node.JS.&lt;br /&gt;
&lt;br /&gt;
The NPM package manager is different from many of the package managers we've used in that you need to install remote packages for every project in which you use them.  This means that you need to '''cd''' to the working directory in which you want to keep your Node.JS JavaScript file, ''and then'' run the following command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm install socket.io&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' If you pass the ''-g'' to ''npm install'', then the package will be installed &amp;quot;globally&amp;quot; on your instance, so all Node.JS projects will be able to use it.  However, this is not recommended for all projects.  [http://blog.nodejs.org/2011/04/06/npm-1-0-link/ Read Node.JS's justification here.]&lt;br /&gt;
&lt;br /&gt;
== Messaging ==&lt;br /&gt;
&lt;br /&gt;
Socket.IO works by having clients send messages to the server and the server send messages to clients.  For example, consider the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Computer A:&lt;br /&gt;
socket.emit(&amp;quot;info&amp;quot;, {&lt;br /&gt;
	&amp;quot;hello&amp;quot;: &amp;quot;world&amp;quot;&lt;br /&gt;
});&lt;br /&gt;
&lt;br /&gt;
// Computer B:&lt;br /&gt;
socket.on(&amp;quot;info&amp;quot;, function (data) {&lt;br /&gt;
	console.log(data.hello);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Computer A could be ''either the client or the server'', and Computer B would be the other.  When '''socket.emit(name, data)''' is called on either end, the callback function in '''socket.on''' that listens for the message named ''name'' is called with the ''data'' from '''socket.emit'''.&lt;br /&gt;
&lt;br /&gt;
== A First Socket.IO Application: Chat Server and Client ==&lt;br /&gt;
&lt;br /&gt;
Building a chat client is surprising simple using Socket.IO and Node.JS, and it gives great insight into the workings of Socket.IO.  Take the time to understand how this example works, and ask questions; if you understand this, the group portion will be easy!&lt;br /&gt;
&lt;br /&gt;
=== The Chat Server ===&lt;br /&gt;
&lt;br /&gt;
You can make a file called ''chat-server.js'' with the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Require the packages we will use:&lt;br /&gt;
var http = require(&amp;quot;http&amp;quot;),&lt;br /&gt;
	socketio = require(&amp;quot;socket.io&amp;quot;),&lt;br /&gt;
	fs = require(&amp;quot;fs&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
// Listen for HTTP connections.  This is essentially a miniature static file server that only serves our one file, client.html:&lt;br /&gt;
var app = http.createServer(function(req, resp){&lt;br /&gt;
	// This callback runs when a new connection is made to our HTTP server.&lt;br /&gt;
	&lt;br /&gt;
	fs.readFile(&amp;quot;client.html&amp;quot;, function(err, data){&lt;br /&gt;
		// This callback runs when the client.html file has been read from the filesystem.&lt;br /&gt;
		&lt;br /&gt;
		if(err) return resp.writeHead(500);&lt;br /&gt;
		resp.writeHead(200);&lt;br /&gt;
		resp.end(data);&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
app.listen(3456);&lt;br /&gt;
&lt;br /&gt;
// Do the Socket.IO magic:&lt;br /&gt;
var io = socketio.listen(app);&lt;br /&gt;
io.sockets.on(&amp;quot;connection&amp;quot;, function(socket){&lt;br /&gt;
	// This callback runs when a new Socket.IO connection is established.&lt;br /&gt;
	&lt;br /&gt;
	socket.on('message_to_server', function(data) {&lt;br /&gt;
		// This callback runs when the server receives a new message from the client.&lt;br /&gt;
		&lt;br /&gt;
		console.log(&amp;quot;message: &amp;quot;+data[&amp;quot;message&amp;quot;]); // log it to the Node.JS output&lt;br /&gt;
		io.sockets.emit(&amp;quot;message_to_client&amp;quot;,{message:data[&amp;quot;message&amp;quot;] }) // broadcast the message to other users&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code makes a simple HTTP server that responds to all connections with the contents of the file &amp;quot;client.html&amp;quot;, which we will make in the next step.  We tell Socket.IO to listen for &amp;quot;message&amp;quot; events, and when it hears one, it should emit a new event called &amp;quot;someone said&amp;quot; back to the connected clients.&lt;br /&gt;
&lt;br /&gt;
=== The Chat Client ===&lt;br /&gt;
&lt;br /&gt;
Here is a front-end client that could work with our server, in ''client.html'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
   &amp;lt;head&amp;gt;&lt;br /&gt;
      &amp;lt;script src=&amp;quot;/socket.io/socket.io.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;
      &amp;lt;script type =&amp;quot;text/javascript&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
      var socketio = io.connect();&lt;br /&gt;
      socketio.on(&amp;quot;message_to_client&amp;quot;,function(data) {&lt;br /&gt;
         //Append an HR thematic break and the escaped HTML of the new message&lt;br /&gt;
         document.getElementById(&amp;quot;chatlog&amp;quot;).appendChild(document.createElement(&amp;quot;hr&amp;quot;));&lt;br /&gt;
         document.getElementById(&amp;quot;chatlog&amp;quot;).appendChild(document.createTextNode(data['message']));&lt;br /&gt;
      });&lt;br /&gt;
&lt;br /&gt;
      function sendMessage(){&lt;br /&gt;
         var msg = document.getElementById(&amp;quot;message_input&amp;quot;).value;&lt;br /&gt;
         socketio.emit(&amp;quot;message_to_server&amp;quot;, {message:msg});&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
      &amp;lt;/script&amp;gt;&lt;br /&gt;
   &amp;lt;/head&amp;gt;&lt;br /&gt;
   &amp;lt;body&amp;gt;&lt;br /&gt;
      &amp;lt;input type=text&amp;quot; id=&amp;quot;message_input&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;button onclick=&amp;quot;sendMessage()&amp;quot;&amp;gt;send&amp;lt;/button&amp;gt;&lt;br /&gt;
      &amp;lt;div id=&amp;quot;chatlog&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
   &amp;lt;/body&amp;gt;&lt;br /&gt;
 &amp;lt;/html&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' This example passes strings as the event data, but you can pass any JavaScript datatype, including object literals.&lt;br /&gt;
&lt;br /&gt;
To see this in action, save these two files in the same directory, cd over to the directory, and start the server:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;$ node chat-server.js&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Fire up your favorite browser and navigate to http://localhost:3456/.  Open the page in two windows.  Violà: you have your (very basic) chat client!&lt;br /&gt;
&lt;br /&gt;
== Resources ==&lt;br /&gt;
&lt;br /&gt;
The [http://socket.io/ Socket.IO web site] has concise examples that tell you pretty much all you need to know in order to build a functional Socket.IO web application.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 7]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Socket.IO&amp;diff=1824</id>
		<title>Socket.IO</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Socket.IO&amp;diff=1824"/>
		<updated>2014-10-31T04:47:17Z</updated>

		<summary type="html">&lt;p&gt;Shane: Indentation&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;AJAX is useful when one-way communication is satisfactory for your web application.  However, what happens when you need two-way communication, like a chat client or multiplayer game?  AJAX isn't the tool for the job.  This is where '''Socket.IO''' comes in.&lt;br /&gt;
&lt;br /&gt;
Built to work natively with Node.JS, Socket.IO enables asynchronous, two-way communication between the server and the client.  This means that the server can send messages to the client without the client having to ask first, as is the case with AJAX.  As you learn Socket.IO, Non-Blocking I/O will become your best friend!&lt;br /&gt;
&lt;br /&gt;
== Installing Socket.IO ==&lt;br /&gt;
&lt;br /&gt;
Before you install Socket.IO, you need to install [[Node.JS]] and NPM, which is often installed automatically when you install Node.JS.&lt;br /&gt;
&lt;br /&gt;
The NPM package manager is different from many of the package managers we've used in that you need to install remote packages for every project in which you use them.  This means that you need to '''cd''' to the working directory in which you want to keep your Node.JS JavaScript file, ''and then'' run the following command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm install socket.io&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' If you pass the ''-g'' to ''npm install'', then the package will be installed &amp;quot;globally&amp;quot; on your instance, so all Node.JS projects will be able to use it.  However, this is not recommended for all projects.  [http://blog.nodejs.org/2011/04/06/npm-1-0-link/ Read Node.JS's justification here.]&lt;br /&gt;
&lt;br /&gt;
== Messaging ==&lt;br /&gt;
&lt;br /&gt;
Socket.IO works by having clients send messages to the server and the server send messages to clients.  For example, consider the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Computer A:&lt;br /&gt;
socket.emit(&amp;quot;info&amp;quot;, {&lt;br /&gt;
	&amp;quot;hello&amp;quot;: &amp;quot;world&amp;quot;&lt;br /&gt;
});&lt;br /&gt;
&lt;br /&gt;
// Computer B:&lt;br /&gt;
socket.on(&amp;quot;info&amp;quot;, function (data) {&lt;br /&gt;
	console.log(data.hello);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Computer A could be ''either the client or the server'', and Computer B would be the other.  When '''socket.emit(name, data)''' is called on either end, the callback function in '''socket.on''' that listens for the message named ''name'' is called with the ''data'' from '''socket.emit'''.&lt;br /&gt;
&lt;br /&gt;
== A First Socket.IO Application: Chat Server and Client ==&lt;br /&gt;
&lt;br /&gt;
Building a chat client is surprising simple using Socket.IO and Node.JS, and it gives great insight into the workings of Socket.IO.  Take the time to understand how this example works, and ask questions; if you understand this, the group portion will be easy!&lt;br /&gt;
&lt;br /&gt;
=== The Chat Server ===&lt;br /&gt;
&lt;br /&gt;
You can make a file called ''chat-server.js'' with the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Require the packages we will use:&lt;br /&gt;
var http = require(&amp;quot;http&amp;quot;),&lt;br /&gt;
	socketio = require(&amp;quot;socket.io&amp;quot;),&lt;br /&gt;
	fs = require(&amp;quot;fs&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
// Listen for HTTP connections.  This is essentially a miniature static file server that only serves our one file, client.html:&lt;br /&gt;
var app = http.createServer(function(req, resp){&lt;br /&gt;
	// This callback runs when a new connection is made to our HTTP server.&lt;br /&gt;
	&lt;br /&gt;
	fs.readFile(&amp;quot;client.html&amp;quot;, function(err, data){&lt;br /&gt;
		// This callback runs when the client.html file has been read from the filesystem.&lt;br /&gt;
		&lt;br /&gt;
		if(err) return resp.writeHead(500);&lt;br /&gt;
		resp.writeHead(200);&lt;br /&gt;
		resp.end(data);&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
app.listen(3456);&lt;br /&gt;
&lt;br /&gt;
// Do the Socket.IO magic:&lt;br /&gt;
var io = socketio.listen(app);&lt;br /&gt;
io.sockets.on(&amp;quot;connection&amp;quot;, function(socket){&lt;br /&gt;
	// This callback runs when a new Socket.IO connection is established.&lt;br /&gt;
	&lt;br /&gt;
	socket.on('message_to_server', function(data) {&lt;br /&gt;
		// This callback runs when the server receives a new message from the client.&lt;br /&gt;
		&lt;br /&gt;
		console.log(&amp;quot;message: &amp;quot;+data[&amp;quot;message&amp;quot;]); // log it to the Node.JS output&lt;br /&gt;
		io.sockets.emit(&amp;quot;message_to_client&amp;quot;,{message:data[&amp;quot;message&amp;quot;] }) // broadcast the message to other users&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code makes a simple HTTP server that responds to all connections with the contents of the file &amp;quot;client.html&amp;quot;, which we will make in the next step.  We tell Socket.IO to listen for &amp;quot;message&amp;quot; events, and when it hears one, it should emit a new event called &amp;quot;someone said&amp;quot; back to the connected clients.&lt;br /&gt;
&lt;br /&gt;
=== The Chat Client ===&lt;br /&gt;
&lt;br /&gt;
Here is a front-end client that could work with our server, in ''client.html'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
   &amp;lt;head&amp;gt;&lt;br /&gt;
      &amp;lt;script src=&amp;quot;/socket.io/socket.io.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;
      &amp;lt;script type =&amp;quot;text/javascript&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
      var socketio = io.connect(&amp;quot;127.0.0.1:3456&amp;quot;);&lt;br /&gt;
      socketio.on(&amp;quot;message_to_client&amp;quot;,function(data) {&lt;br /&gt;
         //Append an HR thematic break and the escaped HTML of the new message&lt;br /&gt;
         document.getElementById(&amp;quot;chatlog&amp;quot;).appendChild(document.createElement(&amp;quot;hr&amp;quot;));&lt;br /&gt;
         document.getElementById(&amp;quot;chatlog&amp;quot;).appendChild(document.createTextNode(data['message']));&lt;br /&gt;
      });&lt;br /&gt;
&lt;br /&gt;
      function sendMessage(){&lt;br /&gt;
         var msg = document.getElementById(&amp;quot;message_input&amp;quot;).value;&lt;br /&gt;
         socketio.emit(&amp;quot;message_to_server&amp;quot;, {message:msg});&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
      &amp;lt;/script&amp;gt;&lt;br /&gt;
   &amp;lt;/head&amp;gt;&lt;br /&gt;
   &amp;lt;body&amp;gt;&lt;br /&gt;
      &amp;lt;input type=text&amp;quot; id=&amp;quot;message_input&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;button onclick=&amp;quot;sendMessage()&amp;quot;&amp;gt;send&amp;lt;/button&amp;gt;&lt;br /&gt;
      &amp;lt;div id=&amp;quot;chatlog&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
   &amp;lt;/body&amp;gt;&lt;br /&gt;
 &amp;lt;/html&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' This example passes strings as the event data, but you can pass any JavaScript datatype, including object literals.&lt;br /&gt;
&lt;br /&gt;
To see this in action, save these two files in the same directory, cd over to the directory, and start the server:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;$ node chat-server.js&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Fire up your favorite browser and navigate to http://localhost:3456/.  Open the page in two windows.  Violà: you have your (very basic) chat client!&lt;br /&gt;
&lt;br /&gt;
== Resources ==&lt;br /&gt;
&lt;br /&gt;
The [http://socket.io/ Socket.IO web site] has concise examples that tell you pretty much all you need to know in order to build a functional Socket.IO web application.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 7]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=HTML_and_CSS&amp;diff=1819</id>
		<title>HTML and CSS</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=HTML_and_CSS&amp;diff=1819"/>
		<updated>2014-10-28T20:01:53Z</updated>

		<summary type="html">&lt;p&gt;Shane: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;You have probably used so-called &amp;quot;What-You-See-Is-What-You-Get&amp;quot; (WYSIWYG) web page editor before.  You select text, press the bold button, and voilà!  Your text is bold.  But what's really happening behing the scenes is that your editor is generating HTML and CSS code.  Indeed, every page you view on the internet is built using HTML and CSS.  In this guide, you will learn the principles of HTML and CSS and learn how they fit together to make a web page.&lt;br /&gt;
&lt;br /&gt;
== Basic Structure of a Web Page ==&lt;br /&gt;
&lt;br /&gt;
The most basic web page is shown below.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
	&amp;lt;title&amp;gt;My First Web Page&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
	&amp;lt;p&amp;gt;Hello World!&amp;lt;/p&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you were to open this page in Firefox, you would see the following:&lt;br /&gt;
&lt;br /&gt;
[[File:BasicHTML.png‎]]&lt;br /&gt;
&lt;br /&gt;
This is the skeleton of every web page on the internet.  Things to notice:&lt;br /&gt;
&lt;br /&gt;
* The page begins with a DOCTYPE declaration.  This is a mandatory part of a web page, and it tells the browser what version of HTML to use when rendering your page.  In this case, the browser should use HTML 5.&lt;br /&gt;
* The rest of the page consists of ''tags'', in a hierarchy as follows:&lt;br /&gt;
** html&lt;br /&gt;
*** head&lt;br /&gt;
**** title&lt;br /&gt;
*** body&lt;br /&gt;
**** p&lt;br /&gt;
&lt;br /&gt;
You can view a web page's source code in your browser; in Firefox, the keyboard shortcut is Ctrl-U (or Command-U), and in Chrome, it is Alt-Ctrl-U (or Option-Command-U).&lt;br /&gt;
&lt;br /&gt;
== Introduction to HTML ==&lt;br /&gt;
&lt;br /&gt;
HTML stands for ''HyperText Markup Language''.  Notice that HTML is ''not'' a programming language, so it doesn't have classes, methods, variables, or anything else you may be used to seeing.  Instead, HTML defines the ''content'' of a web page, and it uses ''tags'' to do that for you.&lt;br /&gt;
&lt;br /&gt;
=== Tags ===&lt;br /&gt;
&lt;br /&gt;
Tags define the content of your page.  Each tag represents an ''element''.  There are two main types of elements: content elements and empty elements.&lt;br /&gt;
&lt;br /&gt;
==== Content Elements ====&lt;br /&gt;
&lt;br /&gt;
A '''content element''' is a container for other elements on your page, and it participates in the nesting hierarchy of a web page.  The general format looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;tagname&amp;gt; Contents &amp;lt;/tagname&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you've used BBCode before in online forums, HTML should look familiar, except that it uses angle brackets (less-than and greater-than signs) instead of square brackets.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' There are actually several different types of content elements, including phrasing content, sectioning content, and flow content.  More details can be found [http://www.w3.org/html/wg/drafts/html/master/dom.html#content-models in the HTML5 spec].&lt;br /&gt;
&lt;br /&gt;
==== Void Elements ====&lt;br /&gt;
&lt;br /&gt;
A '''void element''' or '''empty element''' represents an element on your page that does not participate in the nesting hierarchy.  An empty element looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;tagname /&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Although the trailing slash is optional on void/empty elements, it is considered best practice to include it, and it also makes it more clear what's a content element and what's a void element when reviewing your code.&lt;br /&gt;
&lt;br /&gt;
==== Content Tags with Optional Closing Tag ====&lt;br /&gt;
&lt;br /&gt;
HTML has a quirk in that a few content tags, such as &amp;lt;nowiki&amp;gt;&amp;lt;p&amp;gt;&amp;lt;/nowiki&amp;gt;, &amp;lt;nowiki&amp;gt;&amp;lt;tbody&amp;gt;&amp;lt;/nowiki&amp;gt;, and &amp;lt;nowiki&amp;gt;&amp;lt;li&amp;gt;&amp;lt;/nowiki&amp;gt;, do not require that the end tag be present.  In addition, both the opening and the closing tags &amp;lt;nowiki&amp;gt;&amp;lt;html&amp;gt;&amp;lt;/nowiki&amp;gt;, &amp;lt;nowiki&amp;gt;&amp;lt;head&amp;gt;&amp;lt;/nowiki&amp;gt;, and &amp;lt;nowiki&amp;gt;&amp;lt;body&amp;gt;&amp;lt;/nowiki&amp;gt; may ''sometimes'' be omitted.  For example, the following code will pass the validator as a valid HTML5 document:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;!-- implicit &amp;lt;html▷ --&amp;gt;&lt;br /&gt;
&amp;lt;!-- implicit &amp;lt;head▷ --&amp;gt;&lt;br /&gt;
	&amp;lt;title&amp;gt;My Miniature Document&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;!-- implicit &amp;lt;/head▷ because the &amp;lt;body▷ is starting --&amp;gt;&lt;br /&gt;
&amp;lt;!-- implicit &amp;lt;body▷ --&amp;gt;&lt;br /&gt;
	&amp;lt;div&amp;gt;&lt;br /&gt;
		&amp;lt;p&amp;gt;&lt;br /&gt;
			Hello&lt;br /&gt;
		&amp;lt;!-- implicit &amp;lt;/p▷ because a new &amp;lt;p▷ is starting --&amp;gt;&lt;br /&gt;
		&amp;lt;p&amp;gt;&lt;br /&gt;
			World&lt;br /&gt;
		&amp;lt;!-- implicit &amp;lt;/p▷ because the parent is closing --&amp;gt;&lt;br /&gt;
	&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;!-- implicit &amp;lt;/body▷ because end of document --&amp;gt;&lt;br /&gt;
&amp;lt;!-- implicit &amp;lt;/html▷ because end of document --&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
More information is in [http://www.w3.org/TR/html5/syntax.html#optional-tags the HTML5 spec].&lt;br /&gt;
&lt;br /&gt;
===== Why to Always Include Closing Tags =====&lt;br /&gt;
&lt;br /&gt;
It will make your life easier if you always include closing tags, even if they are technically optional, for the following reasons:&lt;br /&gt;
&lt;br /&gt;
* It is best practice to '''be explicit''' in your code.&lt;br /&gt;
* You can see in the spec how there are strict conditions for when the closing tags are implied and when they are not.  Changing something at the end of your document could have '''adverse consequences''' to something earlier if you are using implicit end tags.&lt;br /&gt;
* Popular browsers such as Internet Explorer 9 will create the incorrect DOM structure when closing tags are omitted, leading to '''hard-to-detect bugs'''&lt;br /&gt;
&lt;br /&gt;
It might be advantageous to take advantage of this HTML quirk is if you are hard-core trying to optimize the load speed of your pages, but in most other cases, omitting closing tags will only cause frustration.&lt;br /&gt;
&lt;br /&gt;
=== Attributes ===&lt;br /&gt;
&lt;br /&gt;
Both content elements and void elements can have attributes that further define their functionality.  You define an attribute like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;contenttag attribute=&amp;quot;value&amp;quot;&amp;gt; Content &amp;lt;/contenttag&amp;gt;&lt;br /&gt;
&amp;lt;emptytag attribute=&amp;quot;value&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Commonly Used Tags ===&lt;br /&gt;
&lt;br /&gt;
For reference, below is a list of commonly used tags in HTML.  For a complete list, see [http://www.w3.org/TR/html5/#contents section 4 of the HTML 5 Specification].&lt;br /&gt;
&lt;br /&gt;
Void elements are distinguished from content elements by the presence of a trailing slash.&lt;br /&gt;
&lt;br /&gt;
==== Semantic Elements ====&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=53bFhkqThCQ&lt;br /&gt;
|time=5m18s&lt;br /&gt;
|desc=Semantic Elements in HTML5&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Use these tags for defining broad sections of your page with a specific purpose.&lt;br /&gt;
&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;header&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines the header section of a web page&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;footer&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines the footer section of a web page&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;nav&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines the section of your page that contains navigation links&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;article&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines an article on your page (useful for screen readers)&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;section&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines a real section of your page; for example, one with unique headings distinct from the rest of the document&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;figure&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines a figure&lt;br /&gt;
** '''&amp;lt;nowiki&amp;gt;&amp;lt;figcaption&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines a caption for that figure (&amp;lt;figcaption&amp;gt; should be nested inside of &amp;lt;figure&amp;gt;)&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;form&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines a form into which the user should input data&lt;br /&gt;
** '''&amp;lt;nowiki&amp;gt;&amp;lt;input type=&amp;quot;text/number/date/radio/etcetera&amp;quot; name=&amp;quot;name&amp;quot; /&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines an input field of a certain type&lt;br /&gt;
** '''&amp;lt;nowiki&amp;gt;&amp;lt;label for=&amp;quot;input-id&amp;quot;&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines a label for an input field with the ID ''input-id''&lt;br /&gt;
** '''&amp;lt;nowiki&amp;gt;&amp;lt;select name=&amp;quot;name&amp;quot;&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines an input field where the user can select one or more choices (like a drop-down box)&lt;br /&gt;
*** '''&amp;lt;nowiki&amp;gt;&amp;lt;option value=&amp;quot;value&amp;quot;&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines an option for the select box&lt;br /&gt;
** '''&amp;lt;nowiki&amp;gt;&amp;lt;textarea name=&amp;quot;&amp;quot;&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines a text box (which is larger than a text field)&lt;br /&gt;
&lt;br /&gt;
For more information on HTML forms, read the article [[HTML Forms]].&lt;br /&gt;
&lt;br /&gt;
==== External Media ====&lt;br /&gt;
&lt;br /&gt;
Use these tags to include external media onto your page.&lt;br /&gt;
&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;iframe src=&amp;quot;source&amp;quot;&amp;gt;&amp;lt;/nowiki&amp;gt;''' Represents a little window on your page into which ''source'' is loaded; ''source'' could be a PDF document, for example, or an entire other web page&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;link rel=&amp;quot;what&amp;quot; type=&amp;quot;mime&amp;quot; href=&amp;quot;source&amp;quot; /&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines an external document ''what'' located at ''source'' with the mime type ''mime'' that should be loaded into your HTML page.  '''Note: &amp;lt;link /&amp;gt; does NOT define a hyperlink! &amp;lt;a&amp;gt; is for that.'''  Used most commonly for including CSS stylesheets.&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;img src=&amp;quot;source&amp;quot; alt=&amp;quot;text&amp;quot; /&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines an image located at ''source'' that has a textual representation of ''text''&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;audio&amp;gt;&amp;lt;/nowiki&amp;gt;''' Represents an audio clip on your page&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;video&amp;gt;&amp;lt;/nowiki&amp;gt;''' Represents a video clip on your web page&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;canvas&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines a canvas for advanced drawing (we will learn more about this in future modules)&lt;br /&gt;
&lt;br /&gt;
==== Outlining Elements ====&lt;br /&gt;
&lt;br /&gt;
Use these elements to define an outline for your page, including definitions and citations.&lt;br /&gt;
&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;h1&amp;gt; to &amp;lt;h6&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines the outline for your page&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;p&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines a paragraph of text&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;dl&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines a Dictionary List&lt;br /&gt;
** '''&amp;lt;nowiki&amp;gt;&amp;lt;dt&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines a Dictionary Term&lt;br /&gt;
** '''&amp;lt;nowiki&amp;gt;&amp;lt;dd&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines a Dictionary Definition&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;table&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines a table for displaying data&lt;br /&gt;
** '''&amp;lt;nowiki&amp;gt;&amp;lt;thead&amp;gt;, &amp;lt;tbody&amp;gt;, &amp;lt;tfoot&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines the heading, body content, and footing of a table&lt;br /&gt;
*** '''&amp;lt;nowiki&amp;gt;&amp;lt;tr&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines a table row&lt;br /&gt;
**** '''&amp;lt;nowiki&amp;gt;&amp;lt;th&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines a table cell that contains a heading&lt;br /&gt;
**** '''&amp;lt;nowiki&amp;gt;&amp;lt;td&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines a table cell that contains data&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;ol&amp;gt; and &amp;lt;ul&amp;gt;&amp;lt;/nowiki&amp;gt;''' Define ordered and unordered lists, respectively (meaning numbered lists and bulleted lists)&lt;br /&gt;
** '''&amp;lt;nowiki&amp;gt;&amp;lt;li&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines a list item for either &amp;lt;nowiki&amp;gt;&amp;lt;ol&amp;gt; or &amp;lt;ul&amp;gt;&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;q&amp;gt;&amp;lt;/nowiki&amp;gt;''' Represents a short, inline quotation quoted from another source&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;blockquote&amp;gt;&amp;lt;/nowiki&amp;gt;''' Represents a longer block of text quoted from another source&lt;br /&gt;
&lt;br /&gt;
==== Miscellaneous Elements ====&lt;br /&gt;
&lt;br /&gt;
This section lists useful elements that don't fit into one of the other categories.&lt;br /&gt;
&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;a href=&amp;quot;destination&amp;quot;&amp;gt;&amp;lt;/nowiki&amp;gt;''' Make a hyperlink to destination&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;br /&amp;gt;&amp;lt;/nowiki&amp;gt;''' Denotes where a line break should appear (note that white space is ignored when rendering, so a line break in the source code is ''not'' reflected in the output)&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;button&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines a clickable button&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;code&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines a piece of computer code&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;output&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines the result of a calculation&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;pre&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines pre-formatted text in which whitespace will be preserved&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;script&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines a script for your page (we will learn a lot more about this in later modules)&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;div&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines a block section of your document (useful for styling)&lt;br /&gt;
* '''&amp;lt;nowiki&amp;gt;&amp;lt;span&amp;gt;&amp;lt;/nowiki&amp;gt;''' Defines an inline section of your document (useful for styling)&lt;br /&gt;
&lt;br /&gt;
=== High School Analogy ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;nowiki&amp;gt;In more ways than not, HTML can be thought of as a markup language for five-paragraph essays that you wrote in history class in high school.  &amp;lt;blockquote&amp;gt; is used to denote long quotations; &amp;lt;h1&amp;gt; through &amp;lt;h6&amp;gt; denote the outline; &amp;lt;p&amp;gt; denotes new paragraphs; &amp;lt;figure&amp;gt; and &amp;lt;figcaption&amp;gt; represent exhibits; &amp;lt;section&amp;gt; could represent chapters if you were writing a longer report; and so on.&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Take home message: HTML defines the ''content'' of your page.  Use it to its full ability.&lt;br /&gt;
&lt;br /&gt;
== Introduction to CSS ==&lt;br /&gt;
&lt;br /&gt;
Notice that we haven't said a word about how things look yet.  This is because that is what CSS is for!&lt;br /&gt;
&lt;br /&gt;
CSS stands for ''Cascading Style Sheets'', and it defines the ''appearance'' of your page.  CSS is composed of ''rules'', and each rule consists of a ''selector'' and one or more ''declarations''.  Let's see an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;css&amp;quot;&amp;gt;&lt;br /&gt;
header {&lt;br /&gt;
	color: blue;&lt;br /&gt;
	font-family: Verdana, sans-serif;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above CSS rule does three things:&lt;br /&gt;
&lt;br /&gt;
* It ''selects'' all &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;&amp;lt;header&amp;gt;&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; elements&lt;br /&gt;
* It ''declares'' the ''property'' '''color''' (i.e. the text color) of the selected elements to be blue&lt;br /&gt;
* It ''declares'' the ''property'' '''font-family''' (i.e. the font &amp;quot;face&amp;quot;) of the selected elements to be Verdana, or alternatively any sans-serif font if Verdana is not available&lt;br /&gt;
&lt;br /&gt;
All CSS rules follow this general format.  The following sections will discuss more detail on CSS selectors and declarations.&lt;br /&gt;
&lt;br /&gt;
=== Selectors ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=W9H95NcbTSw&lt;br /&gt;
|time=5m27s&lt;br /&gt;
|desc=CSS Selectors, Part 1&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
In the previous section's example, the most basic CSS selector was used: selecting by the ''tag name''.  To select by the ''class name'', use a period, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;css&amp;quot;&amp;gt;&lt;br /&gt;
.info {&lt;br /&gt;
	font-weight: bold;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=0a4r4bm1nQA&lt;br /&gt;
|time=1m29s&lt;br /&gt;
|desc=CSS Selectors, Part 2&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
A third common way to select an element is by its ID.  To select by ID, use a number sign, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;css&amp;quot;&amp;gt;&lt;br /&gt;
#medal_table {&lt;br /&gt;
	border-collapse: collapse;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Selectors can be combined.  For example, to select all hyperlinks in any paragraph having the class &amp;quot;alert&amp;quot;, you could do:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;css&amp;quot;&amp;gt;&lt;br /&gt;
p.alert a {&lt;br /&gt;
	font-style: italic;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;p.alert&amp;lt;/code&amp;gt; selects all &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;&amp;lt;p&amp;gt;&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; tags with the class name &amp;quot;alert&amp;quot;.  The space tells CSS to look for all descendants of such paragraphs.  Finally, the &amp;lt;code&amp;gt;a&amp;lt;/code&amp;gt; selects all &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;&amp;lt;a&amp;gt;&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; elements in the resulting set.&lt;br /&gt;
&lt;br /&gt;
It is also very common to use a right-angle bracket to select a ''child'' rather than a ''descendant'', the distinction being that ''descendants'' could be nested at any depth: child, grandchild, and so on, while a ''child'' must be at the next level down in the DOM.  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;css&amp;quot;&amp;gt;&lt;br /&gt;
ul.fruits &amp;gt; li {&lt;br /&gt;
	text-decoration: underline;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some common CSS selectors are listed below.  For a complete list of CSS selectors, see [http://www.w3.org/TR/CSS/#selectors section 4.2 of the CSS Specification].&lt;br /&gt;
&lt;br /&gt;
* '''foo''' selects an element with tag name ''foo''&lt;br /&gt;
* '''.foo''' selects an element with the class name ''foo''&lt;br /&gt;
* '''#foo''' selects an element with the ID ''foo''&lt;br /&gt;
* '''[foo=&amp;quot;bar&amp;quot;]''' selects an element with the attribute ''foo'' whose value is ''bar''&lt;br /&gt;
* '''foo bar''' selects an element matching ''bar'' that is a descendant of an element matching ''foo''&lt;br /&gt;
* '''foo &amp;gt; bar''' selects an element matching ''car'' that is a child of an element matching ''foo''&lt;br /&gt;
* '''foo + bar''' selects an element matching ''bar'' that is the next sibling of an element matching ''foo''&lt;br /&gt;
&lt;br /&gt;
==== Pseudo-Classes ====&lt;br /&gt;
&lt;br /&gt;
Elements can also be selected based on their current state using ''pseudo-classes''.  Pseudo-classes always begin with a colon.  For example, this is how you could change the color of all visited links on your web page:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;css&amp;quot;&amp;gt;&lt;br /&gt;
a:visited {&lt;br /&gt;
	color: #99FF99; /* this example uses a hexadecimal RGB definition for the color, which allows you to&lt;br /&gt;
		mix over 16 million colors */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some common pseudo-classes are listed below.  For a complete list, see [http://www.w3.org/TR/CSS/#selectors section 4.2 of the CSS Specification].&lt;br /&gt;
&lt;br /&gt;
* '''foo:first-child''' selects an element matching ''foo'' that is the first child of its parent (i.e., any ''foo'' that doesn't have older siblings)&lt;br /&gt;
* '''foo:last-child''' selects an element matching ''foo'' that is the last child of its parent&lt;br /&gt;
* '''foo:empty''' selects any element matching ''foo'' that has no children&lt;br /&gt;
* Pseudo-Classes for Form Elements:&lt;br /&gt;
** '''input:checked''' selects all checkboxes and radio buttons that are checked&lt;br /&gt;
* Pseudo-Classes for Hyperlink Elements:&lt;br /&gt;
** '''a:link''' selects all hyperlinks that have not been visited yet&lt;br /&gt;
** '''a:visited''' selects all hyperlinks that have been visited&lt;br /&gt;
* Pseudo-Classes for Interactive Elements (like buttons, hyperlinks, etc):&lt;br /&gt;
** '''foo:active''' selects elements matching ''foo'' that are being pressed on&lt;br /&gt;
** '''foo:hover''' selects elements matching ''foo'' that are being hovered over&lt;br /&gt;
** '''foo:focus''' selects elements matching ''foo'' that are selected (no pun intended)&lt;br /&gt;
&lt;br /&gt;
=== Properties ===&lt;br /&gt;
&lt;br /&gt;
Selectors are used to select elements that need to have styles applied to them, and properties are used to actually define those styles.  Throughout this section, you've seen properties including '''color''', '''font-family''', '''font-style''', and '''text-decoration'''.  There are dozens more properties you can define, some of which are listed below.&lt;br /&gt;
&lt;br /&gt;
For a complete list of CSS properties, see [http://www.w3.org/TR/CSS/#properties section 4.1 of the CSS Specification].&lt;br /&gt;
&lt;br /&gt;
* '''background-image''' sets the background image of an element.  Usage: &amp;lt;code&amp;gt;background-image: url(path/to/image.png);&amp;lt;/code&amp;gt;&lt;br /&gt;
* '''background-color''' sets the background color of an element (note: the image takes precedence over the color; the color will be displayed if the image can't be found)&lt;br /&gt;
* For Tables:&lt;br /&gt;
** '''border-collapse''' removes the spacing between table cells.  Usage: &amp;lt;code&amp;gt;border-collapse: collapse;&amp;lt;/code&amp;gt;&lt;br /&gt;
** Note: You can select td elements that are grandchildren of a table element, and then specify border properties on the td's, like this: &amp;lt;code&amp;gt;#myTable &amp;gt; tr &amp;gt; td { border: 1px solid black; }&amp;lt;/code&amp;gt;&lt;br /&gt;
* '''border''' defines the border around an element.  Usage: &amp;lt;code&amp;gt;border: 1px dashed red;&amp;lt;/code&amp;gt;&lt;br /&gt;
* '''border-radius''' lets you have rounded corners on your elements&lt;br /&gt;
* '''float''' makes the text of a document flow around the element.  Usage: &amp;lt;code&amp;gt;float: left;&amp;lt;/code&amp;gt; (or &amp;lt;code&amp;gt;right&amp;lt;/code&amp;gt;)&lt;br /&gt;
** '''clear''' makes an element stop wrapping around floats and instead move down to where the floats end.  Usage: &amp;lt;code&amp;gt;clear: both;&amp;lt;/code&amp;gt;&lt;br /&gt;
** Note: If you specify multiple object in a for as floating, they will appear next to each other horizontally.&lt;br /&gt;
* '''cursor''' lets you change the type of cursor that appears then your element is in focus.  Example usage: &amp;lt;code&amp;gt;cursor: pointer;&amp;lt;/code&amp;gt;&lt;br /&gt;
* '''font''' lets you specify the font-size, line-height, and font-family in one fell swoop.  Usage: &amp;lt;code&amp;gt;font: 14px/18px Verdana, Arial, sans-serif;&amp;lt;/code&amp;gt;&lt;br /&gt;
* '''list-style-type''' specifies the type of number or bullet used on &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;&amp;lt;ol&amp;gt;&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;'s and &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;&amp;lt;ul&amp;gt;&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;'s&lt;br /&gt;
* '''text-align''' lets you justify text on the left, center, or right&lt;br /&gt;
* '''display''' lets us specify an element as inline or block (see below), and it also enables us to &amp;quot;turn off&amp;quot; an element from being displayed on a page.  Example usage: &amp;lt;code&amp;gt;display: none;&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Units ====&lt;br /&gt;
&lt;br /&gt;
Some CSS properties require that you specify numerical values for things (font-size, line-height, border-width, and so on).  CSS supports a number of units, the most common of which include:&lt;br /&gt;
&lt;br /&gt;
* '''px''', which defines a distance in pixels (relative to screen resolution).&lt;br /&gt;
* '''em''', which defines a distance relative to font size.  (Note: an ''em'' is the width of the capital letter M.  No, I'm not kidding.)&lt;br /&gt;
* '''rem''', which defines a distance relative to the font size of the root element.  Compare to '''em''', which defines a distance relative to the font size of the current element (which might have a different font size than the document root).&lt;br /&gt;
*: '''Note:''' As of October 2012, '''rem''' support covers 79% of the browser market ([http://caniuse.com/rem more info]).  If you intend to build a web application usable by the other 21%, you might not want to avoid '''rem'''s in your CSS.&lt;br /&gt;
* '''pt''', which is a traditional print unit equal to 1/72 of an inch (should appear the same size on all screens regardless of resolution).&lt;br /&gt;
* '''%''', which defines a distance relative to that property of its parent element.  For the most part, you'll only use % when working with the Box Model (see below).&lt;br /&gt;
&lt;br /&gt;
=== The Box Model ===&lt;br /&gt;
&lt;br /&gt;
For the most part, all elements fall into one of two categories:&lt;br /&gt;
&lt;br /&gt;
* Inline (Examples: a, span, strong)&lt;br /&gt;
* Block (Examples: p, div, section)&lt;br /&gt;
&lt;br /&gt;
The properties we've seen thus far apply mostly to inline elements.  As it turns out, CSS has an additional set of properties that describe block elements.  These properties compose the ''box model''.&lt;br /&gt;
&lt;br /&gt;
While inline elements flow with the text, block elements stand on their own.  You can define the space between the block element and the next closest element on the page using ''margin'', the block element's border using ''border'', and the space between the block element's border and its content using ''padding'':&lt;br /&gt;
&lt;br /&gt;
[[File:Box.png]]&lt;br /&gt;
&lt;br /&gt;
For example, you could make a padded box that is centered on the page using this CSS:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;css&amp;quot;&amp;gt;&lt;br /&gt;
div.box {&lt;br /&gt;
	width: 500px;&lt;br /&gt;
	margin: 0 auto; /* when two &amp;quot;arguments&amp;quot; are passed to margin or padding, the first defines top&lt;br /&gt;
		and bottom margin/padding and the second defines left and right margin/padding */&lt;br /&gt;
	padding: 25px; /* when only one &amp;quot;argument&amp;quot; is passed to margin or padding, it defines the&lt;br /&gt;
		margin/padding on all four sides */&lt;br /&gt;
	border: 1px solid black; /* the 1px defines the border-width; the solid defines the border-style;&lt;br /&gt;
		the black defines the border-color */&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is what the resulting box looks like:&lt;br /&gt;
&lt;br /&gt;
[[File:CSSBoxExample.png]]&lt;br /&gt;
&lt;br /&gt;
Note that the ''width'' defines only the ''content width''.  To compute the actual &amp;quot;width&amp;quot; of the element, you need to add the left and right padding border, and margin.&lt;br /&gt;
&lt;br /&gt;
This is only scraping the surface of the CSS box model.  All advanced web sites utilize the box model to its full extent to produce the complex layouts you have come to expect on the internet.  For more information on the CSS box model, read [http://www.w3.org/TR/css3-box/ the W3C specification].&lt;br /&gt;
&lt;br /&gt;
=== Typography ===&lt;br /&gt;
&lt;br /&gt;
Traditionally, Web developers were limited to a small subset of fonts that were commonly installed on all computers:&lt;br /&gt;
&lt;br /&gt;
* Andale Mono&lt;br /&gt;
* Arial&lt;br /&gt;
* Arial Black&lt;br /&gt;
* Comic Sans MS&lt;br /&gt;
* Courier New&lt;br /&gt;
* Georgia&lt;br /&gt;
* Impact&lt;br /&gt;
* Times New Roman&lt;br /&gt;
* Trebuchet MS&lt;br /&gt;
* Verdana&lt;br /&gt;
* Webdings&lt;br /&gt;
&lt;br /&gt;
That was it.  Incredibly limiting.&lt;br /&gt;
&lt;br /&gt;
However, fonts other than these are used widely on the Web.  How?  CSS has evolved to the point where it now allows you to upload a font to your server, and use that font on your site.  My favorite place to go for free Web fonts is [http://fontsquirrel.com/ FontSquirrel].  For more information and more places to get Web fonts, [http://www.sitepoint.com/5-of-the-best-css3-font-tools/ read this article on SitePoint].&lt;br /&gt;
&lt;br /&gt;
== Using HTML and CSS in your Web Page ==&lt;br /&gt;
&lt;br /&gt;
Recall that HTML defines the ''content'' of your page, while CSS defines the ''appearance''.&lt;br /&gt;
&lt;br /&gt;
Most of the HTML you write will be in the &amp;lt;code&amp;gt;&amp;lt;body&amp;gt;&amp;lt;/code&amp;gt; tag, because, naturally, this is where the ''content'' of your page should reside.  CSS, on the other hand, is supplemental to the content, and so it should be included in the &amp;lt;code&amp;gt;&amp;lt;head&amp;gt;&amp;lt;/code&amp;gt; tag, as shown in the following section.&lt;br /&gt;
&lt;br /&gt;
=== How to Include CSS ===&lt;br /&gt;
&lt;br /&gt;
There are three options for using CSS in your web page:&lt;br /&gt;
&lt;br /&gt;
# Loading external stylesheets&lt;br /&gt;
# Embedding stylesheets in the document&lt;br /&gt;
# Inline styles using the style attribute&lt;br /&gt;
&lt;br /&gt;
The first option is almost always preferred in production applications for the following reasons:&lt;br /&gt;
&lt;br /&gt;
* Browsers can cache external stylesheets, so once they've loaded the stylesheet once, they won't have to load it again, making future pages load faster and reducing requests to your server&lt;br /&gt;
* External stylesheets are more modular; that is, they can be included in multiple pages on your web site without the need for copying and pasting embedded stylesheets&lt;br /&gt;
&lt;br /&gt;
To include external stylesheets in your document, place the following empty HTML tag in your &amp;lt;code&amp;gt;&amp;lt;head&amp;gt;&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;link rel=&amp;quot;stylesheet&amp;quot; type=&amp;quot;text/css&amp;quot; href=&amp;quot;path/to/stylesheet.css&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
It may be convenient during development to use embedded stylesheets, because then you don't have to click back and forth between files in your IDE and clear your browser cache.  You may place embedded stylesheets in a &amp;lt;code&amp;gt;&amp;lt;style&amp;gt;&amp;lt;/code&amp;gt; tag, also in your &amp;lt;code&amp;gt;&amp;lt;head&amp;gt;&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;style type=&amp;quot;text/css&amp;quot;&amp;gt;&lt;br /&gt;
styles {&lt;br /&gt;
	go: here;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/style&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
For a variety of reasons, inline styles should almost always be avoided.  Instead of using inline styles, give your element a CSS class, and assign styles to that class in your stylesheet:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;css&amp;quot;&amp;gt;&lt;br /&gt;
p.notice {&lt;br /&gt;
	color: blue;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;p class=&amp;quot;notice&amp;quot;&amp;gt;Well done using classes instead of inline styles!&amp;lt;/p&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Just so you know it when you see it, the following example shows the usage of inline styles, which are declared using the '''style''' attribute.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;p style=&amp;quot;color:red;&amp;quot;&amp;gt;You'd better think twice about using inline styles.&amp;lt;/p&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Quick and Easy Page Layout ===&lt;br /&gt;
&lt;br /&gt;
I like to use the following code when I just want a simple, aesthetically pleasing web page:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
&amp;lt;meta charset=&amp;quot;utf-8&amp;quot;/&amp;gt;&lt;br /&gt;
&amp;lt;title&amp;gt;My Web Page&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;style type=&amp;quot;text/css&amp;quot;&amp;gt;&lt;br /&gt;
body{&lt;br /&gt;
	width: 760px; /* how wide to make your web page */&lt;br /&gt;
	background-color: teal; /* what color to make the background */&lt;br /&gt;
	margin: 0 auto;&lt;br /&gt;
	padding: 0;&lt;br /&gt;
	font:12px/16px Verdana, sans-serif; /* default font */&lt;br /&gt;
}&lt;br /&gt;
div#main{&lt;br /&gt;
	background-color: #FFF;&lt;br /&gt;
	margin: 0;&lt;br /&gt;
	padding: 10px;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/style&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&amp;lt;div id=&amp;quot;main&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!-- CONTENT HERE --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/div&amp;gt;&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Put your document where the &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;&amp;lt;!-- CONTENT HERE --&amp;gt;&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; is.  Your page will go instantly from dull-looking to presentable. ;-)&lt;br /&gt;
&lt;br /&gt;
=== The HTML5 Shiv ===&lt;br /&gt;
&lt;br /&gt;
Some browsers (*cough cough* IE &amp;lt; version 9) do strange things when you apply CSS styles to the newest HTML elements that were introduced with HTML5.  Fortunately, there is a painless solution.  Simply include the following code in your '''&amp;lt;head&amp;gt;''' tag:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!--[if lt IE 9]&amp;gt;&lt;br /&gt;
&amp;lt;script src=&amp;quot;http://html5shiv.googlecode.com/svn/trunk/html5.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;![endif]--&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This so-called '''HTML5 Shiv''' will make older versions of Internet Explorer render your pages more closely to how modern browsers do.&lt;br /&gt;
&lt;br /&gt;
== Validation ==&lt;br /&gt;
{{XKCD&lt;br /&gt;
|id=1144&lt;br /&gt;
|name=tags&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
HTML and to a lesser extent CSS are forgiving when it comes to syntactical errors in your code.  However, it is not good practice to ignore your syntax errors for a variety of reasons:&lt;br /&gt;
&lt;br /&gt;
* '''Faster and More Reliable Rendering.'''  Don't leave it up to your client's browser to decide what you meant when you made your syntax error.&lt;br /&gt;
* '''Interoperability with Compliant Browsers.'''  Although a web page may ''look'' right in your ''testing'' browser, you need to remember that there are ''lots'' of different user agents: other browsers, mobile devices, and screen readers, just to name a few.&lt;br /&gt;
* '''Accessibility.'''  Valid HTML code enables you to be confident that your page will be accessible to people with disabilities, such as the blind.&lt;br /&gt;
* '''Search Engine Optimization.''' Web sites with valid HTML syntax rank higher in search engines like Google.&lt;br /&gt;
* '''Future Proofing.'''  The W3C specification will not be made backwards-incompatible, so writing valid HTML syntax ensures that your page will work well into the future.&lt;br /&gt;
* '''More Professional.'''  No seasoned web developer will publish a page with accidental syntax errors.&lt;br /&gt;
&lt;br /&gt;
The industry standard tool for HTML and CSS syntax checking is the '''[http://validator.w3.org/ W3C Validator]'''.  '''You should ALWAYS validate your code before completing your project!'''  The Validator gives very helpful feedback to help you find and fix syntax errors.&lt;br /&gt;
&lt;br /&gt;
For more information on why it is important to validate, see [http://validator.w3.org/docs/why.html the W3C's recommendation].&lt;br /&gt;
&lt;br /&gt;
=== But why don't… ===&lt;br /&gt;
&lt;br /&gt;
As you play around with the validator, you may have discovered that household name sites like [http://www.google.com/ Google] and [http://www.yahoo.com/ Yahoo] do not pass the validator.  This is a deliberate act on the part of these web sites because of the following reasons:&lt;br /&gt;
&lt;br /&gt;
* '''Download Speed.'''  Sometimes, but not always, valid code adds bytes to the file size.  Sites that serve tens of thousands of requests per second are highly concerned with the increased file size.&lt;br /&gt;
* '''Interoperability with Non-Compliant Browsers.'''  ''Very'' old browsers like Netscape Navigator and Internet Explorer 5 do not respond the way that modern browsers do to the same markup.&lt;br /&gt;
&lt;br /&gt;
However, do not take these as reasons to not validate your own code.  The reasons listed in the previous section almost always outweigh the counterpoints in this section.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 1]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=1804</id>
		<title>Node.JS</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=1804"/>
		<updated>2014-10-14T06:46:55Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* Node.JS Conventions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;AJAX is a useful technology for web applications that need to pull periodic updates from your server.  But what do you do when you have thousands of clients all requesting data that changes real-time?  A PHP+AJAX approach would choke.  It is situations like these that Node.JS comes to the rescue.&lt;br /&gt;
&lt;br /&gt;
== Non-Blocking I/O ==&lt;br /&gt;
&lt;br /&gt;
You dabbled in the concept of non-blocking I/O when you implemented AJAX in the previous JavaScript module.  Node.JS uses this execution model at its core.&lt;br /&gt;
&lt;br /&gt;
The core idea is the use of '''''anonymous functions''''' as ''callbacks'' for processing the results of intensive operations.  Consider the pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
var data = database.query(&amp;quot;select * from news&amp;quot;);&lt;br /&gt;
print data[0].title;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above pseudo-code queries a database, saves the result of the query in a variable named ''data'', and then prints out the first title in ''data''.  The problem arises when multiple clients all want to access the server at the same time.  ''In a blocking I/O model, a client needs to wait until all other clients are finished before it can start its process.''  With intensive operations and thousands of clients, this can easily crash your server!&lt;br /&gt;
&lt;br /&gt;
The solution is to use ''non-blocking I/O''.  Consider this revised pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Non-Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
database.query(&amp;quot;select * from news&amp;quot;, function(data){&lt;br /&gt;
	print data[0].title;&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The revised pseudo-code achieves the same end result as the first version.  However, ''it allows other clients to perform tasks while this process is waiting for the database to be queried!''  The code occurs in two parts: first, we start the query.  Second, ''when the query is complete'', our '''anonymous callback function''' is executed.  In Node.JS, callback functions are usually passed one or more parameters.&lt;br /&gt;
&lt;br /&gt;
Better yet, with non-blocking I/O, you have no concurrency issues, because everything runs in just one thread.  Nifty!&lt;br /&gt;
&lt;br /&gt;
== Installing Node.JS ==&lt;br /&gt;
&lt;br /&gt;
You can get Node.JS from yum or apt-get, but the versions are going to be out dated.  Remember that Node.JS is a rapidly changing language, so a version of Node from last year is going to be drastically different than a version of Node today.&lt;br /&gt;
&lt;br /&gt;
The unofficial instructions for installing Node.JS can be found here: https://gist.github.com/isaacs/579814&lt;br /&gt;
&lt;br /&gt;
There are several choices, but my favorite is probably ''use-nave-no-shell.sh''.&lt;br /&gt;
&lt;br /&gt;
== Your First Node.JS Application: Hello World ==&lt;br /&gt;
&lt;br /&gt;
Let's try running the example application given on the front page of nodejs.org:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var http = require('http');&lt;br /&gt;
http.createServer(function (req, res) {&lt;br /&gt;
	res.writeHead(200, {&lt;br /&gt;
		'Content-Type': 'text/plain'&lt;br /&gt;
	});&lt;br /&gt;
	res.end('Hello World\n');&lt;br /&gt;
}).listen(1337);&lt;br /&gt;
console.log('Server running at http://localhost:1337/');&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Paste the example into a file named `hello.js`, and then run it by calling `node hello.js`.  You should now be able to see your Hello World by visiting your server at port 1337!  (Press ^C to stop the application.)  '''Note:''' If you're running the code from your EC2 instance, you will need to open port 1337.&lt;br /&gt;
&lt;br /&gt;
Let's walk through each line in the above example.&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;code&amp;gt;var http = require('http');&amp;lt;/code&amp;gt; enables us to use Node's built-in HTTP server.  We've been spoiled that languages like PHP automatically load all of the libraries that we need.  However, '''''most functionality in Node.JS is NOT loaded by default.'''''  When you want to use any non-fundamental feature of Node, you need to ''require'' it into a variable, as this example does with the HTTP package.  You should be familiar with this concept when you needed to use ArrayList and other specialty packages in Java in CSE 132.&lt;br /&gt;
* &amp;lt;code&amp;gt;http.createServer(function (req, res) { ... }).listen(1337);&amp;lt;/code&amp;gt; uses the HTTP server API to listen for HTTP connections on port 1337.  The anonymous callback function will be called whenever a connection is made.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.writeHead(200, { 'Content-Type': 'text/plain' });&amp;lt;/code&amp;gt; specifies the Content-Type header to be &amp;quot;text/plain&amp;quot;.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.end('Hello World\n');&amp;lt;/code&amp;gt; writes &amp;quot;Hello World&amp;quot; to the response.&lt;br /&gt;
&lt;br /&gt;
Note the use of non-blocking I/O, even in this one little example.  ''Whenever a connection is made, the callback function will be called and passed parameters associated with that connection.''&lt;br /&gt;
&lt;br /&gt;
== A Static Fileserver Using Node.JS ==&lt;br /&gt;
&lt;br /&gt;
Node.JS does not automatically serve up static files in the way that an Apache/PHP does.  We need to either use an extension that handles this for us, like Express, or we need to write our own code to make a simple static fileserver.  The latter option is really not all that difficult, and it gives good insight into how a static fileserver works.&lt;br /&gt;
&lt;br /&gt;
=== Installing Packages ===&lt;br /&gt;
&lt;br /&gt;
In order for the example code below to work, you need to install the ''mime'' package.  To do this, '''cd to the working directory where you will save your Node.JS JavaScript file''' and run:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;$ npm install mime&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''npm'' is the package manager for Node.JS.  Unlike all of the package managers we've used up to this point, ''npm'' installs dependencies locally, ''not'' globally.  This means that you can have two different projects using different versions of the same package.  ''npm'' will create a ''node_modules'' directory in the CWD and will install the packages into it.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' When using npm to install local dependencies, '''''do not use sudo'''''.  It will screw up your file permissions.&lt;br /&gt;
&lt;br /&gt;
=== Static Fileserver Code ===&lt;br /&gt;
&lt;br /&gt;
The following code will make an HTTP server on port 3456 that serves up all static files in &amp;lt;STATIC DIRECTORY NAME&amp;gt; relative to app.js.&lt;br /&gt;
&lt;br /&gt;
'''Make an attempt to understand this code.'''  It's important that you are comfortable with the non-blocking nature, as well as how we handle file I/O.  There may be quiz questions about this code.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Require the functionality we need to use:&lt;br /&gt;
var http = require('http'),&lt;br /&gt;
	url = require('url'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	mime = require('mime'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	fs = require('fs');&lt;br /&gt;
&lt;br /&gt;
// Make a simple fileserver for all of our static content.&lt;br /&gt;
// Everything underneath &amp;lt;STATIC DIRECTORY NAME&amp;gt; will be served.&lt;br /&gt;
var app = http.createServer(function(req, resp){&lt;br /&gt;
	var filename = path.join(__dirname, &amp;quot;&amp;lt;STATIC DIRECTORY NAME&amp;gt;&amp;quot;, url.parse(req.url).pathname);&lt;br /&gt;
	(fs.exists || path.exists)(filename, function(exists){&lt;br /&gt;
		if (exists) {&lt;br /&gt;
			fs.readFile(filename, function(err, data){&lt;br /&gt;
				if (err) {&lt;br /&gt;
					// File exists but is not readable (permissions issue?)&lt;br /&gt;
					resp.writeHead(500, {&lt;br /&gt;
						&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
					});&lt;br /&gt;
					resp.write(&amp;quot;Internal server error: could not read file&amp;quot;);&lt;br /&gt;
					resp.end();&lt;br /&gt;
					return;&lt;br /&gt;
				}&lt;br /&gt;
				&lt;br /&gt;
				// File exists and is readable&lt;br /&gt;
				var mimetype = mime.lookup(filename);&lt;br /&gt;
				resp.writeHead(200, {&lt;br /&gt;
					&amp;quot;Content-Type&amp;quot;: mimetype&lt;br /&gt;
				});&lt;br /&gt;
				resp.write(data);&lt;br /&gt;
				resp.end();&lt;br /&gt;
				return;&lt;br /&gt;
			});&lt;br /&gt;
		}else{&lt;br /&gt;
			// File does not exist&lt;br /&gt;
			resp.writeHead(404, {&lt;br /&gt;
				&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
			});&lt;br /&gt;
			resp.write(&amp;quot;Requested file not found: &amp;quot;+filename);&lt;br /&gt;
			resp.end();&lt;br /&gt;
			return;&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
app.listen(3456);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Port 3456 ===&lt;br /&gt;
&lt;br /&gt;
We are running our server on port 3456 as opposed to the default web server port, which of course is 80.  We therefore need to open our Node.JS application like this:&lt;br /&gt;
&lt;br /&gt;
http://ec2-xx-xx-xx-xx.compute-1.amazonaws.com:3456/path.extension&lt;br /&gt;
&lt;br /&gt;
However, this won't work on the first time.  ''Why?'' (Try to figure this out on your own before reading the next paragraph.)&lt;br /&gt;
&lt;br /&gt;
We need to open port 3456 on our Amazon EC2 instance.  Remember when you opened port 80 way back in Module 2?  We need to do the same sort of procedure again now.&lt;br /&gt;
&lt;br /&gt;
# Log into your EC2 management console&lt;br /&gt;
# Go to &amp;quot;Security Groups&amp;quot;&lt;br /&gt;
# Select your security group from Module 2&lt;br /&gt;
# Under &amp;quot;Inbound&amp;quot;, create a custom TCP rule for port 3456, and apply your changes.&lt;br /&gt;
&lt;br /&gt;
== Node.JS Security ==&lt;br /&gt;
&lt;br /&gt;
Just because we're writing in JavaScript doesn't mean that we can forget about the security practices you've been learning in the last three months of CSE 330.  XSS is still a problem, as is the use of ''eval'', CSRF attacks, and so on.&lt;br /&gt;
&lt;br /&gt;
Here is a good slideshow introducing Node.JS as well as some security vulnerabilities to look out for: http://www.slideshare.net/ASF-WS/asfws-2012-nodejs-security-old-vulnerabilities-in-new-dresses-par-sven-vetsch&lt;br /&gt;
&lt;br /&gt;
== Node.JS Conventions ==&lt;br /&gt;
&lt;br /&gt;
There ought to be a standard way to save metadata about your app, right?  Well, ''npm'' introduces a straightforward way to do this in the form of a ''package.json'' file.&lt;br /&gt;
&lt;br /&gt;
To make your ''npm'' file with a step-by-step prompt, run in your project root directory:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm init&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One nifty feature of ''package.json'' is the way it automatically handles dependencies.  For example, you can put the following lines in your ''package.json'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
  &amp;quot;dependencies&amp;quot;: {&lt;br /&gt;
    &amp;quot;mime&amp;quot;: &amp;quot;~1.2.11&amp;quot;,&lt;br /&gt;
    &amp;quot;socket.io&amp;quot;: &amp;quot;~0.9.16&amp;quot;,&lt;br /&gt;
  },&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then, back on the command line, when you run&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm install&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
it automatically installs the dependencies for you!  No more headaches of trying to figure out which modules you need to install; all that information is saved for you in your code base.&lt;br /&gt;
&lt;br /&gt;
'''Tip:''' Once you set up your ''package.json'' file, you can automatically add a dependency to it by using the ''--save'' argument on ''npm install'': &amp;lt;code&amp;gt;npm install --save socket.io&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 7]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=1803</id>
		<title>Node.JS</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=1803"/>
		<updated>2014-10-14T06:46:31Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* Node.JS Conventions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;AJAX is a useful technology for web applications that need to pull periodic updates from your server.  But what do you do when you have thousands of clients all requesting data that changes real-time?  A PHP+AJAX approach would choke.  It is situations like these that Node.JS comes to the rescue.&lt;br /&gt;
&lt;br /&gt;
== Non-Blocking I/O ==&lt;br /&gt;
&lt;br /&gt;
You dabbled in the concept of non-blocking I/O when you implemented AJAX in the previous JavaScript module.  Node.JS uses this execution model at its core.&lt;br /&gt;
&lt;br /&gt;
The core idea is the use of '''''anonymous functions''''' as ''callbacks'' for processing the results of intensive operations.  Consider the pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
var data = database.query(&amp;quot;select * from news&amp;quot;);&lt;br /&gt;
print data[0].title;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above pseudo-code queries a database, saves the result of the query in a variable named ''data'', and then prints out the first title in ''data''.  The problem arises when multiple clients all want to access the server at the same time.  ''In a blocking I/O model, a client needs to wait until all other clients are finished before it can start its process.''  With intensive operations and thousands of clients, this can easily crash your server!&lt;br /&gt;
&lt;br /&gt;
The solution is to use ''non-blocking I/O''.  Consider this revised pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Non-Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
database.query(&amp;quot;select * from news&amp;quot;, function(data){&lt;br /&gt;
	print data[0].title;&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The revised pseudo-code achieves the same end result as the first version.  However, ''it allows other clients to perform tasks while this process is waiting for the database to be queried!''  The code occurs in two parts: first, we start the query.  Second, ''when the query is complete'', our '''anonymous callback function''' is executed.  In Node.JS, callback functions are usually passed one or more parameters.&lt;br /&gt;
&lt;br /&gt;
Better yet, with non-blocking I/O, you have no concurrency issues, because everything runs in just one thread.  Nifty!&lt;br /&gt;
&lt;br /&gt;
== Installing Node.JS ==&lt;br /&gt;
&lt;br /&gt;
You can get Node.JS from yum or apt-get, but the versions are going to be out dated.  Remember that Node.JS is a rapidly changing language, so a version of Node from last year is going to be drastically different than a version of Node today.&lt;br /&gt;
&lt;br /&gt;
The unofficial instructions for installing Node.JS can be found here: https://gist.github.com/isaacs/579814&lt;br /&gt;
&lt;br /&gt;
There are several choices, but my favorite is probably ''use-nave-no-shell.sh''.&lt;br /&gt;
&lt;br /&gt;
== Your First Node.JS Application: Hello World ==&lt;br /&gt;
&lt;br /&gt;
Let's try running the example application given on the front page of nodejs.org:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var http = require('http');&lt;br /&gt;
http.createServer(function (req, res) {&lt;br /&gt;
	res.writeHead(200, {&lt;br /&gt;
		'Content-Type': 'text/plain'&lt;br /&gt;
	});&lt;br /&gt;
	res.end('Hello World\n');&lt;br /&gt;
}).listen(1337);&lt;br /&gt;
console.log('Server running at http://localhost:1337/');&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Paste the example into a file named `hello.js`, and then run it by calling `node hello.js`.  You should now be able to see your Hello World by visiting your server at port 1337!  (Press ^C to stop the application.)  '''Note:''' If you're running the code from your EC2 instance, you will need to open port 1337.&lt;br /&gt;
&lt;br /&gt;
Let's walk through each line in the above example.&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;code&amp;gt;var http = require('http');&amp;lt;/code&amp;gt; enables us to use Node's built-in HTTP server.  We've been spoiled that languages like PHP automatically load all of the libraries that we need.  However, '''''most functionality in Node.JS is NOT loaded by default.'''''  When you want to use any non-fundamental feature of Node, you need to ''require'' it into a variable, as this example does with the HTTP package.  You should be familiar with this concept when you needed to use ArrayList and other specialty packages in Java in CSE 132.&lt;br /&gt;
* &amp;lt;code&amp;gt;http.createServer(function (req, res) { ... }).listen(1337);&amp;lt;/code&amp;gt; uses the HTTP server API to listen for HTTP connections on port 1337.  The anonymous callback function will be called whenever a connection is made.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.writeHead(200, { 'Content-Type': 'text/plain' });&amp;lt;/code&amp;gt; specifies the Content-Type header to be &amp;quot;text/plain&amp;quot;.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.end('Hello World\n');&amp;lt;/code&amp;gt; writes &amp;quot;Hello World&amp;quot; to the response.&lt;br /&gt;
&lt;br /&gt;
Note the use of non-blocking I/O, even in this one little example.  ''Whenever a connection is made, the callback function will be called and passed parameters associated with that connection.''&lt;br /&gt;
&lt;br /&gt;
== A Static Fileserver Using Node.JS ==&lt;br /&gt;
&lt;br /&gt;
Node.JS does not automatically serve up static files in the way that an Apache/PHP does.  We need to either use an extension that handles this for us, like Express, or we need to write our own code to make a simple static fileserver.  The latter option is really not all that difficult, and it gives good insight into how a static fileserver works.&lt;br /&gt;
&lt;br /&gt;
=== Installing Packages ===&lt;br /&gt;
&lt;br /&gt;
In order for the example code below to work, you need to install the ''mime'' package.  To do this, '''cd to the working directory where you will save your Node.JS JavaScript file''' and run:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;$ npm install mime&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''npm'' is the package manager for Node.JS.  Unlike all of the package managers we've used up to this point, ''npm'' installs dependencies locally, ''not'' globally.  This means that you can have two different projects using different versions of the same package.  ''npm'' will create a ''node_modules'' directory in the CWD and will install the packages into it.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' When using npm to install local dependencies, '''''do not use sudo'''''.  It will screw up your file permissions.&lt;br /&gt;
&lt;br /&gt;
=== Static Fileserver Code ===&lt;br /&gt;
&lt;br /&gt;
The following code will make an HTTP server on port 3456 that serves up all static files in &amp;lt;STATIC DIRECTORY NAME&amp;gt; relative to app.js.&lt;br /&gt;
&lt;br /&gt;
'''Make an attempt to understand this code.'''  It's important that you are comfortable with the non-blocking nature, as well as how we handle file I/O.  There may be quiz questions about this code.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Require the functionality we need to use:&lt;br /&gt;
var http = require('http'),&lt;br /&gt;
	url = require('url'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	mime = require('mime'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	fs = require('fs');&lt;br /&gt;
&lt;br /&gt;
// Make a simple fileserver for all of our static content.&lt;br /&gt;
// Everything underneath &amp;lt;STATIC DIRECTORY NAME&amp;gt; will be served.&lt;br /&gt;
var app = http.createServer(function(req, resp){&lt;br /&gt;
	var filename = path.join(__dirname, &amp;quot;&amp;lt;STATIC DIRECTORY NAME&amp;gt;&amp;quot;, url.parse(req.url).pathname);&lt;br /&gt;
	(fs.exists || path.exists)(filename, function(exists){&lt;br /&gt;
		if (exists) {&lt;br /&gt;
			fs.readFile(filename, function(err, data){&lt;br /&gt;
				if (err) {&lt;br /&gt;
					// File exists but is not readable (permissions issue?)&lt;br /&gt;
					resp.writeHead(500, {&lt;br /&gt;
						&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
					});&lt;br /&gt;
					resp.write(&amp;quot;Internal server error: could not read file&amp;quot;);&lt;br /&gt;
					resp.end();&lt;br /&gt;
					return;&lt;br /&gt;
				}&lt;br /&gt;
				&lt;br /&gt;
				// File exists and is readable&lt;br /&gt;
				var mimetype = mime.lookup(filename);&lt;br /&gt;
				resp.writeHead(200, {&lt;br /&gt;
					&amp;quot;Content-Type&amp;quot;: mimetype&lt;br /&gt;
				});&lt;br /&gt;
				resp.write(data);&lt;br /&gt;
				resp.end();&lt;br /&gt;
				return;&lt;br /&gt;
			});&lt;br /&gt;
		}else{&lt;br /&gt;
			// File does not exist&lt;br /&gt;
			resp.writeHead(404, {&lt;br /&gt;
				&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
			});&lt;br /&gt;
			resp.write(&amp;quot;Requested file not found: &amp;quot;+filename);&lt;br /&gt;
			resp.end();&lt;br /&gt;
			return;&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
app.listen(3456);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Port 3456 ===&lt;br /&gt;
&lt;br /&gt;
We are running our server on port 3456 as opposed to the default web server port, which of course is 80.  We therefore need to open our Node.JS application like this:&lt;br /&gt;
&lt;br /&gt;
http://ec2-xx-xx-xx-xx.compute-1.amazonaws.com:3456/path.extension&lt;br /&gt;
&lt;br /&gt;
However, this won't work on the first time.  ''Why?'' (Try to figure this out on your own before reading the next paragraph.)&lt;br /&gt;
&lt;br /&gt;
We need to open port 3456 on our Amazon EC2 instance.  Remember when you opened port 80 way back in Module 2?  We need to do the same sort of procedure again now.&lt;br /&gt;
&lt;br /&gt;
# Log into your EC2 management console&lt;br /&gt;
# Go to &amp;quot;Security Groups&amp;quot;&lt;br /&gt;
# Select your security group from Module 2&lt;br /&gt;
# Under &amp;quot;Inbound&amp;quot;, create a custom TCP rule for port 3456, and apply your changes.&lt;br /&gt;
&lt;br /&gt;
== Node.JS Security ==&lt;br /&gt;
&lt;br /&gt;
Just because we're writing in JavaScript doesn't mean that we can forget about the security practices you've been learning in the last three months of CSE 330.  XSS is still a problem, as is the use of ''eval'', CSRF attacks, and so on.&lt;br /&gt;
&lt;br /&gt;
Here is a good slideshow introducing Node.JS as well as some security vulnerabilities to look out for: http://www.slideshare.net/ASF-WS/asfws-2012-nodejs-security-old-vulnerabilities-in-new-dresses-par-sven-vetsch&lt;br /&gt;
&lt;br /&gt;
== Node.JS Conventions ==&lt;br /&gt;
&lt;br /&gt;
There ought to be a standard way to save metadata about your app, right?  Well, ''npm'' introduces a straightforward way to do this in the form of a ''package.json'' file.&lt;br /&gt;
&lt;br /&gt;
To make your ''npm'' file with a step-by-step prompt, run in your project root directory:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm init&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One nifty feature of ''package.json'' is the way it automatically handles dependencies.  For example, you can put the following lines in your ''package.json'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
  &amp;quot;dependencies&amp;quot;: {&lt;br /&gt;
    &amp;quot;mime&amp;quot;: &amp;quot;~1.2.11&amp;quot;,&lt;br /&gt;
    &amp;quot;socket.io&amp;quot;: &amp;quot;~0.9.16&amp;quot;,&lt;br /&gt;
  },&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then, back on the command line, when you run&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm install&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
it automatically installs the dependencies for you!  No more headaches of trying to figure out which modules you need to install; all that information is saved for you in your code base.&lt;br /&gt;
&lt;br /&gt;
'''Tip:''' Once you set up your ''package.json'' file, you can automatically add a dependency to it by using the ''--save'' argument on ''npm install'': &amp;lt;code&amp;gt;npm install --save nave socket.io&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 7]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=1802</id>
		<title>JavaScript</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=1802"/>
		<updated>2014-10-14T06:39:06Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* JavaScript Language Components */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;JavaScript is the most widely used scripting language for implementing client-side functionality in Web applications.  Unlike PHP, JavaScript code is interpreted and executed in a client's web browser (not on the web server).&lt;br /&gt;
&lt;br /&gt;
== JavaScript?  Did you mean Java? ==&lt;br /&gt;
&lt;br /&gt;
'''JavaScript''' is a prototype-based programming language focussed on web interactivity.  It was first introduced in Netscape Navigator, and it in turn gave rise to what is now '''[http://www.ecmascript.org/ ECMAScript]'''.  Originally, JavaScript was called &amp;quot;LiveScript&amp;quot;.  Sun, the developer of Java at the time, wanted a language that would complement its compiled Java language, and so LiveScript was renamed JavaScript.&lt;br /&gt;
&lt;br /&gt;
Beyond that, '''Java and JavaScript are as similar as Ham and Hamster.'''&lt;br /&gt;
&lt;br /&gt;
Java and JavaScript have similar syntax, but the under workings are quite different.  For example, Java requires strict typing, but JavaScript allows for dynamic typing.  Java is object-oriented, but JavaScript is prototype-oriented.  Java is compiled, but JavaScript is interpreted.  Java supports event listeners, but JavaScript makes them a fundamental part of the language.  Java variables are scoped to the innermost method or loop, but JavaScript variables are scoped only to the innermost function.&lt;br /&gt;
&lt;br /&gt;
== JavaScript Language Components ==&lt;br /&gt;
&lt;br /&gt;
This section highlights some features of the JavaScript language that differentiate it from other languages.  For a more comprehensive JavaScript tutorial, the following tutorials are both quality:&lt;br /&gt;
&lt;br /&gt;
* [http://docs.webplatform.org/wiki/javascript WebPlatform]: Great for learning JavaScript for the first time.  Advocates best practices for modern JavaScript development.&lt;br /&gt;
* [http://www.quirksmode.org/js/contents.html QuirksMode]: More advanced than the WebPlatform tutorial, but it thoroughly covers the most powerful aspects of pure JavaScript and gives unparalleled advice on browser compatibility.&lt;br /&gt;
&lt;br /&gt;
Advice: Do '''NOT''' Google for &amp;quot;JavaScript Tutorial&amp;quot;.  The first few hits advocate bad or outdated practices.  Stick with the ones listed here.&lt;br /&gt;
&lt;br /&gt;
=== Variables and Scope ===&lt;br /&gt;
&lt;br /&gt;
To define a variable in JavaScript, use the '''var''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var foo = &amp;quot;bar&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
All variables are objects.  In the case above, the variable '''foo''' is an object of the class '''String'''.&lt;br /&gt;
&lt;br /&gt;
Notice that like PHP, you do not have to explicitly define a type for a variable like '''int''' or '''String'''; this is because JavaScript and PHP are ''dynamically typed languages''.&lt;br /&gt;
&lt;br /&gt;
JavaScript code can access any variable higher in the “function tree”, but not vice-versa.  This is called '''scope'''.  ''All functions create their own scope.''&lt;br /&gt;
&lt;br /&gt;
When you reference a variable, JavaScript will look up through the &amp;quot;function tree&amp;quot; until it finds the variable you asked for.  This means that you could define variables of the same name as global variables inside of functions.  For demonstration of concept:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var a = &amp;quot;hello&amp;quot;;&lt;br /&gt;
var b = &amp;quot;world&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
function sayGoodByeWorld(){&lt;br /&gt;
	var a = &amp;quot;goodbye&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
	alert(a); // goodbye&lt;br /&gt;
	alert(b); // world&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayGoodByeWorld();&lt;br /&gt;
&lt;br /&gt;
alert(a); // hello&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object Literals ===&lt;br /&gt;
&lt;br /&gt;
A very common way of storing and transporting data in JavaScript is by using objects.  You can define an object with certain properties using an '''object literal''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = {&lt;br /&gt;
	color: &amp;quot;red&amp;quot;,&lt;br /&gt;
	flavor: &amp;quot;sweet&amp;quot;,&lt;br /&gt;
	season: &amp;quot;autumn&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(apple.color);  // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
To define a function in JavaScript, use the '''function''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function sayHello(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(); // call the function&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Pass an argument to a function like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function sayHello(name){&lt;br /&gt;
	alert(&amp;quot;Hello, &amp;quot;+name);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(&amp;quot;Todd&amp;quot;); // call the function and pass an argument&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Functions are Objects ====&lt;br /&gt;
&lt;br /&gt;
In JavaScript, functions are objects.  This means that they can be assigned to variables, manipulated on the fly, and even passed as arguments to other functions!  '''''This is an extremely important feature of JavaScript''''' that makes it such a robust language for web development.&lt;br /&gt;
&lt;br /&gt;
You create a function variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayHello = function(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(); // call the function&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Observe that you can make [[#Variables and Scope|scope-dependent]] functions in this way.&lt;br /&gt;
&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=HaPlj796ngQ&lt;br /&gt;
|time=5m45s&lt;br /&gt;
|desc=JavaScript Closures&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
A '''closure''' is a way to separate a certain snippet of JavaScript code from the global scope.  This is useful if you do not want to &amp;quot;muck up&amp;quot; global variables.  Closures are nothing more than anonymous functions that are called as soon as they are created:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
​var a = &amp;quot;hello&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
(​​​​function(){&lt;br /&gt;
	var b = &amp;quot;world&amp;quot;;&lt;br /&gt;
	&lt;br /&gt;
	alert(a); // hello&lt;br /&gt;
	alert(b); // world&lt;br /&gt;
})();&lt;br /&gt;
&lt;br /&gt;
alert(a); // hello&lt;br /&gt;
alert(b);​ // ReferenceError: b is not defined​​​​​​​​​​​​​​​&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Passing Variables to a Closure&lt;br /&gt;
|desc=This example demonstrates how you can &amp;quot;save&amp;quot; previous versions of a variable using closures.  This is possible because of scoping and the fact that function variables can be returned as objects.&lt;br /&gt;
|fiddle_id=YURqa&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Most JavaScript libraries (like jQuery) write all of their code in a closure.  What this means is that except for one or two variable names (jQuery or $), everything associated with the library is completely self-contained.&lt;br /&gt;
&lt;br /&gt;
=== Prototypal Inheritance ===&lt;br /&gt;
&lt;br /&gt;
JavaScript implements '''prototypal inheritance''', as opposed to a language like Java or C++, which implements '''classical inheritance'''.  JavaScript is one of only a handful of languages implementing prototype-based inheritance.&lt;br /&gt;
&lt;br /&gt;
Here's how it works.  Every callable object (function) has a '''prototype'''.  When instances of that object are created, their properties and methods are copied (inherited) from the prototype.  Additionally, changes made to the prototype later in the program are &amp;quot;copied&amp;quot; to every instance.&lt;br /&gt;
&lt;br /&gt;
For example, if you wanted to make a method on all strings that added a “!”, you could modify String’s prototype:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
String.prototype.bang = function(){&lt;br /&gt;
	return this+&amp;quot;!&amp;quot;; // Notice: the context is the instance itself&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(&amp;quot;Hello&amp;quot;.bang()); // alerts Hello!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To &amp;quot;extend&amp;quot; an object, just copy its prototype to a new object.  However, since classical inheritance and prototypal inheritance are different concepts, copying prototypes may have results that you don't expect.  [http://beej.us/blog/data/javascript-prototypes-inheritance/ This article] seems to have a pretty good explanation with example implementations.&lt;br /&gt;
&lt;br /&gt;
=== Context ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=0a4r4bm1nQA&lt;br /&gt;
|time=4m32s&lt;br /&gt;
|desc=The ''this'' Variable in JavaScript&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Every function is called on a certain object, which is not necessarily the same object in which it was defined.  This is called '''context'''.&lt;br /&gt;
&lt;br /&gt;
To call a function on an arbitrary context, use either '''call''' or '''apply'''.  ''call'' takes a list of arguments, while ''apply'' takes them all in an array.&lt;br /&gt;
&lt;br /&gt;
To access the current context, use the '''this''' keyword.  Demonstration of concept:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayThisColor = function(){&lt;br /&gt;
	alert(this.color);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
var apple = { color: &amp;quot;red&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
sayThisColor();   // undefined&lt;br /&gt;
sayThisColor.call(apple); // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Events ==&lt;br /&gt;
&lt;br /&gt;
Events are really what make JavaScript such a powerful language for web development.&lt;br /&gt;
&lt;br /&gt;
Rather than being thread based, JavaScript is event based.  Since all JavaScript code runs in a single thread, '''there are no concurrency issues'''.  When an event occurs, JavaScript automatically calls the ''event callback'' as soon as all previous events' callbacks have finished executing.&lt;br /&gt;
&lt;br /&gt;
Code in the form of a '''callback function''' is associated with events via a '''listener'''.  For example, the following JavaScript causes ''sayHello()'' (the callback function) to be run whenever the button with ID &amp;quot;hello&amp;quot; is clicked (the event):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayHello = function(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
document.getElementById(&amp;quot;hello&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, sayHello, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Binding Callbacks to a Button Click&lt;br /&gt;
|fiddle_id=L8c4Z&lt;br /&gt;
|cse330=true&lt;br /&gt;
|desc=In this example, notice how we bind the callback function when the ''DOMContentLoaded'' event fires.  This is because JavaScript requires that the button has been parsed by the browser before it can add event listeners to it.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The '''addEventListener''' method takes three parameters:&lt;br /&gt;
* The event type&lt;br /&gt;
* The callback function&lt;br /&gt;
*: The callback function is passed one parameter: the event object.&lt;br /&gt;
* A boolean representing bubble (false) or capture (true) phase&lt;br /&gt;
*: You usually want Bubble phase.  For more information on event phase, see [[#Event Phase]]&lt;br /&gt;
&lt;br /&gt;
Note that versions of Internet Explorer prior to version 9 required that you use a different, albeit similar, function for assigning event listeners called '''attachEvent'''.  attachEvent takes the same arguments as addEventListener, except you need to put '''on''' before the event type (e.g. &amp;quot;onclick&amp;quot;), and the third argument (phase) is not necessary.&lt;br /&gt;
&lt;br /&gt;
It is perfectly valid to use an '''anonymous function''' as your callback function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;hello&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, function(event){&lt;br /&gt;
	alert(&amp;quot;Hello, World!  Event Type: &amp;quot;+event.type);&lt;br /&gt;
}, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QuirksMode has perhaps the best series of articles about the ins and outs of JavaScript events on the internet: http://www.quirksmode.org/js/contents.html#events&lt;br /&gt;
&lt;br /&gt;
=== The Event Object ===&lt;br /&gt;
&lt;br /&gt;
Callback functions are passed one argument: an ''event object''.  You see above that one property of the event object is ''event.type''.  To see the full list of properties of the event object, you could run the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;my_btn&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, function(event){&lt;br /&gt;
	var strout = &amp;quot;&amp;quot;;&lt;br /&gt;
	for(var i in event){&lt;br /&gt;
		strout += i + &amp;quot;: &amp;quot; + event[i] + &amp;quot;\n&amp;quot;;&lt;br /&gt;
	}&lt;br /&gt;
	console.log(strout);&lt;br /&gt;
}, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some of the most useful properties and methods include:&lt;br /&gt;
* '''event.target''' references the object on which the event occurred.&lt;br /&gt;
* '''event.currentTarget''' references the object whose listener is currently being processed.&lt;br /&gt;
*: ''Note:'' event.target and event.currentTarget might be the same or might be different, depending on whether you are listening for bubbled events.&lt;br /&gt;
* '''event.preventDefault()''' stops the normal result of the event from being executed.  For example, if you listen for a form's ''submit'' event, you can call event.preventDefault() to stop the form from being submitted.&lt;br /&gt;
* '''event.stopPropagation()''' prevents any other event listeners from being executed.  For more detail, read the section on Event Phase below.&lt;br /&gt;
&lt;br /&gt;
For more detail on the event object, see [http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html#interface-Event the W3C specification].&lt;br /&gt;
&lt;br /&gt;
'''Note:''' If your callback function does not take any parameters, it will still run; you just won't have as easy of access to the event object.&lt;br /&gt;
&lt;br /&gt;
=== Event Handlers and Memory Management ===&lt;br /&gt;
&lt;br /&gt;
JavaScript is an automatically garbage-collected language, meaning that memory management is mostly taken care of for you.  However, there are some instances when you need to be careful about creating &amp;quot;zombie&amp;quot; objects.  One common &amp;quot;gotcha&amp;quot; instance of this is in event listeners.&lt;br /&gt;
&lt;br /&gt;
For example, consider the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Declare an object&lt;br /&gt;
var myObject = {&lt;br /&gt;
	fn: function(event) {&lt;br /&gt;
		alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
// Make a property of that object listen for some event&lt;br /&gt;
document.getElementById(&amp;quot;my-div&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, myObject.fn, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, myObject will ''not'' be garbage collected, even if it goes out of scope, so long as its property ''fn'' is a listener for an event on the div.  In order to release myObject from memory, you need o do the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// If we want myObject to be garbage collected when it leaves scope, we need to remove the event listener.&lt;br /&gt;
document.getElementById(&amp;quot;my-div&amp;quot;).removeEventListener(&amp;quot;click&amp;quot;, myObject.fn, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Event Phase ===&lt;br /&gt;
&lt;br /&gt;
In JavaScript, events occur in two phases: '''Capture Phase''' and '''Bubble Phase'''.  Consider the following HTML document:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&amp;lt;title&amp;gt;Event Test&amp;lt;/title&amp;gt;&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
  &amp;lt;div id=&amp;quot;box&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;button id=&amp;quot;btn&amp;quot;&amp;gt;&lt;br /&gt;
      Hello&lt;br /&gt;
    &amp;lt;/button&amp;gt;&lt;br /&gt;
  &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Suppose the user clicks on the &amp;quot;Hello&amp;quot; button.  Events will be fired in the following order:&lt;br /&gt;
&lt;br /&gt;
# Capture Phase CLICK on the Document&lt;br /&gt;
# Capture Phase CLICK on the Body&lt;br /&gt;
# Capture Phase CLICK on the Div#box&lt;br /&gt;
# Target Phase CLICK on the Button#btn&lt;br /&gt;
# Bubble Phase CLICK on the Div#box&lt;br /&gt;
# Bubble Phase CLICK on the Body&lt;br /&gt;
# Bubble Phase CLICK on the Document&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Using Capture Phase to Enable or Disable a Toolbar&lt;br /&gt;
|fiddle_id=r32Dz&lt;br /&gt;
|desc=We bind an event in the capture phase to the div with ID ''toolbar''.  When ''e.stopPropagation()'' is called, the event does not reach the buttons in the toolbar.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Graphically, here is the order in which an event occurs in three generic nested elements:&lt;br /&gt;
&lt;br /&gt;
[[File:EventPhase.gif]]&lt;br /&gt;
&lt;br /&gt;
Why is this useful?  Suppose you have a control panel (toolbar, etc) that you want to temporarily deactivate.  (For example, Bold/Italic/Underline buttons on a graphic text editor that currently has no content.)  You could keep bubble phase event listeners on your buttons, but prevent those events from occurring by stopping the event in the capture phase on the parent element before the event reaches your buttons!  Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var disableToolbarFunc = function(e){&lt;br /&gt;
	e.stopPropogation();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// To disable toolbar:&lt;br /&gt;
document.getElementById(&amp;quot;box&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, disableToolbarFunc, true);&lt;br /&gt;
&lt;br /&gt;
// To re-enable toolbar:&lt;br /&gt;
document.getElementById(&amp;quot;box&amp;quot;).removeEventListener(&amp;quot;click&amp;quot;, disableToolbarFunc, true);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Word of caution:''' Like many great things in web development, capture phase does not work in versions of Internet Explorer prior to version 9.  There is no elegant substitution for older versions of Internet Explorer.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' When the event reaches the innermost element, there is no distinction between capture phase and bubble phase.  The order in which event handlers were added to the element determines the order in which those callbacks are evaluated.&lt;br /&gt;
&lt;br /&gt;
== Document Object Model ==&lt;br /&gt;
&lt;br /&gt;
The '''Document Object Model (DOM)'''  is what enables JavaScript to manipulate the content of your web page.&lt;br /&gt;
&lt;br /&gt;
=== Nodes and Traversing the DOM ===&lt;br /&gt;
&lt;br /&gt;
Each element on your page, whether it is a &amp;lt;nowiki&amp;gt;&amp;lt;p&amp;gt;, &amp;lt;img/&amp;gt;&amp;lt;/nowiki&amp;gt;, a string of text, or even an attribute, is called a '''node'''.&lt;br /&gt;
&lt;br /&gt;
Every node, except for the document itself, has exactly one parent.  A single node may have multiple children.&lt;br /&gt;
&lt;br /&gt;
Consider the following HTML code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;ul id=&amp;quot;my-list&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;fruits&amp;quot;&amp;gt;Apples&amp;lt;/li&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;citrus&amp;quot;&amp;gt;Oranges and &amp;lt;strong&amp;gt;Lemons&amp;lt;/strong&amp;gt;&amp;lt;/li&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;berries&amp;quot;&amp;gt;Cherries&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ul&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, the ul with ID &amp;quot;my-list&amp;quot; has three child '''element nodes''' (the three li's) as well as four child '''text nodes''' (the whitespace counts as a text node) and a child '''attribute node'''.  The second LI has one child '''text node''' as well as one child '''element node''' and one child '''attribute node'''.&lt;br /&gt;
&lt;br /&gt;
The DOM can be traversed in JavaScript.  First, let's look at an example.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
e = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;citrus&amp;quot;)[0].lastChild.nodeName;&lt;br /&gt;
alert(e);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Currently Selected Radio Button&lt;br /&gt;
|fiddle_id=SHcng&lt;br /&gt;
|desc=In pure JavaScript, in order to determine the currently selected radio button, it is necessary to iterate over an array of pointers to all possible radio buttons, and stop when you find one that is &amp;quot;checked&amp;quot;.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The above snippet gets the element with class name '''citrus''' that is a child of the element with ID '''my-list''' (the second LI in the example above), and alerts the type of its second child node (which in this case is '''STRONG''').&lt;br /&gt;
&lt;br /&gt;
Some common methods for traversing the DOM include:&lt;br /&gt;
&lt;br /&gt;
* Node.parentNode&lt;br /&gt;
* Node.childNodes - returns an array of nodes&lt;br /&gt;
* Node.firstChild - same as Node.childNodes[0]&lt;br /&gt;
* Node.lastChild - same as Node.childNodes[Node.childNodes.length-1]&lt;br /&gt;
* Node.previousSibling&lt;br /&gt;
* Node.nextSibling&lt;br /&gt;
&lt;br /&gt;
You can also search for child (including all descendants) using one of the following methods:&lt;br /&gt;
&lt;br /&gt;
* Node.getElementsByTagName(&amp;quot;tag-name&amp;quot;) - returns an array of element nodes having the tag name '''tag-name''' that are descendants of Node&lt;br /&gt;
* Node.getElementById(&amp;quot;id&amp;quot;) - returns a single node having the ID '''id''' that is a descendant of Node&lt;br /&gt;
* Node.getElementsByName(&amp;quot;what-name&amp;quot;) - returns an array of element nodes having their '''name''' attribute set to '''what-name'''.  Useful for radio buttons and other form elements.&lt;br /&gt;
* Node.getElementsByClassName(&amp;quot;class&amp;quot;) - returns an array of nodes having the class '''class'''&lt;br /&gt;
*: '''Note:''' As of October 2012, 82% of the browser market supports Node.getElementsByClassName ([http://caniuse.com/getelementsbyclassname more info]).  In order to support the other 18%, you need to either add your own getElementsByClassName to Node's prototype or use a JavaScript library like jQuery or MooTools.&lt;br /&gt;
&lt;br /&gt;
It is common in JavaScript to have long statements like the one in the example above, where you call methods on several objects in sequence.&lt;br /&gt;
&lt;br /&gt;
=== Creating, Moving, and Removing Nodes ===&lt;br /&gt;
&lt;br /&gt;
You will frequently find yourself wanting to modify the DOM.  JavaScript provides methods that help you do this.&lt;br /&gt;
&lt;br /&gt;
Consider the same HTML as above.  If you wanted to add another element to the list, you could use this code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var newLi = document.createElement(&amp;quot;li&amp;quot;);  // creates a node with the tag name li&lt;br /&gt;
newLi.appendChild(document.createTextNode(&amp;quot;Broccoli&amp;quot;));&lt;br /&gt;
newLi.setAttribute(&amp;quot;class&amp;quot;, &amp;quot;veggies&amp;quot;);&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).appendChild(newLi);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to remove the apples from the list, you could do:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;fruits&amp;quot;)[0];&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).removeChild(apple);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to move the apples to the end of the list, you could do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;fruits&amp;quot;)[0];&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).appendChild(apple);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that '''Node.append()''' both removes a node from its previous location ''and'' appends it to its new location, which is always going to be as the last child of the parent node.&lt;br /&gt;
&lt;br /&gt;
In summary, here are the methods to know from this section:&lt;br /&gt;
&lt;br /&gt;
* Node.append(otherNode) - removes otherNode from its current location in the DOM (if applicable) and then adds it as the last child of Node&lt;br /&gt;
* Node.removeChild(otherNode) - removes otherNode, a child of Node, from the DOM&lt;br /&gt;
* document.createElement(&amp;quot;tag-name&amp;quot;) - create a new node with the tag name &amp;quot;tag-name&amp;quot;&lt;br /&gt;
* document.createTextNode(&amp;quot;text&amp;quot;) - create a node containing only the string '''text'''&lt;br /&gt;
* Node.setAttribute(&amp;quot;attribute&amp;quot;, &amp;quot;value&amp;quot;) - sets the attribute node of name &amp;quot;attribute&amp;quot; to &amp;quot;value&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=== DOM Shortcuts ===&lt;br /&gt;
&lt;br /&gt;
In the above sections, we have been creating, reading, modifying, and deleting Nodes.  This is the most &amp;quot;correct&amp;quot; way to change the content of a web page from inside JavaScript.&lt;br /&gt;
&lt;br /&gt;
This section documents a few shortcuts that are not as &amp;quot;pure&amp;quot; as using Nodes but can be less confusing and cumbersome.&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Displaying Information&lt;br /&gt;
|fiddle_id=Q3BPZ&lt;br /&gt;
|desc=This example shows how to use some of the shortcut methods for using JavaScript to display information on the page.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
==== textContent ====&lt;br /&gt;
&lt;br /&gt;
Using textContent to display information is probably the easiest method out there.  For example, the following code overwrites whatever is in the element with ID &amp;quot;holder&amp;quot; with the string &amp;quot;Hello World&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).textContent = &amp;quot;Hello World&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to instead append the text, simply use '''+=''' instead of '''=''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).textContent += &amp;quot; -  Later, he said Hello World  - &amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that textContent displays strings literally; that is, it does not allow for HTML.  Setting the textContent property also removes any HTML that may have already been in that element.&lt;br /&gt;
&lt;br /&gt;
==== innerHTML ====&lt;br /&gt;
&lt;br /&gt;
If you need to use HTML in your output but don't want to use the method described earlier in this section, a straightforward strategy is to use the innerHTML property of an element. For example, the following code would add a paragraph saying &amp;quot;Hello World&amp;quot; to the element with ID &amp;quot;holder&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).innerHTML += &amp;quot;&amp;lt;p&amp;gt;Hello World&amp;lt;/p&amp;gt;&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Important:''' You need to be careful to prevent XSS-type attacks if you display information using innerHTML.  For example, be sure to escape a user-supplied string before appending it to innerHTML.&lt;br /&gt;
&lt;br /&gt;
=== JavaScript Inspectors ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=PKzrmbN-pMg&lt;br /&gt;
|time=4m13s&lt;br /&gt;
|desc=Using Firebug, WebKit Inspector, and IE Developer Tools&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Various browsers and browser plugins give you, the developer, tools to debug your code, inspect the DOM, and much more.  Using these tools is essential for an efficient workflow.&lt;br /&gt;
&lt;br /&gt;
* '''Firebug'''.  Firebug is a plugin for Firefox that is a toolkit full of web developer tools, one of which is a DOM inspector.  To inspect the DOM of a web page, simply open the Firebug window while viewing the web page.&lt;br /&gt;
* '''WebKit Inspector'''.  The WebKit Inspector, which is available in both Chrome and Safari, enables you to see the DOM tree and relationships between elements.  However, its DOM inspection tools are not as robust as those of Firebug.&lt;br /&gt;
* '''Opera Dragonfly'''.  The web browser Opera comes with a web developer toolkit similar to the WebKit Inspector called Dragonfly.  It is important that you test your sites in Opera, because although Opera has only a small fraction of the desktop browser market, it is second only to WebKit on the mobile market.  Opera also has extremely strong CSS support, so it is good for testing for bugs in your CSS.&lt;br /&gt;
&lt;br /&gt;
All of the above-mentioned tools enable you to look at the DOM of your web page and find what properties and methods are associated with each node.  This is helpful because if you have JavaScript that manipulates HTML elements, you cannot tell which properties are associated with which elements by looking at the source code alone.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 6]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=1797</id>
		<title>Node.JS</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=1797"/>
		<updated>2014-10-03T08:10:37Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* Installing Packages */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;AJAX is a useful technology for web applications that need to pull periodic updates from your server.  But what do you do when you have thousands of clients all requesting data that changes real-time?  A PHP+AJAX approach would choke.  It is situations like these that Node.JS comes to the rescue.&lt;br /&gt;
&lt;br /&gt;
== Non-Blocking I/O ==&lt;br /&gt;
&lt;br /&gt;
You dabbled in the concept of non-blocking I/O when you implemented AJAX in the previous JavaScript module.  Node.JS uses this execution model at its core.&lt;br /&gt;
&lt;br /&gt;
The core idea is the use of '''''anonymous functions''''' as ''callbacks'' for processing the results of intensive operations.  Consider the pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
var data = database.query(&amp;quot;select * from news&amp;quot;);&lt;br /&gt;
print data[0].title;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above pseudo-code queries a database, saves the result of the query in a variable named ''data'', and then prints out the first title in ''data''.  The problem arises when multiple clients all want to access the server at the same time.  ''In a blocking I/O model, a client needs to wait until all other clients are finished before it can start its process.''  With intensive operations and thousands of clients, this can easily crash your server!&lt;br /&gt;
&lt;br /&gt;
The solution is to use ''non-blocking I/O''.  Consider this revised pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Non-Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
database.query(&amp;quot;select * from news&amp;quot;, function(data){&lt;br /&gt;
	print data[0].title;&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The revised pseudo-code achieves the same end result as the first version.  However, ''it allows other clients to perform tasks while this process is waiting for the database to be queried!''  The code occurs in two parts: first, we start the query.  Second, ''when the query is complete'', our '''anonymous callback function''' is executed.  In Node.JS, callback functions are usually passed one or more parameters.&lt;br /&gt;
&lt;br /&gt;
Better yet, with non-blocking I/O, you have no concurrency issues, because everything runs in just one thread.  Nifty!&lt;br /&gt;
&lt;br /&gt;
== Installing Node.JS ==&lt;br /&gt;
&lt;br /&gt;
You can get Node.JS from yum or apt-get, but the versions are going to be out dated.  Remember that Node.JS is a rapidly changing language, so a version of Node from last year is going to be drastically different than a version of Node today.&lt;br /&gt;
&lt;br /&gt;
The unofficial instructions for installing Node.JS can be found here: https://gist.github.com/isaacs/579814&lt;br /&gt;
&lt;br /&gt;
There are several choices, but my favorite is probably ''use-nave-no-shell.sh''.&lt;br /&gt;
&lt;br /&gt;
== Your First Node.JS Application: Hello World ==&lt;br /&gt;
&lt;br /&gt;
Let's try running the example application given on the front page of nodejs.org:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var http = require('http');&lt;br /&gt;
http.createServer(function (req, res) {&lt;br /&gt;
	res.writeHead(200, {&lt;br /&gt;
		'Content-Type': 'text/plain'&lt;br /&gt;
	});&lt;br /&gt;
	res.end('Hello World\n');&lt;br /&gt;
}).listen(1337);&lt;br /&gt;
console.log('Server running at http://localhost:1337/');&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Paste the example into a file named `hello.js`, and then run it by calling `node hello.js`.  You should now be able to see your Hello World by visiting your server at port 1337!  (Press ^C to stop the application.)  '''Note:''' If you're running the code from your EC2 instance, you will need to open port 1337.&lt;br /&gt;
&lt;br /&gt;
Let's walk through each line in the above example.&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;code&amp;gt;var http = require('http');&amp;lt;/code&amp;gt; enables us to use Node's built-in HTTP server.  We've been spoiled that languages like PHP automatically load all of the libraries that we need.  However, '''''most functionality in Node.JS is NOT loaded by default.'''''  When you want to use any non-fundamental feature of Node, you need to ''require'' it into a variable, as this example does with the HTTP package.  You should be familiar with this concept when you needed to use ArrayList and other specialty packages in Java in CSE 132.&lt;br /&gt;
* &amp;lt;code&amp;gt;http.createServer(function (req, res) { ... }).listen(1337);&amp;lt;/code&amp;gt; uses the HTTP server API to listen for HTTP connections on port 1337.  The anonymous callback function will be called whenever a connection is made.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.writeHead(200, { 'Content-Type': 'text/plain' });&amp;lt;/code&amp;gt; specifies the Content-Type header to be &amp;quot;text/plain&amp;quot;.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.end('Hello World\n');&amp;lt;/code&amp;gt; writes &amp;quot;Hello World&amp;quot; to the response.&lt;br /&gt;
&lt;br /&gt;
Note the use of non-blocking I/O, even in this one little example.  ''Whenever a connection is made, the callback function will be called and passed parameters associated with that connection.''&lt;br /&gt;
&lt;br /&gt;
== A Static Fileserver Using Node.JS ==&lt;br /&gt;
&lt;br /&gt;
Node.JS does not automatically serve up static files in the way that an Apache/PHP does.  We need to either use an extension that handles this for us, like Express, or we need to write our own code to make a simple static fileserver.  The latter option is really not all that difficult, and it gives good insight into how a static fileserver works.&lt;br /&gt;
&lt;br /&gt;
=== Installing Packages ===&lt;br /&gt;
&lt;br /&gt;
In order for the example code below to work, you need to install the ''mime'' package.  To do this, '''cd to the working directory where you will save your Node.JS JavaScript file''' and run:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;$ npm install mime&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''npm'' is the package manager for Node.JS.  Unlike all of the package managers we've used up to this point, ''npm'' installs dependencies locally, ''not'' globally.  This means that you can have two different projects using different versions of the same package.  ''npm'' will create a ''node_modules'' directory in the CWD and will install the packages into it.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' When using npm to install local dependencies, '''''do not use sudo'''''.  It will screw up your file permissions.&lt;br /&gt;
&lt;br /&gt;
=== Static Fileserver Code ===&lt;br /&gt;
&lt;br /&gt;
The following code will make an HTTP server on port 3456 that serves up all static files in &amp;lt;STATIC DIRECTORY NAME&amp;gt; relative to app.js.&lt;br /&gt;
&lt;br /&gt;
'''Make an attempt to understand this code.'''  It's important that you are comfortable with the non-blocking nature, as well as how we handle file I/O.  There may be quiz questions about this code.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Require the functionality we need to use:&lt;br /&gt;
var http = require('http'),&lt;br /&gt;
	url = require('url'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	mime = require('mime'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	fs = require('fs');&lt;br /&gt;
&lt;br /&gt;
// Make a simple fileserver for all of our static content.&lt;br /&gt;
// Everything underneath &amp;lt;STATIC DIRECTORY NAME&amp;gt; will be served.&lt;br /&gt;
var app = http.createServer(function(req, resp){&lt;br /&gt;
	var filename = path.join(__dirname, &amp;quot;&amp;lt;STATIC DIRECTORY NAME&amp;gt;&amp;quot;, url.parse(req.url).pathname);&lt;br /&gt;
	(fs.exists || path.exists)(filename, function(exists){&lt;br /&gt;
		if (exists) {&lt;br /&gt;
			fs.readFile(filename, function(err, data){&lt;br /&gt;
				if (err) {&lt;br /&gt;
					// File exists but is not readable (permissions issue?)&lt;br /&gt;
					resp.writeHead(500, {&lt;br /&gt;
						&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
					});&lt;br /&gt;
					resp.write(&amp;quot;Internal server error: could not read file&amp;quot;);&lt;br /&gt;
					resp.end();&lt;br /&gt;
					return;&lt;br /&gt;
				}&lt;br /&gt;
				&lt;br /&gt;
				// File exists and is readable&lt;br /&gt;
				var mimetype = mime.lookup(filename);&lt;br /&gt;
				resp.writeHead(200, {&lt;br /&gt;
					&amp;quot;Content-Type&amp;quot;: mimetype&lt;br /&gt;
				});&lt;br /&gt;
				resp.write(data);&lt;br /&gt;
				resp.end();&lt;br /&gt;
				return;&lt;br /&gt;
			});&lt;br /&gt;
		}else{&lt;br /&gt;
			// File does not exist&lt;br /&gt;
			resp.writeHead(404, {&lt;br /&gt;
				&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
			});&lt;br /&gt;
			resp.write(&amp;quot;Requested file not found: &amp;quot;+filename);&lt;br /&gt;
			resp.end();&lt;br /&gt;
			return;&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
app.listen(3456);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Port 3456 ===&lt;br /&gt;
&lt;br /&gt;
We are running our server on port 3456 as opposed to the default web server port, which of course is 80.  We therefore need to open our Node.JS application like this:&lt;br /&gt;
&lt;br /&gt;
http://ec2-xx-xx-xx-xx.compute-1.amazonaws.com:3456/path.extension&lt;br /&gt;
&lt;br /&gt;
However, this won't work on the first time.  ''Why?'' (Try to figure this out on your own before reading the next paragraph.)&lt;br /&gt;
&lt;br /&gt;
We need to open port 3456 on our Amazon EC2 instance.  Remember when you opened port 80 way back in Module 2?  We need to do the same sort of procedure again now.&lt;br /&gt;
&lt;br /&gt;
# Log into your EC2 management console&lt;br /&gt;
# Go to &amp;quot;Security Groups&amp;quot;&lt;br /&gt;
# Select your security group from Module 2&lt;br /&gt;
# Under &amp;quot;Inbound&amp;quot;, create a custom TCP rule for port 3456, and apply your changes.&lt;br /&gt;
&lt;br /&gt;
== Node.JS Security ==&lt;br /&gt;
&lt;br /&gt;
Just because we're writing in JavaScript doesn't mean that we can forget about the security practices you've been learning in the last three months of CSE 330.  XSS is still a problem, as is the use of ''eval'', CSRF attacks, and so on.&lt;br /&gt;
&lt;br /&gt;
Here is a good slideshow introducing Node.JS as well as some security vulnerabilities to look out for: http://www.slideshare.net/ASF-WS/asfws-2012-nodejs-security-old-vulnerabilities-in-new-dresses-par-sven-vetsch&lt;br /&gt;
&lt;br /&gt;
== Node.JS Conventions ==&lt;br /&gt;
&lt;br /&gt;
There ought to be a standard way to save metadata about your app, right?  Well, ''npm'' introduces a straightforward way to do this in the form of a ''package.json'' file.&lt;br /&gt;
&lt;br /&gt;
To make your ''npm'' file with a step-by-step prompt, run in your project root directory:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm init&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One nifty feature of ''package.json'' is the way it automatically handles dependencies.  For example, you can put the following lines in your ''package.json'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
  &amp;quot;dependencies&amp;quot;: {&lt;br /&gt;
    &amp;quot;mime&amp;quot;: &amp;quot;~1.2.11&amp;quot;,&lt;br /&gt;
    &amp;quot;socket.io&amp;quot;: &amp;quot;~0.9.16&amp;quot;,&lt;br /&gt;
  },&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then, back on the command line, when you run&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm install&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
it automatically installs the dependencies for you!  No more headaches of trying to figure out which modules you need to install; all that information is saved for you in your code base.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 7]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=1796</id>
		<title>Node.JS</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=1796"/>
		<updated>2014-10-03T08:10:13Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* Installing Packages */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;AJAX is a useful technology for web applications that need to pull periodic updates from your server.  But what do you do when you have thousands of clients all requesting data that changes real-time?  A PHP+AJAX approach would choke.  It is situations like these that Node.JS comes to the rescue.&lt;br /&gt;
&lt;br /&gt;
== Non-Blocking I/O ==&lt;br /&gt;
&lt;br /&gt;
You dabbled in the concept of non-blocking I/O when you implemented AJAX in the previous JavaScript module.  Node.JS uses this execution model at its core.&lt;br /&gt;
&lt;br /&gt;
The core idea is the use of '''''anonymous functions''''' as ''callbacks'' for processing the results of intensive operations.  Consider the pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
var data = database.query(&amp;quot;select * from news&amp;quot;);&lt;br /&gt;
print data[0].title;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above pseudo-code queries a database, saves the result of the query in a variable named ''data'', and then prints out the first title in ''data''.  The problem arises when multiple clients all want to access the server at the same time.  ''In a blocking I/O model, a client needs to wait until all other clients are finished before it can start its process.''  With intensive operations and thousands of clients, this can easily crash your server!&lt;br /&gt;
&lt;br /&gt;
The solution is to use ''non-blocking I/O''.  Consider this revised pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Non-Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
database.query(&amp;quot;select * from news&amp;quot;, function(data){&lt;br /&gt;
	print data[0].title;&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The revised pseudo-code achieves the same end result as the first version.  However, ''it allows other clients to perform tasks while this process is waiting for the database to be queried!''  The code occurs in two parts: first, we start the query.  Second, ''when the query is complete'', our '''anonymous callback function''' is executed.  In Node.JS, callback functions are usually passed one or more parameters.&lt;br /&gt;
&lt;br /&gt;
Better yet, with non-blocking I/O, you have no concurrency issues, because everything runs in just one thread.  Nifty!&lt;br /&gt;
&lt;br /&gt;
== Installing Node.JS ==&lt;br /&gt;
&lt;br /&gt;
You can get Node.JS from yum or apt-get, but the versions are going to be out dated.  Remember that Node.JS is a rapidly changing language, so a version of Node from last year is going to be drastically different than a version of Node today.&lt;br /&gt;
&lt;br /&gt;
The unofficial instructions for installing Node.JS can be found here: https://gist.github.com/isaacs/579814&lt;br /&gt;
&lt;br /&gt;
There are several choices, but my favorite is probably ''use-nave-no-shell.sh''.&lt;br /&gt;
&lt;br /&gt;
== Your First Node.JS Application: Hello World ==&lt;br /&gt;
&lt;br /&gt;
Let's try running the example application given on the front page of nodejs.org:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var http = require('http');&lt;br /&gt;
http.createServer(function (req, res) {&lt;br /&gt;
	res.writeHead(200, {&lt;br /&gt;
		'Content-Type': 'text/plain'&lt;br /&gt;
	});&lt;br /&gt;
	res.end('Hello World\n');&lt;br /&gt;
}).listen(1337);&lt;br /&gt;
console.log('Server running at http://localhost:1337/');&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Paste the example into a file named `hello.js`, and then run it by calling `node hello.js`.  You should now be able to see your Hello World by visiting your server at port 1337!  (Press ^C to stop the application.)  '''Note:''' If you're running the code from your EC2 instance, you will need to open port 1337.&lt;br /&gt;
&lt;br /&gt;
Let's walk through each line in the above example.&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;code&amp;gt;var http = require('http');&amp;lt;/code&amp;gt; enables us to use Node's built-in HTTP server.  We've been spoiled that languages like PHP automatically load all of the libraries that we need.  However, '''''most functionality in Node.JS is NOT loaded by default.'''''  When you want to use any non-fundamental feature of Node, you need to ''require'' it into a variable, as this example does with the HTTP package.  You should be familiar with this concept when you needed to use ArrayList and other specialty packages in Java in CSE 132.&lt;br /&gt;
* &amp;lt;code&amp;gt;http.createServer(function (req, res) { ... }).listen(1337);&amp;lt;/code&amp;gt; uses the HTTP server API to listen for HTTP connections on port 1337.  The anonymous callback function will be called whenever a connection is made.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.writeHead(200, { 'Content-Type': 'text/plain' });&amp;lt;/code&amp;gt; specifies the Content-Type header to be &amp;quot;text/plain&amp;quot;.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.end('Hello World\n');&amp;lt;/code&amp;gt; writes &amp;quot;Hello World&amp;quot; to the response.&lt;br /&gt;
&lt;br /&gt;
Note the use of non-blocking I/O, even in this one little example.  ''Whenever a connection is made, the callback function will be called and passed parameters associated with that connection.''&lt;br /&gt;
&lt;br /&gt;
== A Static Fileserver Using Node.JS ==&lt;br /&gt;
&lt;br /&gt;
Node.JS does not automatically serve up static files in the way that an Apache/PHP does.  We need to either use an extension that handles this for us, like Express, or we need to write our own code to make a simple static fileserver.  The latter option is really not all that difficult, and it gives good insight into how a static fileserver works.&lt;br /&gt;
&lt;br /&gt;
=== Installing Packages ===&lt;br /&gt;
&lt;br /&gt;
In order for the example code below to work, you need to install the ''mime'' package.  To do this, '''cd to the working directory where you will save your Node.JS JavaScript file''' and run:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;$ npm install mime&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''npm'' is the package manager for Node.JS.  Unlike all of the package managers we've used up to this point, ''npm'' installs dependencies locally, ''not'' globally.  This means that you can have two different projects using different versions of the same package.  ''npm'' will create a ''node_modules'' directory in the CWD and will install the packages into it.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' When using npm to install local dependencies, '''''please do not use sudo'''''.&lt;br /&gt;
&lt;br /&gt;
=== Static Fileserver Code ===&lt;br /&gt;
&lt;br /&gt;
The following code will make an HTTP server on port 3456 that serves up all static files in &amp;lt;STATIC DIRECTORY NAME&amp;gt; relative to app.js.&lt;br /&gt;
&lt;br /&gt;
'''Make an attempt to understand this code.'''  It's important that you are comfortable with the non-blocking nature, as well as how we handle file I/O.  There may be quiz questions about this code.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Require the functionality we need to use:&lt;br /&gt;
var http = require('http'),&lt;br /&gt;
	url = require('url'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	mime = require('mime'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	fs = require('fs');&lt;br /&gt;
&lt;br /&gt;
// Make a simple fileserver for all of our static content.&lt;br /&gt;
// Everything underneath &amp;lt;STATIC DIRECTORY NAME&amp;gt; will be served.&lt;br /&gt;
var app = http.createServer(function(req, resp){&lt;br /&gt;
	var filename = path.join(__dirname, &amp;quot;&amp;lt;STATIC DIRECTORY NAME&amp;gt;&amp;quot;, url.parse(req.url).pathname);&lt;br /&gt;
	(fs.exists || path.exists)(filename, function(exists){&lt;br /&gt;
		if (exists) {&lt;br /&gt;
			fs.readFile(filename, function(err, data){&lt;br /&gt;
				if (err) {&lt;br /&gt;
					// File exists but is not readable (permissions issue?)&lt;br /&gt;
					resp.writeHead(500, {&lt;br /&gt;
						&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
					});&lt;br /&gt;
					resp.write(&amp;quot;Internal server error: could not read file&amp;quot;);&lt;br /&gt;
					resp.end();&lt;br /&gt;
					return;&lt;br /&gt;
				}&lt;br /&gt;
				&lt;br /&gt;
				// File exists and is readable&lt;br /&gt;
				var mimetype = mime.lookup(filename);&lt;br /&gt;
				resp.writeHead(200, {&lt;br /&gt;
					&amp;quot;Content-Type&amp;quot;: mimetype&lt;br /&gt;
				});&lt;br /&gt;
				resp.write(data);&lt;br /&gt;
				resp.end();&lt;br /&gt;
				return;&lt;br /&gt;
			});&lt;br /&gt;
		}else{&lt;br /&gt;
			// File does not exist&lt;br /&gt;
			resp.writeHead(404, {&lt;br /&gt;
				&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
			});&lt;br /&gt;
			resp.write(&amp;quot;Requested file not found: &amp;quot;+filename);&lt;br /&gt;
			resp.end();&lt;br /&gt;
			return;&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
app.listen(3456);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Port 3456 ===&lt;br /&gt;
&lt;br /&gt;
We are running our server on port 3456 as opposed to the default web server port, which of course is 80.  We therefore need to open our Node.JS application like this:&lt;br /&gt;
&lt;br /&gt;
http://ec2-xx-xx-xx-xx.compute-1.amazonaws.com:3456/path.extension&lt;br /&gt;
&lt;br /&gt;
However, this won't work on the first time.  ''Why?'' (Try to figure this out on your own before reading the next paragraph.)&lt;br /&gt;
&lt;br /&gt;
We need to open port 3456 on our Amazon EC2 instance.  Remember when you opened port 80 way back in Module 2?  We need to do the same sort of procedure again now.&lt;br /&gt;
&lt;br /&gt;
# Log into your EC2 management console&lt;br /&gt;
# Go to &amp;quot;Security Groups&amp;quot;&lt;br /&gt;
# Select your security group from Module 2&lt;br /&gt;
# Under &amp;quot;Inbound&amp;quot;, create a custom TCP rule for port 3456, and apply your changes.&lt;br /&gt;
&lt;br /&gt;
== Node.JS Security ==&lt;br /&gt;
&lt;br /&gt;
Just because we're writing in JavaScript doesn't mean that we can forget about the security practices you've been learning in the last three months of CSE 330.  XSS is still a problem, as is the use of ''eval'', CSRF attacks, and so on.&lt;br /&gt;
&lt;br /&gt;
Here is a good slideshow introducing Node.JS as well as some security vulnerabilities to look out for: http://www.slideshare.net/ASF-WS/asfws-2012-nodejs-security-old-vulnerabilities-in-new-dresses-par-sven-vetsch&lt;br /&gt;
&lt;br /&gt;
== Node.JS Conventions ==&lt;br /&gt;
&lt;br /&gt;
There ought to be a standard way to save metadata about your app, right?  Well, ''npm'' introduces a straightforward way to do this in the form of a ''package.json'' file.&lt;br /&gt;
&lt;br /&gt;
To make your ''npm'' file with a step-by-step prompt, run in your project root directory:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm init&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One nifty feature of ''package.json'' is the way it automatically handles dependencies.  For example, you can put the following lines in your ''package.json'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
  &amp;quot;dependencies&amp;quot;: {&lt;br /&gt;
    &amp;quot;mime&amp;quot;: &amp;quot;~1.2.11&amp;quot;,&lt;br /&gt;
    &amp;quot;socket.io&amp;quot;: &amp;quot;~0.9.16&amp;quot;,&lt;br /&gt;
  },&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then, back on the command line, when you run&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm install&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
it automatically installs the dependencies for you!  No more headaches of trying to figure out which modules you need to install; all that information is saved for you in your code base.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 7]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=1795</id>
		<title>Node.JS</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=1795"/>
		<updated>2014-10-03T08:08:28Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* Installing Node.JS */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;AJAX is a useful technology for web applications that need to pull periodic updates from your server.  But what do you do when you have thousands of clients all requesting data that changes real-time?  A PHP+AJAX approach would choke.  It is situations like these that Node.JS comes to the rescue.&lt;br /&gt;
&lt;br /&gt;
== Non-Blocking I/O ==&lt;br /&gt;
&lt;br /&gt;
You dabbled in the concept of non-blocking I/O when you implemented AJAX in the previous JavaScript module.  Node.JS uses this execution model at its core.&lt;br /&gt;
&lt;br /&gt;
The core idea is the use of '''''anonymous functions''''' as ''callbacks'' for processing the results of intensive operations.  Consider the pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
var data = database.query(&amp;quot;select * from news&amp;quot;);&lt;br /&gt;
print data[0].title;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above pseudo-code queries a database, saves the result of the query in a variable named ''data'', and then prints out the first title in ''data''.  The problem arises when multiple clients all want to access the server at the same time.  ''In a blocking I/O model, a client needs to wait until all other clients are finished before it can start its process.''  With intensive operations and thousands of clients, this can easily crash your server!&lt;br /&gt;
&lt;br /&gt;
The solution is to use ''non-blocking I/O''.  Consider this revised pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Non-Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
database.query(&amp;quot;select * from news&amp;quot;, function(data){&lt;br /&gt;
	print data[0].title;&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The revised pseudo-code achieves the same end result as the first version.  However, ''it allows other clients to perform tasks while this process is waiting for the database to be queried!''  The code occurs in two parts: first, we start the query.  Second, ''when the query is complete'', our '''anonymous callback function''' is executed.  In Node.JS, callback functions are usually passed one or more parameters.&lt;br /&gt;
&lt;br /&gt;
Better yet, with non-blocking I/O, you have no concurrency issues, because everything runs in just one thread.  Nifty!&lt;br /&gt;
&lt;br /&gt;
== Installing Node.JS ==&lt;br /&gt;
&lt;br /&gt;
You can get Node.JS from yum or apt-get, but the versions are going to be out dated.  Remember that Node.JS is a rapidly changing language, so a version of Node from last year is going to be drastically different than a version of Node today.&lt;br /&gt;
&lt;br /&gt;
The unofficial instructions for installing Node.JS can be found here: https://gist.github.com/isaacs/579814&lt;br /&gt;
&lt;br /&gt;
There are several choices, but my favorite is probably ''use-nave-no-shell.sh''.&lt;br /&gt;
&lt;br /&gt;
== Your First Node.JS Application: Hello World ==&lt;br /&gt;
&lt;br /&gt;
Let's try running the example application given on the front page of nodejs.org:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var http = require('http');&lt;br /&gt;
http.createServer(function (req, res) {&lt;br /&gt;
	res.writeHead(200, {&lt;br /&gt;
		'Content-Type': 'text/plain'&lt;br /&gt;
	});&lt;br /&gt;
	res.end('Hello World\n');&lt;br /&gt;
}).listen(1337);&lt;br /&gt;
console.log('Server running at http://localhost:1337/');&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Paste the example into a file named `hello.js`, and then run it by calling `node hello.js`.  You should now be able to see your Hello World by visiting your server at port 1337!  (Press ^C to stop the application.)  '''Note:''' If you're running the code from your EC2 instance, you will need to open port 1337.&lt;br /&gt;
&lt;br /&gt;
Let's walk through each line in the above example.&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;code&amp;gt;var http = require('http');&amp;lt;/code&amp;gt; enables us to use Node's built-in HTTP server.  We've been spoiled that languages like PHP automatically load all of the libraries that we need.  However, '''''most functionality in Node.JS is NOT loaded by default.'''''  When you want to use any non-fundamental feature of Node, you need to ''require'' it into a variable, as this example does with the HTTP package.  You should be familiar with this concept when you needed to use ArrayList and other specialty packages in Java in CSE 132.&lt;br /&gt;
* &amp;lt;code&amp;gt;http.createServer(function (req, res) { ... }).listen(1337);&amp;lt;/code&amp;gt; uses the HTTP server API to listen for HTTP connections on port 1337.  The anonymous callback function will be called whenever a connection is made.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.writeHead(200, { 'Content-Type': 'text/plain' });&amp;lt;/code&amp;gt; specifies the Content-Type header to be &amp;quot;text/plain&amp;quot;.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.end('Hello World\n');&amp;lt;/code&amp;gt; writes &amp;quot;Hello World&amp;quot; to the response.&lt;br /&gt;
&lt;br /&gt;
Note the use of non-blocking I/O, even in this one little example.  ''Whenever a connection is made, the callback function will be called and passed parameters associated with that connection.''&lt;br /&gt;
&lt;br /&gt;
== A Static Fileserver Using Node.JS ==&lt;br /&gt;
&lt;br /&gt;
Node.JS does not automatically serve up static files in the way that an Apache/PHP does.  We need to either use an extension that handles this for us, like Express, or we need to write our own code to make a simple static fileserver.  The latter option is really not all that difficult, and it gives good insight into how a static fileserver works.&lt;br /&gt;
&lt;br /&gt;
=== Installing Packages ===&lt;br /&gt;
&lt;br /&gt;
In order for the example code below to work, you need to install the ''mime'' package.  To do this, '''cd to the working directory where you will save your Node.JS JavaScript file''' and run:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;$ npm install mime&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''npm''' is the package manager for Node.JS.  Unlike all of the package managers we've used up to this point, ''npm'' installs dependencies locally, ''not'' globally.  This means that you can have two different projects using different versions of the same package.  ''npm'' will create a ''node_modules'' directory in the CWD and will install the packages into it.&lt;br /&gt;
&lt;br /&gt;
=== Static Fileserver Code ===&lt;br /&gt;
&lt;br /&gt;
The following code will make an HTTP server on port 3456 that serves up all static files in &amp;lt;STATIC DIRECTORY NAME&amp;gt; relative to app.js.&lt;br /&gt;
&lt;br /&gt;
'''Make an attempt to understand this code.'''  It's important that you are comfortable with the non-blocking nature, as well as how we handle file I/O.  There may be quiz questions about this code.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Require the functionality we need to use:&lt;br /&gt;
var http = require('http'),&lt;br /&gt;
	url = require('url'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	mime = require('mime'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	fs = require('fs');&lt;br /&gt;
&lt;br /&gt;
// Make a simple fileserver for all of our static content.&lt;br /&gt;
// Everything underneath &amp;lt;STATIC DIRECTORY NAME&amp;gt; will be served.&lt;br /&gt;
var app = http.createServer(function(req, resp){&lt;br /&gt;
	var filename = path.join(__dirname, &amp;quot;&amp;lt;STATIC DIRECTORY NAME&amp;gt;&amp;quot;, url.parse(req.url).pathname);&lt;br /&gt;
	(fs.exists || path.exists)(filename, function(exists){&lt;br /&gt;
		if (exists) {&lt;br /&gt;
			fs.readFile(filename, function(err, data){&lt;br /&gt;
				if (err) {&lt;br /&gt;
					// File exists but is not readable (permissions issue?)&lt;br /&gt;
					resp.writeHead(500, {&lt;br /&gt;
						&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
					});&lt;br /&gt;
					resp.write(&amp;quot;Internal server error: could not read file&amp;quot;);&lt;br /&gt;
					resp.end();&lt;br /&gt;
					return;&lt;br /&gt;
				}&lt;br /&gt;
				&lt;br /&gt;
				// File exists and is readable&lt;br /&gt;
				var mimetype = mime.lookup(filename);&lt;br /&gt;
				resp.writeHead(200, {&lt;br /&gt;
					&amp;quot;Content-Type&amp;quot;: mimetype&lt;br /&gt;
				});&lt;br /&gt;
				resp.write(data);&lt;br /&gt;
				resp.end();&lt;br /&gt;
				return;&lt;br /&gt;
			});&lt;br /&gt;
		}else{&lt;br /&gt;
			// File does not exist&lt;br /&gt;
			resp.writeHead(404, {&lt;br /&gt;
				&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
			});&lt;br /&gt;
			resp.write(&amp;quot;Requested file not found: &amp;quot;+filename);&lt;br /&gt;
			resp.end();&lt;br /&gt;
			return;&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
app.listen(3456);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Port 3456 ===&lt;br /&gt;
&lt;br /&gt;
We are running our server on port 3456 as opposed to the default web server port, which of course is 80.  We therefore need to open our Node.JS application like this:&lt;br /&gt;
&lt;br /&gt;
http://ec2-xx-xx-xx-xx.compute-1.amazonaws.com:3456/path.extension&lt;br /&gt;
&lt;br /&gt;
However, this won't work on the first time.  ''Why?'' (Try to figure this out on your own before reading the next paragraph.)&lt;br /&gt;
&lt;br /&gt;
We need to open port 3456 on our Amazon EC2 instance.  Remember when you opened port 80 way back in Module 2?  We need to do the same sort of procedure again now.&lt;br /&gt;
&lt;br /&gt;
# Log into your EC2 management console&lt;br /&gt;
# Go to &amp;quot;Security Groups&amp;quot;&lt;br /&gt;
# Select your security group from Module 2&lt;br /&gt;
# Under &amp;quot;Inbound&amp;quot;, create a custom TCP rule for port 3456, and apply your changes.&lt;br /&gt;
&lt;br /&gt;
== Node.JS Security ==&lt;br /&gt;
&lt;br /&gt;
Just because we're writing in JavaScript doesn't mean that we can forget about the security practices you've been learning in the last three months of CSE 330.  XSS is still a problem, as is the use of ''eval'', CSRF attacks, and so on.&lt;br /&gt;
&lt;br /&gt;
Here is a good slideshow introducing Node.JS as well as some security vulnerabilities to look out for: http://www.slideshare.net/ASF-WS/asfws-2012-nodejs-security-old-vulnerabilities-in-new-dresses-par-sven-vetsch&lt;br /&gt;
&lt;br /&gt;
== Node.JS Conventions ==&lt;br /&gt;
&lt;br /&gt;
There ought to be a standard way to save metadata about your app, right?  Well, ''npm'' introduces a straightforward way to do this in the form of a ''package.json'' file.&lt;br /&gt;
&lt;br /&gt;
To make your ''npm'' file with a step-by-step prompt, run in your project root directory:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm init&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One nifty feature of ''package.json'' is the way it automatically handles dependencies.  For example, you can put the following lines in your ''package.json'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
  &amp;quot;dependencies&amp;quot;: {&lt;br /&gt;
    &amp;quot;mime&amp;quot;: &amp;quot;~1.2.11&amp;quot;,&lt;br /&gt;
    &amp;quot;socket.io&amp;quot;: &amp;quot;~0.9.16&amp;quot;,&lt;br /&gt;
  },&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then, back on the command line, when you run&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm install&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
it automatically installs the dependencies for you!  No more headaches of trying to figure out which modules you need to install; all that information is saved for you in your code base.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 7]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=1794</id>
		<title>Node.JS</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=1794"/>
		<updated>2014-10-03T08:07:53Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* Installing Node.JS */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;AJAX is a useful technology for web applications that need to pull periodic updates from your server.  But what do you do when you have thousands of clients all requesting data that changes real-time?  A PHP+AJAX approach would choke.  It is situations like these that Node.JS comes to the rescue.&lt;br /&gt;
&lt;br /&gt;
== Non-Blocking I/O ==&lt;br /&gt;
&lt;br /&gt;
You dabbled in the concept of non-blocking I/O when you implemented AJAX in the previous JavaScript module.  Node.JS uses this execution model at its core.&lt;br /&gt;
&lt;br /&gt;
The core idea is the use of '''''anonymous functions''''' as ''callbacks'' for processing the results of intensive operations.  Consider the pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
var data = database.query(&amp;quot;select * from news&amp;quot;);&lt;br /&gt;
print data[0].title;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above pseudo-code queries a database, saves the result of the query in a variable named ''data'', and then prints out the first title in ''data''.  The problem arises when multiple clients all want to access the server at the same time.  ''In a blocking I/O model, a client needs to wait until all other clients are finished before it can start its process.''  With intensive operations and thousands of clients, this can easily crash your server!&lt;br /&gt;
&lt;br /&gt;
The solution is to use ''non-blocking I/O''.  Consider this revised pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Non-Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
database.query(&amp;quot;select * from news&amp;quot;, function(data){&lt;br /&gt;
	print data[0].title;&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The revised pseudo-code achieves the same end result as the first version.  However, ''it allows other clients to perform tasks while this process is waiting for the database to be queried!''  The code occurs in two parts: first, we start the query.  Second, ''when the query is complete'', our '''anonymous callback function''' is executed.  In Node.JS, callback functions are usually passed one or more parameters.&lt;br /&gt;
&lt;br /&gt;
Better yet, with non-blocking I/O, you have no concurrency issues, because everything runs in just one thread.  Nifty!&lt;br /&gt;
&lt;br /&gt;
== Installing Node.JS ==&lt;br /&gt;
&lt;br /&gt;
You can get Node.JS from yum or apt-get, but the versions are going to be out dated.  Remember that Node.JS is a rapidly changing language, so a version of Node from last year is going to be drastically different than a version of Node today.&lt;br /&gt;
&lt;br /&gt;
The official instructions for installing Node.JS can be found here: https://gist.github.com/isaacs/579814&lt;br /&gt;
&lt;br /&gt;
There are several choices, but my favorite is probably ''use-nave-no-shell.sh''.&lt;br /&gt;
&lt;br /&gt;
== Your First Node.JS Application: Hello World ==&lt;br /&gt;
&lt;br /&gt;
Let's try running the example application given on the front page of nodejs.org:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var http = require('http');&lt;br /&gt;
http.createServer(function (req, res) {&lt;br /&gt;
	res.writeHead(200, {&lt;br /&gt;
		'Content-Type': 'text/plain'&lt;br /&gt;
	});&lt;br /&gt;
	res.end('Hello World\n');&lt;br /&gt;
}).listen(1337);&lt;br /&gt;
console.log('Server running at http://localhost:1337/');&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Paste the example into a file named `hello.js`, and then run it by calling `node hello.js`.  You should now be able to see your Hello World by visiting your server at port 1337!  (Press ^C to stop the application.)  '''Note:''' If you're running the code from your EC2 instance, you will need to open port 1337.&lt;br /&gt;
&lt;br /&gt;
Let's walk through each line in the above example.&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;code&amp;gt;var http = require('http');&amp;lt;/code&amp;gt; enables us to use Node's built-in HTTP server.  We've been spoiled that languages like PHP automatically load all of the libraries that we need.  However, '''''most functionality in Node.JS is NOT loaded by default.'''''  When you want to use any non-fundamental feature of Node, you need to ''require'' it into a variable, as this example does with the HTTP package.  You should be familiar with this concept when you needed to use ArrayList and other specialty packages in Java in CSE 132.&lt;br /&gt;
* &amp;lt;code&amp;gt;http.createServer(function (req, res) { ... }).listen(1337);&amp;lt;/code&amp;gt; uses the HTTP server API to listen for HTTP connections on port 1337.  The anonymous callback function will be called whenever a connection is made.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.writeHead(200, { 'Content-Type': 'text/plain' });&amp;lt;/code&amp;gt; specifies the Content-Type header to be &amp;quot;text/plain&amp;quot;.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.end('Hello World\n');&amp;lt;/code&amp;gt; writes &amp;quot;Hello World&amp;quot; to the response.&lt;br /&gt;
&lt;br /&gt;
Note the use of non-blocking I/O, even in this one little example.  ''Whenever a connection is made, the callback function will be called and passed parameters associated with that connection.''&lt;br /&gt;
&lt;br /&gt;
== A Static Fileserver Using Node.JS ==&lt;br /&gt;
&lt;br /&gt;
Node.JS does not automatically serve up static files in the way that an Apache/PHP does.  We need to either use an extension that handles this for us, like Express, or we need to write our own code to make a simple static fileserver.  The latter option is really not all that difficult, and it gives good insight into how a static fileserver works.&lt;br /&gt;
&lt;br /&gt;
=== Installing Packages ===&lt;br /&gt;
&lt;br /&gt;
In order for the example code below to work, you need to install the ''mime'' package.  To do this, '''cd to the working directory where you will save your Node.JS JavaScript file''' and run:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;$ npm install mime&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''npm''' is the package manager for Node.JS.  Unlike all of the package managers we've used up to this point, ''npm'' installs dependencies locally, ''not'' globally.  This means that you can have two different projects using different versions of the same package.  ''npm'' will create a ''node_modules'' directory in the CWD and will install the packages into it.&lt;br /&gt;
&lt;br /&gt;
=== Static Fileserver Code ===&lt;br /&gt;
&lt;br /&gt;
The following code will make an HTTP server on port 3456 that serves up all static files in &amp;lt;STATIC DIRECTORY NAME&amp;gt; relative to app.js.&lt;br /&gt;
&lt;br /&gt;
'''Make an attempt to understand this code.'''  It's important that you are comfortable with the non-blocking nature, as well as how we handle file I/O.  There may be quiz questions about this code.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Require the functionality we need to use:&lt;br /&gt;
var http = require('http'),&lt;br /&gt;
	url = require('url'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	mime = require('mime'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	fs = require('fs');&lt;br /&gt;
&lt;br /&gt;
// Make a simple fileserver for all of our static content.&lt;br /&gt;
// Everything underneath &amp;lt;STATIC DIRECTORY NAME&amp;gt; will be served.&lt;br /&gt;
var app = http.createServer(function(req, resp){&lt;br /&gt;
	var filename = path.join(__dirname, &amp;quot;&amp;lt;STATIC DIRECTORY NAME&amp;gt;&amp;quot;, url.parse(req.url).pathname);&lt;br /&gt;
	(fs.exists || path.exists)(filename, function(exists){&lt;br /&gt;
		if (exists) {&lt;br /&gt;
			fs.readFile(filename, function(err, data){&lt;br /&gt;
				if (err) {&lt;br /&gt;
					// File exists but is not readable (permissions issue?)&lt;br /&gt;
					resp.writeHead(500, {&lt;br /&gt;
						&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
					});&lt;br /&gt;
					resp.write(&amp;quot;Internal server error: could not read file&amp;quot;);&lt;br /&gt;
					resp.end();&lt;br /&gt;
					return;&lt;br /&gt;
				}&lt;br /&gt;
				&lt;br /&gt;
				// File exists and is readable&lt;br /&gt;
				var mimetype = mime.lookup(filename);&lt;br /&gt;
				resp.writeHead(200, {&lt;br /&gt;
					&amp;quot;Content-Type&amp;quot;: mimetype&lt;br /&gt;
				});&lt;br /&gt;
				resp.write(data);&lt;br /&gt;
				resp.end();&lt;br /&gt;
				return;&lt;br /&gt;
			});&lt;br /&gt;
		}else{&lt;br /&gt;
			// File does not exist&lt;br /&gt;
			resp.writeHead(404, {&lt;br /&gt;
				&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
			});&lt;br /&gt;
			resp.write(&amp;quot;Requested file not found: &amp;quot;+filename);&lt;br /&gt;
			resp.end();&lt;br /&gt;
			return;&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
app.listen(3456);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Port 3456 ===&lt;br /&gt;
&lt;br /&gt;
We are running our server on port 3456 as opposed to the default web server port, which of course is 80.  We therefore need to open our Node.JS application like this:&lt;br /&gt;
&lt;br /&gt;
http://ec2-xx-xx-xx-xx.compute-1.amazonaws.com:3456/path.extension&lt;br /&gt;
&lt;br /&gt;
However, this won't work on the first time.  ''Why?'' (Try to figure this out on your own before reading the next paragraph.)&lt;br /&gt;
&lt;br /&gt;
We need to open port 3456 on our Amazon EC2 instance.  Remember when you opened port 80 way back in Module 2?  We need to do the same sort of procedure again now.&lt;br /&gt;
&lt;br /&gt;
# Log into your EC2 management console&lt;br /&gt;
# Go to &amp;quot;Security Groups&amp;quot;&lt;br /&gt;
# Select your security group from Module 2&lt;br /&gt;
# Under &amp;quot;Inbound&amp;quot;, create a custom TCP rule for port 3456, and apply your changes.&lt;br /&gt;
&lt;br /&gt;
== Node.JS Security ==&lt;br /&gt;
&lt;br /&gt;
Just because we're writing in JavaScript doesn't mean that we can forget about the security practices you've been learning in the last three months of CSE 330.  XSS is still a problem, as is the use of ''eval'', CSRF attacks, and so on.&lt;br /&gt;
&lt;br /&gt;
Here is a good slideshow introducing Node.JS as well as some security vulnerabilities to look out for: http://www.slideshare.net/ASF-WS/asfws-2012-nodejs-security-old-vulnerabilities-in-new-dresses-par-sven-vetsch&lt;br /&gt;
&lt;br /&gt;
== Node.JS Conventions ==&lt;br /&gt;
&lt;br /&gt;
There ought to be a standard way to save metadata about your app, right?  Well, ''npm'' introduces a straightforward way to do this in the form of a ''package.json'' file.&lt;br /&gt;
&lt;br /&gt;
To make your ''npm'' file with a step-by-step prompt, run in your project root directory:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm init&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One nifty feature of ''package.json'' is the way it automatically handles dependencies.  For example, you can put the following lines in your ''package.json'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
  &amp;quot;dependencies&amp;quot;: {&lt;br /&gt;
    &amp;quot;mime&amp;quot;: &amp;quot;~1.2.11&amp;quot;,&lt;br /&gt;
    &amp;quot;socket.io&amp;quot;: &amp;quot;~0.9.16&amp;quot;,&lt;br /&gt;
  },&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then, back on the command line, when you run&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm install&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
it automatically installs the dependencies for you!  No more headaches of trying to figure out which modules you need to install; all that information is saved for you in your code base.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 7]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=1793</id>
		<title>Node.JS</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=1793"/>
		<updated>2014-10-03T08:07:12Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* Installing Node.JS */ Fixing Node.JS installation process.  The one-liner I posted last year sadly doesn't work anymore.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;AJAX is a useful technology for web applications that need to pull periodic updates from your server.  But what do you do when you have thousands of clients all requesting data that changes real-time?  A PHP+AJAX approach would choke.  It is situations like these that Node.JS comes to the rescue.&lt;br /&gt;
&lt;br /&gt;
== Non-Blocking I/O ==&lt;br /&gt;
&lt;br /&gt;
You dabbled in the concept of non-blocking I/O when you implemented AJAX in the previous JavaScript module.  Node.JS uses this execution model at its core.&lt;br /&gt;
&lt;br /&gt;
The core idea is the use of '''''anonymous functions''''' as ''callbacks'' for processing the results of intensive operations.  Consider the pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
var data = database.query(&amp;quot;select * from news&amp;quot;);&lt;br /&gt;
print data[0].title;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above pseudo-code queries a database, saves the result of the query in a variable named ''data'', and then prints out the first title in ''data''.  The problem arises when multiple clients all want to access the server at the same time.  ''In a blocking I/O model, a client needs to wait until all other clients are finished before it can start its process.''  With intensive operations and thousands of clients, this can easily crash your server!&lt;br /&gt;
&lt;br /&gt;
The solution is to use ''non-blocking I/O''.  Consider this revised pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Non-Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
database.query(&amp;quot;select * from news&amp;quot;, function(data){&lt;br /&gt;
	print data[0].title;&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The revised pseudo-code achieves the same end result as the first version.  However, ''it allows other clients to perform tasks while this process is waiting for the database to be queried!''  The code occurs in two parts: first, we start the query.  Second, ''when the query is complete'', our '''anonymous callback function''' is executed.  In Node.JS, callback functions are usually passed one or more parameters.&lt;br /&gt;
&lt;br /&gt;
Better yet, with non-blocking I/O, you have no concurrency issues, because everything runs in just one thread.  Nifty!&lt;br /&gt;
&lt;br /&gt;
== Installing Node.JS ==&lt;br /&gt;
&lt;br /&gt;
You can get Node.JS from yum or apt-get, but the versions are going to be out dated.  Remember that Node.JS is a rapidly changing language, so a version of Node from last year is going to be drastically different than a version of Node today.&lt;br /&gt;
&lt;br /&gt;
The official instructions for installing Node.JS can be found here: https://gist.github.com/isaacs/579814&lt;br /&gt;
&lt;br /&gt;
There are several choices, but my favorite is probably *use-nave-no-shell.sh*.&lt;br /&gt;
&lt;br /&gt;
== Your First Node.JS Application: Hello World ==&lt;br /&gt;
&lt;br /&gt;
Let's try running the example application given on the front page of nodejs.org:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var http = require('http');&lt;br /&gt;
http.createServer(function (req, res) {&lt;br /&gt;
	res.writeHead(200, {&lt;br /&gt;
		'Content-Type': 'text/plain'&lt;br /&gt;
	});&lt;br /&gt;
	res.end('Hello World\n');&lt;br /&gt;
}).listen(1337);&lt;br /&gt;
console.log('Server running at http://localhost:1337/');&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Paste the example into a file named `hello.js`, and then run it by calling `node hello.js`.  You should now be able to see your Hello World by visiting your server at port 1337!  (Press ^C to stop the application.)  '''Note:''' If you're running the code from your EC2 instance, you will need to open port 1337.&lt;br /&gt;
&lt;br /&gt;
Let's walk through each line in the above example.&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;code&amp;gt;var http = require('http');&amp;lt;/code&amp;gt; enables us to use Node's built-in HTTP server.  We've been spoiled that languages like PHP automatically load all of the libraries that we need.  However, '''''most functionality in Node.JS is NOT loaded by default.'''''  When you want to use any non-fundamental feature of Node, you need to ''require'' it into a variable, as this example does with the HTTP package.  You should be familiar with this concept when you needed to use ArrayList and other specialty packages in Java in CSE 132.&lt;br /&gt;
* &amp;lt;code&amp;gt;http.createServer(function (req, res) { ... }).listen(1337);&amp;lt;/code&amp;gt; uses the HTTP server API to listen for HTTP connections on port 1337.  The anonymous callback function will be called whenever a connection is made.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.writeHead(200, { 'Content-Type': 'text/plain' });&amp;lt;/code&amp;gt; specifies the Content-Type header to be &amp;quot;text/plain&amp;quot;.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.end('Hello World\n');&amp;lt;/code&amp;gt; writes &amp;quot;Hello World&amp;quot; to the response.&lt;br /&gt;
&lt;br /&gt;
Note the use of non-blocking I/O, even in this one little example.  ''Whenever a connection is made, the callback function will be called and passed parameters associated with that connection.''&lt;br /&gt;
&lt;br /&gt;
== A Static Fileserver Using Node.JS ==&lt;br /&gt;
&lt;br /&gt;
Node.JS does not automatically serve up static files in the way that an Apache/PHP does.  We need to either use an extension that handles this for us, like Express, or we need to write our own code to make a simple static fileserver.  The latter option is really not all that difficult, and it gives good insight into how a static fileserver works.&lt;br /&gt;
&lt;br /&gt;
=== Installing Packages ===&lt;br /&gt;
&lt;br /&gt;
In order for the example code below to work, you need to install the ''mime'' package.  To do this, '''cd to the working directory where you will save your Node.JS JavaScript file''' and run:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;$ npm install mime&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''npm''' is the package manager for Node.JS.  Unlike all of the package managers we've used up to this point, ''npm'' installs dependencies locally, ''not'' globally.  This means that you can have two different projects using different versions of the same package.  ''npm'' will create a ''node_modules'' directory in the CWD and will install the packages into it.&lt;br /&gt;
&lt;br /&gt;
=== Static Fileserver Code ===&lt;br /&gt;
&lt;br /&gt;
The following code will make an HTTP server on port 3456 that serves up all static files in &amp;lt;STATIC DIRECTORY NAME&amp;gt; relative to app.js.&lt;br /&gt;
&lt;br /&gt;
'''Make an attempt to understand this code.'''  It's important that you are comfortable with the non-blocking nature, as well as how we handle file I/O.  There may be quiz questions about this code.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Require the functionality we need to use:&lt;br /&gt;
var http = require('http'),&lt;br /&gt;
	url = require('url'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	mime = require('mime'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	fs = require('fs');&lt;br /&gt;
&lt;br /&gt;
// Make a simple fileserver for all of our static content.&lt;br /&gt;
// Everything underneath &amp;lt;STATIC DIRECTORY NAME&amp;gt; will be served.&lt;br /&gt;
var app = http.createServer(function(req, resp){&lt;br /&gt;
	var filename = path.join(__dirname, &amp;quot;&amp;lt;STATIC DIRECTORY NAME&amp;gt;&amp;quot;, url.parse(req.url).pathname);&lt;br /&gt;
	(fs.exists || path.exists)(filename, function(exists){&lt;br /&gt;
		if (exists) {&lt;br /&gt;
			fs.readFile(filename, function(err, data){&lt;br /&gt;
				if (err) {&lt;br /&gt;
					// File exists but is not readable (permissions issue?)&lt;br /&gt;
					resp.writeHead(500, {&lt;br /&gt;
						&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
					});&lt;br /&gt;
					resp.write(&amp;quot;Internal server error: could not read file&amp;quot;);&lt;br /&gt;
					resp.end();&lt;br /&gt;
					return;&lt;br /&gt;
				}&lt;br /&gt;
				&lt;br /&gt;
				// File exists and is readable&lt;br /&gt;
				var mimetype = mime.lookup(filename);&lt;br /&gt;
				resp.writeHead(200, {&lt;br /&gt;
					&amp;quot;Content-Type&amp;quot;: mimetype&lt;br /&gt;
				});&lt;br /&gt;
				resp.write(data);&lt;br /&gt;
				resp.end();&lt;br /&gt;
				return;&lt;br /&gt;
			});&lt;br /&gt;
		}else{&lt;br /&gt;
			// File does not exist&lt;br /&gt;
			resp.writeHead(404, {&lt;br /&gt;
				&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
			});&lt;br /&gt;
			resp.write(&amp;quot;Requested file not found: &amp;quot;+filename);&lt;br /&gt;
			resp.end();&lt;br /&gt;
			return;&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
app.listen(3456);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Port 3456 ===&lt;br /&gt;
&lt;br /&gt;
We are running our server on port 3456 as opposed to the default web server port, which of course is 80.  We therefore need to open our Node.JS application like this:&lt;br /&gt;
&lt;br /&gt;
http://ec2-xx-xx-xx-xx.compute-1.amazonaws.com:3456/path.extension&lt;br /&gt;
&lt;br /&gt;
However, this won't work on the first time.  ''Why?'' (Try to figure this out on your own before reading the next paragraph.)&lt;br /&gt;
&lt;br /&gt;
We need to open port 3456 on our Amazon EC2 instance.  Remember when you opened port 80 way back in Module 2?  We need to do the same sort of procedure again now.&lt;br /&gt;
&lt;br /&gt;
# Log into your EC2 management console&lt;br /&gt;
# Go to &amp;quot;Security Groups&amp;quot;&lt;br /&gt;
# Select your security group from Module 2&lt;br /&gt;
# Under &amp;quot;Inbound&amp;quot;, create a custom TCP rule for port 3456, and apply your changes.&lt;br /&gt;
&lt;br /&gt;
== Node.JS Security ==&lt;br /&gt;
&lt;br /&gt;
Just because we're writing in JavaScript doesn't mean that we can forget about the security practices you've been learning in the last three months of CSE 330.  XSS is still a problem, as is the use of ''eval'', CSRF attacks, and so on.&lt;br /&gt;
&lt;br /&gt;
Here is a good slideshow introducing Node.JS as well as some security vulnerabilities to look out for: http://www.slideshare.net/ASF-WS/asfws-2012-nodejs-security-old-vulnerabilities-in-new-dresses-par-sven-vetsch&lt;br /&gt;
&lt;br /&gt;
== Node.JS Conventions ==&lt;br /&gt;
&lt;br /&gt;
There ought to be a standard way to save metadata about your app, right?  Well, ''npm'' introduces a straightforward way to do this in the form of a ''package.json'' file.&lt;br /&gt;
&lt;br /&gt;
To make your ''npm'' file with a step-by-step prompt, run in your project root directory:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm init&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One nifty feature of ''package.json'' is the way it automatically handles dependencies.  For example, you can put the following lines in your ''package.json'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
  &amp;quot;dependencies&amp;quot;: {&lt;br /&gt;
    &amp;quot;mime&amp;quot;: &amp;quot;~1.2.11&amp;quot;,&lt;br /&gt;
    &amp;quot;socket.io&amp;quot;: &amp;quot;~0.9.16&amp;quot;,&lt;br /&gt;
  },&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then, back on the command line, when you run&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm install&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
it automatically installs the dependencies for you!  No more headaches of trying to figure out which modules you need to install; all that information is saved for you in your code base.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 7]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=1787</id>
		<title>JavaScript</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=1787"/>
		<updated>2014-09-19T02:10:20Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* innerHTML */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;JavaScript is the most widely used scripting language for implementing client-side functionality in Web applications.  Unlike PHP, JavaScript code is interpreted and executed in a client's web browser (not on the web server).&lt;br /&gt;
&lt;br /&gt;
== JavaScript?  Did you mean Java? ==&lt;br /&gt;
&lt;br /&gt;
'''JavaScript''' is a prototype-based programming language focussed on web interactivity.  It was first introduced in Netscape Navigator, and it in turn gave rise to what is now '''[http://www.ecmascript.org/ ECMAScript]'''.  Originally, JavaScript was called &amp;quot;LiveScript&amp;quot;.  Sun, the developer of Java at the time, wanted a language that would complement its compiled Java language, and so LiveScript was renamed JavaScript.&lt;br /&gt;
&lt;br /&gt;
Beyond that, '''Java and JavaScript are as similar as Ham and Hamster.'''&lt;br /&gt;
&lt;br /&gt;
Java and JavaScript have similar syntax, but the under workings are quite different.  For example, Java requires strict typing, but JavaScript allows for dynamic typing.  Java is object-oriented, but JavaScript is prototype-oriented.  Java is compiled, but JavaScript is interpreted.  Java supports event listeners, but JavaScript makes them a fundamental part of the language.  Java variables are scoped to the innermost method or loop, but JavaScript variables are scoped only to the innermost function.&lt;br /&gt;
&lt;br /&gt;
== JavaScript Language Components ==&lt;br /&gt;
&lt;br /&gt;
This section highlights some features of the JavaScript language that differentiate it from other languages.  For a more comprehensive JavaScript tutorial, the following tutorials are both quality:&lt;br /&gt;
&lt;br /&gt;
* [http://docs.webplatform.org/wiki/javascript/tutorials WebPlatform]: Great for learning JavaScript for the first time.  Advocates best practices for modern JavaScript development.&lt;br /&gt;
* [http://www.quirksmode.org/js/contents.html QuirksMode]: More advanced than the WebPlatform tutorial, but it thoroughly covers the most powerful aspects of pure JavaScript and gives unparalleled advice on browser compatibility.&lt;br /&gt;
&lt;br /&gt;
Advice: Do '''NOT''' Google for &amp;quot;JavaScript Tutorial&amp;quot;.  The first few hits advocate bad or outdated practices.  Stick with the ones listed here.&lt;br /&gt;
&lt;br /&gt;
=== Variables and Scope ===&lt;br /&gt;
&lt;br /&gt;
To define a variable in JavaScript, use the '''var''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var foo = &amp;quot;bar&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
All variables are objects.  In the case above, the variable '''foo''' is an object of the class '''String'''.&lt;br /&gt;
&lt;br /&gt;
Notice that like PHP, you do not have to explicitly define a type for a variable like '''int''' or '''String'''; this is because JavaScript and PHP are ''dynamically typed languages''.&lt;br /&gt;
&lt;br /&gt;
JavaScript code can access any variable higher in the “function tree”, but not vice-versa.  This is called '''scope'''.  ''All functions create their own scope.''&lt;br /&gt;
&lt;br /&gt;
When you reference a variable, JavaScript will look up through the &amp;quot;function tree&amp;quot; until it finds the variable you asked for.  This means that you could define variables of the same name as global variables inside of functions.  For demonstration of concept:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var a = &amp;quot;hello&amp;quot;;&lt;br /&gt;
var b = &amp;quot;world&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
function sayGoodByeWorld(){&lt;br /&gt;
	var a = &amp;quot;goodbye&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
	alert(a); // goodbye&lt;br /&gt;
	alert(b); // world&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayGoodByeWorld();&lt;br /&gt;
&lt;br /&gt;
alert(a); // hello&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object Literals ===&lt;br /&gt;
&lt;br /&gt;
A very common way of storing and transporting data in JavaScript is by using objects.  You can define an object with certain properties using an '''object literal''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = {&lt;br /&gt;
	color: &amp;quot;red&amp;quot;,&lt;br /&gt;
	flavor: &amp;quot;sweet&amp;quot;,&lt;br /&gt;
	season: &amp;quot;autumn&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(apple.color);  // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
To define a function in JavaScript, use the '''function''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function sayHello(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(); // call the function&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Pass an argument to a function like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function sayHello(name){&lt;br /&gt;
	alert(&amp;quot;Hello, &amp;quot;+name);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(&amp;quot;Todd&amp;quot;); // call the function and pass an argument&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Functions are Objects ====&lt;br /&gt;
&lt;br /&gt;
In JavaScript, functions are objects.  This means that they can be assigned to variables, manipulated on the fly, and even passed as arguments to other functions!  '''''This is an extremely important feature of JavaScript''''' that makes it such a robust language for web development.&lt;br /&gt;
&lt;br /&gt;
You create a function variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayHello = function(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(); // call the function&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Observe that you can make [[#Variables and Scope|scope-dependent]] functions in this way.&lt;br /&gt;
&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=HaPlj796ngQ&lt;br /&gt;
|time=5m45s&lt;br /&gt;
|desc=JavaScript Closures&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
A '''closure''' is a way to separate a certain snippet of JavaScript code from the global scope.  This is useful if you do not want to &amp;quot;muck up&amp;quot; global variables.  Closures are nothing more than anonymous functions that are called as soon as they are created:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
​var a = &amp;quot;hello&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
(​​​​function(){&lt;br /&gt;
	var b = &amp;quot;world&amp;quot;;&lt;br /&gt;
	&lt;br /&gt;
	alert(a); // hello&lt;br /&gt;
	alert(b); // world&lt;br /&gt;
})();&lt;br /&gt;
&lt;br /&gt;
alert(a); // hello&lt;br /&gt;
alert(b);​ // ReferenceError: b is not defined​​​​​​​​​​​​​​​&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Passing Variables to a Closure&lt;br /&gt;
|desc=This example demonstrates how you can &amp;quot;save&amp;quot; previous versions of a variable using closures.  This is possible because of scoping and the fact that function variables can be returned as objects.&lt;br /&gt;
|fiddle_id=YURqa&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Most JavaScript libraries (like jQuery) write all of their code in a closure.  What this means is that except for one or two variable names (jQuery or $), everything associated with the library is completely self-contained.&lt;br /&gt;
&lt;br /&gt;
=== Prototypal Inheritance ===&lt;br /&gt;
&lt;br /&gt;
JavaScript implements '''prototypal inheritance''', as opposed to a language like Java or C++, which implements '''classical inheritance'''.  JavaScript is one of only a handful of languages implementing prototype-based inheritance.&lt;br /&gt;
&lt;br /&gt;
Here's how it works.  Every callable object (function) has a '''prototype'''.  When instances of that object are created, their properties and methods are copied (inherited) from the prototype.  Additionally, changes made to the prototype later in the program are &amp;quot;copied&amp;quot; to every instance.&lt;br /&gt;
&lt;br /&gt;
For example, if you wanted to make a method on all strings that added a “!”, you could modify String’s prototype:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
String.prototype.bang = function(){&lt;br /&gt;
	return this+&amp;quot;!&amp;quot;; // Notice: the context is the instance itself&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(&amp;quot;Hello&amp;quot;.bang()); // alerts Hello!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To &amp;quot;extend&amp;quot; an object, just copy its prototype to a new object.  However, since classical inheritance and prototypal inheritance are different concepts, copying prototypes may have results that you don't expect.  [http://beej.us/blog/data/javascript-prototypes-inheritance/ This article] seems to have a pretty good explanation with example implementations.&lt;br /&gt;
&lt;br /&gt;
=== Context ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=0a4r4bm1nQA&lt;br /&gt;
|time=4m32s&lt;br /&gt;
|desc=The ''this'' Variable in JavaScript&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Every function is called on a certain object, which is not necessarily the same object in which it was defined.  This is called '''context'''.&lt;br /&gt;
&lt;br /&gt;
To call a function on an arbitrary context, use either '''call''' or '''apply'''.  ''call'' takes a list of arguments, while ''apply'' takes them all in an array.&lt;br /&gt;
&lt;br /&gt;
To access the current context, use the '''this''' keyword.  Demonstration of concept:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayThisColor = function(){&lt;br /&gt;
	alert(this.color);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
var apple = { color: &amp;quot;red&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
sayThisColor();   // undefined&lt;br /&gt;
sayThisColor.call(apple); // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Events ==&lt;br /&gt;
&lt;br /&gt;
Events are really what make JavaScript such a powerful language for web development.&lt;br /&gt;
&lt;br /&gt;
Rather than being thread based, JavaScript is event based.  Since all JavaScript code runs in a single thread, '''there are no concurrency issues'''.  When an event occurs, JavaScript automatically calls the ''event callback'' as soon as all previous events' callbacks have finished executing.&lt;br /&gt;
&lt;br /&gt;
Code in the form of a '''callback function''' is associated with events via a '''listener'''.  For example, the following JavaScript causes ''sayHello()'' (the callback function) to be run whenever the button with ID &amp;quot;hello&amp;quot; is clicked (the event):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayHello = function(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
document.getElementById(&amp;quot;hello&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, sayHello, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Binding Callbacks to a Button Click&lt;br /&gt;
|fiddle_id=L8c4Z&lt;br /&gt;
|cse330=true&lt;br /&gt;
|desc=In this example, notice how we bind the callback function when the ''DOMContentLoaded'' event fires.  This is because JavaScript requires that the button has been parsed by the browser before it can add event listeners to it.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The '''addEventListener''' method takes three parameters:&lt;br /&gt;
* The event type&lt;br /&gt;
* The callback function&lt;br /&gt;
*: The callback function is passed one parameter: the event object.&lt;br /&gt;
* A boolean representing bubble (false) or capture (true) phase&lt;br /&gt;
*: You usually want Bubble phase.  For more information on event phase, see [[#Event Phase]]&lt;br /&gt;
&lt;br /&gt;
Note that versions of Internet Explorer prior to version 9 required that you use a different, albeit similar, function for assigning event listeners called '''attachEvent'''.  attachEvent takes the same arguments as addEventListener, except you need to put '''on''' before the event type (e.g. &amp;quot;onclick&amp;quot;), and the third argument (phase) is not necessary.&lt;br /&gt;
&lt;br /&gt;
It is perfectly valid to use an '''anonymous function''' as your callback function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;hello&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, function(event){&lt;br /&gt;
	alert(&amp;quot;Hello, World!  Event Type: &amp;quot;+event.type);&lt;br /&gt;
}, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QuirksMode has perhaps the best series of articles about the ins and outs of JavaScript events on the internet: http://www.quirksmode.org/js/contents.html#events&lt;br /&gt;
&lt;br /&gt;
=== The Event Object ===&lt;br /&gt;
&lt;br /&gt;
Callback functions are passed one argument: an ''event object''.  You see above that one property of the event object is ''event.type''.  To see the full list of properties of the event object, you could run the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;my_btn&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, function(event){&lt;br /&gt;
	var strout = &amp;quot;&amp;quot;;&lt;br /&gt;
	for(var i in event){&lt;br /&gt;
		strout += i + &amp;quot;: &amp;quot; + event[i] + &amp;quot;\n&amp;quot;;&lt;br /&gt;
	}&lt;br /&gt;
	console.log(strout);&lt;br /&gt;
}, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some of the most useful properties and methods include:&lt;br /&gt;
* '''event.target''' references the object on which the event occurred.&lt;br /&gt;
* '''event.currentTarget''' references the object whose listener is currently being processed.&lt;br /&gt;
*: ''Note:'' event.target and event.currentTarget might be the same or might be different, depending on whether you are listening for bubbled events.&lt;br /&gt;
* '''event.preventDefault()''' stops the normal result of the event from being executed.  For example, if you listen for a form's ''submit'' event, you can call event.preventDefault() to stop the form from being submitted.&lt;br /&gt;
* '''event.stopPropagation()''' prevents any other event listeners from being executed.  For more detail, read the section on Event Phase below.&lt;br /&gt;
&lt;br /&gt;
For more detail on the event object, see [http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html#interface-Event the W3C specification].&lt;br /&gt;
&lt;br /&gt;
'''Note:''' If your callback function does not take any parameters, it will still run; you just won't have as easy of access to the event object.&lt;br /&gt;
&lt;br /&gt;
=== Event Handlers and Memory Management ===&lt;br /&gt;
&lt;br /&gt;
JavaScript is an automatically garbage-collected language, meaning that memory management is mostly taken care of for you.  However, there are some instances when you need to be careful about creating &amp;quot;zombie&amp;quot; objects.  One common &amp;quot;gotcha&amp;quot; instance of this is in event listeners.&lt;br /&gt;
&lt;br /&gt;
For example, consider the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Declare an object&lt;br /&gt;
var myObject = {&lt;br /&gt;
	fn: function(event) {&lt;br /&gt;
		alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
// Make a property of that object listen for some event&lt;br /&gt;
document.getElementById(&amp;quot;my-div&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, myObject.fn, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, myObject will ''not'' be garbage collected, even if it goes out of scope, so long as its property ''fn'' is a listener for an event on the div.  In order to release myObject from memory, you need o do the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// If we want myObject to be garbage collected when it leaves scope, we need to remove the event listener.&lt;br /&gt;
document.getElementById(&amp;quot;my-div&amp;quot;).removeEventListener(&amp;quot;click&amp;quot;, myObject.fn, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Event Phase ===&lt;br /&gt;
&lt;br /&gt;
In JavaScript, events occur in two phases: '''Capture Phase''' and '''Bubble Phase'''.  Consider the following HTML document:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&amp;lt;title&amp;gt;Event Test&amp;lt;/title&amp;gt;&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
  &amp;lt;div id=&amp;quot;box&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;button id=&amp;quot;btn&amp;quot;&amp;gt;&lt;br /&gt;
      Hello&lt;br /&gt;
    &amp;lt;/button&amp;gt;&lt;br /&gt;
  &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Suppose the user clicks on the &amp;quot;Hello&amp;quot; button.  Events will be fired in the following order:&lt;br /&gt;
&lt;br /&gt;
# Capture Phase CLICK on the Document&lt;br /&gt;
# Capture Phase CLICK on the Body&lt;br /&gt;
# Capture Phase CLICK on the Div#box&lt;br /&gt;
# Target Phase CLICK on the Button#btn&lt;br /&gt;
# Bubble Phase CLICK on the Div#box&lt;br /&gt;
# Bubble Phase CLICK on the Body&lt;br /&gt;
# Bubble Phase CLICK on the Document&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Using Capture Phase to Enable or Disable a Toolbar&lt;br /&gt;
|fiddle_id=r32Dz&lt;br /&gt;
|desc=We bind an event in the capture phase to the div with ID ''toolbar''.  When ''e.stopPropagation()'' is called, the event does not reach the buttons in the toolbar.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Graphically, here is the order in which an event occurs in three generic nested elements:&lt;br /&gt;
&lt;br /&gt;
[[File:EventPhase.gif]]&lt;br /&gt;
&lt;br /&gt;
Why is this useful?  Suppose you have a control panel (toolbar, etc) that you want to temporarily deactivate.  (For example, Bold/Italic/Underline buttons on a graphic text editor that currently has no content.)  You could keep bubble phase event listeners on your buttons, but prevent those events from occurring by stopping the event in the capture phase on the parent element before the event reaches your buttons!  Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var disableToolbarFunc = function(e){&lt;br /&gt;
	e.stopPropogation();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// To disable toolbar:&lt;br /&gt;
document.getElementById(&amp;quot;box&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, disableToolbarFunc, true);&lt;br /&gt;
&lt;br /&gt;
// To re-enable toolbar:&lt;br /&gt;
document.getElementById(&amp;quot;box&amp;quot;).removeEventListener(&amp;quot;click&amp;quot;, disableToolbarFunc, true);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Word of caution:''' Like many great things in web development, capture phase does not work in versions of Internet Explorer prior to version 9.  There is no elegant substitution for older versions of Internet Explorer.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' When the event reaches the innermost element, there is no distinction between capture phase and bubble phase.  The order in which event handlers were added to the element determines the order in which those callbacks are evaluated.&lt;br /&gt;
&lt;br /&gt;
== Document Object Model ==&lt;br /&gt;
&lt;br /&gt;
The '''Document Object Model (DOM)'''  is what enables JavaScript to manipulate the content of your web page.&lt;br /&gt;
&lt;br /&gt;
=== Nodes and Traversing the DOM ===&lt;br /&gt;
&lt;br /&gt;
Each element on your page, whether it is a &amp;lt;nowiki&amp;gt;&amp;lt;p&amp;gt;, &amp;lt;img/&amp;gt;&amp;lt;/nowiki&amp;gt;, a string of text, or even an attribute, is called a '''node'''.&lt;br /&gt;
&lt;br /&gt;
Every node, except for the document itself, has exactly one parent.  A single node may have multiple children.&lt;br /&gt;
&lt;br /&gt;
Consider the following HTML code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;ul id=&amp;quot;my-list&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;fruits&amp;quot;&amp;gt;Apples&amp;lt;/li&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;citrus&amp;quot;&amp;gt;Oranges and &amp;lt;strong&amp;gt;Lemons&amp;lt;/strong&amp;gt;&amp;lt;/li&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;berries&amp;quot;&amp;gt;Cherries&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ul&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, the ul with ID &amp;quot;my-list&amp;quot; has three child '''element nodes''' (the three li's) as well as four child '''text nodes''' (the whitespace counts as a text node) and a child '''attribute node'''.  The second LI has one child '''text node''' as well as one child '''element node''' and one child '''attribute node'''.&lt;br /&gt;
&lt;br /&gt;
The DOM can be traversed in JavaScript.  First, let's look at an example.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
e = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;citrus&amp;quot;)[0].lastChild.nodeName;&lt;br /&gt;
alert(e);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Currently Selected Radio Button&lt;br /&gt;
|fiddle_id=SHcng&lt;br /&gt;
|desc=In pure JavaScript, in order to determine the currently selected radio button, it is necessary to iterate over an array of pointers to all possible radio buttons, and stop when you find one that is &amp;quot;checked&amp;quot;.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The above snippet gets the element with class name '''citrus''' that is a child of the element with ID '''my-list''' (the second LI in the example above), and alerts the type of its second child node (which in this case is '''STRONG''').&lt;br /&gt;
&lt;br /&gt;
Some common methods for traversing the DOM include:&lt;br /&gt;
&lt;br /&gt;
* Node.parentNode&lt;br /&gt;
* Node.childNodes - returns an array of nodes&lt;br /&gt;
* Node.firstChild - same as Node.childNodes[0]&lt;br /&gt;
* Node.lastChild - same as Node.childNodes[Node.childNodes.length-1]&lt;br /&gt;
* Node.previousSibling&lt;br /&gt;
* Node.nextSibling&lt;br /&gt;
&lt;br /&gt;
You can also search for child (including all descendants) using one of the following methods:&lt;br /&gt;
&lt;br /&gt;
* Node.getElementsByTagName(&amp;quot;tag-name&amp;quot;) - returns an array of element nodes having the tag name '''tag-name''' that are descendants of Node&lt;br /&gt;
* Node.getElementById(&amp;quot;id&amp;quot;) - returns a single node having the ID '''id''' that is a descendant of Node&lt;br /&gt;
* Node.getElementsByName(&amp;quot;what-name&amp;quot;) - returns an array of element nodes having their '''name''' attribute set to '''what-name'''.  Useful for radio buttons and other form elements.&lt;br /&gt;
* Node.getElementsByClassName(&amp;quot;class&amp;quot;) - returns an array of nodes having the class '''class'''&lt;br /&gt;
*: '''Note:''' As of October 2012, 82% of the browser market supports Node.getElementsByClassName ([http://caniuse.com/getelementsbyclassname more info]).  In order to support the other 18%, you need to either add your own getElementsByClassName to Node's prototype or use a JavaScript library like jQuery or MooTools.&lt;br /&gt;
&lt;br /&gt;
It is common in JavaScript to have long statements like the one in the example above, where you call methods on several objects in sequence.&lt;br /&gt;
&lt;br /&gt;
=== Creating, Moving, and Removing Nodes ===&lt;br /&gt;
&lt;br /&gt;
You will frequently find yourself wanting to modify the DOM.  JavaScript provides methods that help you do this.&lt;br /&gt;
&lt;br /&gt;
Consider the same HTML as above.  If you wanted to add another element to the list, you could use this code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var newLi = document.createElement(&amp;quot;li&amp;quot;);  // creates a node with the tag name li&lt;br /&gt;
newLi.appendChild(document.createTextNode(&amp;quot;Broccoli&amp;quot;));&lt;br /&gt;
newLi.setAttribute(&amp;quot;class&amp;quot;, &amp;quot;veggies&amp;quot;);&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).appendChild(newLi);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to remove the apples from the list, you could do:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;fruits&amp;quot;)[0];&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).removeChild(apple);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to move the apples to the end of the list, you could do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;fruits&amp;quot;)[0];&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).appendChild(apple);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that '''Node.append()''' both removes a node from its previous location ''and'' appends it to its new location, which is always going to be as the last child of the parent node.&lt;br /&gt;
&lt;br /&gt;
In summary, here are the methods to know from this section:&lt;br /&gt;
&lt;br /&gt;
* Node.append(otherNode) - removes otherNode from its current location in the DOM (if applicable) and then adds it as the last child of Node&lt;br /&gt;
* Node.removeChild(otherNode) - removes otherNode, a child of Node, from the DOM&lt;br /&gt;
* document.createElement(&amp;quot;tag-name&amp;quot;) - create a new node with the tag name &amp;quot;tag-name&amp;quot;&lt;br /&gt;
* document.createTextNode(&amp;quot;text&amp;quot;) - create a node containing only the string '''text'''&lt;br /&gt;
* Node.setAttribute(&amp;quot;attribute&amp;quot;, &amp;quot;value&amp;quot;) - sets the attribute node of name &amp;quot;attribute&amp;quot; to &amp;quot;value&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=== DOM Shortcuts ===&lt;br /&gt;
&lt;br /&gt;
In the above sections, we have been creating, reading, modifying, and deleting Nodes.  This is the most &amp;quot;correct&amp;quot; way to change the content of a web page from inside JavaScript.&lt;br /&gt;
&lt;br /&gt;
This section documents a few shortcuts that are not as &amp;quot;pure&amp;quot; as using Nodes but can be less confusing and cumbersome.&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Displaying Information&lt;br /&gt;
|fiddle_id=Q3BPZ&lt;br /&gt;
|desc=This example shows how to use some of the shortcut methods for using JavaScript to display information on the page.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
==== textContent ====&lt;br /&gt;
&lt;br /&gt;
Using textContent to display information is probably the easiest method out there.  For example, the following code overwrites whatever is in the element with ID &amp;quot;holder&amp;quot; with the string &amp;quot;Hello World&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).textContent = &amp;quot;Hello World&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to instead append the text, simply use '''+=''' instead of '''=''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).textContent += &amp;quot; -  Later, he said Hello World  - &amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that textContent displays strings literally; that is, it does not allow for HTML.  Setting the textContent property also removes any HTML that may have already been in that element.&lt;br /&gt;
&lt;br /&gt;
==== innerHTML ====&lt;br /&gt;
&lt;br /&gt;
If you need to use HTML in your output but don't want to use the method described earlier in this section, a straightforward strategy is to use the innerHTML property of an element. For example, the following code would add a paragraph saying &amp;quot;Hello World&amp;quot; to the element with ID &amp;quot;holder&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).innerHTML += &amp;quot;&amp;lt;p&amp;gt;Hello World&amp;lt;/p&amp;gt;&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Important:''' You need to be careful to prevent XSS-type attacks if you display information using innerHTML.  For example, be sure to escape a user-supplied string before appending it to innerHTML.&lt;br /&gt;
&lt;br /&gt;
=== JavaScript Inspectors ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=PKzrmbN-pMg&lt;br /&gt;
|time=4m13s&lt;br /&gt;
|desc=Using Firebug, WebKit Inspector, and IE Developer Tools&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Various browsers and browser plugins give you, the developer, tools to debug your code, inspect the DOM, and much more.  Using these tools is essential for an efficient workflow.&lt;br /&gt;
&lt;br /&gt;
* '''Firebug'''.  Firebug is a plugin for Firefox that is a toolkit full of web developer tools, one of which is a DOM inspector.  To inspect the DOM of a web page, simply open the Firebug window while viewing the web page.&lt;br /&gt;
* '''WebKit Inspector'''.  The WebKit Inspector, which is available in both Chrome and Safari, enables you to see the DOM tree and relationships between elements.  However, its DOM inspection tools are not as robust as those of Firebug.&lt;br /&gt;
* '''Opera Dragonfly'''.  The web browser Opera comes with a web developer toolkit similar to the WebKit Inspector called Dragonfly.  It is important that you test your sites in Opera, because although Opera has only a small fraction of the desktop browser market, it is second only to WebKit on the mobile market.  Opera also has extremely strong CSS support, so it is good for testing for bugs in your CSS.&lt;br /&gt;
&lt;br /&gt;
All of the above-mentioned tools enable you to look at the DOM of your web page and find what properties and methods are associated with each node.  This is helpful because if you have JavaScript that manipulates HTML elements, you cannot tell which properties are associated with which elements by looking at the source code alone.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 6]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=1786</id>
		<title>JavaScript</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=1786"/>
		<updated>2014-09-19T02:06:23Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* Events */ Fixing broken link&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;JavaScript is the most widely used scripting language for implementing client-side functionality in Web applications.  Unlike PHP, JavaScript code is interpreted and executed in a client's web browser (not on the web server).&lt;br /&gt;
&lt;br /&gt;
== JavaScript?  Did you mean Java? ==&lt;br /&gt;
&lt;br /&gt;
'''JavaScript''' is a prototype-based programming language focussed on web interactivity.  It was first introduced in Netscape Navigator, and it in turn gave rise to what is now '''[http://www.ecmascript.org/ ECMAScript]'''.  Originally, JavaScript was called &amp;quot;LiveScript&amp;quot;.  Sun, the developer of Java at the time, wanted a language that would complement its compiled Java language, and so LiveScript was renamed JavaScript.&lt;br /&gt;
&lt;br /&gt;
Beyond that, '''Java and JavaScript are as similar as Ham and Hamster.'''&lt;br /&gt;
&lt;br /&gt;
Java and JavaScript have similar syntax, but the under workings are quite different.  For example, Java requires strict typing, but JavaScript allows for dynamic typing.  Java is object-oriented, but JavaScript is prototype-oriented.  Java is compiled, but JavaScript is interpreted.  Java supports event listeners, but JavaScript makes them a fundamental part of the language.  Java variables are scoped to the innermost method or loop, but JavaScript variables are scoped only to the innermost function.&lt;br /&gt;
&lt;br /&gt;
== JavaScript Language Components ==&lt;br /&gt;
&lt;br /&gt;
This section highlights some features of the JavaScript language that differentiate it from other languages.  For a more comprehensive JavaScript tutorial, the following tutorials are both quality:&lt;br /&gt;
&lt;br /&gt;
* [http://docs.webplatform.org/wiki/javascript/tutorials WebPlatform]: Great for learning JavaScript for the first time.  Advocates best practices for modern JavaScript development.&lt;br /&gt;
* [http://www.quirksmode.org/js/contents.html QuirksMode]: More advanced than the WebPlatform tutorial, but it thoroughly covers the most powerful aspects of pure JavaScript and gives unparalleled advice on browser compatibility.&lt;br /&gt;
&lt;br /&gt;
Advice: Do '''NOT''' Google for &amp;quot;JavaScript Tutorial&amp;quot;.  The first few hits advocate bad or outdated practices.  Stick with the ones listed here.&lt;br /&gt;
&lt;br /&gt;
=== Variables and Scope ===&lt;br /&gt;
&lt;br /&gt;
To define a variable in JavaScript, use the '''var''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var foo = &amp;quot;bar&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
All variables are objects.  In the case above, the variable '''foo''' is an object of the class '''String'''.&lt;br /&gt;
&lt;br /&gt;
Notice that like PHP, you do not have to explicitly define a type for a variable like '''int''' or '''String'''; this is because JavaScript and PHP are ''dynamically typed languages''.&lt;br /&gt;
&lt;br /&gt;
JavaScript code can access any variable higher in the “function tree”, but not vice-versa.  This is called '''scope'''.  ''All functions create their own scope.''&lt;br /&gt;
&lt;br /&gt;
When you reference a variable, JavaScript will look up through the &amp;quot;function tree&amp;quot; until it finds the variable you asked for.  This means that you could define variables of the same name as global variables inside of functions.  For demonstration of concept:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var a = &amp;quot;hello&amp;quot;;&lt;br /&gt;
var b = &amp;quot;world&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
function sayGoodByeWorld(){&lt;br /&gt;
	var a = &amp;quot;goodbye&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
	alert(a); // goodbye&lt;br /&gt;
	alert(b); // world&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayGoodByeWorld();&lt;br /&gt;
&lt;br /&gt;
alert(a); // hello&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object Literals ===&lt;br /&gt;
&lt;br /&gt;
A very common way of storing and transporting data in JavaScript is by using objects.  You can define an object with certain properties using an '''object literal''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = {&lt;br /&gt;
	color: &amp;quot;red&amp;quot;,&lt;br /&gt;
	flavor: &amp;quot;sweet&amp;quot;,&lt;br /&gt;
	season: &amp;quot;autumn&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(apple.color);  // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
To define a function in JavaScript, use the '''function''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function sayHello(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(); // call the function&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Pass an argument to a function like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function sayHello(name){&lt;br /&gt;
	alert(&amp;quot;Hello, &amp;quot;+name);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(&amp;quot;Todd&amp;quot;); // call the function and pass an argument&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Functions are Objects ====&lt;br /&gt;
&lt;br /&gt;
In JavaScript, functions are objects.  This means that they can be assigned to variables, manipulated on the fly, and even passed as arguments to other functions!  '''''This is an extremely important feature of JavaScript''''' that makes it such a robust language for web development.&lt;br /&gt;
&lt;br /&gt;
You create a function variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayHello = function(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(); // call the function&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Observe that you can make [[#Variables and Scope|scope-dependent]] functions in this way.&lt;br /&gt;
&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=HaPlj796ngQ&lt;br /&gt;
|time=5m45s&lt;br /&gt;
|desc=JavaScript Closures&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
A '''closure''' is a way to separate a certain snippet of JavaScript code from the global scope.  This is useful if you do not want to &amp;quot;muck up&amp;quot; global variables.  Closures are nothing more than anonymous functions that are called as soon as they are created:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
​var a = &amp;quot;hello&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
(​​​​function(){&lt;br /&gt;
	var b = &amp;quot;world&amp;quot;;&lt;br /&gt;
	&lt;br /&gt;
	alert(a); // hello&lt;br /&gt;
	alert(b); // world&lt;br /&gt;
})();&lt;br /&gt;
&lt;br /&gt;
alert(a); // hello&lt;br /&gt;
alert(b);​ // ReferenceError: b is not defined​​​​​​​​​​​​​​​&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Passing Variables to a Closure&lt;br /&gt;
|desc=This example demonstrates how you can &amp;quot;save&amp;quot; previous versions of a variable using closures.  This is possible because of scoping and the fact that function variables can be returned as objects.&lt;br /&gt;
|fiddle_id=YURqa&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Most JavaScript libraries (like jQuery) write all of their code in a closure.  What this means is that except for one or two variable names (jQuery or $), everything associated with the library is completely self-contained.&lt;br /&gt;
&lt;br /&gt;
=== Prototypal Inheritance ===&lt;br /&gt;
&lt;br /&gt;
JavaScript implements '''prototypal inheritance''', as opposed to a language like Java or C++, which implements '''classical inheritance'''.  JavaScript is one of only a handful of languages implementing prototype-based inheritance.&lt;br /&gt;
&lt;br /&gt;
Here's how it works.  Every callable object (function) has a '''prototype'''.  When instances of that object are created, their properties and methods are copied (inherited) from the prototype.  Additionally, changes made to the prototype later in the program are &amp;quot;copied&amp;quot; to every instance.&lt;br /&gt;
&lt;br /&gt;
For example, if you wanted to make a method on all strings that added a “!”, you could modify String’s prototype:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
String.prototype.bang = function(){&lt;br /&gt;
	return this+&amp;quot;!&amp;quot;; // Notice: the context is the instance itself&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(&amp;quot;Hello&amp;quot;.bang()); // alerts Hello!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To &amp;quot;extend&amp;quot; an object, just copy its prototype to a new object.  However, since classical inheritance and prototypal inheritance are different concepts, copying prototypes may have results that you don't expect.  [http://beej.us/blog/data/javascript-prototypes-inheritance/ This article] seems to have a pretty good explanation with example implementations.&lt;br /&gt;
&lt;br /&gt;
=== Context ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=0a4r4bm1nQA&lt;br /&gt;
|time=4m32s&lt;br /&gt;
|desc=The ''this'' Variable in JavaScript&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Every function is called on a certain object, which is not necessarily the same object in which it was defined.  This is called '''context'''.&lt;br /&gt;
&lt;br /&gt;
To call a function on an arbitrary context, use either '''call''' or '''apply'''.  ''call'' takes a list of arguments, while ''apply'' takes them all in an array.&lt;br /&gt;
&lt;br /&gt;
To access the current context, use the '''this''' keyword.  Demonstration of concept:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayThisColor = function(){&lt;br /&gt;
	alert(this.color);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
var apple = { color: &amp;quot;red&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
sayThisColor();   // undefined&lt;br /&gt;
sayThisColor.call(apple); // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Events ==&lt;br /&gt;
&lt;br /&gt;
Events are really what make JavaScript such a powerful language for web development.&lt;br /&gt;
&lt;br /&gt;
Rather than being thread based, JavaScript is event based.  Since all JavaScript code runs in a single thread, '''there are no concurrency issues'''.  When an event occurs, JavaScript automatically calls the ''event callback'' as soon as all previous events' callbacks have finished executing.&lt;br /&gt;
&lt;br /&gt;
Code in the form of a '''callback function''' is associated with events via a '''listener'''.  For example, the following JavaScript causes ''sayHello()'' (the callback function) to be run whenever the button with ID &amp;quot;hello&amp;quot; is clicked (the event):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayHello = function(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
document.getElementById(&amp;quot;hello&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, sayHello, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Binding Callbacks to a Button Click&lt;br /&gt;
|fiddle_id=L8c4Z&lt;br /&gt;
|cse330=true&lt;br /&gt;
|desc=In this example, notice how we bind the callback function when the ''DOMContentLoaded'' event fires.  This is because JavaScript requires that the button has been parsed by the browser before it can add event listeners to it.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The '''addEventListener''' method takes three parameters:&lt;br /&gt;
* The event type&lt;br /&gt;
* The callback function&lt;br /&gt;
*: The callback function is passed one parameter: the event object.&lt;br /&gt;
* A boolean representing bubble (false) or capture (true) phase&lt;br /&gt;
*: You usually want Bubble phase.  For more information on event phase, see [[#Event Phase]]&lt;br /&gt;
&lt;br /&gt;
Note that versions of Internet Explorer prior to version 9 required that you use a different, albeit similar, function for assigning event listeners called '''attachEvent'''.  attachEvent takes the same arguments as addEventListener, except you need to put '''on''' before the event type (e.g. &amp;quot;onclick&amp;quot;), and the third argument (phase) is not necessary.&lt;br /&gt;
&lt;br /&gt;
It is perfectly valid to use an '''anonymous function''' as your callback function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;hello&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, function(event){&lt;br /&gt;
	alert(&amp;quot;Hello, World!  Event Type: &amp;quot;+event.type);&lt;br /&gt;
}, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QuirksMode has perhaps the best series of articles about the ins and outs of JavaScript events on the internet: http://www.quirksmode.org/js/contents.html#events&lt;br /&gt;
&lt;br /&gt;
=== The Event Object ===&lt;br /&gt;
&lt;br /&gt;
Callback functions are passed one argument: an ''event object''.  You see above that one property of the event object is ''event.type''.  To see the full list of properties of the event object, you could run the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;my_btn&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, function(event){&lt;br /&gt;
	var strout = &amp;quot;&amp;quot;;&lt;br /&gt;
	for(var i in event){&lt;br /&gt;
		strout += i + &amp;quot;: &amp;quot; + event[i] + &amp;quot;\n&amp;quot;;&lt;br /&gt;
	}&lt;br /&gt;
	console.log(strout);&lt;br /&gt;
}, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some of the most useful properties and methods include:&lt;br /&gt;
* '''event.target''' references the object on which the event occurred.&lt;br /&gt;
* '''event.currentTarget''' references the object whose listener is currently being processed.&lt;br /&gt;
*: ''Note:'' event.target and event.currentTarget might be the same or might be different, depending on whether you are listening for bubbled events.&lt;br /&gt;
* '''event.preventDefault()''' stops the normal result of the event from being executed.  For example, if you listen for a form's ''submit'' event, you can call event.preventDefault() to stop the form from being submitted.&lt;br /&gt;
* '''event.stopPropagation()''' prevents any other event listeners from being executed.  For more detail, read the section on Event Phase below.&lt;br /&gt;
&lt;br /&gt;
For more detail on the event object, see [http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html#interface-Event the W3C specification].&lt;br /&gt;
&lt;br /&gt;
'''Note:''' If your callback function does not take any parameters, it will still run; you just won't have as easy of access to the event object.&lt;br /&gt;
&lt;br /&gt;
=== Event Handlers and Memory Management ===&lt;br /&gt;
&lt;br /&gt;
JavaScript is an automatically garbage-collected language, meaning that memory management is mostly taken care of for you.  However, there are some instances when you need to be careful about creating &amp;quot;zombie&amp;quot; objects.  One common &amp;quot;gotcha&amp;quot; instance of this is in event listeners.&lt;br /&gt;
&lt;br /&gt;
For example, consider the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Declare an object&lt;br /&gt;
var myObject = {&lt;br /&gt;
	fn: function(event) {&lt;br /&gt;
		alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
// Make a property of that object listen for some event&lt;br /&gt;
document.getElementById(&amp;quot;my-div&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, myObject.fn, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, myObject will ''not'' be garbage collected, even if it goes out of scope, so long as its property ''fn'' is a listener for an event on the div.  In order to release myObject from memory, you need o do the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// If we want myObject to be garbage collected when it leaves scope, we need to remove the event listener.&lt;br /&gt;
document.getElementById(&amp;quot;my-div&amp;quot;).removeEventListener(&amp;quot;click&amp;quot;, myObject.fn, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Event Phase ===&lt;br /&gt;
&lt;br /&gt;
In JavaScript, events occur in two phases: '''Capture Phase''' and '''Bubble Phase'''.  Consider the following HTML document:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&amp;lt;title&amp;gt;Event Test&amp;lt;/title&amp;gt;&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
  &amp;lt;div id=&amp;quot;box&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;button id=&amp;quot;btn&amp;quot;&amp;gt;&lt;br /&gt;
      Hello&lt;br /&gt;
    &amp;lt;/button&amp;gt;&lt;br /&gt;
  &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Suppose the user clicks on the &amp;quot;Hello&amp;quot; button.  Events will be fired in the following order:&lt;br /&gt;
&lt;br /&gt;
# Capture Phase CLICK on the Document&lt;br /&gt;
# Capture Phase CLICK on the Body&lt;br /&gt;
# Capture Phase CLICK on the Div#box&lt;br /&gt;
# Target Phase CLICK on the Button#btn&lt;br /&gt;
# Bubble Phase CLICK on the Div#box&lt;br /&gt;
# Bubble Phase CLICK on the Body&lt;br /&gt;
# Bubble Phase CLICK on the Document&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Using Capture Phase to Enable or Disable a Toolbar&lt;br /&gt;
|fiddle_id=r32Dz&lt;br /&gt;
|desc=We bind an event in the capture phase to the div with ID ''toolbar''.  When ''e.stopPropagation()'' is called, the event does not reach the buttons in the toolbar.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Graphically, here is the order in which an event occurs in three generic nested elements:&lt;br /&gt;
&lt;br /&gt;
[[File:EventPhase.gif]]&lt;br /&gt;
&lt;br /&gt;
Why is this useful?  Suppose you have a control panel (toolbar, etc) that you want to temporarily deactivate.  (For example, Bold/Italic/Underline buttons on a graphic text editor that currently has no content.)  You could keep bubble phase event listeners on your buttons, but prevent those events from occurring by stopping the event in the capture phase on the parent element before the event reaches your buttons!  Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var disableToolbarFunc = function(e){&lt;br /&gt;
	e.stopPropogation();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// To disable toolbar:&lt;br /&gt;
document.getElementById(&amp;quot;box&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, disableToolbarFunc, true);&lt;br /&gt;
&lt;br /&gt;
// To re-enable toolbar:&lt;br /&gt;
document.getElementById(&amp;quot;box&amp;quot;).removeEventListener(&amp;quot;click&amp;quot;, disableToolbarFunc, true);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Word of caution:''' Like many great things in web development, capture phase does not work in versions of Internet Explorer prior to version 9.  There is no elegant substitution for older versions of Internet Explorer.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' When the event reaches the innermost element, there is no distinction between capture phase and bubble phase.  The order in which event handlers were added to the element determines the order in which those callbacks are evaluated.&lt;br /&gt;
&lt;br /&gt;
== Document Object Model ==&lt;br /&gt;
&lt;br /&gt;
The '''Document Object Model (DOM)'''  is what enables JavaScript to manipulate the content of your web page.&lt;br /&gt;
&lt;br /&gt;
=== Nodes and Traversing the DOM ===&lt;br /&gt;
&lt;br /&gt;
Each element on your page, whether it is a &amp;lt;nowiki&amp;gt;&amp;lt;p&amp;gt;, &amp;lt;img/&amp;gt;&amp;lt;/nowiki&amp;gt;, a string of text, or even an attribute, is called a '''node'''.&lt;br /&gt;
&lt;br /&gt;
Every node, except for the document itself, has exactly one parent.  A single node may have multiple children.&lt;br /&gt;
&lt;br /&gt;
Consider the following HTML code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;ul id=&amp;quot;my-list&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;fruits&amp;quot;&amp;gt;Apples&amp;lt;/li&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;citrus&amp;quot;&amp;gt;Oranges and &amp;lt;strong&amp;gt;Lemons&amp;lt;/strong&amp;gt;&amp;lt;/li&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;berries&amp;quot;&amp;gt;Cherries&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ul&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, the ul with ID &amp;quot;my-list&amp;quot; has three child '''element nodes''' (the three li's) as well as four child '''text nodes''' (the whitespace counts as a text node) and a child '''attribute node'''.  The second LI has one child '''text node''' as well as one child '''element node''' and one child '''attribute node'''.&lt;br /&gt;
&lt;br /&gt;
The DOM can be traversed in JavaScript.  First, let's look at an example.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
e = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;citrus&amp;quot;)[0].lastChild.nodeName;&lt;br /&gt;
alert(e);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Currently Selected Radio Button&lt;br /&gt;
|fiddle_id=SHcng&lt;br /&gt;
|desc=In pure JavaScript, in order to determine the currently selected radio button, it is necessary to iterate over an array of pointers to all possible radio buttons, and stop when you find one that is &amp;quot;checked&amp;quot;.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The above snippet gets the element with class name '''citrus''' that is a child of the element with ID '''my-list''' (the second LI in the example above), and alerts the type of its second child node (which in this case is '''STRONG''').&lt;br /&gt;
&lt;br /&gt;
Some common methods for traversing the DOM include:&lt;br /&gt;
&lt;br /&gt;
* Node.parentNode&lt;br /&gt;
* Node.childNodes - returns an array of nodes&lt;br /&gt;
* Node.firstChild - same as Node.childNodes[0]&lt;br /&gt;
* Node.lastChild - same as Node.childNodes[Node.childNodes.length-1]&lt;br /&gt;
* Node.previousSibling&lt;br /&gt;
* Node.nextSibling&lt;br /&gt;
&lt;br /&gt;
You can also search for child (including all descendants) using one of the following methods:&lt;br /&gt;
&lt;br /&gt;
* Node.getElementsByTagName(&amp;quot;tag-name&amp;quot;) - returns an array of element nodes having the tag name '''tag-name''' that are descendants of Node&lt;br /&gt;
* Node.getElementById(&amp;quot;id&amp;quot;) - returns a single node having the ID '''id''' that is a descendant of Node&lt;br /&gt;
* Node.getElementsByName(&amp;quot;what-name&amp;quot;) - returns an array of element nodes having their '''name''' attribute set to '''what-name'''.  Useful for radio buttons and other form elements.&lt;br /&gt;
* Node.getElementsByClassName(&amp;quot;class&amp;quot;) - returns an array of nodes having the class '''class'''&lt;br /&gt;
*: '''Note:''' As of October 2012, 82% of the browser market supports Node.getElementsByClassName ([http://caniuse.com/getelementsbyclassname more info]).  In order to support the other 18%, you need to either add your own getElementsByClassName to Node's prototype or use a JavaScript library like jQuery or MooTools.&lt;br /&gt;
&lt;br /&gt;
It is common in JavaScript to have long statements like the one in the example above, where you call methods on several objects in sequence.&lt;br /&gt;
&lt;br /&gt;
=== Creating, Moving, and Removing Nodes ===&lt;br /&gt;
&lt;br /&gt;
You will frequently find yourself wanting to modify the DOM.  JavaScript provides methods that help you do this.&lt;br /&gt;
&lt;br /&gt;
Consider the same HTML as above.  If you wanted to add another element to the list, you could use this code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var newLi = document.createElement(&amp;quot;li&amp;quot;);  // creates a node with the tag name li&lt;br /&gt;
newLi.appendChild(document.createTextNode(&amp;quot;Broccoli&amp;quot;));&lt;br /&gt;
newLi.setAttribute(&amp;quot;class&amp;quot;, &amp;quot;veggies&amp;quot;);&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).appendChild(newLi);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to remove the apples from the list, you could do:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;fruits&amp;quot;)[0];&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).removeChild(apple);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to move the apples to the end of the list, you could do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;fruits&amp;quot;)[0];&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).appendChild(apple);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that '''Node.append()''' both removes a node from its previous location ''and'' appends it to its new location, which is always going to be as the last child of the parent node.&lt;br /&gt;
&lt;br /&gt;
In summary, here are the methods to know from this section:&lt;br /&gt;
&lt;br /&gt;
* Node.append(otherNode) - removes otherNode from its current location in the DOM (if applicable) and then adds it as the last child of Node&lt;br /&gt;
* Node.removeChild(otherNode) - removes otherNode, a child of Node, from the DOM&lt;br /&gt;
* document.createElement(&amp;quot;tag-name&amp;quot;) - create a new node with the tag name &amp;quot;tag-name&amp;quot;&lt;br /&gt;
* document.createTextNode(&amp;quot;text&amp;quot;) - create a node containing only the string '''text'''&lt;br /&gt;
* Node.setAttribute(&amp;quot;attribute&amp;quot;, &amp;quot;value&amp;quot;) - sets the attribute node of name &amp;quot;attribute&amp;quot; to &amp;quot;value&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=== DOM Shortcuts ===&lt;br /&gt;
&lt;br /&gt;
In the above sections, we have been creating, reading, modifying, and deleting Nodes.  This is the most &amp;quot;correct&amp;quot; way to change the content of a web page from inside JavaScript.&lt;br /&gt;
&lt;br /&gt;
This section documents a few shortcuts that are not as &amp;quot;pure&amp;quot; as using Nodes but can be less confusing and cumbersome.&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Displaying Information&lt;br /&gt;
|fiddle_id=Q3BPZ&lt;br /&gt;
|desc=This example shows how to use some of the shortcut methods for using JavaScript to display information on the page.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
==== textContent ====&lt;br /&gt;
&lt;br /&gt;
Using textContent to display information is probably the easiest method out there.  For example, the following code overwrites whatever is in the element with ID &amp;quot;holder&amp;quot; with the string &amp;quot;Hello World&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).textContent = &amp;quot;Hello World&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to instead append the text, simply use '''+=''' instead of '''=''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).textContent += &amp;quot; -  Later, he said Hello World  - &amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that textContent displays strings literally; that is, it does not allow for HTML.  Setting the textContent property also removes any HTML that may have already been in that element.&lt;br /&gt;
&lt;br /&gt;
==== innerHTML ====&lt;br /&gt;
&lt;br /&gt;
If you need to use HTML in your output but don't want to use the method described earlier in this section, a straightforward strategy is to use the innerHTML property of an element. For example, the following code would add a paragraph saying &amp;quot;Hello World&amp;quot; to the element with ID &amp;quot;holder&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).innerHTML += &amp;quot;&amp;lt;p&amp;gt;Hello World&amp;lt;/p&amp;gt;&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Important:''' You need to be careful to prevent XSS-type attacks if you display information using innerHTML.  You should be sure, for example, that your JSON data is sanitized on the server.&lt;br /&gt;
&lt;br /&gt;
=== JavaScript Inspectors ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=PKzrmbN-pMg&lt;br /&gt;
|time=4m13s&lt;br /&gt;
|desc=Using Firebug, WebKit Inspector, and IE Developer Tools&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Various browsers and browser plugins give you, the developer, tools to debug your code, inspect the DOM, and much more.  Using these tools is essential for an efficient workflow.&lt;br /&gt;
&lt;br /&gt;
* '''Firebug'''.  Firebug is a plugin for Firefox that is a toolkit full of web developer tools, one of which is a DOM inspector.  To inspect the DOM of a web page, simply open the Firebug window while viewing the web page.&lt;br /&gt;
* '''WebKit Inspector'''.  The WebKit Inspector, which is available in both Chrome and Safari, enables you to see the DOM tree and relationships between elements.  However, its DOM inspection tools are not as robust as those of Firebug.&lt;br /&gt;
* '''Opera Dragonfly'''.  The web browser Opera comes with a web developer toolkit similar to the WebKit Inspector called Dragonfly.  It is important that you test your sites in Opera, because although Opera has only a small fraction of the desktop browser market, it is second only to WebKit on the mobile market.  Opera also has extremely strong CSS support, so it is good for testing for bugs in your CSS.&lt;br /&gt;
&lt;br /&gt;
All of the above-mentioned tools enable you to look at the DOM of your web page and find what properties and methods are associated with each node.  This is helpful because if you have JavaScript that manipulates HTML elements, you cannot tell which properties are associated with which elements by looking at the source code alone.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 6]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Choosing_a_Platform&amp;diff=1777</id>
		<title>Choosing a Platform</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Choosing_a_Platform&amp;diff=1777"/>
		<updated>2014-09-04T03:51:57Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* Node.JS Cons */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;You've learned a large variety of platforms in this course.  Which one should you use?  This page summarizes some of the pros and cons of each platform.&lt;br /&gt;
&lt;br /&gt;
== PHP ==&lt;br /&gt;
&lt;br /&gt;
[[PHP]] is a language built for server-side web development.  You built a [[Module 2|file sharing application]] and a [[Module 3|news syndication site]] in PHP.&lt;br /&gt;
&lt;br /&gt;
=== PHP Pros ===&lt;br /&gt;
&lt;br /&gt;
* '''Largest support community:''' Easy to find help if you get stuck.&lt;br /&gt;
* '''Distribution:''' Runs on virtually any web server in existence.&lt;br /&gt;
* '''Easy to Debug:''' Because there is no framework involved and the PHP interpreter is robust, it is easier to pinpoint bugs and wrap your head around what is going on behind the scenes.&lt;br /&gt;
&lt;br /&gt;
=== PHP Cons ===&lt;br /&gt;
&lt;br /&gt;
* '''Language:''' Few people will say that PHP is the most elegant language known to mankind.  The language makes it easy to fall into the trap of bad coding practices.&lt;br /&gt;
* '''Security:''' PHP does very little for you automatically in terms of web security.&lt;br /&gt;
&lt;br /&gt;
== Django ==&lt;br /&gt;
&lt;br /&gt;
[[Web Frameworks|Django]] is a web frameworks written in the [[Python]] scripting language.  In more ways than not, it is the Python equivalent of [[wikipedia:Ruby on Rails|Ruby on Rails]].&lt;br /&gt;
&lt;br /&gt;
=== Django Pros ===&lt;br /&gt;
&lt;br /&gt;
* '''Less Code:''' Implementing common web design patterns, like social login or commenting, is usually as easy as a ''pip install''.&lt;br /&gt;
* '''Conventions:''' Django forces you to write neat and organized code, leading to better software engineering practices and scalability down the road.&lt;br /&gt;
* '''Security:''' Django automatically implements common security practices, leading to a more robust web application.&lt;br /&gt;
&lt;br /&gt;
=== Django Cons ===&lt;br /&gt;
&lt;br /&gt;
* '''Difficult to Debug:''' Django's high level of abstraction is a double-edged sword, because bugs and errors are sometimes difficult to find and can take hours to fix.&lt;br /&gt;
* '''Heavyweight:''' Django is designed for larger web applications, and it is not suitable for smaller projects with just one or two controllers.&lt;br /&gt;
&lt;br /&gt;
== Bottle and Flask ==&lt;br /&gt;
&lt;br /&gt;
Bottle is a web ''microframework'' written in the [[Python]] scripting language.  Flask is similar option.  Although you did not explicitly use Bottle or Flask during a module, it's worth listing on this page.  In more ways than not, Bottle and Flask are the Python equivalents of the better-known [[wikipedia:Sinatra (software)|Sinatra]], a Ruby microframework.&lt;br /&gt;
&lt;br /&gt;
=== Bottle and Flask Pros ===&lt;br /&gt;
&lt;br /&gt;
* '''Lightweight:''' There are few enough files that you can find your way around and be in full control of your application logic.&lt;br /&gt;
* '''Access to Python Libraries:''' A lot of the things you do in Django you can do in Bottle and Flask, except that you have more control over the ways that they are implemented.&lt;br /&gt;
&lt;br /&gt;
=== Bottle and Flask Cons ===&lt;br /&gt;
&lt;br /&gt;
* '''Lack of Conventions:''' Bottle and Flask give you the tools you need to build maintainable code, but unlike Django, they don't force you to.  It's easy to end up with Python scripts containing hundreds of lines of unrelated application logic.&lt;br /&gt;
&lt;br /&gt;
== Node.JS and Express ==&lt;br /&gt;
&lt;br /&gt;
[[Node.JS]] is a low-level implementation of JavaScript that enables you to write networked and web applications.  Express is a Sinatra-like microframework that runs on top of Node.jS.&lt;br /&gt;
&lt;br /&gt;
It is also worth bringing your attention to [http://www.meteor.com/ Meteor], a bleeding-edge framework for Node.JS that abstracts away client-server communications.  (Watch the promo video; it's pretty awesome.)&lt;br /&gt;
&lt;br /&gt;
=== Node.JS Pros ===&lt;br /&gt;
&lt;br /&gt;
* '''Speed:''' Node.JS is the fastest of the options on this page.  It is easy to scale up your Node.JS applications.&lt;br /&gt;
* '''Modern:''' Node.JS is also the newest of the options on this page, so most of the plugins you find for it use the best and latest practices.&lt;br /&gt;
* '''Language:''' With Node.JS, you can use just one language for both your server-side and client-side logic.&lt;br /&gt;
* '''Real-Time Options:''' Node.JS enables you to write real-time applications with ease, for example, with Socket.IO.&lt;br /&gt;
&lt;br /&gt;
=== Node.JS Cons ===&lt;br /&gt;
&lt;br /&gt;
* '''Lack of Conventions:''' Like Bottle, Flask, and most other microframeworks, Node.JS and Express don't force you to stick to predefined conventions, giving the potential to build messy code.&lt;br /&gt;
* '''Poor Error Handling:''' PHP and many other options run under tried-and-true Apache, so if your program throws an exception, other concurrent requests will still be processed.  However, a single exception in Node.JS will crash your entire server.  You therefore need to be extra careful in error handling, more so than in PHP, Django, and so on.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 8]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript_Frameworks&amp;diff=1767</id>
		<title>JavaScript Frameworks</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript_Frameworks&amp;diff=1767"/>
		<updated>2014-08-25T08:11:41Z</updated>

		<summary type="html">&lt;p&gt;Shane: Adding &amp;quot;Former Content&amp;quot; category tag&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;There is a large variety of JavaScript frameworks.  In this article, we document how to go about performing common tasks in Prototype, MooTools, Dojo (AMD), jQuery, and ExtJS.&lt;br /&gt;
&lt;br /&gt;
== Task 1: Perform a Task on DOM Content Loaded ==&lt;br /&gt;
&lt;br /&gt;
=== Prototype ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.observe(&amp;quot;dom:loaded&amp;quot;, function() {&lt;br /&gt;
	alert(&amp;quot;DOM Content Loaded!&amp;quot;);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== MooTools ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
window.addEvent('domready', function() {&lt;br /&gt;
	alert(&amp;quot;DOM Content Loaded!&amp;quot;);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Dojo ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
require([&amp;quot;dojo/domReady!&amp;quot;], function() {&lt;br /&gt;
	alert(&amp;quot;DOM Content Loaded!&amp;quot;);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== jQuery ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
$(document).ready(function(){&lt;br /&gt;
	alert(&amp;quot;DOM Content Loaded!&amp;quot;);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== ExtJS ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
Ext.onReady(function(){&lt;br /&gt;
	alert(&amp;quot;DOM Content Loaded!&amp;quot;);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Task 2: Add a Click Listener to a Button and Alert the Button's Label ==&lt;br /&gt;
&lt;br /&gt;
=== Prototype ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
$('myButton').observe('click', function(event) {&lt;br /&gt;
	var element = event.element();&lt;br /&gt;
	var text = element.textContent;&lt;br /&gt;
	alert(&amp;quot;You Clicked My Button: &amp;quot;+text);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== MooTools ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
$('myButton').addEvent('click', function(){&lt;br /&gt;
	var text = this.get('text');&lt;br /&gt;
	alert(&amp;quot;You Clicked My Button: &amp;quot;+text);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Dojo ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
require([&amp;quot;dojo/query&amp;quot;], function(query){&lt;br /&gt;
	query(&amp;quot;#myButton&amp;quot;).on(&amp;quot;click&amp;quot;, function(e){&lt;br /&gt;
		var text = this.textContent;&lt;br /&gt;
		alert(&amp;quot;You Clicked My Button: &amp;quot;+text);&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== jQuery ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
$(&amp;quot;#myButton&amp;quot;).click(function(){&lt;br /&gt;
	var text = $(this).text();&lt;br /&gt;
	alert(&amp;quot;You Clicked My Button: &amp;quot;+text);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== ExtJS ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
Ext.get(&amp;quot;myButton&amp;quot;).on(&amp;quot;click&amp;quot;, function(event, element, options){&lt;br /&gt;
	var text = element.textContent; // option 1: use the DOM&lt;br /&gt;
	var text = this.getHTML(); // option 2: use ExtJS's API&lt;br /&gt;
	var text = Ext.get(element).getHTML(); // option 3: useful when the scope of the callback is not an Ext Element&lt;br /&gt;
	alert(&amp;quot;You Clicked My Button: &amp;quot;+text);&lt;br /&gt;
});&lt;br /&gt;
&lt;br /&gt;
// Alternative syntax that also allows you to pass parameters:&lt;br /&gt;
Ext.get(&amp;quot;myButton&amp;quot;).on({&lt;br /&gt;
    &amp;quot;click&amp;quot;: {&lt;br /&gt;
        fn: function(event, element, options){&lt;br /&gt;
	        var text = element.textContent;&lt;br /&gt;
	        alert(&amp;quot;You Clicked My Button: &amp;quot;+text+&amp;quot; &amp;quot;+options.hello);&lt;br /&gt;
        },&lt;br /&gt;
        hello: &amp;quot;world&amp;quot;&lt;br /&gt;
    }&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Task 3: Create a new list item containing a strong tag, and then append it to the document ==&lt;br /&gt;
&lt;br /&gt;
=== Prototype ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var li = Builder.node('li', {&lt;br /&gt;
	title: &amp;quot;My New List Item&amp;quot;&lt;br /&gt;
}, [&lt;br /&gt;
	Builder.node('strong', &amp;quot;To Do:&amp;quot;),&lt;br /&gt;
	&amp;quot;Water The Garden&amp;quot;&lt;br /&gt;
]);&lt;br /&gt;
$(&amp;quot;myList&amp;quot;).appendChild(li);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== MooTools ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var li = new Element('li', {&lt;br /&gt;
	title: &amp;quot;My New List Item&amp;quot;&lt;br /&gt;
});&lt;br /&gt;
var strong = new Element('strong');&lt;br /&gt;
strong.appendText(&amp;quot;To Do:&amp;quot;);&lt;br /&gt;
li.inject(strong);&lt;br /&gt;
li.appendText(&amp;quot;Water the Garden&amp;quot;);&lt;br /&gt;
$(&amp;quot;myList&amp;quot;).inject(li);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Dojo ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
require([&amp;quot;dojo/dom-construct&amp;quot;], function(domConstruct){&lt;br /&gt;
	var li = domConstruct.create(&amp;quot;li&amp;quot;, {&lt;br /&gt;
		title: &amp;quot;My New List Item&amp;quot;,&lt;br /&gt;
		innerHTML: &amp;quot;&amp;lt;strong&amp;gt;To Do:&amp;lt;/strong&amp;gt; Water the Garden&amp;quot;&lt;br /&gt;
	}, &amp;quot;myList&amp;quot;);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== jQuery ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var li = $(&amp;quot;&amp;lt;li&amp;gt;&amp;lt;strong&amp;gt;To Do:&amp;lt;/strong&amp;gt; Water the Garden&amp;lt;/li&amp;gt;&amp;quot;);&lt;br /&gt;
li.attr(&amp;quot;title&amp;quot;, &amp;quot;My New List Item&amp;quot;);&lt;br /&gt;
$(&amp;quot;#myList&amp;quot;).append(li);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== ExtJS ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
Ext.DomHelper.useDom = true; // optional: forces text node creation on strings rather than innerHTML manipulation&lt;br /&gt;
&lt;br /&gt;
Ext.DomHelper.append(&amp;quot;myList&amp;quot;, {&lt;br /&gt;
	tag: &amp;quot;li&amp;quot;,&lt;br /&gt;
	title: &amp;quot;My New List Item&amp;quot;,&lt;br /&gt;
	children: [&lt;br /&gt;
		{ tag: &amp;quot;strong&amp;quot;, html: &amp;quot;To Do: &amp;quot; },&lt;br /&gt;
		&amp;quot;Water the Garden&amp;quot;&lt;br /&gt;
	]&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
Much of the content on this page was inspired by http://davidwalsh.name/mootools-jquery-dojo&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 6]]&lt;br /&gt;
[[Category:Former Content]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Extensible_Calendar&amp;diff=1766</id>
		<title>Extensible Calendar</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Extensible_Calendar&amp;diff=1766"/>
		<updated>2014-08-25T08:08:51Z</updated>

		<summary type="html">&lt;p&gt;Shane: Adding &amp;quot;Former Content&amp;quot; category tag&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page documents a tutorial for using the [http://ext.ensible.com/products/calendar/ Extensible Calendar Pro API] with Django as the back end.&lt;br /&gt;
&lt;br /&gt;
== REST ==&lt;br /&gt;
&lt;br /&gt;
The Extensible Calendar is going to connect to your server via AJAX calls.  These calls conform to a web application paradigm known as '''REST''', or ''REpresentational State Transfer''.  In particular, the application will automatically send requests with the following HTTP methods:&lt;br /&gt;
&lt;br /&gt;
* '''GET''' when it wants to read something&lt;br /&gt;
* '''POST''' when it wants to create something&lt;br /&gt;
* '''PUT''' when it wants to change something&lt;br /&gt;
* '''DELETE''' when it wants to remove something&lt;br /&gt;
&lt;br /&gt;
You recognize ''GET'' and ''POST'' from Module 2.  All along, there were actually more than just these two request methods.  REST simply takes advantage of all of them.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' In practice, since older browsers do not support the additional HTTP request methods required by REST, the actual implementation of ''PUT'' and ''DELETE'' will most likely be ''POST'' with an additional header defining the request type.  The frameworks takes care of this difference under the hood.&lt;br /&gt;
&lt;br /&gt;
== The Back End ==&lt;br /&gt;
&lt;br /&gt;
First, we will set up the back end.&lt;br /&gt;
&lt;br /&gt;
=== Creating the App with Source Control ===&lt;br /&gt;
&lt;br /&gt;
Start by making a new Django project and app.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ django-admin.py startproject cse330calendar&lt;br /&gt;
$ cd cse330calendar&lt;br /&gt;
$ python manage.py startapp cal&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Right now would be a good time to set up your IDE and source control.  Create a new Komodo project in the &amp;quot;cse330calendar&amp;quot; directory, and set up a repo on the &amp;quot;cse330calendar&amp;quot; in SourceTree.  Make frequent commits after each step of the process.&lt;br /&gt;
&lt;br /&gt;
=== Initial Configuration ===&lt;br /&gt;
&lt;br /&gt;
Go into ''settings.py'' and configure your database.&lt;br /&gt;
&lt;br /&gt;
Enable the admin panel, which requires editing both ''settings.py'' and ''urls.py''.  Add the ''cal'' application to the admin panel by creating ''cal/admin.py'' with the following content:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from django.contrib import admin&lt;br /&gt;
&lt;br /&gt;
# We will create these models in the next step&lt;br /&gt;
from cal.models import Cal, Event&lt;br /&gt;
&lt;br /&gt;
admin.site.register(Cal)&lt;br /&gt;
admin.site.register(Event)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, add &amp;quot;cal&amp;quot; to the INSTALLED_APPS list in ''settings.py''.&lt;br /&gt;
&lt;br /&gt;
=== Creating the Models ===&lt;br /&gt;
&lt;br /&gt;
Set up the models required for the Extensible Calendar.  We have already done this work for you.  Copy the following code into your ''cal/models.py'' file.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from django.db import models&lt;br /&gt;
&lt;br /&gt;
# Extensible wants two models: a &amp;quot;calendar&amp;quot; model and an &amp;quot;event&amp;quot; model.&lt;br /&gt;
# The &amp;quot;calendar&amp;quot; model represents a collection of events.  Note that the end&lt;br /&gt;
# application supports multiple calendars in the same view, with the events&lt;br /&gt;
# in each calendar having a different background color.&lt;br /&gt;
# &lt;br /&gt;
# First we will define our calendar model, `Cal`, and then we will define&lt;br /&gt;
# our event model, `Event`.&lt;br /&gt;
&lt;br /&gt;
class Cal(models.Model):&lt;br /&gt;
	# Title of the calendar&lt;br /&gt;
	title = models.CharField(max_length=50)&lt;br /&gt;
&lt;br /&gt;
	# Text description of the calendar&lt;br /&gt;
	description = models.CharField(max_length=200)&lt;br /&gt;
&lt;br /&gt;
	 # Color ID (1-32)&lt;br /&gt;
	color = models.IntegerField(default=1)&lt;br /&gt;
&lt;br /&gt;
	# Boolean for whether the calendar is hidden by default&lt;br /&gt;
	hidden = models.BooleanField(default=False)&lt;br /&gt;
&lt;br /&gt;
class Event(models.Model):&lt;br /&gt;
	# Declare a one-to-many relationship with Cal&lt;br /&gt;
	cal = models.ForeignKey(Cal)&lt;br /&gt;
&lt;br /&gt;
	# Title of the event&lt;br /&gt;
	title = models.CharField(max_length=50)&lt;br /&gt;
&lt;br /&gt;
	# DateTime of event start&lt;br /&gt;
	start = models.DateTimeField()&lt;br /&gt;
&lt;br /&gt;
	# DateTime of event end&lt;br /&gt;
	end = models.DateTimeField()&lt;br /&gt;
&lt;br /&gt;
	# Additional information that can be associated with an event:&lt;br /&gt;
	loc = models.CharField(max_length=50) # Location&lt;br /&gt;
	notes = models.CharField(max_length=200) # Notes&lt;br /&gt;
	url = models.CharField(max_length=100) # URL&lt;br /&gt;
	ad = models.BooleanField(default=False) # Is this an all-day event&lt;br /&gt;
	rem = models.CharField(max_length=200) # Reminder&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, sync the db.  After you do this, run the Django server and play around with the admin panel to make sure everything is in working order.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python manage.py syncdb&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Tastypie ===&lt;br /&gt;
&lt;br /&gt;
Django does not come with REST support out of the box, so we need to install an additional framework.  I have so far had success with '''[http://django-tastypie.readthedocs.org/en/latest/tutorial.html Tastypie]''', and I will be using Tastypie throughout this tutorial.&lt;br /&gt;
&lt;br /&gt;
Start by installing Tastypie.  There are instructions on the above link.&lt;br /&gt;
&lt;br /&gt;
Your ''cal/api.py'' file can contain simply:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from tastypie.resources import ModelResource&lt;br /&gt;
from tastypie.paginator import Paginator&lt;br /&gt;
from cal.models import Cal, Event&lt;br /&gt;
from tastypie.fields import ToOneField&lt;br /&gt;
&lt;br /&gt;
class CalResource(ModelResource):&lt;br /&gt;
	class Meta:&lt;br /&gt;
		queryset = Cal.objects.all()&lt;br /&gt;
		paginator_class = Paginator&lt;br /&gt;
&lt;br /&gt;
class EventResource(ModelResource):&lt;br /&gt;
	cid = ToOneField(CalResource, &amp;quot;cal&amp;quot;, full=True)&lt;br /&gt;
	class Meta:&lt;br /&gt;
		queryset = Event.objects.all()&lt;br /&gt;
		paginator_class = Paginator&lt;br /&gt;
		always_return_data = True&lt;br /&gt;
	def dehydrate_cid(self, bundle):&lt;br /&gt;
		return bundle.obj.cal.id&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above snippet, we also are installing the ''Paginator'' utility.  The Extensible Calendar requires that your data have pagination.&lt;br /&gt;
&lt;br /&gt;
You will be modifying this file later on in this tutorial.&lt;br /&gt;
&lt;br /&gt;
I also recommend making JSON the default output format for Tastypie.  To do this, add the following line to your ''settings.py'' file:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
TASTYPIE_DEFAULT_FORMATS = ['json']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
While you're inside ''settings.py'', go ahead and add the following line as well.  It may save you headaches down the road.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
APPEND_SLASH=True&lt;br /&gt;
TASTYPIE_ALLOW_MISSING_SLASH=False&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Routing ===&lt;br /&gt;
&lt;br /&gt;
Let's create an empty ''index.html'' for our site.  We will be modifying it later.  Create the file in ''cal/templates/cal/index.html''.  Then add it to ''cal/views.py'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from django.shortcuts import render&lt;br /&gt;
&lt;br /&gt;
def index(request):&lt;br /&gt;
    return render(request, 'cal/index.html', {})&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Also add it to ''cal/urls.py'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from django.conf.urls import patterns, url&lt;br /&gt;
&lt;br /&gt;
from cal import views&lt;br /&gt;
&lt;br /&gt;
urlpatterns = patterns('',&lt;br /&gt;
    url(r'^$', views.index, name='index')&lt;br /&gt;
)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, add ''cal'' to your core ''urls.py'' file, which by now should look something like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from django.conf.urls import patterns, include, url&lt;br /&gt;
from cal.api import CalResource, EventResource&lt;br /&gt;
&lt;br /&gt;
# Uncomment the next two lines to enable the admin:&lt;br /&gt;
from django.contrib import admin&lt;br /&gt;
admin.autodiscover()&lt;br /&gt;
&lt;br /&gt;
# RESTful setup:&lt;br /&gt;
cal_resource = CalResource()&lt;br /&gt;
event_resource = EventResource()&lt;br /&gt;
&lt;br /&gt;
urlpatterns = patterns('',&lt;br /&gt;
    # Admin page&lt;br /&gt;
    url(r'^admin/', include(admin.site.urls)),&lt;br /&gt;
&lt;br /&gt;
    # Templates&lt;br /&gt;
    url(r'^', include('cal.urls')),&lt;br /&gt;
&lt;br /&gt;
    # RESTful URLs&lt;br /&gt;
    url(r'^', include(cal_resource.urls)),&lt;br /&gt;
    url(r'^', include(event_resource.urls)),&lt;br /&gt;
)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Try launching [http://localhost:8000/cal/ http://localhost:8000/cal/] in your browser.  If everything is working properly, you should see a JSON representation of the data in your calendar.&lt;br /&gt;
&lt;br /&gt;
=== Additional Work on the Back End ===&lt;br /&gt;
&lt;br /&gt;
In the above example, we have implemented a read-only API for your calendar.  You will need to use Django Auth to add users and to only reveal those calendars associated with a user.  You will also need to implement the writing site of Tastypie.  Almost all of these steps are in the Tastypie documentation.&lt;br /&gt;
&lt;br /&gt;
== The Front End ==&lt;br /&gt;
&lt;br /&gt;
So far, all of our work has been setting up our database, models, and server API.  Now, we need to set up the front end that takes the JSON data and displays it in a GUI for the end user.&lt;br /&gt;
&lt;br /&gt;
=== Installing Extensible ===&lt;br /&gt;
&lt;br /&gt;
Start by downloading the Extensible library from the official web site.  Save the download in ''cal/static/vendor/extensible''.&lt;br /&gt;
&lt;br /&gt;
=== Extensible Config File ===&lt;br /&gt;
&lt;br /&gt;
Copy the file at ''cal/static/vendor/extensible/Extensible-config.js'' into the ''cal/static/cal'' directory.  Make the following changes:&lt;br /&gt;
&lt;br /&gt;
# Change the Ext JS version on line 59 from '''4.2.0''' to '''4.1.1'''&lt;br /&gt;
# Comment out the line that includes the ''examples.js'' file (around line 179)&lt;br /&gt;
&lt;br /&gt;
=== The Core Extensible Code ===&lt;br /&gt;
&lt;br /&gt;
The examples on the Extensible documentation are helpful, but if you have never used Ext.JS before, it is easy to get lost.  We have therefore written an ''index.html'' file and an ''app.js'' file to get you started.&lt;br /&gt;
&lt;br /&gt;
Put the following code in ''cal/templates/cal/index.html'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
{% load staticfiles %}&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
	&amp;lt;title&amp;gt;Calendar&amp;lt;/title&amp;gt;&lt;br /&gt;
	&amp;lt;script type=&amp;quot;text/javascript&amp;quot; src=&amp;quot;{% static 'cal/Extensible-config.js' %}&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;
	&amp;lt;script type=&amp;quot;text/javascript&amp;quot; src=&amp;quot;{% static 'cal/app.js' %}&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div id=&amp;quot;calbox&amp;quot; style=&amp;quot;width:600px; height:400px;&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;span id=&amp;quot;app-msg&amp;quot; class=&amp;quot;x-hidden&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Put the following code in ''cal/static/cal/app.js'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Demo Extensible Calendar App&lt;br /&gt;
// Created for CSE 330S by Shane Carr&lt;br /&gt;
// Washington University in St. Louis&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
// Ext.JS wants you to use `Ext.define` when making a custom component.&lt;br /&gt;
Ext.define(&amp;quot;CSE330.Calendar&amp;quot;, {&lt;br /&gt;
&lt;br /&gt;
	// List the classes we use inside this component.  This enables Ext.JS to load&lt;br /&gt;
	// the files containing the definitions for these classes more efficiently.&lt;br /&gt;
	requires: [],&lt;br /&gt;
&lt;br /&gt;
	// Main code for our component&lt;br /&gt;
	constructor: function(){&lt;br /&gt;
		// Set up the calendar store&lt;br /&gt;
		this.calendarStore = Ext.create(&amp;quot;Extensible.calendar.data.MemoryCalendarStore&amp;quot;, {&lt;br /&gt;
			autoLoad: true,&lt;br /&gt;
			storeId: &amp;quot;Calendars&amp;quot;,&lt;br /&gt;
			proxy: {&lt;br /&gt;
				type: &amp;quot;rest&amp;quot;,&lt;br /&gt;
				url: &amp;quot;/cal/&amp;quot;,&lt;br /&gt;
				startParam: &amp;quot;offset&amp;quot;,&lt;br /&gt;
				reader: {&lt;br /&gt;
					type: &amp;quot;json&amp;quot;,&lt;br /&gt;
					root: &amp;quot;objects&amp;quot;&lt;br /&gt;
				},&lt;br /&gt;
				writer: {&lt;br /&gt;
					type: &amp;quot;json&amp;quot;,&lt;br /&gt;
					nameProperty: &amp;quot;mapping&amp;quot;&lt;br /&gt;
				}&lt;br /&gt;
			}&lt;br /&gt;
		});&lt;br /&gt;
&lt;br /&gt;
		// Set up the event store&lt;br /&gt;
		this.eventStore = Ext.create(&amp;quot;Extensible.calendar.data.MemoryEventStore&amp;quot;, {&lt;br /&gt;
			autoLoad: true,&lt;br /&gt;
			storeId: &amp;quot;Events&amp;quot;,&lt;br /&gt;
			proxy: {&lt;br /&gt;
				type: &amp;quot;rest&amp;quot;,&lt;br /&gt;
				url: &amp;quot;/event/&amp;quot;,&lt;br /&gt;
				startParam: &amp;quot;offset&amp;quot;,&lt;br /&gt;
				reader: {&lt;br /&gt;
					type: &amp;quot;json&amp;quot;,&lt;br /&gt;
					root: &amp;quot;objects&amp;quot;,&lt;br /&gt;
				},&lt;br /&gt;
				writer: {&lt;br /&gt;
					type: &amp;quot;json&amp;quot;,&lt;br /&gt;
					nameProperty: &amp;quot;mapping&amp;quot;&lt;br /&gt;
				}&lt;br /&gt;
			}&lt;br /&gt;
		});&lt;br /&gt;
&lt;br /&gt;
		// Set up the panel (view)&lt;br /&gt;
		this.container = Ext.create('Extensible.calendar.CalendarPanel', {&lt;br /&gt;
			renderTo: Ext.get(&amp;quot;calbox&amp;quot;),&lt;br /&gt;
			title: &amp;quot;My CSE330 Calendar&amp;quot;,&lt;br /&gt;
			width: &amp;quot;100%&amp;quot;,&lt;br /&gt;
			height: &amp;quot;100%&amp;quot;,&lt;br /&gt;
			id: &amp;quot;ext-calendar-main&amp;quot;,&lt;br /&gt;
			eventStore: this.eventStore,&lt;br /&gt;
			calendarStore: this.calendarStore,&lt;br /&gt;
			monthViewCfg: {&lt;br /&gt;
				showHeader: true // show the days of the week&lt;br /&gt;
			}&lt;br /&gt;
		});&lt;br /&gt;
&lt;br /&gt;
	}&lt;br /&gt;
});&lt;br /&gt;
&lt;br /&gt;
Ext.onReady(function(){&lt;br /&gt;
	Ext.create(&amp;quot;CSE330.Calendar&amp;quot;);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You should be able to load [http://localhost:8000/ http://localhost:8000/] and see an empty calendar with all events you have thusfar put in your database.  Exciting!&lt;br /&gt;
&lt;br /&gt;
=== Additional Work on the Front End ===&lt;br /&gt;
&lt;br /&gt;
Again, right now you have a read-only calendar without any sort of authentication.  You need to tie these two pieces together.&lt;br /&gt;
&lt;br /&gt;
If you look at the web inspector, you can see the requests that Extensible sends to your server when you try to create or modify an event using the front-end GUI.  You need to make sure that your server and Extensible work together, both sending and receiving compatible formats.&lt;br /&gt;
&lt;br /&gt;
You can implement log in and log out over AJAX via the Tastypie API.  There are examples of how to do this in the documentation.&lt;br /&gt;
&lt;br /&gt;
== Help with Debugging ==&lt;br /&gt;
&lt;br /&gt;
Wrapping your head around Extensible, Django-Tastypie, and how to make the two frameworks talk to each other is a daunting task.  The goal of this section is to help you learn how to debug this process.&lt;br /&gt;
&lt;br /&gt;
=== Tutorial for Debugging the Create Event Mechanism ===&lt;br /&gt;
&lt;br /&gt;
Let's first take a look at what happens when you try to add a new event via the Extensible GUI.  When you click somewhere on the calendar, a little dialog opens, and in it you can specify the details of your event.  However, when you press &amp;quot;Save&amp;quot;, you see the following error in the console:&lt;br /&gt;
&lt;br /&gt;
[[File:Extensible-Debugging-Unauthorized.png]]&lt;br /&gt;
&lt;br /&gt;
Whoopsy daisy, we got a '''401 Unauthorized''' from the server!  This means that Django-Tastypie thinks that we don't have enough permissions to edit this resource.  We need to tell Tastypie that we do indeed have such permissions.&lt;br /&gt;
&lt;br /&gt;
Let's temporarily open up the event to be globally editable.  Refer to [http://django-tastypie.readthedocs.org/en/latest/tutorial.html#hooking-up-the-resource-s this section of the Tastypie guide] for an example of how to do this.  Try figuring it out on your own before reading on.&lt;br /&gt;
&lt;br /&gt;
You may have figured out that we need to specify these changes inside the ''cal/api.py'' file.  In particular, if we add the following line to the ''Meta'' of the ''EventResource'' class, we in effect open up the resource to be globally editable.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# Add to the Event meta&lt;br /&gt;
authorization = Authorization()&lt;br /&gt;
&lt;br /&gt;
# don't forget to put an import statement at the top of your file!&lt;br /&gt;
#      from tastypie.authorization import Authorization&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Great!  Now let's try sending our request again.  You'll see that you get a '''400 Bad Request''' error.  That sounds scary!  What's happening?&lt;br /&gt;
&lt;br /&gt;
Let's head on over to the &amp;quot;Network&amp;quot; panel of the web inspector.  Scroll to the bottom of the page to find the latest network request.  Click it, and then choose the &amp;quot;Response&amp;quot; tab.  You'll see something like this:&lt;br /&gt;
&lt;br /&gt;
[[File:Extensible-Debugging-Response-Error.png]]&lt;br /&gt;
&lt;br /&gt;
Hey, look!  There's an error that we can fix.  Let's look at it in more detail.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;&lt;br /&gt;
The 'cid' field was given data that was not a URI, not a dictionary-alike and does not have a 'pk' attribute: 1.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It sounds like Tastypie doesn't like whatever we're sending as the ''cid'' field.  Let's go check on what we're actually sending.  To do this, click on the &amp;quot;Headers&amp;quot; tab in the web inspector, and scroll down to &amp;quot;Request Payload&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
[[File:Extensible-Debugging-Request-Payload.png]]&lt;br /&gt;
&lt;br /&gt;
So we're clearly sending an integer calendar ID in the ''cid'' field.  Why wouldn't Tastypie like this?  I don't know; let's google the error!&lt;br /&gt;
&lt;br /&gt;
Note that when we google something, we need to take specific field names out of our search.  In our case, this is the &amp;quot;cid&amp;quot; field name as well as the value of &amp;quot;1&amp;quot;.  With that in mind, here are the hits:&lt;br /&gt;
&lt;br /&gt;
[[File:Extensible-Debugging-Google-Hits.png]]&lt;br /&gt;
&lt;br /&gt;
Look at that!  We're clearly not the first people to run into this error.&lt;br /&gt;
&lt;br /&gt;
The first Stack Overflow question looks verbose.  Let's try the second one.&lt;br /&gt;
&lt;br /&gt;
Hey, you find something that might provide you a clue!&lt;br /&gt;
&lt;br /&gt;
[[File:Extensible-Debugging-StackOverflow-Answer.png]]&lt;br /&gt;
&lt;br /&gt;
So we need to make our data field resemble one of those two options: either a dictionary with a &amp;quot;pk&amp;quot; field or a resource URL.&lt;br /&gt;
&lt;br /&gt;
But how can we change the data format?  We could do it from the Extensible side, or we could do it from the Tastypie side.  Since we have greater control over Tastypie than Extensible, let's do it on the Tastypie side.&lt;br /&gt;
&lt;br /&gt;
[http://django-tastypie.readthedocs.org/en/latest/resources.html The Resources guide for Tastypie] seems like a reasonable place to start.  Read it and try to find the method that enables you to modify incoming data before Tastypie puts it into the model.&lt;br /&gt;
&lt;br /&gt;
If you pinpointed the ''hydrate_FOO'' method, you were right!  We simply need to define this method to transform the incoming data into the format that Tastypie wants.&lt;br /&gt;
&lt;br /&gt;
Based on the &amp;quot;simple example&amp;quot; under ''hydrate_FOO'', the following definition seems reasonable.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# Part of the EventResource class&lt;br /&gt;
&lt;br /&gt;
	def hydrate_cid(self, bundle):&lt;br /&gt;
		bundle.data[&amp;quot;cid&amp;quot;] = &amp;quot;/cal/%d/&amp;quot; % bundle.data[&amp;quot;cid&amp;quot;]&lt;br /&gt;
		return bundle&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, we are transforming the incoming ''cid'' number to a resource URL.  For example, '''3''' will be transformed into '''/cal/3/''', the format that Tastypie wants according to the Stack Overflow post.&lt;br /&gt;
&lt;br /&gt;
Okay, great!  Let's save and see where we stand.  Try creating an event through the GUI.&lt;br /&gt;
&lt;br /&gt;
Hey, it looks like something happened!  We received a ''201'' request back from the server!  Let's take a peek at our database.  Enter a Django shell and enter the following commands.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# Run these commands inside a Django shell&lt;br /&gt;
from cal.models import Cal, Event&lt;br /&gt;
map(lambda v: &amp;quot;%d %s&amp;quot; % (v.id, v.title), Event.objects.all())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The first line imports your modules into the shell, and the second line queries them via ORM and displays a list of the events with an ID and a title.&lt;br /&gt;
&lt;br /&gt;
What do you see that's interesting?  Hey, the &amp;quot;Banana Event&amp;quot; that I just added has ID 0!  That's not cool.  How do we fix it?&lt;br /&gt;
&lt;br /&gt;
You may remember from the Django tutorial that Django will automatically assign the next available ID if you leave the ''id'' field empty in the new model.  So, let's go ahead and transform all '''0''' IDs in Tastypie to '''None'''.&lt;br /&gt;
&lt;br /&gt;
Try writing the necessary ''hydrate_id'' method.  You should get something like the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# Part of the EventResource class&lt;br /&gt;
&lt;br /&gt;
	def hydrate_id(self, bundle):&lt;br /&gt;
		if bundle.data[&amp;quot;id&amp;quot;] == 0:&lt;br /&gt;
			bundle.data[&amp;quot;id&amp;quot;] = None&lt;br /&gt;
		return bundle&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Save and try again.  What do you know, it works now!  Each new event is now assigned a unique ID.&lt;br /&gt;
&lt;br /&gt;
=== Next Steps ===&lt;br /&gt;
&lt;br /&gt;
So hopefully you now have the knowledge you need to complete the module.  In summary, when you need help, do the following:&lt;br /&gt;
&lt;br /&gt;
# Look at the web inspector console&lt;br /&gt;
# Look at the network activity&lt;br /&gt;
# Look at the server log&lt;br /&gt;
# When you find an error that looks useful, google it (remove application-specific terms)&lt;br /&gt;
# When fixing the problem, refer to documentation&lt;br /&gt;
# When the problem is fixed, commit your code!&lt;br /&gt;
&lt;br /&gt;
If you still need help, ask in class or come to office hours.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 6]]&lt;br /&gt;
[[Category:Former Content]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Ext_JS&amp;diff=1765</id>
		<title>Ext JS</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Ext_JS&amp;diff=1765"/>
		<updated>2014-08-25T08:08:22Z</updated>

		<summary type="html">&lt;p&gt;Shane: Adding &amp;quot;Former Content&amp;quot; category tag&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Ext JS is a ''JavaScript Framework''.  It serves two main functions:&lt;br /&gt;
&lt;br /&gt;
* Simplifies common operations that would take many lines in pure JavaScript&lt;br /&gt;
* Provides a selection of APIs for client-side gadgets&lt;br /&gt;
&lt;br /&gt;
As you read through this article, you might find it helpful to play with some of the examples.  Feel free to open up a new [http://jsfiddle.net/ JSFiddle], and where it says &amp;quot;Choose a Framework&amp;quot;, select a recent version of Ext JS (version 4+).&lt;br /&gt;
&lt;br /&gt;
== Using Ext JS in Your Site ==&lt;br /&gt;
&lt;br /&gt;
For the purposes of this class, you can go ahead and hot-link Ext JS from Sencha's CDN (Content Delivery Network) by putting the following line in your &amp;lt;head&amp;gt; section:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&amp;lt;script src=&amp;quot;//cdn.sencha.io/ext-4.2.0-gpl/ext-all-dev.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
That's it!  You can now use Ext in your web application and follow along with the examples below.&lt;br /&gt;
&lt;br /&gt;
=== A Note about File Size ===&lt;br /&gt;
&lt;br /&gt;
While convenient, the above version of Ext JS from Sencha's CDN is ''huge'', over 5 MB.  There are two main reasons for this:&lt;br /&gt;
&lt;br /&gt;
# The above version is the '''dev''' version, which will give you helpful errors in the WebKit Inspector.&lt;br /&gt;
# The above version comes with a whole bunch of GUI tools that you probably will never be using.&lt;br /&gt;
 &lt;br /&gt;
A functionally equivalent version (minus the dev tools) that is 1 MB in size is also available from Sencha's CDN:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&amp;lt;script src=&amp;quot;//cdn.sencha.io/ext-4.2.0-gpl/ext-all.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, if you don't plan on using the GUI features of Ext JS, you can use this 213 KB version:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&amp;lt;script src=&amp;quot;//cdn.sencha.io/ext-4.2.0-gpl/ext.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== A Note about Licensing ===&lt;br /&gt;
&lt;br /&gt;
Sencha's Ext JS platform, as well as most Ext APIs like [[#Extensible Calendar|Extensible's Calendar Pro]], is dual-licensed: you can use it under ''either'' the free [http://www.gnu.org/licenses/gpl.html GNU GPL] ''or'' a paid commercial license.&lt;br /&gt;
&lt;br /&gt;
For the purposes of this course, you may use both Ext and all of its APIs for free under the terms of the GNU GPL.  Indeed, you may continue using them for free even when you're developing a finished commercial application in real life.  The catch is that it is not legal to use GNU GPL components in a finished product unless that project is also released under the GNU GPL.  At that point, if you don't want to post your source code for others to see and modify, you'll need to pay Sencha for the license.&lt;br /&gt;
&lt;br /&gt;
== Selecting an Element ==&lt;br /&gt;
&lt;br /&gt;
In pure JavaScript, you used functions like ''document.getElementById()'' in order to select elements.  The functions provided by the W3C work fine, but they are often limiting.  Ext Core provides functionality that lets you make more advanced element selections in fewer lines.&lt;br /&gt;
&lt;br /&gt;
=== Select by ID ===&lt;br /&gt;
&lt;br /&gt;
To select an element by its ID and then perform an action on it, use '''Ext.fly(id)''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Add the class &amp;quot;required&amp;quot; to the element with id &amp;quot;myDiv&amp;quot;:&lt;br /&gt;
Ext.fly(&amp;quot;myDiv&amp;quot;).addCls(&amp;quot;required&amp;quot;);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you need to pass the element by reference, use '''Ext.get(id)''' instead:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Add the class &amp;quot;required&amp;quot; to an element passed as an argument:&lt;br /&gt;
function setElementRequired( element ){&lt;br /&gt;
	element.addCls(&amp;quot;required&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// Call the above function, passing the element with id &amp;quot;myDiv&amp;quot; as the argument:&lt;br /&gt;
setElementRequired( Ext.get(&amp;quot;myDiv&amp;quot;) );&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' Ext.fly() is faster than Ext.get().  However, Ext.fly() does not return a useful reference like Ext.get() does.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' element.addCls() adds a CSS class to that element.  Prior to version 4 of Ext JS, it was simply element.addClass().&lt;br /&gt;
&lt;br /&gt;
Calls to most Ext Element methods can be chained:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Add the class &amp;quot;required&amp;quot; to the element with id &amp;quot;myDiv&amp;quot;, then make it slowly fade away,&lt;br /&gt;
// all in one line:&lt;br /&gt;
Ext.fly(&amp;quot;myDiv&amp;quot;).addClass(&amp;quot;required&amp;quot;).ghost();&lt;br /&gt;
&lt;br /&gt;
// The above line is functionally equivalent to:&lt;br /&gt;
Ext.fly(&amp;quot;myDiv&amp;quot;).addClass(&amp;quot;required&amp;quot;);&lt;br /&gt;
Ext.fly(&amp;quot;myDiv&amp;quot;).ghost();&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Ext Core Select&lt;br /&gt;
|fiddle_id=M4LAn&lt;br /&gt;
|desc=This example illustrates one use of '''Ext.select()'''.  Notice how the Ext selector for the &amp;quot;games&amp;quot; list works exactly the same as the selector for the &amp;quot;movies&amp;quot; list.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
=== Select by CSS Selector ===&lt;br /&gt;
&lt;br /&gt;
CSS provides a syntax with which you are already familiar for selecting elements.  Ext enables us to use CSS selectors within JavaScript to select elements via '''Ext.select(selector)'''.  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
Ext.select(&amp;quot;ul.games li:nth-child(2n)&amp;quot;).addClass(&amp;quot;required&amp;quot;);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Document Ready ==&lt;br /&gt;
&lt;br /&gt;
When a browser loads JavaScript from a server, it runs the code as soon as it is treated.  This can cause problems if your JavaScript depends on content later in the document.  Consider the following example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
	&amp;lt;title&amp;gt;JavaScript Execution Order&amp;lt;/title&amp;gt;&lt;br /&gt;
	&amp;lt;script&amp;gt;&lt;br /&gt;
		alert( Ext.fly(&amp;quot;myDiv&amp;quot;).getHTML() );&lt;br /&gt;
	&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
	&amp;lt;div id=&amp;quot;myDiv&amp;quot;&amp;gt;Hello World&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This raises the following exception: &amp;quot;Uncaught TypeError: Cannot read property 'textContent' of null.&amp;quot;  Why?  ''Because the JavaScript is run before the Div is created!''&lt;br /&gt;
&lt;br /&gt;
Ext solves this problem by enabling us to bind JavaScript code to the '''DOMContentLoaded''' event, which fires as soon as the document is loaded.  (This is different from the '''load''' event, which fires when the ''entire web page'' is loaded, including images.)  Simply use '''Ext.onReady''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
	&amp;lt;title&amp;gt;JavaScript Execution Order&amp;lt;/title&amp;gt;&lt;br /&gt;
	&amp;lt;script&amp;gt;&lt;br /&gt;
		Ext.onReady(function(){&lt;br /&gt;
			alert( Ext.fly(&amp;quot;myDiv&amp;quot;).getHTML() );&lt;br /&gt;
		});&lt;br /&gt;
	&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
	&amp;lt;div id=&amp;quot;myDiv&amp;quot;&amp;gt;Hello World&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
While you could do this in pure JavaScript, there are backwards compatibility issues with that approach which Ext handles behind the scenes.&lt;br /&gt;
&lt;br /&gt;
== Utility Methods ==&lt;br /&gt;
&lt;br /&gt;
Ext JS provides a variety of tools that enable you to perform other common tasks more easily.&lt;br /&gt;
&lt;br /&gt;
=== Strings ===&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=String Utility Functions&lt;br /&gt;
|fiddle_id=2APe8&lt;br /&gt;
|desc=Demonstration of some of Ext's string utility functions.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
You can access Ext's String utility functions inside '''Ext.String'''.  See the JSFiddle example for a demonstration.  Some of the useful functions include:&lt;br /&gt;
&lt;br /&gt;
* '''Ext.String.trim(str)''' trims ''str'' of leading whitespace.&lt;br /&gt;
* '''Ext.String.ellipsis(str, len)''' puts a (fake) ellipsis after ''len'' characters in ''str''&lt;br /&gt;
* '''Ext.String.escape(str)''' escapes ' and \ characters from ''str''&lt;br /&gt;
* '''Ext.String.format(format, arg0, arg1, ...)''' is Ext's version of ''sprintf'' (see the example for a demonstration)&lt;br /&gt;
* '''Ext.String.htmlEncode(str)''' encodes HTML special characters to make a string safe for display; similar to PHP's ''htmlentities()'' or ''htmlspecialchars()''&lt;br /&gt;
*: Note: This is aliased as '''Ext.util.Format.htmlEncode(str)'''&lt;br /&gt;
&lt;br /&gt;
A complete list is available [http://localhost/~sffc/libraries/ext-4.1.1a/docs/index.html#!/api/Ext.String in the Ext JS documentation].&lt;br /&gt;
&lt;br /&gt;
=== Creating DOM Elements ===&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Creating Elements&lt;br /&gt;
|fiddle_id=Dgn5r&lt;br /&gt;
|desc=Demonstration of how Ext can create elements for the DOM.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Ext JS makes it easy to create new DOM elements on the fly.  The following code creates a new list item inside the unordered list with ID &amp;quot;myList&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
Ext.DomHelper.useDom = true; // See next section for an explanation of this line&lt;br /&gt;
&lt;br /&gt;
Ext.fly(&amp;quot;myList&amp;quot;).createChild({&lt;br /&gt;
	tag: &amp;quot;li&amp;quot;,&lt;br /&gt;
	children: [&lt;br /&gt;
		{&lt;br /&gt;
			tag: &amp;quot;strong&amp;quot;,&lt;br /&gt;
			children: [&lt;br /&gt;
				&amp;quot;To Do: &amp;quot;&lt;br /&gt;
			]&lt;br /&gt;
		},&lt;br /&gt;
		&amp;quot;Water the garden&amp;quot;&lt;br /&gt;
	]&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The HTML generated by the above example would be:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt;&amp;lt;strong&amp;gt;To Do: &amp;lt;/strong&amp;gt;Water the Garden&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
See the JSFiddle example for a demonstration.&lt;br /&gt;
&lt;br /&gt;
==== Preventing HTML Injection ====&lt;br /&gt;
&lt;br /&gt;
If you pass a string where Ext JS expects a child element, Ext will treat the string as an HTML string by default.  This may open your application to XSS vulnerabilities if you are not careful.  It is therefore recommended that you force Ext to create text nodes (thereby displaying strings literally) by putting this line at the top of your JavaScript file:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
Ext.DomHelper.useDom = true;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Event Binding ===&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Event Binding&lt;br /&gt;
|fiddle_id=JRRNC&lt;br /&gt;
|desc=How to use Ext to bind events.  Gives examples of the `scope` and `options` parameters.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Event binding is relatively straightforward using Ext:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
Ext.fly(&amp;quot;myButton&amp;quot;).on(&amp;quot;click&amp;quot;, function(){&lt;br /&gt;
	alert(&amp;quot;You clicked my button&amp;quot;);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The ''Ext.Element.on()'' method takes four parameters: the event type, the callback function, the scope of the callback function, and an options object.  The callback function is passed three parameters: the event object, the target element, and the options object.  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var myObject = {&lt;br /&gt;
	say: function(message){&lt;br /&gt;
		alert(message);&lt;br /&gt;
	}&lt;br /&gt;
};&lt;br /&gt;
Ext.fly(&amp;quot;myButton&amp;quot;).on(&amp;quot;click&amp;quot;, function(event, element, options){&lt;br /&gt;
	this.say(options.message);&lt;br /&gt;
}), myObject, {&lt;br /&gt;
	message: &amp;quot;Hello World&amp;quot;&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Other Helpful Utilities ===&lt;br /&gt;
&lt;br /&gt;
* '''Ext.Number.constrain(num, min, max)''' returns ''num'' iff it is between ''min'' and ''max'', or otherwise ''min'' if the number was smaller or ''max'' if the number was bigger&lt;br /&gt;
* '''Ext.Number.randomInt(min, max)''' returns a random integer between ''min'' and ''max'' inclusive.&lt;br /&gt;
* '''Ext.Object.getKeys(obj)''' returns all keys from the object literal ''obj''&lt;br /&gt;
* '''Ext.Object.each(obj, fn)''' iterates through the object literal ''obj'', calling ''fn(key, value)'' on each key/value pair.&lt;br /&gt;
* '''Ext.each(arr, fn)''' iterates through the array ''arr'', calling ''fn(value, index)'' on each item in the array.&lt;br /&gt;
* '''Ext.Array.map(arr, fn)''' returns an array containing the return value of ''fn(value, index)'' on each item in ''arr''.&lt;br /&gt;
* '''Ext.Array.min(arr)''' and '''.max(arr)''' and '''.mean(arr)''' return the maximum value, minimum value, and average value of ''arr'', respectively.&lt;br /&gt;
* '''Ext.toArray(non_arr)''' converts the iterable ''non_arr'' into a true Array.  Especially useful for dealing with the ''arguments'' non-array: &amp;lt;code&amp;gt;alert( Ext.Array.toArray(arguments).join(&amp;quot; - &amp;quot;) );&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== AJAX ==&lt;br /&gt;
&lt;br /&gt;
Ext Core makes AJAX easy.  The following code fetches and parses the contents of '''data.json''' and then displays it on the page:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
Ext.Ajax.request({&lt;br /&gt;
	url: &amp;quot;data.json&amp;quot;,&lt;br /&gt;
	success: function(response){&lt;br /&gt;
		var jsonData = Ext.decode(response);&lt;br /&gt;
		Ext.fly(&amp;quot;myDiv&amp;quot;).setHTML( jsonData.description );&lt;br /&gt;
	},&lt;br /&gt;
	failure: function(respose){&lt;br /&gt;
		console.log( &amp;quot;Error loading data; received error code &amp;quot; + response.status );&lt;br /&gt;
	}&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The following code sends a comment ID to '''comment_ajax.php''', which responds with a JSON object containing the comment's HTML:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
Ext.Ajax.request({&lt;br /&gt;
	url: &amp;quot;comment_ajax.php&amp;quot;,&lt;br /&gt;
	params: {&lt;br /&gt;
		comment_id: 45&lt;br /&gt;
	},&lt;br /&gt;
	success: function(response){&lt;br /&gt;
		var jsonData = Ext.decode(response);&lt;br /&gt;
		// Sanitize the response before displaying it on the page:&lt;br /&gt;
		var sanitizedComment = Ext.util.Format.htmlEncode( jsonData.contents );&lt;br /&gt;
		Ext.fly(&amp;quot;myDiv&amp;quot;).setHTML( sanitizedComment );&lt;br /&gt;
	},&lt;br /&gt;
	failure: function(respose){&lt;br /&gt;
		console.log( &amp;quot;Error loading data; received error code &amp;quot; + response.status );&lt;br /&gt;
	}&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' When parameters are given, Ext sends a POST request by default.  If no parameters are given, Ext sends a GET request.  If you want to send a GET request but also prevent caching, set the ''disableCaching'' option to ''true''.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' We use '''Ext.util.Format.htmlEncode(str)''' in the above example.  This is Ext's closest equivalent to PHP's '''htmlencode($str)'''.&lt;br /&gt;
&lt;br /&gt;
=== Submitting an Entire Form over AJAX ===&lt;br /&gt;
&lt;br /&gt;
Ext gives us another handy feature for AJAX requests: it enables us to automatically send the entire contents of a form.  For example, suppose we had the following form in HTML:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;form id=&amp;quot;myForm&amp;quot; action=&amp;quot;login.php&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;label&amp;gt;Username: &amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;usr&amp;quot; /&amp;gt;&amp;lt;/label&amp;gt;&lt;br /&gt;
	&amp;lt;label&amp;gt;Password: &amp;lt;input type=&amp;quot;password&amp;quot; name=&amp;quot;pwd&amp;quot; /&amp;gt;&amp;lt;/label&amp;gt;&lt;br /&gt;
&amp;lt;/form&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We can submit this form asynchronously in just one line of Ext:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
Ext.Ajax.request({ form: &amp;quot;myForm&amp;quot; });&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In practice, you may want to bind a function that submits the form in this manner to the ''submit'' event of that form.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
Ext.fly(&amp;quot;myFormId&amp;quot;).on(&amp;quot;submit&amp;quot;, function(event, element){&lt;br /&gt;
	event.preventDefault();&lt;br /&gt;
	Ext.Ajax.request({&lt;br /&gt;
		form: element,&lt;br /&gt;
		success: function(response) {&lt;br /&gt;
			console.log(&amp;quot;Success&amp;quot;, response);&lt;br /&gt;
		},&lt;br /&gt;
		failure: function(response) {&lt;br /&gt;
			console.log(&amp;quot;Failure&amp;quot;, response);&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Model View Controller ==&lt;br /&gt;
&lt;br /&gt;
What really sets Ext.JS apart from other JavaScript libraries is the toolset it gives you to create GUI components.  Ext.JS has an MVC engine that works on the front end of your application.&lt;br /&gt;
&lt;br /&gt;
=== Models, Stores, and Proxies ===&lt;br /&gt;
&lt;br /&gt;
Ext.JS adds a fourth concept to the MVC pattern: '''stores'''.  A &amp;quot;store&amp;quot; is a collection of ''records'', where a ''record'' is an instance of a ''model''.  In a lot of ways, if a model in Ext.JS is like a row in SQL, then a store in Ext.JS is like a table in SQL.&lt;br /&gt;
&lt;br /&gt;
Ext.JS also introduces the concept of '''proxies''': a mechanism that syncs the data in your front-end application to the server.  In Ext.JS, a proxy is typically associated with a store.  Ext.JS conforms to the ''RESTful paradigm'' in web application development.&lt;br /&gt;
&lt;br /&gt;
For an example of models, stores, and proxies, see [[Extensible Calendar]].&lt;br /&gt;
&lt;br /&gt;
=== The Lino Framework ===&lt;br /&gt;
&lt;br /&gt;
This wiki would not be complete without mentioning [http://www.lino-framework.org/ Lino], a framework that integrates Ext.JS into the Django stack.  You may earn creative portion points on Module 6 if you choose to implement your project using the Lino framework.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 6]]&lt;br /&gt;
[[Category:Former Content]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Workflow&amp;diff=1746</id>
		<title>Workflow</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Workflow&amp;diff=1746"/>
		<updated>2014-06-13T20:35:13Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* Bitbucket */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;The few minutes it takes to optimize your workflow will be the best few minutes you will spend in CSE 330 and your career.  It is remarkable how many hours you can save just by using the best interface for text editing and deployment.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
There are going to be several aspects to our workflow in CSE 330, and we will be switching between multiple different programs.  Here is how they all fit together.&lt;br /&gt;
&lt;br /&gt;
=== Running Commands ===&lt;br /&gt;
&lt;br /&gt;
''Mac OS X:'' You will be running commands on your local machine using '''Terminal''', which you can find in your Applications -&amp;gt; Utilities folder.  You will be connecting to your server via SSH also in Terminal.&lt;br /&gt;
&lt;br /&gt;
''Windows:'' You will be running commands on your local machine using '''Cygwin''', which you will install in the next section.  You will be connecting to your server via SSH also in Cygwin.&lt;br /&gt;
&lt;br /&gt;
=== Version Control ===&lt;br /&gt;
&lt;br /&gt;
You will be using '''SourceTree''' as a frontend to the '''Git''' version control system.  Git enables you to keep track of changes to your source code.&lt;br /&gt;
&lt;br /&gt;
=== Text Editing ===&lt;br /&gt;
&lt;br /&gt;
You will be using '''Komodo Edit''' as your text editing tool.&lt;br /&gt;
&lt;br /&gt;
=== File Transfer ===&lt;br /&gt;
&lt;br /&gt;
You will be using '''FileZilla''' as your tool for uploading files from your local working directory to your remote server.&lt;br /&gt;
&lt;br /&gt;
=== Flowchart ===&lt;br /&gt;
&lt;br /&gt;
If you are more visual, this flowchart might help:&lt;br /&gt;
&lt;br /&gt;
[[File:CSE-330-Workflow.png]]&lt;br /&gt;
&lt;br /&gt;
The flowchart illustrates 3 methods to copy files to your cloud instance: via your text editor, via an external SFTP client, and by cloning your remote Git repository.  We will be primarily using '''Option 2''' in CSE 330 this semester.&lt;br /&gt;
&lt;br /&gt;
In the flowchart, your ''Git Client'' is SourceTree and your ''Text Editor'' is Komodo.  The ''SFTP Client'' could be FileZilla.&lt;br /&gt;
&lt;br /&gt;
== Cygwin ==&lt;br /&gt;
&lt;br /&gt;
{{RequiredInstructions|content=&lt;br /&gt;
&lt;br /&gt;
'''Cygwin''' is a Linux Terminal emulator for Windows.&lt;br /&gt;
&lt;br /&gt;
Mac OS X users do not need to install Cygwin since OS X itself is a derivative of Unix, which is an ancestor of Linux.  The Terminal utility is all you need.&lt;br /&gt;
&lt;br /&gt;
=== Installation ===&lt;br /&gt;
&lt;br /&gt;
The CEC lab machines already have Cygwin installed.  Follow these instructions to get Cygwin up and running on your personal PC.&lt;br /&gt;
&lt;br /&gt;
# Run ''setup.exe'' from http://www.cygwin.com/&lt;br /&gt;
# Keep the Cygwin directory as the default, ''C:\cygwin''.  Choose a place like ''C:\cygwin\downloads'' to download the installation files.  Choose any download site, although probably one with a .com suffix is best when you're in the US.&lt;br /&gt;
# In the &amp;quot;Select Packages&amp;quot; screen, select the following packages:&lt;br /&gt;
#* Net -&amp;gt; openssh&lt;br /&gt;
#* Net -&amp;gt; openssl&lt;br /&gt;
#* Python -&amp;gt; python (you will need this for Module 4)&lt;br /&gt;
#* Devel -&amp;gt; git (version control system)&lt;br /&gt;
#* One or more of the following:&lt;br /&gt;
#** Editors -&amp;gt; vim&lt;br /&gt;
#** Editors -&amp;gt; emacs&lt;br /&gt;
#** Editors -&amp;gt; nano&lt;br /&gt;
# Allow the installation to complete.&lt;br /&gt;
&lt;br /&gt;
Throughout the rest of this course, when we say to &amp;quot;open a terminal&amp;quot;, if you are on Windows, we mean to &amp;quot;open Cygwin&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Thanks to [http://inside.mines.edu/~gmurray/HowTo/sshNotes.html our colleagues at Mines] for some tips on configuring Cygwin and SSH.&lt;br /&gt;
&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
== Bitbucket ==&lt;br /&gt;
&lt;br /&gt;
{{RequiredInstructions|content=&lt;br /&gt;
&lt;br /&gt;
'''Bitbucket''' is a service that enables you to store your code for free in the cloud.  It is similar in spirit to Github, but with a different mission statement.&lt;br /&gt;
&lt;br /&gt;
=== Creating a Bitbucket Account ===&lt;br /&gt;
&lt;br /&gt;
Go to [https://bitbucket.org/account/signup/ Bitbucket.org] to create an account.&lt;br /&gt;
&lt;br /&gt;
'''Important:''' Use your @wustl.edu e-mail address to create your account.  This will put your account on the &amp;quot;educational plan&amp;quot;, which removes some limitations of the free account.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' If you know someone who uses Bitbucket, you can ask them to invite you as a friend.  This will increase the member limit on the inviter's private repos.&lt;br /&gt;
&lt;br /&gt;
=== Adding Your Key to Bitbucket ===&lt;br /&gt;
&lt;br /&gt;
# First make sure that you've finished the [[SSH]] guide configuration instructions.&lt;br /&gt;
#: We will use the same key for connecting to your remote server as for connecting to Bitbucket.  (This is completely valid practice.)&lt;br /&gt;
# Go to the &amp;quot;SSH keys&amp;quot; section of the settings panel (Manage Account -&amp;gt; SSH Keys)&lt;br /&gt;
# Add a new key.&lt;br /&gt;
#* I recommend naming it after the computer you're using; if you're in the CEC, for example, you could name it &amp;quot;Warehouse Cygwin&amp;quot;.&lt;br /&gt;
#* The contents of your key is the contents of your ''id_rsa.pub''.  It looks like &amp;lt;code&amp;gt;ssh-rsa AAAAB3blahblahblahblah yourname@somedomain&amp;lt;/code&amp;gt;.  It is exactly the same thing that you had to paste into the ''authorized_keys'' file on your EC2 instance.&lt;br /&gt;
&lt;br /&gt;
You will now be able to push code to your Bitbucket repository using your personal SSH key.&lt;br /&gt;
&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
== SourceTree ==&lt;br /&gt;
&lt;br /&gt;
'''SourceTree''' is a tool that enables you to perform version control using a graphical user interface.  It is free and available for Windows 7+ and Mac OS X 10.6+.&lt;br /&gt;
&lt;br /&gt;
SourceTree is available on the Mac App Store.  Windows users (and OS X users who don't like the App Store) may install it from http://sourcetreeapp.com/&lt;br /&gt;
&lt;br /&gt;
=== Git ===&lt;br /&gt;
&lt;br /&gt;
'''[[wikipedia:Git (software)|Git]]''' is a ''distributed version control system'' that enables you to track changes to your code and work with collaborators on the same code base.  In CSE 132, you used ''Subversion (SVN)'', which is also version control system.&lt;br /&gt;
&lt;br /&gt;
Git, like SVN, is a command-line tool.  However, SourceTree enables you to use Git without having to pull up a Terminal window every time you need to perform an action.&lt;br /&gt;
&lt;br /&gt;
[[Git|In Module 5]], you will learn more advanced techniques for using Git.  However, for Modules 2-4, you will be using Git primarily as a method to push your changes to your remote repository.&lt;br /&gt;
&lt;br /&gt;
=== Configuring Git/SourceTree ===&lt;br /&gt;
&lt;br /&gt;
{{RequiredInstructions|content=&lt;br /&gt;
&lt;br /&gt;
Once you install SourceTree, you need to tell it your name so that it knows how to tag changes you make.&lt;br /&gt;
&lt;br /&gt;
# Open the SourceTree Preferences (SourceTree-&amp;gt;Preferences on OS X or Tools-&amp;gt;Options on Windows).&lt;br /&gt;
# Check the box that says &amp;quot;Allow SourceTree to modify your global Mercurial and Git configuration files&amp;quot;.&lt;br /&gt;
# Enter your name and e-mail address.&lt;br /&gt;
#: '''Note:''' This actually does the same thing as running &amp;lt;code&amp;gt;git config --global user.name &amp;lt;NAME HERE&amp;gt;&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;git config --global user.email &amp;lt;EMAIL HERE&amp;gt;&amp;lt;/code&amp;gt; from the command line.&lt;br /&gt;
# Go to the &amp;quot;Git&amp;quot; tab, and make the following changes:&lt;br /&gt;
#* Uncheck &amp;quot;Use the staging area&amp;quot;.  You will learn about staging in Git in Module 5, but for Modules 2-4 we will skip the staging area.&lt;br /&gt;
#* Check &amp;quot;Disable SSL certificate validation&amp;quot;.  This is necessary for the git repos hosted in the CEC.  (Note: this semester we are using BitBucket repos instead of CEC repos, so you can leave this box unchecked if you prefer.)&lt;br /&gt;
# Close the preferences window.&lt;br /&gt;
&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
=== Cloning a Repository ===&lt;br /&gt;
&lt;br /&gt;
[[File:SourceTree-Clone.png|400px|thumb|right|Screenshot of cloning a repository in SourceTree]]&lt;br /&gt;
&lt;br /&gt;
We will start by ''cloning'' a remote Git repository.&lt;br /&gt;
&lt;br /&gt;
&amp;quot;Cloning&amp;quot; in Git is much like &amp;quot;checking out&amp;quot; in SVN: a remote copy of the repository is copied down to a local working directory.  '''Word of Caution:''' Git uses the term &amp;quot;checkout&amp;quot; to mean something different (which you will learn in Module 5), so ''do not'' use the words &amp;quot;clone&amp;quot; and &amp;quot;checkout&amp;quot; interchangeably.&lt;br /&gt;
&lt;br /&gt;
If you wanted to clone a repository on the command line, the command would be:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;$ git clone git://www.example.com/url-of-repo destination-path&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In SourceTree, go to '''File-&amp;gt;New''', enter the remote repository URL and the destination path, and press &amp;quot;Clone&amp;quot;.  The destination path is where you want the repository's files to be copied on your personal computer; the path should point to either an empty or a nonexistent directory on your personal computer.  In the screenshot, I am cloning the repository for the Fedora Linux kernel.&lt;br /&gt;
&lt;br /&gt;
The remote repository will now be cloned onto your personal computer and all ready to use.&lt;br /&gt;
&lt;br /&gt;
=== Committing ===&lt;br /&gt;
&lt;br /&gt;
[[File:SourceTree-commit.jpg|400px|thumb|right|Screenshot of committing to a repository in SourceTree]]&lt;br /&gt;
&lt;br /&gt;
When you make changes to files or add new files, you need to ''commit'' them to your working repository.  '''Note:''' When you &amp;quot;commit&amp;quot; something in SVN, it means that you are sending your changes to the remote repository.  This is ''not'' the case in Git, as we will see shortly.&lt;br /&gt;
&lt;br /&gt;
To prepare your commit, press the &amp;quot;Commit&amp;quot; button in the SourceTree toolbar.  See the screenshot for an example.&lt;br /&gt;
&lt;br /&gt;
Select the files you want to commit, and enter a commit message summarizing the changes you've made since your last commit.  When you're ready, press &amp;quot;Commit&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
The command line equivalent of this would be:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ git add --all # adds untracked files to the repository and stages them for the commit&lt;br /&gt;
$ git commit -am &amp;quot;This is an example commit&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
What happens now is that your changes are recorded ''in your own local working copy of the Git repository''.  The changes have '''''not''''' been saved in the remote repository.  You need to do this by ''pushing'' them.&lt;br /&gt;
&lt;br /&gt;
=== Pushing ===&lt;br /&gt;
&lt;br /&gt;
Git is different from SVN in that you can use it completely independently from a remote repository.  Thus, in Git, you need to perform the &amp;quot;commit&amp;quot; and &amp;quot;push&amp;quot; steps separately.&lt;br /&gt;
&lt;br /&gt;
''After'' you perform a commit, you need to ''push'' your commit to your remote repository.  To do this, press the &amp;quot;Push&amp;quot; button in SourceTree, and then press &amp;quot;OK&amp;quot;.  The command line equivalent is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;$ git push master # assuming your branch is still named the default &amp;quot;master&amp;quot;&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' You do not need to push after every commit.  You could have 4 or 5 commits before you actually perform the push.  When you push, all commits will be pushed.&lt;br /&gt;
&lt;br /&gt;
=== Pulling ===&lt;br /&gt;
&lt;br /&gt;
In SVN, if you want to download changes from your remote repository, you performed an ''update''.  In Git, you perform a ''pull''.&lt;br /&gt;
&lt;br /&gt;
Pulling is (usually) as simple as pressing the &amp;quot;Pull&amp;quot; button in SourceTree.  The command line equivalent is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;$ git pull master&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' If you want to download the changes from the remote repository but not overwrite your current working copy, you can perform a ''fetch'' instead.&lt;br /&gt;
&lt;br /&gt;
== Pageant and PuTTYgen: SSH Keys for Windows ==&lt;br /&gt;
&lt;br /&gt;
{{RequiredInstructions|content=&lt;br /&gt;
&lt;br /&gt;
'''Pageant''' is a Windows utility that enables applications like SourceTree and Komodo Edit (which we will install in the next step) to be able to use your SSH keys when authenticating on remote services (like Bitbucket and your EC2 instance).  '''PuTTYgen''' is a utility that converts SSH keys into a format that Pageant can understand.&lt;br /&gt;
&lt;br /&gt;
'''Mac OS X and Linux users may skip this section.'''&lt;br /&gt;
&lt;br /&gt;
=== Installing Pageant and PuTTYgen ===&lt;br /&gt;
&lt;br /&gt;
Pageant and PuTTYgen both come bundled with SourceTree, so you do not need to install them separately.  However, if you weren't using SourceTree, you could install them from: http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html&lt;br /&gt;
&lt;br /&gt;
=== Using PuTTYgen ===&lt;br /&gt;
&lt;br /&gt;
We will use PuTTYgen to convert our SSH keys into Pageant's format, ''*.ppk''.&lt;br /&gt;
&lt;br /&gt;
# Launch PuTTYgen.  If you downloaded ''puttygen.exe'', just open it; if you are using the SourceTree version, you can find it under the Tools menu:&lt;br /&gt;
#: [[File:LaunchPuTTYgen.jpg]]&lt;br /&gt;
# Inside PuTTYgen, click &amp;quot;Load&amp;quot; next to &amp;quot;Load an existing private key file&amp;quot;.  We want to load the private key we generated in [[SSH|the SSH guide]] using ''ssh-keygen''.&lt;br /&gt;
#* If you are using a CEC machine, the key will be at: &amp;lt;code&amp;gt;H:\.ssh\id_rsa&amp;lt;/code&amp;gt;&lt;br /&gt;
#* If you are using your own computer, the key should be at: &amp;lt;code&amp;gt;C:\cygwin\home\&amp;lt;your name&amp;gt;\.ssh\id_rsa&amp;lt;/code&amp;gt;&lt;br /&gt;
#: Note that you might need to choose &amp;quot;All Files (*.*)&amp;quot; in order to see the file.&lt;br /&gt;
# When the key gets loaded, click &amp;quot;Save private key&amp;quot;&lt;br /&gt;
#: FileZilla, which will also need this *.ppk key, does not play nicely with passphrases, so leave the passphrase blank.&lt;br /&gt;
#: A good place to save the file would be back in Cygwin's ''.ssh'' directory:&lt;br /&gt;
#* CEC lab machines: &amp;lt;code&amp;gt;H:\.ssh\id_rsa.ppk&amp;lt;/code&amp;gt;&lt;br /&gt;
#* Personal machines: &amp;lt;code&amp;gt;C:\cygwin\home\&amp;lt;your name&amp;gt;\.ssh\id_rsa.ppk&amp;lt;/code&amp;gt;&lt;br /&gt;
# Close PuTTYgen.&lt;br /&gt;
&lt;br /&gt;
=== Using Pageant ===&lt;br /&gt;
&lt;br /&gt;
To launch Pageant, either run ''pageant.exe'' or select it from the Tools menu in SourceTree:&lt;br /&gt;
&lt;br /&gt;
[[File:LaunchPageant.jpg]]&lt;br /&gt;
&lt;br /&gt;
The first time you launch pageant, it will ask you to select a key.  Select the ''*.ppk'' file you saved in the previous section.&lt;br /&gt;
&lt;br /&gt;
If you wish to add more keys to Pageant, right-click on its icon down in the start bar:&lt;br /&gt;
&lt;br /&gt;
[[File:UsePageant.jpg]]&lt;br /&gt;
&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
=== Adding Pageant as a Startup Item ===&lt;br /&gt;
&lt;br /&gt;
If you are using your own computer, it may be convenient to add Pageant as a startup item so that you don't need to go into SourceTree and turn it on every time you reboot your computer.&lt;br /&gt;
&lt;br /&gt;
# Download ''pageant.exe'' if you were using SourceTree&lt;br /&gt;
# Open your Startup Items folder, located at Start Menu -&amp;gt; All Programs -&amp;gt; Startup (right-click and say &amp;quot;Open&amp;quot;)&lt;br /&gt;
# Right-click inside the folder and say &amp;quot;New -&amp;gt; Shortcut&amp;quot;.  For the location, enter:&lt;br /&gt;
#: &amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;&amp;quot;C:\path\to\pageant.exe&amp;quot; &amp;quot;c:\path\to\key.ppk&amp;quot;&amp;lt;/source&amp;gt;&lt;br /&gt;
#: This will cause Pageant to open and automatically load your key.&lt;br /&gt;
# Press &amp;quot;Next&amp;quot;.  Enter a name and press &amp;quot;Finish&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Thanks to [http://www.ualberta.ca/CNS/RESEARCH/LinuxClusters/pka-putty.html the University of Alberta] for this tip.&lt;br /&gt;
&lt;br /&gt;
== FileZilla ==&lt;br /&gt;
&lt;br /&gt;
{{RequiredInstructions|content=&lt;br /&gt;
&lt;br /&gt;
You can use SFTP from the command line, or you can use any GUI file transfer client.  All FTP clients I have seen also support SFTP.  One popular FTP client is [http://www.filezilla-project.org/ Filezilla].&lt;br /&gt;
&lt;br /&gt;
# Download and install FileZilla from http://filezilla-project.org/download.php?type=client&lt;br /&gt;
#: If you are using a lab computer, you can save it to your H drive.&lt;br /&gt;
# When you launch FileZilla, go to Edit→Settings or FileZilla→Preferences, and go to the SFTP options (under Connection).  Click &amp;quot;Add keyfile…&amp;quot;.&lt;br /&gt;
#* '''Windows users:''' Choose the *.ppk file that you made earlier using Puttygen.&lt;br /&gt;
#* '''Unix users:'''&lt;br /&gt;
#*# Choose your ''id_rsa'' file.   '''OS X Tip:''' Press Shift+Command+Period to reveal hidden files in the file chooser window.&lt;br /&gt;
#*# FileZilla will want to make a *.ppk file.  A good place to save it would be the .ssh directory as ''id_rsa.ppk''.&lt;br /&gt;
#: When finished, press '''OK''' (not the red ×) to save your changes.&lt;br /&gt;
# Back on the main FileZilla screen, there are four fields: Host, Username, Password, and Port.  Fill them in as follows:&lt;br /&gt;
#* '''Hostname:''' sftp://ec2-xxx-xx-xx-xxx.compute-1.amazonaws.com/&lt;br /&gt;
#* '''Username:''' The username you created on your server.&lt;br /&gt;
#* '''Password:''' Since you are using a key, you may leave this blank.&lt;br /&gt;
#*: If you changed your SSH settings to allow password-based authentication, then you could put your password in here.&lt;br /&gt;
#* '''Port:''' 22&lt;br /&gt;
# Then click Quickconnect.  If everything is configured correctly, FileZilla should log into your server.&lt;br /&gt;
&lt;br /&gt;
[[File:FileZilla.png]]&lt;br /&gt;
&lt;br /&gt;
On the left and right of the FileZilla window, you can drag files between your computer and your server.  Thus, you can edit a file in a text editor like Notepad++ on your decktop, and then upload it to your server by simply dragging it from the left pane to the right pane in FileZilla.&lt;br /&gt;
&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
== Komodo Edit ==&lt;br /&gt;
&lt;br /&gt;
{{RequiredInstructions|content=&lt;br /&gt;
&lt;br /&gt;
[[File:Komodo.png|200px]]&lt;br /&gt;
&lt;br /&gt;
This semester in CSE 330, we will be using Komodo Edit as our editor of choice.  We chose this editor because:&lt;br /&gt;
&lt;br /&gt;
# It is free for everyone.&lt;br /&gt;
# It runs on Windows, Mac OS X, and Linux.&lt;br /&gt;
# It supports all of the languages we will be using in this class.&lt;br /&gt;
# It has a decent amount tools like auto-completion that will speed up your workflow.&lt;br /&gt;
&lt;br /&gt;
=== Installation ===&lt;br /&gt;
&lt;br /&gt;
Komodo Edit is already installed on the CEC lab machines.  If you prefer to use your personal computer, download it from the web site: http://www.activestate.com/komodo-edit&lt;br /&gt;
&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
=== SSH Access ===&lt;br /&gt;
&lt;br /&gt;
You can configure Komodo Edit to connect to your EC2 instance (to implement option 1 in the flowchart above) .  However, because of a buggy and incomplete implementation in Komodo, '''this is not recommended or required for the purposes of CSE 330.'''  For the brave-hearted, instructions can be found here: [[Komodo Edit with SSH Access]]&lt;br /&gt;
&lt;br /&gt;
== Starting a Project ==&lt;br /&gt;
&lt;br /&gt;
Start a new Komodo Project whenever you start a new assignment.&lt;br /&gt;
&lt;br /&gt;
# Create a repo on Bitbucket and clone it to your local machine.&lt;br /&gt;
# In Komodo, choose '''Project -&amp;gt; New Project''' (or press shift-ctrl-N).&lt;br /&gt;
# Navigate to the cloned directory, enter a name for the project (e.g., ''Module2Group.komodoproject''), and press &amp;quot;Save&amp;quot;.&lt;br /&gt;
# You should now see a window like this:&lt;br /&gt;
#: [[File:Workflow-1.png]]&lt;br /&gt;
# Press ctrl-N (or cmd-N) to create a new file.  Save it in your project.  For example, you could create a page named ''index.html'' with the [[HTML and CSS#Quick and Easy Page Layout|Quick and Easy Page Layout]]:&lt;br /&gt;
#: [[File:Workflow-2.png]]&lt;br /&gt;
&lt;br /&gt;
'''Tip:''' To change between files without using a mouse, press ctrl-PageUp and ctrl-PageDown (cmd instead of ctrl on OS X).  Many computers without explicit PageUp and PageDown buttons bind them to fn-Up and fn-Down.  For example, on a MacBook Pro, to change to the next tab, you would press three keys: fn+cmd+down.&lt;br /&gt;
&lt;br /&gt;
When you are ready, use FileZilla to upload your files to your server via SFTP.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 2]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_2&amp;diff=1721</id>
		<title>Module 2</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_2&amp;diff=1721"/>
		<updated>2014-05-02T19:39:05Z</updated>

		<summary type="html">&lt;p&gt;Shane: Clarification from fall semester&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__ &lt;br /&gt;
Module 2 introduces you to Linux, a command-line environment, the Apache web server, and PHP.  You will create and configure your own cloud instance, install Apache and related software, and then form groups to make a simple file sharing site.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;span style=&amp;quot;font-size:1.3em; line-height:1.2em; color:blue;&amp;quot;&amp;gt;'''DO NOT WAIT UNTIL THE LAST MINUTE TO START ON THIS (or any) MODULE!'''  The most common reason students perform poorly in this class is procrastination.  You have been warned.&amp;lt;/span&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[Linux]]&lt;br /&gt;
* [[Bash]]&lt;br /&gt;
* [[Amazon Web Services]]&lt;br /&gt;
* [[SSH]]&lt;br /&gt;
* [[Apache]]&lt;br /&gt;
* [[PHP]]&lt;br /&gt;
* [[Workflow]]&lt;br /&gt;
* [[Web Application Security, Part 1]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
{{RequiredInstructions|content=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;span style=&amp;quot;color:red&amp;quot;&amp;gt;There are a lot of wiki pages that you need to read in order to complete the individual portion of Module 2.  The wiki pages contain an assortment of required steps, optional steps, and information.  To make things easier, we have highlighted the ''required steps'' with a red bar, like you see on the left of this message.  Do not skip anything marked with a red bar, or else you will not have a perfectly configured instance.&amp;lt;/span&amp;gt;&lt;br /&gt;
&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
=== Learn About Linux ===&lt;br /&gt;
&lt;br /&gt;
Linux is an open-source operating system based on UNIX. Linux is highly versatile and is used in a wide range of applications.&lt;br /&gt;
&lt;br /&gt;
If you are not a Linux guru, read the Linux guide to get started: [[Linux]]&lt;br /&gt;
&lt;br /&gt;
=== Install Cygwin: Windows Users Only ===&lt;br /&gt;
&lt;br /&gt;
You will need Cygwin in order to log into and configure your EC2 instance.  Cygwin is already installed on the CEC machines.  Instructions for installing Cygwin on your personal machine are located in [[Workflow#Cygwin|the Workflow guide]].&lt;br /&gt;
&lt;br /&gt;
Mac OS X users should located the &amp;quot;Terminal&amp;quot; application, which is installed by default; you will need this in the coming steps.&lt;br /&gt;
&lt;br /&gt;
=== Create an AWS EC2 Instance ===&lt;br /&gt;
&lt;br /&gt;
Once you understand [[Linux]], you need to set up your Amazon EC2 Instance.  Use the AWS article to guide you through the process: [[Amazon Web Services]]&lt;br /&gt;
&lt;br /&gt;
=== Configure SSH ===&lt;br /&gt;
&lt;br /&gt;
Follow the instructions in [[SSH#SSH Configuration|the SSH guide]] to do the following:&lt;br /&gt;
&lt;br /&gt;
# Create your own SSH key pair&lt;br /&gt;
# Log in as the default user to your EC2 instance&lt;br /&gt;
# Create a new user&lt;br /&gt;
# Give the new user your SSH public key&lt;br /&gt;
&lt;br /&gt;
From now on, when you need to log into your EC2 instance as an administrator, just pop up a terminal and run:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ssh your-username@ec2-xx-xx-xx-xx.compute-1.amazonaws.com&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Install Essential Packages ===&lt;br /&gt;
&lt;br /&gt;
Recall that software installation in Linux instances is usually handled through '''apt''' (Debian) or '''yum''' (RHEL).  For more information, refer to [[Linux#Repository-Based Package Managers|the Linux guide]].&lt;br /&gt;
&lt;br /&gt;
To make sure everything is working properly, '''install your first package(s) according to the ''Essential Packages'' subsection in the Linux guide.'''&lt;br /&gt;
&lt;br /&gt;
=== Set the Timezone ===&lt;br /&gt;
&lt;br /&gt;
'''Set your server to use US Central time (America/Chicago).'''  Instructions are in the Linux guide: [[Linux#Synchronizing Date and Time]]&lt;br /&gt;
&lt;br /&gt;
=== Set Up the Apache Web Server ===&lt;br /&gt;
&lt;br /&gt;
You need to '''install the Apache web server on your EC2 instance'''.  Refer to [[Apache|the Apache guide]].&lt;br /&gt;
&lt;br /&gt;
In order for your web server to be accessible, you need to '''open up Port 80 on your EC2 instance'''.  Instructions are in the AWS guide: [[Amazon Web Services#Enabling Web Access to your EC2 Instance]]&lt;br /&gt;
&lt;br /&gt;
'''Enable the UserDir module in Apache.'''  Instructions are in the Apache guide: [[Apache#The UserDir Module]]&lt;br /&gt;
&lt;br /&gt;
=== Install PHP ===&lt;br /&gt;
&lt;br /&gt;
You need to '''install PHP on your EC2 server'''.  Instructions are at the top of the PHP guide: [[PHP]]&lt;br /&gt;
&lt;br /&gt;
You need to '''configure PHP to show errors'''.  Instructions are immediately below installation in the PHP guide.&lt;br /&gt;
&lt;br /&gt;
=== Learn the PHP Language ===&lt;br /&gt;
&lt;br /&gt;
Before you can continue, you will need to make yourself acquainted with PHP language components.  Read the PHP guide for an overview: [[PHP#PHP Language Components]]&lt;br /&gt;
&lt;br /&gt;
=== Set Up your Workspace ===&lt;br /&gt;
&lt;br /&gt;
You are now ready to set up the workspace that you will be using for the rest of the semester.  Follow the instructions in [[Workflow]] to:&lt;br /&gt;
&lt;br /&gt;
# Make an account on Bitbucket&lt;br /&gt;
# Make a repository for your individual work for CSE 330&lt;br /&gt;
# Install SourceTree&lt;br /&gt;
# '''Windows only:''' Set up Pageant so that SourceTree can conect to Bitbucket&lt;br /&gt;
# Clone your CSE 330 repo from Bitbucket&lt;br /&gt;
# Install Komodo Edit&lt;br /&gt;
# Create a Komodo Edit Project inside of your Git repository&lt;br /&gt;
# Add the ''*.komodoproject'' file to ''.gitignore''&lt;br /&gt;
# Install FileZilla&lt;br /&gt;
# Connect FileZilla to your remote instance&lt;br /&gt;
&lt;br /&gt;
=== Calculator ===&lt;br /&gt;
&lt;br /&gt;
'''Make a calculator using PHP and an HTML form.'''  The form should have two inputs.  The form should submit a GET request either back to the same page or to a different results page.  The calculator should support addition, subtraction, multiplication, and division by means of a radio button group on the page.  (Consider edge cases!)&lt;br /&gt;
&lt;br /&gt;
== Group Project ==&lt;br /&gt;
&lt;br /&gt;
You will work in pairs (that means you and one other person) on this project.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;span style=&amp;quot;font-size:1.3em; line-height:1.2em; color:blue;&amp;quot;&amp;gt;In this module, and all future modules, the group portion builds off of material you learn in the individual portion.  You should therefore complete the individual portions prior to working on the group portions.  (Trust us: it will make your life easier!)&amp;lt;/span&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Important Reminder:''' frequently commit your work to your repository as a backup!&lt;br /&gt;
&lt;br /&gt;
=== Simple File Sharing Site ===&lt;br /&gt;
&lt;br /&gt;
You will be making a simple file sharing site that supports uploading, viewing, and deleting files associated with various users.  Details:&lt;br /&gt;
&lt;br /&gt;
* You should have a file named '''users.txt''' stored in a secure place on your filesystem.  It should have at least three usernames, with one username per line.&lt;br /&gt;
*: Passwords add an extra layer of complexity (encryption) that we will cover in Module 3.  You will not earn credit for implementing passwords as your creative portion for this module.&lt;br /&gt;
* Users of the file sharing site should be able to enter their username and then log in.&lt;br /&gt;
*: You may implement logins using session variables, or you may implement them using a GET parameter that is passed between pages.  You will need to always use sessions starting in Module 3.&lt;br /&gt;
* Users should see a list of all files associated with their username after the log in.&lt;br /&gt;
* Users should be able to view, upload, and delete files associated with their username.&lt;br /&gt;
* The URI should NOT reveal the internal file structure of your web site.&lt;br /&gt;
** Example of what not to do:  http://www.example.com/download.php?file=/home/paul/file.txt&lt;br /&gt;
** Another bad example:  http://www.example.com/~user/file.txt&lt;br /&gt;
** Good example: http://www.example.com/view.php?user=music&amp;amp;name=file.txt&lt;br /&gt;
*: In general, don't reveal any internal information about the site.&lt;br /&gt;
*: '''Food for thought:''' Given that Apache processes (with the exception of the main process) do not run as root, but rather as the user apache, how can you allow both your user account and the php scripts to read and write the necessary files?&lt;br /&gt;
* You should customize your file sharing site by implementing an additional feature or two as part of the '''creative portion'''.&lt;br /&gt;
&lt;br /&gt;
You will probably find the PHP guide on this wiki to be helpful: [[PHP#Other PHP Tips]]&lt;br /&gt;
&lt;br /&gt;
=== Web Security and Validation ===&lt;br /&gt;
&lt;br /&gt;
Your project needs to demonstrate that thought was put into web security and best practice.  For more information, see this week's Web Application Security guide: [[Web Application Security, Part 1]]&lt;br /&gt;
&lt;br /&gt;
In particular:&lt;br /&gt;
&lt;br /&gt;
* '''Your application needs to follow the conventions of FIEO (Filter Input and Escape Output)'''.  Things you should filter include file names, usernames, and so on.&lt;br /&gt;
* '''Your project must pass the W3C Validator with no errors'''.  For more information, see the HTML and CSS guide: [[HTML and CSS#Validation]]&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 100 points total.&lt;br /&gt;
&lt;br /&gt;
# '''Cloud Instance and Web Server (30 Points):'''&lt;br /&gt;
#* You can SSH into your instance using your own custom username and SSH key (15 points)&lt;br /&gt;
#* Your custom username is able to perform SUDO commands (5 points)&lt;br /&gt;
#* The time zone is correct on your instance (5 points)&lt;br /&gt;
#* The UserDir Apache module is working (5 points)&lt;br /&gt;
# '''PHP Calculator (15 Points):'''&lt;br /&gt;
#* The calculator is able to perform all four functions (2 points each)&lt;br /&gt;
#* Each function is given as a radio button choice (4 points)&lt;br /&gt;
#* The calculator page passes the W3C HTML validator (3 points)&lt;br /&gt;
# '''File Sharing Site (40 Points):'''&lt;br /&gt;
#* '''''File Management (25 Points):'''''&lt;br /&gt;
#** Users should not be able to see any files until they enter a username and log in (4 points)&lt;br /&gt;
#**: ''Remember that users.txt should be stored in a secure location on your filesystem.  That is, '''you should not be able to type any URL into your browser and see the raw users.txt file!'''''&lt;br /&gt;
#** Users can see a list of all files they have uploaded (4 points)&lt;br /&gt;
#** Users can open files they have previously uploaded (5 points)&lt;br /&gt;
#**: ''Note: Users should be able to open not only plain text files but also other file formats: images, spreadsheets, etc.''&lt;br /&gt;
#** Users can upload files (4 points)&lt;br /&gt;
#**: ''Note: Like users.txt, uploaded files should be stored in a secure location on your filesystem.  That is, '''do not keep your uploads directory underneath a directory served by Apache!'''''&lt;br /&gt;
#** Users can delete files.  If a file is &amp;quot;deleted&amp;quot;, it should actually be removed from the filesystem (4 points)&lt;br /&gt;
#** The directory structure is hidden (2 points)&lt;br /&gt;
#** Users can log out (2 points)&lt;br /&gt;
#**: ''Note: If using session variables, you must ''actually'' log out the user by destroying their session; i.e., don't just redirect them to the login screen.''&lt;br /&gt;
#* '''''Best Practices (10 Points):'''''&lt;br /&gt;
#** Code is well formatted and easy to read (4 points)&lt;br /&gt;
#** The site follows the FIEO philosophy (3 points)&lt;br /&gt;
#** All pages pass the W3C validator (3 points)&lt;br /&gt;
#* '''''Usability (5 Points):'''''&lt;br /&gt;
#** Site is intuitive to use and navigate (4 points)&lt;br /&gt;
#** Site is visually appealing (1 point)&lt;br /&gt;
# '''Creative Portion (15 Points)''' (see below)&lt;br /&gt;
&lt;br /&gt;
=== Creative Portion ===&lt;br /&gt;
&lt;br /&gt;
This module, and all future modules, will require that you invest some time into creating additional features for your group project.  Plan to invest at least 60 minutes of your time into the creative portion.&lt;br /&gt;
&lt;br /&gt;
* The creative portion is an opportunity for you to learn material of your own interest.&lt;br /&gt;
* You will not earn credit for a creative-portion feature that simply rehashes something you've already done in a previous module.&lt;br /&gt;
&lt;br /&gt;
If you need ideas for a creative portion, or if you want to know whether or not your creative portion idea is &amp;quot;hard enough&amp;quot;, ask a TA.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 2]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=SSH&amp;diff=1720</id>
		<title>SSH</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=SSH&amp;diff=1720"/>
		<updated>2014-05-02T19:29:18Z</updated>

		<summary type="html">&lt;p&gt;Shane: AWS has upgraded from Precise to Trusty&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Secure SHell, or '''SSH''', is the leading interface for connecting as an administrator from your local computer to something on the cloud.  You will be using exclusively SSH to execute commands and upload files to your cloud instance.  If you use a Git hosting service like BitBucket or Github, you will need SSH in order to save your changes there as well.&lt;br /&gt;
&lt;br /&gt;
SSH access requires that the ''sshd'' daemon is running on the remote machine.  By default, SSH is preinstalled on your EC2 instance.  If you are not using an EC2 instance, simply install '''ssh''' from yum or apt on the remote machine.&lt;br /&gt;
&lt;br /&gt;
== SSH Keys ==&lt;br /&gt;
&lt;br /&gt;
SSH can work using password-based authentication, but it is more common nowadays, and also more secure, to use ''public and private keys'', also known as a ''key pair''.&lt;br /&gt;
&lt;br /&gt;
Here's how it works.  You have a private copy of your key, called your '''private key'''.  Servers to which you want to connect have an analog to your private key called your '''public key'''.  When you attempt to connect to a server using your private key, the server checks to see if any of its public keys &amp;quot;fits&amp;quot; your private key, and if it finds a match, it lets you in.&lt;br /&gt;
&lt;br /&gt;
You can think of the ''private key'' as the &amp;quot;key&amp;quot; and the ''public key'' as the &amp;quot;lock&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
== SSH Configuration ==&lt;br /&gt;
&lt;br /&gt;
This section discusses how to set up your computer and your remote instance for SSH.  You need to do this only once.&lt;br /&gt;
&lt;br /&gt;
{{RequiredInstructions|content=&lt;br /&gt;
&lt;br /&gt;
=== Creating an SSH Key Pair ===&lt;br /&gt;
&lt;br /&gt;
You should create your own SSH Key Pair.  You will keep the private key on your own computer, and you will upload the public key to all places to which you need to connect.&lt;br /&gt;
&lt;br /&gt;
To generate a key pair, open Terminal or [[Workflow#Cygwin|Cygwin, which you will need to install if on a personal Windows computer,]] and run the following command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;# Run on Local Machine in Terminal or Cygwin&lt;br /&gt;
$ ssh-keygen&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Important:''' Don't name the file unless you are using a CEC machine. If you are using a CEC machine, name the file ''/cygdrive/h/.ssh/id_rsa''&lt;br /&gt;
&lt;br /&gt;
For the purposes of this course, you do not need to enter a passphrase, although you would probably want one in real life.&lt;br /&gt;
&lt;br /&gt;
Your keys should have been created in ~/.ssh.  Check to make sure they exist using the ''ls'' command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ls ~/.ssh&lt;br /&gt;
id_rsa  id_rsa.pub&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''id_rsa'' is your private key, and ''id_rsa.pub'' is the corresponding public key.  Let's look at the public signature of your key pair:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ cat ~/.ssh/id_rsa.pub&lt;br /&gt;
ssh-rsa AAAA3Bblahblahblahblah yourname@somedomain&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We will need this later.  Let's now add our key to the ''ssh-agent''.&lt;br /&gt;
&lt;br /&gt;
==== SSH Agent: OS X ====&lt;br /&gt;
&lt;br /&gt;
Run the following command to add your key to the SSH agent in Mac OS X.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;# Non-Cygwin&lt;br /&gt;
$ ssh-add&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== SSH Agent: Cygwin ====&lt;br /&gt;
&lt;br /&gt;
In order to make the SSH agent run when you start Cygwin, you need to run a couple more commands (these will add a line to your .bashrc file, which runs automatically on startup):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
# Cygwin only&lt;br /&gt;
$ echo &amp;quot;eval \`ssh-agent -s\`; ssh-add&amp;quot; &amp;gt;&amp;gt; ~/.bashrc&lt;br /&gt;
$ source ~/.bashrc # reload the Bash shell&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you get this scary-looking error after you run the second command…&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;&lt;br /&gt;
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&lt;br /&gt;
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @&lt;br /&gt;
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
…then you need to do the following to fix the permissions:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
# Cygwin only&lt;br /&gt;
$ chgrp Users /path/to/id_rsa&lt;br /&gt;
$ chmod 600 /path/to/id_rsa&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Amazon EC2 SSH Configuration ===&lt;br /&gt;
&lt;br /&gt;
When you first created your EC2 instance, you downloaded a *.pem file.  This is the ''private key'' for the default user ('''ubuntu''' on Ubuntu or '''ec2-user''' on AMI).  We need use this key to connect to your instance using the default user, at which point we will create a new custom user.  We will give that new user the public key that you created in the previous step.  You will then be able to log into your custom user using your personal key pair, so you won't need the default user again (although you should keep the *.pem file around just in case).&lt;br /&gt;
&lt;br /&gt;
==== Logging In as the Default User ====&lt;br /&gt;
&lt;br /&gt;
To connect to the default user on your Amazon EC2 instance, run this command in Terminal or Cygwin:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
# Run on Local Machine&lt;br /&gt;
$ ssh -i /path/to/default-privatekey.pem ubuntu@ec2-xx-xx-xx-xx.compute-1.amazonaws.com # or ec2-user@... for AMI&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Important:''' As soon as you are able to successfully log in, commands you type into your prompt will be executed on the remote instance, ''not'' your local machine.&lt;br /&gt;
&lt;br /&gt;
If you get this scary-looking warning:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;&lt;br /&gt;
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&lt;br /&gt;
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @&lt;br /&gt;
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
…then you need to correctly set the permissions on your *.pem file.  You should know how to do this from the Linux guide, but in case you didn't catch that detail, run:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
# Run on Local Machine&lt;br /&gt;
&lt;br /&gt;
# Cygwin Only:&lt;br /&gt;
$ chgrp Users /path/to/default-privatekey.pem&lt;br /&gt;
&lt;br /&gt;
# Terminal and Cygwin:&lt;br /&gt;
$ chmod 600 /path/to/default-privatekey.pem&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Food for Thought:''' Why you wouldn't want other people viewing your private key file?&lt;br /&gt;
&lt;br /&gt;
==== Creating a New User with SSH Permissions ====&lt;br /&gt;
&lt;br /&gt;
First, you need to create your new user with sudo and SSH permissions.  Again, the instructions for this are in the Linux guide, but to keep everything in one place, the commands are:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
# Run these on your instance, not on your local machine!&lt;br /&gt;
&lt;br /&gt;
# Don't forget to customize `My Full Name` and `&amp;lt;username here&amp;gt;`:&lt;br /&gt;
$ sudo useradd -r -m -c &amp;quot;My Full Name&amp;quot; &amp;lt;username here&amp;gt;&lt;br /&gt;
$ sudo passwd &amp;lt;username here&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# Ubuntu only:&lt;br /&gt;
$ sudo chsh -s /bin/bash &amp;lt;username here&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# You need to add your username to the sudoers list.  Refer to the Linux guide for details.&lt;br /&gt;
#  Ubuntu: Look around line 19.&lt;br /&gt;
#  Amazon AMI: Look around line 99.&lt;br /&gt;
$ sudo visudo &lt;br /&gt;
&lt;br /&gt;
# Ubuntu only: add your user to the SSH whitelist:&lt;br /&gt;
$ echo &amp;quot;AllowUsers &amp;lt;username here&amp;gt; ubuntu&amp;quot; | sudo tee -a /etc/ssh/sshd_config&lt;br /&gt;
&lt;br /&gt;
# Restart the SSH server:&lt;br /&gt;
$ sudo service ssh restart || sudo service sshd restart&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Okay, cool: we have created our custom username on our remote instance.  Now, we need to enable this account to accept our SSH key when authenticating.  To do this, we need to add our public key to a file named '''authorized_keys''', which is stored in your remote username's SSH configuration directory.&lt;br /&gt;
&lt;br /&gt;
To create the directory and edit the file, run on your instance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
# Switch to our own user to ensure that permissions are set correctly:&lt;br /&gt;
$ su &amp;lt;username here&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# Change the working directory to our user's home directory:&lt;br /&gt;
$ cd&lt;br /&gt;
&lt;br /&gt;
# Make the nonexistent SSH configuration directory and set its permissions:&lt;br /&gt;
$ mkdir .ssh&lt;br /&gt;
$ chmod 700 .ssh&lt;br /&gt;
&lt;br /&gt;
# Create the `authorized_keys` file and set the permissions&lt;br /&gt;
$ touch .ssh/authorized_keys&lt;br /&gt;
$ chmod 600 .ssh/authorized_keys&lt;br /&gt;
&lt;br /&gt;
# Edit the `authorized_keys` file&lt;br /&gt;
$ nano .ssh/authorized_keys&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For more detail on editing files on the command line, see [[Linux#File Editors|the Linux guide]].&lt;br /&gt;
&lt;br /&gt;
Inside of the `authorized_keys` file, paste in your public key.  Your public key is the content of `~/.ssh/id_rsa.pub` '''on your local machine''' (it starts with &amp;quot;ssh-rsa&amp;quot;).  There are a few ways to get it onto your clipboard:&lt;br /&gt;
&lt;br /&gt;
# '''OS X Only:''' Open a new Terminal and run: &amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;cat ~/.ssh/id_rsa.pub | pbcopy&amp;lt;/source&amp;gt; This immediately copies the contents of your public key to your clipboard.&lt;br /&gt;
# '''Windows Only:''' Navigate to id_rsa.pub manually, open it in your favorite text editor (like Notepad++), select all, and copy.  The location of id_rsa.pub might be: ''C:\cygwin\home\username\.ssh\id_rsa.pub''&lt;br /&gt;
# '''&amp;amp;#42;NIX Only:''' Open a new Terminal and copy the output of the following command: &amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;cat ~/.ssh/id_rsa.pub&amp;lt;/source&amp;gt; Note that this won't work as advertised in Cygwin because Cygwin adds extra line breaks when you try to copy out of it.&lt;br /&gt;
&lt;br /&gt;
When finished, save and close `authorized_keys`.&lt;br /&gt;
&lt;br /&gt;
'''Food for Thought:''' How would you enable your remote user to authenticate over SSH using the same default key instead of the one you created using ''ssh-keygen''?&lt;br /&gt;
&lt;br /&gt;
==== Logging In as your New User ====&lt;br /&gt;
&lt;br /&gt;
Let's test whether we can log into our instance using our own username and our own key pair. Open up a new Terminal or Cygwin and run:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ssh &amp;lt;username here&amp;gt;@ec2-xx-xx-xx-xx.compute-1.amazonaws.com&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is how you will be SSHing into your instances for the remainder of the semester.&lt;br /&gt;
&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
=== Troubleshooting ===&lt;br /&gt;
&lt;br /&gt;
Almost everyone receives the following error at some point in their career: &amp;lt;code&amp;gt;Permission denied (publickey)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Here are some possible causes for the error.&lt;br /&gt;
&lt;br /&gt;
==== The Authorized Keys File ====&lt;br /&gt;
&lt;br /&gt;
Make sure that your remote ''authorized_keys'' file contains ''exactly'' your public signature from ''id_rsa.pub''.&lt;br /&gt;
&lt;br /&gt;
===== Pasting into Vi =====&lt;br /&gt;
&lt;br /&gt;
If you used vi to edit your file and you forgot to enter &amp;quot;insert&amp;quot; mode before pasting in your key, it is possible that you lost the first &amp;quot;s&amp;quot; in &amp;quot;ssh-rsa&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
Check the contents of authorized_keys via &amp;lt;code&amp;gt;cat ~/.ssh/authorized_keys&amp;lt;/code&amp;gt; on your server.  If the output starts with &amp;quot;sh-rsa&amp;quot; instead of &amp;quot;ssh-rsa&amp;quot;, edit the authorized_keys file and add the second '''s'''.&lt;br /&gt;
&lt;br /&gt;
===== Unintentional Line Breaks =====&lt;br /&gt;
&lt;br /&gt;
If you got your key via a &amp;lt;code&amp;gt;cat ~/.ssh/id_rsa.pub&amp;lt;/code&amp;gt; and then copied it from the terminal, it's possible that you unintentionally introduced line breaks.  Ensure that the key is represented by only one line of text.&lt;br /&gt;
&lt;br /&gt;
==== Permissions ====&lt;br /&gt;
&lt;br /&gt;
They need to be correct on both the client side and on the server side.&lt;br /&gt;
&lt;br /&gt;
* Local ''.ssh'' = 700&lt;br /&gt;
* Local ''id_rsa'' = 600&lt;br /&gt;
* Remote ''.ssh'' = 700&lt;br /&gt;
* Remote ''authorized_keys'' = 600&lt;br /&gt;
&lt;br /&gt;
If you are in Cygwin and the permissions don't seem to change, you might need to add the troubled file to a usergroup, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ chgrp Users .ssh/id_rsa&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== The SSH Agent ====&lt;br /&gt;
&lt;br /&gt;
You need to be sending the correct key along with your SSH Agent.  Run the following command, and you should see some output:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ssh-add -l&lt;br /&gt;
2048 ab:cd:ef:ab:cd:ef:ab:cd:ef:ab:cd:ef:ab:cd:ef:ab:cd /path/to/.ssh/id_rsa (RSA)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you don't see any output, or if the output does not contain your ''id_rsa'', then you need to run:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ssh-add /path/to/.ssh/id_rsa&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== More SSH Server Configurations ===&lt;br /&gt;
&lt;br /&gt;
Up to this point, we have been using all of the default SSH configurations.  Like most things in Linux, SSH can be customized.&lt;br /&gt;
&lt;br /&gt;
For the purposes of CSE 330, the additional configurations in this short section are optional; this serves only as a reference.&lt;br /&gt;
&lt;br /&gt;
==== Disabling Root Access ====&lt;br /&gt;
&lt;br /&gt;
It is almost always a good idea to disable root access over ssh. This could be done by editing ''/etc/ssh/sshd_config'' and setting  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;PermitRootLogin no&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You will need to restart the SSH server for changes to take effect:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ sudo service ssh restart # Debian version&lt;br /&gt;
$ sudo service sshd restart # RHEL version&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Enabling Password-Based Authentication ====&lt;br /&gt;
&lt;br /&gt;
Up to this point, we have been using key pairs for SSH.  A public/private key pair is generally considered to be more secure, but it requires that you always have access to your private key file when you want to log into your remote machine.&lt;br /&gt;
&lt;br /&gt;
By default, EC2 instances allow only public/private key pair authentication.  You can enable password-based authentication by setting the PaswordAuthentication option in ''/etc/ssh/sshd_config'' to '''yes''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;PasswordAuthentication yes&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There may be a line with this option that you can un-comment.  For me, it is line 25.  You will need to restart the server for changes to take effect.&lt;br /&gt;
&lt;br /&gt;
If possible, however, you should restrict yourself to using private and public keys.&lt;br /&gt;
&lt;br /&gt;
== Using SSH ==&lt;br /&gt;
&lt;br /&gt;
Once you have completed the [[#SSH Configuration]] section above, all you need to do in order to SSH into your instance is to open a terminal and run:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ssh &amp;lt;username here&amp;gt;@ec2-xx-xx-xx-xx.compute-1.amazonaws.com&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== PuTTY ===&lt;br /&gt;
&lt;br /&gt;
'''This short section about PuTTY serves only as a reference.'''&lt;br /&gt;
&lt;br /&gt;
If you have Cygwin available, you should use it to SSH into your instance.  However, if you are using a different computer, you might not have Cygwin at your fingertips.  In this case, a lighter-weight SSH client called '''PuTTY''' is available for Windows.&lt;br /&gt;
&lt;br /&gt;
You can download PuTTY from: http://www.chiark.greenend.org.uk/~sgtatham/putty/&lt;br /&gt;
&lt;br /&gt;
Amazon provides [http://docs.amazonwebservices.com/AWSEC2/latest/GettingStartedGuide/ConnectToInstanceLinux.html#connect-from-windows-machine a great tutorial on how to connect to a virtual machine from Windows].&lt;br /&gt;
&lt;br /&gt;
PuTTY is fairly simple and straight forward with one caveat: Amazon's ''*.pem'' files are SSH private key files, and they need to be converted to PuTTY's own '''.ppk''' format.  To do this, use the ''puttygen.exe'' utility available from the same page as PuTTY.  Select &amp;quot;Import&amp;quot; under the conversions menu, load the amazon ''*.pem'' key file, and press the &amp;quot;Save Private Key&amp;quot; button.&lt;br /&gt;
&lt;br /&gt;
Copy and paste works similarly to the X Window System in Unix. You use the left mouse button to select text in the PuTTY window. The act of selection automatically copies the text to the clipboard: there is no need to press Ctrl-Ins or Ctrl-C or anything else. In fact, pressing Ctrl-C will send a Ctrl-C character to the other end of your connection (just like it does the rest of the time), which may have unpleasant effects. The only thing you need to do, to copy text to the clipboard, is to select it.&lt;br /&gt;
&lt;br /&gt;
To paste the clipboard contents into a PuTTY window, by default you click the right mouse button. If you have a three-button mouse and are used to X applications, you can configure pasting to be done by the middle button instead, but this is not the default because most Windows users don't have a middle button at all. &lt;br /&gt;
&lt;br /&gt;
Here is a good PuTTY tutorial that you might find useful to get started: http://kb.mediatemple.net/questions/1595/Using+SSH+in+Putty+%28Windows%29&lt;br /&gt;
&lt;br /&gt;
== SSHFS and SFTP ==&lt;br /&gt;
&lt;br /&gt;
In addition to just SSH, your SSH server also supports '''SSHFS''', which enables you to mount your remote instance as a disk on your local computer, and '''SFTP''', which is a file transfer protocol that enables you to upload files directly to your instance.&lt;br /&gt;
&lt;br /&gt;
=== SSHFS ===&lt;br /&gt;
&lt;br /&gt;
SSHFS is a filesystem client which allows secure mounting of remote file systems. While there are other ways to mount remote file systems, SSHFS has the advantage of being able to mount a file system located on any host that has an SSH daemon running without any host side installation or configuration. This means that you can easily access and edit your files using all of your local applications including IDEs. &lt;br /&gt;
&lt;br /&gt;
As you may have inferred from the name, the underlying implementation utilizes SSH File Transfer Protocol in combination with FUSE, a package now included in the kernel that allows unprivileged users to easily create their own file systems in userspace (see the wikipedia entry for more information [http://en.wikipedia.org/wiki/Filesystem_in_Userspace]).&lt;br /&gt;
&lt;br /&gt;
To mount a share using password based authentication, the command is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ sshfs user@domain:/path/to/remote/directory /path/to/local/mountpoint&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For example, to mount the directory /home/joe/myfiles in the user ''joe'''s home directory for a machine with the domain schmoesfiles.org using SSHFS you would enter the command&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ sshfs joe@www.schmoesfiles.org:myfiles&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that if you are using public key authentication, the command to mount the remote filesystem may need to be slightly different:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ sshfs -o IdentityFile=/path/to/private/key user@domain:/path/to/remote/directory /path/to/local/mountpoint&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To unmount the filesystem, you can use the following command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ fusermount -u /path/to/local/mountpoint&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== SFTP ===&lt;br /&gt;
&lt;br /&gt;
Any server running an SSH server is also compatible with '''SFTP''' or Secure File Transfer Protocol.  (Compare to FTP, or File Transfer Protocol.)  SFTP is a convenient way to edit files on your computer and then upload them to your server in just a few clicks.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 2]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Amazon_Web_Services&amp;diff=1719</id>
		<title>Amazon Web Services</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Amazon_Web_Services&amp;diff=1719"/>
		<updated>2014-05-02T19:29:08Z</updated>

		<summary type="html">&lt;p&gt;Shane: AWS has upgraded from Precise to Trusty&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Amazon Web Services provides a method to publish web sites on virtual machines in the &amp;quot;cloud.&amp;quot;  In CSE330, you will be using an EC2 instance to host your web site.&lt;br /&gt;
&lt;br /&gt;
Before reading this guide, you should be familiar with Linux and the various distributions of Linux.  Fore more information, refer to [[Linux#Linux Distributions|the Linux guide]].&lt;br /&gt;
&lt;br /&gt;
== Creating and Configuring your EC2 Instance ==&lt;br /&gt;
&lt;br /&gt;
{{RequiredInstructions|content=&lt;br /&gt;
&lt;br /&gt;
Follow these steps to get to the AWS Management Console:&lt;br /&gt;
&lt;br /&gt;
# Create an AWS account: http://aws.amazon.com/&lt;br /&gt;
# Sign up for the EC2 Web Service: http://aws.amazon.com/ec2/&lt;br /&gt;
# Log in to the AWS Management Console&lt;br /&gt;
&lt;br /&gt;
To create your new virtual machine, click '''Launch Instance'''.  Do the following to configure your instance:&lt;br /&gt;
&lt;br /&gt;
# Use the Classic Wizard.&lt;br /&gt;
# Now choose what distribution of Linux you would like to use.  For more information on distributions, refer to [[Linux#Linux Distributions|the Linux guide]].  The following are both good choices, and throughout the wiki, the instructions are equally comprehensive for both.  This semester, we will be teaching this class using Ubuntu, but you are free to use either one.&lt;br /&gt;
#* Ubuntu Server 14.04 LTS (based on Debian)&lt;br /&gt;
#* Amazon Linux AMI (based on RHEL)&lt;br /&gt;
# The default instance variables are all fine.  Click Continue until you get to the &amp;quot;Create Key Pair&amp;quot; screen.&lt;br /&gt;
# Create a new Key Pair.  Enter some name for it, and then click &amp;quot;Create &amp;amp; Download your Key Pair&amp;quot;.  '''Save your key somewhere secure.'''  In addition to using it to authenticate for this instance, you will be able to use the same key for additional instances.&lt;br /&gt;
# Create a new Security Group.  The security groups you create determine whether a port is open or blocked for your server.&lt;br /&gt;
#* You need to open the SSH port on your server.  To do this, select &amp;quot;SSH&amp;quot; from the drop-down box, and then click &amp;quot;Add Rule.&amp;quot;&lt;br /&gt;
#: We will be opening more ports by modifying the security group at a later time.  Click Continue.&lt;br /&gt;
# You are now ready to launch your virtual server!  Click Launch.&lt;br /&gt;
&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
== Starting and Stopping your EC2 Instance ==&lt;br /&gt;
&lt;br /&gt;
You can start and stop your instance by right-clicking on the instance.  The options are down in the &amp;quot;Instance Lifecycle&amp;quot; section.&lt;br /&gt;
&lt;br /&gt;
=== Amazon EC2 Gives You One Free Micro Instance ===&lt;br /&gt;
&lt;br /&gt;
It is free to keep '''''one''''' micro instance running at all times.  Keeping your instance running around the clock will make your life easier, because then you won't need to always change your hostname in your SSH clients.&lt;br /&gt;
&lt;br /&gt;
For additional Micro instances, or for larger instances, you will be charged hourly for their use.  One non-free Micro instance costs about $14/month; a Small instance costs about $43/month.&lt;br /&gt;
&lt;br /&gt;
=== Terminate vs Stop ===&lt;br /&gt;
&lt;br /&gt;
Never &amp;quot;terminate&amp;quot; your instance, as this PERMANENTLY DELETES the instance! Any time you are done using the instance you should instead &amp;quot;stop&amp;quot; the instance and then when you are ready to resume work you should &amp;quot;start&amp;quot; the instance.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' Frequently committing your work to your repository is a safety net in case something horrible happens to your instance.&lt;br /&gt;
&lt;br /&gt;
== Enabling Web Access to your EC2 Instance ==&lt;br /&gt;
&lt;br /&gt;
{{RequiredInstructions|content=&lt;br /&gt;
&lt;br /&gt;
Once you have configured [[Apache]] (which you will do later in this Module), you will need to open up your EC2 instance to web traffic.  (By default amazon blocks all traffic to our instance.)&lt;br /&gt;
&lt;br /&gt;
Go to the Security Groups under Network &amp;amp; Security on the EC2 webpage. Select your security group, click on the Inbound Tab. Add a new Custom TCP rule with a Port range of 80.  Leave the Source at 0.0.0.0/0 (for all traffic). Click Add Rule, and then click Apply Rule Change.&lt;br /&gt;
&lt;br /&gt;
To make sure things are working, create a file, like '''hello.txt''', in your web server root.  Give it some content (might I suggest &amp;quot;Hello, world!&amp;quot;).&lt;br /&gt;
&lt;br /&gt;
* In the Amazon AMI, the web server root is at /var/www/html&lt;br /&gt;
* In Ubuntu 12.04 LTS, the web server root is at /var/www&lt;br /&gt;
&lt;br /&gt;
For more information on editing files on the command line, refer to [[Linux#File Editors|the Linux guide]].&lt;br /&gt;
&lt;br /&gt;
You should now be able to visit your server load up the file using your web browser!  Example Link: http://ec2-xxx-xxx-xxx-xx.compute-1.amazonaws.com/hello.txt&lt;br /&gt;
&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 2]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Apache&amp;diff=1718</id>
		<title>Apache</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Apache&amp;diff=1718"/>
		<updated>2014-05-02T19:28:56Z</updated>

		<summary type="html">&lt;p&gt;Shane: AWS has upgraded from Precise to Trusty&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;''Apache'' is the industry standard web server for Linux distributions.  It is highly configurable and has a wide range of modules ready for different needs.&lt;br /&gt;
&lt;br /&gt;
{{XKCD&lt;br /&gt;
|name=permanence&lt;br /&gt;
|id=910&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
== What is a web server? ==&lt;br /&gt;
&lt;br /&gt;
A web server is software that listens for connections to your machine, and when a connection is receive, processes the request and responds with the appropriate information.  Most web servers listen on port 80, which is reserved for the purpose, and use the HTTP protocol.&lt;br /&gt;
&lt;br /&gt;
For example, when you visit this wiki, you are sending a request over the internet to some machine that is probably located somewhere in EIT (the user seldom knows exactly where the machine is located).  The web server receives your request, and it processes the data you sent.  Finally, the server prepares a response (the web page), and sends it back to you.&lt;br /&gt;
&lt;br /&gt;
== Installing Apache ==&lt;br /&gt;
&lt;br /&gt;
{{RequiredInstructions|content=&lt;br /&gt;
&lt;br /&gt;
In yum, Apache is distributed under the package name '''httpd''' (for ''hypertext transfer protocol daemon'').  In apt, it is distributed under the name '''apache2'''.  Use the package manager associated with your distribution to install Apache.  (For more information on how to use yum and apt, see [[Linux#Repository-Based Package Managers|the Linux guide]].)&lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
# Debian version&lt;br /&gt;
$ sudo apt-get update&lt;br /&gt;
$ sudo apt-get install apache2&lt;br /&gt;
&lt;br /&gt;
# RHEL version&lt;br /&gt;
$ sudo yum install httpd&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When Apache is installed through apt, the HTTP Daemon will be automatically to added as a startup item.  If you are using the Amazon AMI, you need to run this command to add Apache as a startup item:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ sudo /sbin/chkconfig --levels 235 httpd on # RHEL only&lt;br /&gt;
$ &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In RHEL, all Apache configurations are stored in ''/etc/httpd/conf/httpd.conf''.  Debian takes a more modular approach, having separate directories for each type of configuration, all located in ''/etc/apache2/''.  For more detail on Debian's approach, see http://www.control-escape.com/web/configuring-apache2-debian.html&lt;br /&gt;
&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
== Apache Directives ==&lt;br /&gt;
&lt;br /&gt;
You define your settings for Apache using ''directives''.  Some of the directives you will likely encounter include:&lt;br /&gt;
&lt;br /&gt;
* '''DocumentRoot:''' The path to the directory where the top level web files are going to be stored.&lt;br /&gt;
* '''IfModule:'''  The following block would be included if specified module exists.&lt;br /&gt;
* '''User:''' Which user apache2 will run as.&lt;br /&gt;
* '''Group:''' Which group will have group access to default web files.&lt;br /&gt;
* '''AccessFileName:''' The name of the access file (that specifies user names/passwords and other limitations to files/directories).&lt;br /&gt;
* '''ErrorLog:''' Where any errors will be written.&lt;br /&gt;
* '''Include:''' Include some other files.&lt;br /&gt;
* '''LogFormat:''' How to write a log message.&lt;br /&gt;
* '''ErrorDocument:''' Files to display for some HTTP errors (500, 404, 402 etc.).&lt;br /&gt;
* '''Alias:''' Map a directory URL to some other location on your filesystem.  Requires that the ''Alias'' module be loaded.&lt;br /&gt;
&lt;br /&gt;
=== .htaccess Files ===&lt;br /&gt;
&lt;br /&gt;
You can also specify some Apache configurations without delving into the master configuration file.  To do this, put a file named ''.htaccess'' in any directory that Apache is serving.  All directives in it will be interpreted as if they were in a Directory directive in the master configuration file.&lt;br /&gt;
&lt;br /&gt;
'''VERY IMPORTANT:''' The directory containing ''.htaccess'' must not have the '''AllowOverride None''' directive in the master configuration file in order for '''.htaccess''' to be read.  In Debian, '''AllowOverride None''' is enabled by default!  The Apache configuration file you need to edit in Debian is ''/etc/apache2/sites-available/default'' (remove the '''AllowOverride None''' located on line 11).&lt;br /&gt;
&lt;br /&gt;
=== Directory Directive ===&lt;br /&gt;
&lt;br /&gt;
Use the Directory directive to assign other directives to a specific directory.  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;apache&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;Directory /var/www/&amp;gt;&lt;br /&gt;
	Options Indexes FollowSymLinks &lt;br /&gt;
	AllowOverride None&lt;br /&gt;
	Order allow,deny&lt;br /&gt;
	allow from all&lt;br /&gt;
	RedirectMatch ^/$ /apache2-default/&lt;br /&gt;
&amp;lt;/Directory&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This sets options for the ''/var/www'' directory.&lt;br /&gt;
# The '''Options''' directive says that:&lt;br /&gt;
## If no index page is present in a directory, display a directory index page instead&lt;br /&gt;
## Apache will follow symbolic links in the directory&lt;br /&gt;
# '''AllowOverride None''' says that ''.htaccess'' files cannot alter the Apache options in this directory and all sub-directories&lt;br /&gt;
# '''Order allow,deny''' and '''Allow from all''' specifies that anybody is allowed to access this server via HTTP.&lt;br /&gt;
&lt;br /&gt;
Note that this directory is actually the root directory of the web server.&lt;br /&gt;
&lt;br /&gt;
== The UserDir Module ==&lt;br /&gt;
&lt;br /&gt;
{{RequiredInstructions|content=&lt;br /&gt;
&lt;br /&gt;
The UserDir module lets you access files for any user on the server with a ~, e.g., http://ec2-xxx-xxx-xxx-xx.compute-1.amazonaws.com/~paul/&lt;br /&gt;
&lt;br /&gt;
This module comes installed, but not activated by default.&lt;br /&gt;
&lt;br /&gt;
=== Enabling UserDir in Debian ===&lt;br /&gt;
&lt;br /&gt;
If you are using a Debian-based distribution for your server (like Ubuntu Server), simply run the following command to enable the module:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ sudo a2enmod userdir&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then [[#Restarting Apache and Testing|restart Apache]] for the changes to take effect.  Now, all users will be able to store their own personal web site in public_html inside their home directory.&lt;br /&gt;
&lt;br /&gt;
To make sure everything is working, create a test file in your home directory under public_html, and then point your browser to it: http://ec2-xxx-xx-xx-xxx.compute-1.amazonaws.com/~yourUserName/hello.txt&lt;br /&gt;
&lt;br /&gt;
'''Note:''' The UserDir configuration file, which already has all the correct settings, is located at ''/etc/apache2/mods-available/userdir.conf''&lt;br /&gt;
&lt;br /&gt;
'''Note:''' Users need to manually create public_html.  It is not created automatically.&lt;br /&gt;
&lt;br /&gt;
=== Enabling UserDir in RHEL ===&lt;br /&gt;
&lt;br /&gt;
If you are using an RHEL-based distribution for your server (like the Amazon AMI), you need to edit the master Apache configuration file.&lt;br /&gt;
&lt;br /&gt;
Open ''/etc/httpd/conf/httpd.conf'' in your favorite text editor.  For more information on command-line text editors, refer to [[Linux#File Editors|the Linux guide]].&lt;br /&gt;
&lt;br /&gt;
Find the line that says&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;apache&amp;quot;&amp;gt;UserDir disabled&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and change it to&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;apache&amp;quot;&amp;gt;UserDir disabled root&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Additionally, find the line that says&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;apache&amp;quot;&amp;gt;#UserDir public_html&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and uncomment it; that is, remove the # so that you have&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;apache&amp;quot;&amp;gt;UserDir public_html&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This tells Apache that the directory containing each user's html files is a subdirectory of their home directory called public_html.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' Users need to manually create public_html.  It is not created automatically.&lt;br /&gt;
&lt;br /&gt;
You may also need to change the permissions of your user directory and your public_html directory to allow Apache to read and execute inside them.  To do this, run the following commands:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ sudo chmod o+x /home/myUserName&lt;br /&gt;
$ sudo chmod o+rx /home/myUserName/public_html&lt;br /&gt;
$ &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, [[#Restarting Apache and Testing|restart Apache]].&lt;br /&gt;
&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
=== Remapping UserDir ===&lt;br /&gt;
&lt;br /&gt;
If you want to change the name of the UserDir web server root from '''public_html''' to something else like '''.html''', follow these instructions.  (You do not need to do this for the purposes of CSE 330; this serves as a reference.)&lt;br /&gt;
&lt;br /&gt;
# Rename your '''public_html''' to '''.html'''&lt;br /&gt;
#* The &amp;quot;.&amp;quot; in front of the directory name means that the directory is a hidden one.  You will not see it with the normal &amp;quot;ls&amp;quot; command.  Use &amp;quot;ls -a&amp;quot; to see hidden files as well.&lt;br /&gt;
# Edit the UserDir configuration file.&lt;br /&gt;
#* In RHEL, edit the master Apache configuration file at ''/etc/httpd/conf/httpd.conf''&lt;br /&gt;
#* In Debian, edit the UserDir configuration file at ''/etc/apache2/mods-available/userdir.conf''&lt;br /&gt;
# Find the line that reads &amp;lt;code&amp;gt;UserDir public_html&amp;lt;/code&amp;gt; and change it to &amp;lt;code&amp;gt;UserDir .html/&amp;lt;/code&amp;gt;&lt;br /&gt;
# [[#Restarting Apache and Testing|Restart Apache]].&lt;br /&gt;
&lt;br /&gt;
== Apache Logs ==&lt;br /&gt;
&lt;br /&gt;
Apache creates two log files: one for all access attempts to your server, and one for errors.  The locations of these log files are:&lt;br /&gt;
&lt;br /&gt;
* '''Debian:'''&lt;br /&gt;
** '''Access Log:''' /var/log/apache2/access.log&lt;br /&gt;
** '''Error Log:''' /var/log/apache2/error.log&lt;br /&gt;
* '''RHEL:'''&lt;br /&gt;
** '''Access Log:''' /var/log/httpd/access_log&lt;br /&gt;
** '''Error Log:''' /var/log/httpd/error_log&lt;br /&gt;
&lt;br /&gt;
You might find it helpful to see access and errors appear &amp;quot;live&amp;quot; in your terminal window as they are created.  To do this, you can use the [[Linux#Command Reference|tail -f]] command.  Since the log files have strict permissions, you will need to also use sudo.  Example on Debian:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ sudo tail -f /var/log/apache2/error.log&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Virtual Hosts ==&lt;br /&gt;
&lt;br /&gt;
'''Virtual Hosts''' are used to run multiple Apache web servers from the same machine.  Virtual hosts can listen for connections on different ports and/or different hostnames, serving completely different web sites to each.  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;apache&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;VirtualHost cse330.dyndns.org&amp;gt;&lt;br /&gt;
	ServerAdmin webmaster@localhost&lt;br /&gt;
	ServerName cse330.dyndns.org&lt;br /&gt;
	DocumentRoot /home/www/cse330/&lt;br /&gt;
	ErrorLog /var/log/httpd/error_log&lt;br /&gt;
	LogLevel warn&lt;br /&gt;
	CustomLog /var/log/apache2/access_log combined&lt;br /&gt;
	ServerSignature On&lt;br /&gt;
&amp;lt;/VirtualHost&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This configuration enables any requests that use a host name of ''cse330.dyndns.org'' will use ''/home/www/cse330'' as the root document directory.  Make sure that the DocumentRoot directory exists and is readable by the httpd process.  In RHEL, Apache runs as the '''apache''' user.  In Debian, it runs as the '''www-data''' user.&lt;br /&gt;
&lt;br /&gt;
It is good practice to put raw server configuration files in ''/etc/httpd/sites-available'' in RHEL or ''/etc/apache2/sites-available'' in Debian.  To activate a site, create a symlink from the configuration in ''sites-available'' to a sibling directory called ''sites-enabled''.  In Debian, these directories are already set up for you, and Debian Apache even provides the '''a2ensite''' and '''a2dissite''' commands to create or destroy the symlinks!  In RHEL, you have to do this by hand.&lt;br /&gt;
&lt;br /&gt;
== Restarting Apache and Testing ==&lt;br /&gt;
&lt;br /&gt;
Whenever you make changes to the Apache configuration files, you will need to restart Apache for the changes to take effect.  There are several different ways to restart Apache; they all functionally do (almost) the same thing, so choose your favorite:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ sudo /usr/sbin/apachectl restart   # works on both Debian and RHEL&lt;br /&gt;
$ sudo apachectl restart    # if /usr/sbin is in your PATH (which it is by default in Debian, but not RHEL)&lt;br /&gt;
$ sudo /etc/init.d/httpd restart   # on RHEL&lt;br /&gt;
$ sudo /etc/init.d/apache2 restart   # on Debian&lt;br /&gt;
$ sudo /sbin/service httpd restart   # on RHEL&lt;br /&gt;
$ sudo /usr/sbin/service apache2 restart   # on Debian&lt;br /&gt;
$ sudo service httpd restart    # on RHEL&lt;br /&gt;
$ sudo service apache2 restart    # on Debian&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you're torn for which version is the &amp;quot;best&amp;quot; to use, the commands involving '''apachectl''' (think &amp;quot;Apache Control&amp;quot;) are written by the Apache folks themselves.  This has a couple advantages:&lt;br /&gt;
* They show you errors in the startup process (if there are any)&lt;br /&gt;
* They give you the option to perform a &amp;quot;soft&amp;quot; restart; that is, a restart that allows any pending connections to complete.  To perform a soft restart, use ''graceful'': &amp;lt;code&amp;gt;sudo apachectl graceful&amp;lt;/code&amp;gt;&lt;br /&gt;
In my anecdotal experience, the '''apachectl''' commands are also faster than the '''service''' or '''init.d''' commands.&lt;br /&gt;
&lt;br /&gt;
To make sure everything is working, create a test file in your home directory under public_html, and then point your browser to it: http://ec2-xxx-xx-xx-xxx.compute-1.amazonaws.com/~yourUserName/hello.txt&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 2]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Choosing_a_Platform&amp;diff=1699</id>
		<title>Choosing a Platform</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Choosing_a_Platform&amp;diff=1699"/>
		<updated>2014-01-11T12:00:59Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* PHP Pros */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;You've learned a large variety of platforms in this course.  Which one should you use?  This page summarizes some of the pros and cons of each platform.&lt;br /&gt;
&lt;br /&gt;
== PHP ==&lt;br /&gt;
&lt;br /&gt;
[[PHP]] is a language built for server-side web development.  You built a [[Module 2|file sharing application]] and a [[Module 3|news syndication site]] in PHP.&lt;br /&gt;
&lt;br /&gt;
=== PHP Pros ===&lt;br /&gt;
&lt;br /&gt;
* '''Largest support community:''' Easy to find help if you get stuck.&lt;br /&gt;
* '''Distribution:''' Runs on virtually any web server in existence.&lt;br /&gt;
* '''Easy to Debug:''' Because there is no framework involved and the PHP interpreter is robust, it is easier to pinpoint bugs and wrap your head around what is going on behind the scenes.&lt;br /&gt;
&lt;br /&gt;
=== PHP Cons ===&lt;br /&gt;
&lt;br /&gt;
* '''Language:''' Few people will say that PHP is the most elegant language known to mankind.  The language makes it easy to fall into the trap of bad coding practices.&lt;br /&gt;
* '''Security:''' PHP does very little for you automatically in terms of web security.&lt;br /&gt;
&lt;br /&gt;
== Django ==&lt;br /&gt;
&lt;br /&gt;
[[Web Frameworks|Django]] is a web frameworks written in the [[Python]] scripting language.  In more ways than not, it is the Python equivalent of [[wikipedia:Ruby on Rails|Ruby on Rails]].&lt;br /&gt;
&lt;br /&gt;
=== Django Pros ===&lt;br /&gt;
&lt;br /&gt;
* '''Less Code:''' Implementing common web design patterns, like social login or commenting, is usually as easy as a ''pip install''.&lt;br /&gt;
* '''Conventions:''' Django forces you to write neat and organized code, leading to better software engineering practices and scalability down the road.&lt;br /&gt;
* '''Security:''' Django automatically implements common security practices, leading to a more robust web application.&lt;br /&gt;
&lt;br /&gt;
=== Django Cons ===&lt;br /&gt;
&lt;br /&gt;
* '''Difficult to Debug:''' Django's high level of abstraction is a double-edged sword, because bugs and errors are sometimes difficult to find and can take hours to fix.&lt;br /&gt;
* '''Heavyweight:''' Django is designed for larger web applications, and it is not suitable for smaller projects with just one or two controllers.&lt;br /&gt;
&lt;br /&gt;
== Bottle and Flask ==&lt;br /&gt;
&lt;br /&gt;
Bottle is a web ''microframework'' written in the [[Python]] scripting language.  Flask is similar option.  Although you did not explicitly use Bottle or Flask during a module, it's worth listing on this page.  In more ways than not, Bottle and Flask are the Python equivalents of the better-known [[wikipedia:Sinatra (software)|Sinatra]], a Ruby microframework.&lt;br /&gt;
&lt;br /&gt;
=== Bottle and Flask Pros ===&lt;br /&gt;
&lt;br /&gt;
* '''Lightweight:''' There are few enough files that you can find your way around and be in full control of your application logic.&lt;br /&gt;
* '''Access to Python Libraries:''' A lot of the things you do in Django you can do in Bottle and Flask, except that you have more control over the ways that they are implemented.&lt;br /&gt;
&lt;br /&gt;
=== Bottle and Flask Cons ===&lt;br /&gt;
&lt;br /&gt;
* '''Lack of Conventions:''' Bottle and Flask give you the tools you need to build maintainable code, but unlike Django, they don't force you to.  It's easy to end up with Python scripts containing hundreds of lines of unrelated application logic.&lt;br /&gt;
&lt;br /&gt;
== Node.JS and Express ==&lt;br /&gt;
&lt;br /&gt;
[[Node.JS]] is a low-level implementation of JavaScript that enables you to write networked and web applications.  Express is a Sinatra-like microframework that runs on top of Node.jS.&lt;br /&gt;
&lt;br /&gt;
It is also worth bringing your attention to [http://www.meteor.com/ Meteor], a bleeding-edge framework for Node.JS that abstracts away client-server communications.  (Watch the promo video; it's pretty awesome.)&lt;br /&gt;
&lt;br /&gt;
=== Node.JS Pros ===&lt;br /&gt;
&lt;br /&gt;
* '''Speed:''' Node.JS is the fastest of the options on this page.  It is easy to scale up your Node.JS applications.&lt;br /&gt;
* '''Modern:''' Node.JS is also the newest of the options on this page, so most of the plugins you find for it use the best and latest practices.&lt;br /&gt;
* '''Language:''' With Node.JS, you can use just one language for both your server-side and client-side logic.&lt;br /&gt;
* '''Real-Time Options:''' Node.JS enables you to write real-time applications with ease, for example, with Socket.IO.&lt;br /&gt;
&lt;br /&gt;
=== Node.JS Cons ===&lt;br /&gt;
&lt;br /&gt;
* '''Lack of Conventions:''' Like Bottle, Flask, and most other microframeworks, Node.JS and Express don't force you to stick to predefined conventions, giving the potential to build messy code.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 8]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Choosing_a_Platform&amp;diff=1698</id>
		<title>Choosing a Platform</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Choosing_a_Platform&amp;diff=1698"/>
		<updated>2014-01-11T11:58:18Z</updated>

		<summary type="html">&lt;p&gt;Shane: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;You've learned a large variety of platforms in this course.  Which one should you use?  This page summarizes some of the pros and cons of each platform.&lt;br /&gt;
&lt;br /&gt;
== PHP ==&lt;br /&gt;
&lt;br /&gt;
[[PHP]] is a language built for server-side web development.  You built a [[Module 2|file sharing application]] and a [[Module 3|news syndication site]] in PHP.&lt;br /&gt;
&lt;br /&gt;
=== PHP Pros ===&lt;br /&gt;
&lt;br /&gt;
* '''Largest support community:''' Easy to find help if you get stuck.&lt;br /&gt;
* '''Distribution:''' Runs on virtually any web server in existence.&lt;br /&gt;
* '''Easy to Debug:''' Because there is no framework involved and the PHP interpreter is well maintained, it is easier to pinpoint bugs and wrap your head around what is going on behind the scenes.&lt;br /&gt;
&lt;br /&gt;
=== PHP Cons ===&lt;br /&gt;
&lt;br /&gt;
* '''Language:''' Few people will say that PHP is the most elegant language known to mankind.  The language makes it easy to fall into the trap of bad coding practices.&lt;br /&gt;
* '''Security:''' PHP does very little for you automatically in terms of web security.&lt;br /&gt;
&lt;br /&gt;
== Django ==&lt;br /&gt;
&lt;br /&gt;
[[Web Frameworks|Django]] is a web frameworks written in the [[Python]] scripting language.  In more ways than not, it is the Python equivalent of [[wikipedia:Ruby on Rails|Ruby on Rails]].&lt;br /&gt;
&lt;br /&gt;
=== Django Pros ===&lt;br /&gt;
&lt;br /&gt;
* '''Less Code:''' Implementing common web design patterns, like social login or commenting, is usually as easy as a ''pip install''.&lt;br /&gt;
* '''Conventions:''' Django forces you to write neat and organized code, leading to better software engineering practices and scalability down the road.&lt;br /&gt;
* '''Security:''' Django automatically implements common security practices, leading to a more robust web application.&lt;br /&gt;
&lt;br /&gt;
=== Django Cons ===&lt;br /&gt;
&lt;br /&gt;
* '''Difficult to Debug:''' Django's high level of abstraction is a double-edged sword, because bugs and errors are sometimes difficult to find and can take hours to fix.&lt;br /&gt;
* '''Heavyweight:''' Django is designed for larger web applications, and it is not suitable for smaller projects with just one or two controllers.&lt;br /&gt;
&lt;br /&gt;
== Bottle and Flask ==&lt;br /&gt;
&lt;br /&gt;
Bottle is a web ''microframework'' written in the [[Python]] scripting language.  Flask is similar option.  Although you did not explicitly use Bottle or Flask during a module, it's worth listing on this page.  In more ways than not, Bottle and Flask are the Python equivalents of the better-known [[wikipedia:Sinatra (software)|Sinatra]], a Ruby microframework.&lt;br /&gt;
&lt;br /&gt;
=== Bottle and Flask Pros ===&lt;br /&gt;
&lt;br /&gt;
* '''Lightweight:''' There are few enough files that you can find your way around and be in full control of your application logic.&lt;br /&gt;
* '''Access to Python Libraries:''' A lot of the things you do in Django you can do in Bottle and Flask, except that you have more control over the ways that they are implemented.&lt;br /&gt;
&lt;br /&gt;
=== Bottle and Flask Cons ===&lt;br /&gt;
&lt;br /&gt;
* '''Lack of Conventions:''' Bottle and Flask give you the tools you need to build maintainable code, but unlike Django, they don't force you to.  It's easy to end up with Python scripts containing hundreds of lines of unrelated application logic.&lt;br /&gt;
&lt;br /&gt;
== Node.JS and Express ==&lt;br /&gt;
&lt;br /&gt;
[[Node.JS]] is a low-level implementation of JavaScript that enables you to write networked and web applications.  Express is a Sinatra-like microframework that runs on top of Node.jS.&lt;br /&gt;
&lt;br /&gt;
It is also worth bringing your attention to [http://www.meteor.com/ Meteor], a bleeding-edge framework for Node.JS that abstracts away client-server communications.  (Watch the promo video; it's pretty awesome.)&lt;br /&gt;
&lt;br /&gt;
=== Node.JS Pros ===&lt;br /&gt;
&lt;br /&gt;
* '''Speed:''' Node.JS is the fastest of the options on this page.  It is easy to scale up your Node.JS applications.&lt;br /&gt;
* '''Modern:''' Node.JS is also the newest of the options on this page, so most of the plugins you find for it use the best and latest practices.&lt;br /&gt;
* '''Language:''' With Node.JS, you can use just one language for both your server-side and client-side logic.&lt;br /&gt;
* '''Real-Time Options:''' Node.JS enables you to write real-time applications with ease, for example, with Socket.IO.&lt;br /&gt;
&lt;br /&gt;
=== Node.JS Cons ===&lt;br /&gt;
&lt;br /&gt;
* '''Lack of Conventions:''' Like Bottle, Flask, and most other microframeworks, Node.JS and Express don't force you to stick to predefined conventions, giving the potential to build messy code.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 8]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Choosing_a_Platform&amp;diff=1697</id>
		<title>Choosing a Platform</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Choosing_a_Platform&amp;diff=1697"/>
		<updated>2014-01-11T11:55:32Z</updated>

		<summary type="html">&lt;p&gt;Shane: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;You've learned a large variety of platforms in this course.  Which one should you use?  This page summarizes some of the pros and cons of each platform.&lt;br /&gt;
&lt;br /&gt;
== PHP ==&lt;br /&gt;
&lt;br /&gt;
[[PHP]] is a language built for server-side web development.  You built a [[Module 2|file sharing application]] and a [[Module 3|news syndication site]] in PHP.&lt;br /&gt;
&lt;br /&gt;
=== PHP Pros ===&lt;br /&gt;
&lt;br /&gt;
* '''Largest support community:''' Easy to find help if you get stuck.&lt;br /&gt;
* '''Distribution:''' Runs on virtually any web server in existence.&lt;br /&gt;
* '''Simplicity:''' More than any of the other options, PHP is easy to develop.&lt;br /&gt;
&lt;br /&gt;
=== PHP Cons ===&lt;br /&gt;
&lt;br /&gt;
* '''Language:''' Few people will say that PHP is the most elegant language known to mankind.  The language makes it easy to fall into the trap of bad coding practices.&lt;br /&gt;
* '''Security:''' PHP does very little for you automatically in terms of web security.&lt;br /&gt;
&lt;br /&gt;
== Django ==&lt;br /&gt;
&lt;br /&gt;
[[Web Frameworks|Django]] is a web frameworks written in the [[Python]] scripting language.  In more ways than not, it is the Python equivalent of [[wikipedia:Ruby on Rails|Ruby on Rails]].&lt;br /&gt;
&lt;br /&gt;
=== Django Pros ===&lt;br /&gt;
&lt;br /&gt;
* '''Less Code:''' Implementing common web design patterns, like social login or commenting, is usually as easy as a ''pip install''.&lt;br /&gt;
* '''Conventions:''' Django forces you to write neat and organized code, leading to better software engineering practices and scalability down the road.&lt;br /&gt;
* '''Security:''' Django automatically implements common security practices, leading to a more robust web application.&lt;br /&gt;
&lt;br /&gt;
=== Django Cons ===&lt;br /&gt;
&lt;br /&gt;
* '''Difficult to Debug:''' Django's high level of abstraction is a double-edged sword, because bugs and errors are sometimes difficult to find and can take hours to fix.&lt;br /&gt;
* '''Heavyweight:''' Django is designed for larger web applications, and it is not suitable for smaller projects with just one or two controllers.&lt;br /&gt;
&lt;br /&gt;
== Bottle and Flask ==&lt;br /&gt;
&lt;br /&gt;
Bottle is a web ''microframework'' written in the [[Python]] scripting language.  Flask is similar option.  Although you did not explicitly use Bottle or Flask during a module, it's worth listing on this page.  In more ways than not, Bottle and Flask are the Python equivalents of the better-known [[wikipedia:Sinatra (software)|Sinatra]], a Ruby microframework.&lt;br /&gt;
&lt;br /&gt;
=== Bottle and Flask Pros ===&lt;br /&gt;
&lt;br /&gt;
* '''Lightweight:''' There are few enough files that you can find your way around and be in full control of your application logic.&lt;br /&gt;
* '''Access to Python Libraries:''' A lot of the things you do in Django you can do in Bottle and Flask, except that you have more control over the ways that they are implemented.&lt;br /&gt;
&lt;br /&gt;
=== Bottle and Flask Cons ===&lt;br /&gt;
&lt;br /&gt;
* '''Lack of Conventions:''' Bottle and Flask give you the tools you need to build maintainable code, but unlike Django, they don't force you to.  It's easy to end up with Python scripts containing hundreds of lines of unrelated application logic.&lt;br /&gt;
&lt;br /&gt;
== Node.JS and Express ==&lt;br /&gt;
&lt;br /&gt;
[[Node.JS]] is a low-level implementation of JavaScript that enables you to write networked and web applications.  Express is a Sinatra-like microframework that runs on top of Node.jS.&lt;br /&gt;
&lt;br /&gt;
It is also worth bringing your attention to [http://www.meteor.com/ Meteor], a bleeding-edge framework for Node.JS that abstracts away client-server communications.  (Watch the promo video; it's pretty awesome.)&lt;br /&gt;
&lt;br /&gt;
=== Node.JS Pros ===&lt;br /&gt;
&lt;br /&gt;
* '''Speed:''' Node.JS is the fastest of the options on this page.  It is easy to scale up your Node.JS applications.&lt;br /&gt;
* '''Modern:''' Node.JS is also the newest of the options on this page, so most of the plugins you find for it use the best and latest practices.&lt;br /&gt;
* '''Language:''' With Node.JS, you can use just one language for both your server-side and client-side logic.&lt;br /&gt;
* '''Real-Time Options:''' Node.JS enables you to write real-time applications with ease, for example, with Socket.IO.&lt;br /&gt;
&lt;br /&gt;
=== Node.JS Cons ===&lt;br /&gt;
&lt;br /&gt;
* '''Lack of Conventions:''' Like Bottle, Flask, and most other microframeworks, Node.JS and Express don't force you to stick to predefined conventions, giving the potential to build messy code.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 8]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Regular_Expressions&amp;diff=1696</id>
		<title>Regular Expressions</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Regular_Expressions&amp;diff=1696"/>
		<updated>2014-01-11T11:53:05Z</updated>

		<summary type="html">&lt;p&gt;Shane: Adding Regex XKCD&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Is this string a phone number?  Is it an e-mail address?  Is it a URL?  How do I parse the time of day out of this date string?  How do I find all words in the string that contain the letter &amp;quot;a&amp;quot;?&lt;br /&gt;
&lt;br /&gt;
The tool we use to answer these questions is '''regular expressions'''.  Regular expressions are a powerhouse for string matching.&lt;br /&gt;
&lt;br /&gt;
This guide serves as an introduction to regular expressions.  However, there is enough to discuss about them that regular expressions could be their ''own class''.  We will only be scratching the surface so that you can get up and running with regular expressions and start to use them in your projects.&lt;br /&gt;
&lt;br /&gt;
{{XKCD&lt;br /&gt;
|name=regex_golf&lt;br /&gt;
|id=1313&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
== Testing Regular Expressions ==&lt;br /&gt;
&lt;br /&gt;
There are several tools freely available online to assist you when writing regular expressions.  In this wiki, we will be using two:&lt;br /&gt;
&lt;br /&gt;
* '''[http://regexpal.com/ RegExPal]:''' Performs a global search on an input string.  Best for writing regular expressions used for parsing text.&lt;br /&gt;
* '''[http://www.debuggex.com/ Debuggex]:''' Matches a regular expression against the input string, but does not support searches.  Shows a schematic to help you understand what your regular expression is doing.  Best for fine-tuning regular expressions that act on known input formats.&lt;br /&gt;
&lt;br /&gt;
You can view all regular expressions on this page in RegExPal or Debuggex by pressing &amp;quot;View in _____&amp;quot; above each example.&lt;br /&gt;
&lt;br /&gt;
== Your First Regular Expression ==&lt;br /&gt;
&lt;br /&gt;
Here we go.  If you wish to follow along, click &amp;quot;View in RegExPal&amp;quot; below; Debuggex does not work well for this example.&lt;br /&gt;
&lt;br /&gt;
{{RegexExample&lt;br /&gt;
|regex=\b\ware\b&lt;br /&gt;
|str=The tortoise and the hare took on a dare to find the rare Aare.&lt;br /&gt;
|method=regexpal&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
This regular expression finds all words of the form &amp;quot;_are&amp;quot;, where _ is an alphanumeric character, and matches that first letter.  Let's go through the parts of this regular expression.&lt;br /&gt;
&lt;br /&gt;
* '''\b''' means &amp;quot;word boundary&amp;quot;.  If we didn't have the '''\b''''s, then this regular expression would also match words like &amp;quot;dayc'''are'''&amp;quot; or &amp;quot;app'''are'''l&amp;quot; or &amp;quot;'''are'''st&amp;quot;.&lt;br /&gt;
* '''\w''' means &amp;quot;any alphanumeric character or underscore&amp;quot;.  Thus, this regular expression will match '''dare''', '''care''', '''zare''', '''5are''', '''_are''', and so on.&lt;br /&gt;
* '''are''' are literal characters in the regular expression.&lt;br /&gt;
&lt;br /&gt;
Here is a little animation to help you visualize how this regular expression is assembled:&lt;br /&gt;
&lt;br /&gt;
[[File:RegexExampleAnimation-32.gif]]&lt;br /&gt;
&lt;br /&gt;
== Regular Expression Syntax ==&lt;br /&gt;
&lt;br /&gt;
Character classes and modifiers enable you to fine-tune your matches..&lt;br /&gt;
&lt;br /&gt;
=== Character Classes ===&lt;br /&gt;
&lt;br /&gt;
A '''character class''' enables you to match any one of a set of characters.  Surround your characters of interest in square brackets.&lt;br /&gt;
&lt;br /&gt;
The following regular expression matches all occurrences of a vowel:&lt;br /&gt;
&lt;br /&gt;
{{RegexExample&lt;br /&gt;
|regex=[aeiou]&lt;br /&gt;
|str=The quick brown fox jumps over the lazy dog.&lt;br /&gt;
|method=regexpal&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Character classes can be ''negated'' by starting the character set with a caret '''^'''.  For example, the following regular expression matches all occurrences of a consonant:&lt;br /&gt;
&lt;br /&gt;
{{RegexExample&lt;br /&gt;
|regex=[^aeiou\W]&lt;br /&gt;
|str=The quick brown fox jumps over the lazy dog.&lt;br /&gt;
|method=regexpal&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The '''\W''' is a shorthand character class that prevents the above regular expression from also matching non-word characters.&lt;br /&gt;
&lt;br /&gt;
=== Shorthand Character Classes ===&lt;br /&gt;
&lt;br /&gt;
Some character classes are provided for you by default.&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;text-align:center; font-size:1.2em;&amp;quot; cellpadding=&amp;quot;10&amp;quot;&lt;br /&gt;
!Description&lt;br /&gt;
!Literal Character Class&lt;br /&gt;
!Shorthand&lt;br /&gt;
|-&lt;br /&gt;
|Digit&lt;br /&gt;
|[0-9]&lt;br /&gt;
|\d&lt;br /&gt;
|-&lt;br /&gt;
|Word Character&lt;br /&gt;
|[A-Za-z0-9_]&lt;br /&gt;
|\w&lt;br /&gt;
|-&lt;br /&gt;
|Whitespace&lt;br /&gt;
|[ \t\r\n]&lt;br /&gt;
|\s&lt;br /&gt;
|-&lt;br /&gt;
|Non-Digit&lt;br /&gt;
|[^0-9]&lt;br /&gt;
|\D&lt;br /&gt;
|-&lt;br /&gt;
|Non-Word Character&lt;br /&gt;
|[^A-Za-z0-9_]&lt;br /&gt;
|\W&lt;br /&gt;
|-&lt;br /&gt;
|Non-Whitespace&lt;br /&gt;
|[^ \t\r\n]&lt;br /&gt;
|\S&lt;br /&gt;
|-&lt;br /&gt;
|Wildcard character except for line breaks&lt;br /&gt;
|[^\r\n]&lt;br /&gt;
|.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=== Quantifiers ===&lt;br /&gt;
&lt;br /&gt;
For a character, character class, or group, you can specify a required number of occurrences.&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;text-align:center; font-size:1.2em;&amp;quot; cellpadding=&amp;quot;10&amp;quot;&lt;br /&gt;
!Description&lt;br /&gt;
!Syntax&lt;br /&gt;
!Example&lt;br /&gt;
|-&lt;br /&gt;
|Zero or more of&lt;br /&gt;
| *&lt;br /&gt;
|Match any string, even the empty string: &amp;lt;code&amp;gt;.*&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
|One or more of&lt;br /&gt;
| +&lt;br /&gt;
|Match any string, except for the empty string: &amp;lt;code&amp;gt;.+&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
|Zero or one of&lt;br /&gt;
| ?&lt;br /&gt;
|Match either &amp;quot;color&amp;quot; or &amp;quot;colour&amp;quot;: &amp;lt;code&amp;gt;colou?r&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
|''N'' of&lt;br /&gt;
| {N}&lt;br /&gt;
|Match all three-digit numbers: &amp;lt;code&amp;gt;\b\d{3}\b&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
|Between ''M'' and ''N'' of&lt;br /&gt;
| {M,N}&lt;br /&gt;
|Match all two- or three-digit numbers: &amp;lt;code&amp;gt;\b\d{2,3}\b&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
==== Greedy and Lazy Quantifiers ====&lt;br /&gt;
&lt;br /&gt;
By default, the '''*''' and '''+''' quantifiers are '''greedy''': this means that they will continue searching until the end of the string if they can.  More often, however, you want them to stop as soon as something matching the next part of your regular expression is found.  This is where '''lazy''' modifiers come into play.&lt;br /&gt;
&lt;br /&gt;
To make '''*''' or '''+''' lazy, simply add a '''?''', as in '''*?''' and '''+?'''.&lt;br /&gt;
&lt;br /&gt;
For example, you might write the following regular expression to match all HTML tags (view in RegExPal to follow along):&lt;br /&gt;
&lt;br /&gt;
{{RegexExample&lt;br /&gt;
|regex=&amp;lt;.+&amp;gt;&lt;br /&gt;
|str=Hello &amp;lt;p&amp;gt;&amp;lt;strong&amp;gt;Roses&amp;lt;/strong&amp;gt; are &amp;lt;em class=&amp;quot;red&amp;quot;&amp;gt;Red&amp;lt;/em&amp;gt;&amp;lt;/p&amp;gt; Goodbye&lt;br /&gt;
|method=regexpal&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
However, this will not separately match the HTML tags; instead, it will start from the first occurrence of '''&amp;lt;''' and continue until the ''last'' occurrence of '''&amp;gt;'''.  This is the ''greedy'' behavior.  The following regular expression will perform what you want:&lt;br /&gt;
&lt;br /&gt;
{{RegexExample&lt;br /&gt;
|regex=&amp;lt;.+?&amp;gt;&lt;br /&gt;
|str=Hello &amp;lt;p&amp;gt;&amp;lt;strong&amp;gt;Roses&amp;lt;/strong&amp;gt; are &amp;lt;em class=&amp;quot;red&amp;quot;&amp;gt;Red&amp;lt;/em&amp;gt;&amp;lt;/p&amp;gt; Goodbye&lt;br /&gt;
|method=regexpal&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Now, the match will stop as soon as a '''&amp;gt;''' is encountered.&lt;br /&gt;
&lt;br /&gt;
=== Anchors ===&lt;br /&gt;
&lt;br /&gt;
If your regular expression begins with a cared '''^''', you will generate only one match, which must be at the beginning of the string.  If your regular expression ends with a dollar sign '''$''', you will generate only one match, which must be at the end of the string.  If your regular expression starts with a '''^''' ''and'' ends with a '''$''', you will match if and only if the entire string matches the entire regular expression.&lt;br /&gt;
&lt;br /&gt;
For example, the following regular expression generates a match on all strings that start with a capital letter:&lt;br /&gt;
&lt;br /&gt;
{{RegexExample&lt;br /&gt;
|regex=^[A-Z]&lt;br /&gt;
|str=Hello World&lt;br /&gt;
|method=regexpal&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The following regular expression tests whether the entire string is a valid US phone number:&lt;br /&gt;
&lt;br /&gt;
{{RegexExample&lt;br /&gt;
|regex=^\d{3}-\d{3}-\d{4}$&lt;br /&gt;
|str=314-935-5555&lt;br /&gt;
|method=regexpal&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
=== Groups ===&lt;br /&gt;
&lt;br /&gt;
'''Groups''' enable you to perform operations on multi-character strings.  To specify a group, surround it with parentheses '''()'''.&lt;br /&gt;
&lt;br /&gt;
For example, the following regular expression crudely matches a domain name:&lt;br /&gt;
&lt;br /&gt;
{{RegexExample&lt;br /&gt;
|regex=[\w\-]+(\.[\w\-]+)+&lt;br /&gt;
|str=example.co.uk&lt;br /&gt;
|method=debuggex&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
First, we match one or more word character or hyphen, and then we match one or more suffixes, each suffix consisting of a period followed by one or more word characters.&lt;br /&gt;
&lt;br /&gt;
== Regular Expression Examples ==&lt;br /&gt;
&lt;br /&gt;
You know know enough to write some pretty sophisticated regular expressions.&lt;br /&gt;
&lt;br /&gt;
Can you figure out what the following regular expression matches?&lt;br /&gt;
&lt;br /&gt;
{{RegexExample&lt;br /&gt;
|regex=^[\w!#$%&amp;amp;'*+/=?^_`{}~-]+@[\w\-]+(\.[\w\-]+)+$&lt;br /&gt;
|str=me@example.com&lt;br /&gt;
|method=debuggex&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
If you guessed &amp;quot;e-mail address&amp;quot;, you are correct!  You can recognize that our domain-name regular expression has been copied after the &amp;quot;@&amp;quot; sign, and before the &amp;quot;@&amp;quot; sign is simply one or more of an alphanumeric or a handful of other characters.  We also surrounded the regex with '''^''' and '''$''' to ensure that we match the entire string.&lt;br /&gt;
&lt;br /&gt;
Can you guess this one?&lt;br /&gt;
&lt;br /&gt;
{{RegexExample&lt;br /&gt;
|regex=^\d{1,3}(\.\d{1,3}){3}$&lt;br /&gt;
|str=128.252.202.246&lt;br /&gt;
|method=debuggex&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
This will match an IP address (IPv3).  We use the quantifier-on-group trick like we did earlier when we matched valid domain names.&lt;br /&gt;
&lt;br /&gt;
Note: Both of these examples are crude.  You should use formal regular expressions issued by organizations like the IETF when matching e-mail addresses and the like.&lt;br /&gt;
&lt;br /&gt;
== Groups ==&lt;br /&gt;
&lt;br /&gt;
One use of regular expressions is when you want to extract information of a known format out of a string.  This is when ''groups'' come into play.&lt;br /&gt;
&lt;br /&gt;
For example, consider the phone number expression from before.  Suppose we test it against the phone number &amp;quot;123-456-7890&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
{{RegexExample&lt;br /&gt;
|regex=\d{3}-(\d{3})-\d{4}&lt;br /&gt;
|str=123-456-7890&lt;br /&gt;
|method=debuggex&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Notice how we put parentheses around the second set of digits.  This makes the second set of digits a ''group''.  View the regular expressin in Debuggex, and you can see how the second set of numbers in the phone number is matched as the group.&lt;br /&gt;
&lt;br /&gt;
What happens if we put parentheses around all three?&lt;br /&gt;
&lt;br /&gt;
{{RegexExample&lt;br /&gt;
|regex=(\d{3})-(\d{3})-(\d{4})&lt;br /&gt;
|str=123-456-7890&lt;br /&gt;
|method=debuggex&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
We now have ''three'' groups matched:&lt;br /&gt;
&lt;br /&gt;
# '''123'''&lt;br /&gt;
# '''456'''&lt;br /&gt;
# '''7890'''&lt;br /&gt;
&lt;br /&gt;
We can also have groups within other groups.  For example, we could match the area code (the first set), the office code (the second set), the station code (the third set), and the subscriber code (the second and third sets combined):&lt;br /&gt;
&lt;br /&gt;
{{RegexExample&lt;br /&gt;
|regex=(\d{3})-((\d{3})-(\d{4}))&lt;br /&gt;
|str=123-456-7890&lt;br /&gt;
|method=debuggex&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Open that in Debuggex to visualize how the groups are formed.&lt;br /&gt;
&lt;br /&gt;
Different programming languages all have different ways to extract groups from a match.  These different methods are documented in the next section.&lt;br /&gt;
&lt;br /&gt;
=== Non-Capturing Groups ===&lt;br /&gt;
&lt;br /&gt;
You can ignore certain groups from being matched by appending '''?:''' to the start of the parentheses.  For example, if you wanted to ignore matches from the group in the URL regex we made above, you would add '''?:''' in the correct spot:&lt;br /&gt;
&lt;br /&gt;
{{RegexExample&lt;br /&gt;
|regex=[\w\-]+(?:\.[\w\-]+)+&lt;br /&gt;
|str=bbc.co.uk&lt;br /&gt;
|method=debuggex&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
== Using Regular Expressions in Programming Languages ==&lt;br /&gt;
&lt;br /&gt;
You are learning three new programming languages in CSE 330: [[PHP]] (from Module 2), [[Python]] (from Module 4), and [[JavaScript]] (from Module 6).  Below, you may find how to implement regular expressions in each of these three languages.&lt;br /&gt;
&lt;br /&gt;
The example is a function that tests whether a string matches a regular expression representing an e-mail address, and if it does, the function returns the domain name from the e-mail.&lt;br /&gt;
&lt;br /&gt;
=== PHP ===&lt;br /&gt;
&lt;br /&gt;
The magic function in PHP is '''preg_match($regex, $str, $matches)''', where ''$regex'' is the regular expression, ''$str'' is the string to test, and ''$matches'' is an extra argument which will be modified to contain the matches array.  By convention, the regular expression itself must be surrounded in forward slashes.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;PHP&amp;quot;&amp;gt;&lt;br /&gt;
function domain_from_email($str){&lt;br /&gt;
	$email_regex = &amp;quot;/^[\w!#$%&amp;amp;'*+\/=?^_`{|}~-]+@([\w\-]+(?:\.[\w\-]+)+)$/&amp;quot;;&lt;br /&gt;
	if(preg_match($email_regex, $str, $matches)){&lt;br /&gt;
		return $matches[1];&lt;br /&gt;
	} else return false;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
echo domain_from_email(&amp;quot;sam@bbc.co.uk&amp;quot;); // bbc.co.uk&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you want to perform a global search for ''all'' matches of a regular expression, use '''preg_match_all($regex, $str, $matches)''' instead.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;PHP&amp;quot;&amp;gt;&lt;br /&gt;
function find_all_email_domains($str){&lt;br /&gt;
	$email_regex = &amp;quot;/\b[\w!#$%&amp;amp;'*+\/=?^_`{|}~-]+@([\w\-]+(?:\.[\w\-]+)+)\b/&amp;quot;;&lt;br /&gt;
	preg_match_all($email_regex, $str, $matches);&lt;br /&gt;
	return $matches[1];&lt;br /&gt;
}&lt;br /&gt;
 &lt;br /&gt;
print_r(find_all_email_domains(&amp;quot;sam@bbc.co.uk, julie@amazon.com, rick@wustl.edu&amp;quot;));&lt;br /&gt;
// Array ( [0] =&amp;gt; bbc.co.uk [1] =&amp;gt; amazon.com [2] =&amp;gt; wustl.edu )&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Python ===&lt;br /&gt;
&lt;br /&gt;
To use regular expressions in Python, you need to import the '''re''' module.  From there, you can compile your regular expression and perform searches with it.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import re&lt;br /&gt;
&lt;br /&gt;
email_regex = re.compile(r&amp;quot;^[\w!#$%&amp;amp;'*+/=?^_`{|}~-]+@([\w\-]+(?:\.[\w\-]+)+)$&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
def domain_from_email(test):&lt;br /&gt;
	match = email_regex.match(test)&lt;br /&gt;
	if match is not None:&lt;br /&gt;
		return match.group(1)&lt;br /&gt;
	else:&lt;br /&gt;
		return False&lt;br /&gt;
&lt;br /&gt;
print(domain_from_email(&amp;quot;sam@bbc.co.uk&amp;quot;)) # bbc.co.uk&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that we prefix our regex string with an &amp;quot;r&amp;quot;, for a &amp;quot;raw string&amp;quot;.  This is to prevent Python from trying to parse special characters in our regular expression.&lt;br /&gt;
&lt;br /&gt;
To perform global searches, use the regex '''findall''' method:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import re&lt;br /&gt;
&lt;br /&gt;
email_regex = re.compile(r&amp;quot;\b[\w!#$%&amp;amp;'*+/=?^_`{|}~-]+@([\w\-]+(?:\.[\w\-]+)+)\b&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
def find_all_email_domains(test):&lt;br /&gt;
	return email_regex.findall(test)&lt;br /&gt;
&lt;br /&gt;
print(find_all_email_domains(&amp;quot;sam@bbc.co.uk, julie@amazon.com, rick@wustl.edu&amp;quot;))&lt;br /&gt;
# ['bbc.co.uk', 'amazon.com', 'wustl.edu']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In Python if you want to use the \b in a regex string (without declaring the string as raw) you need to use the \\b instead of \b . Consider the examples below, which provide the same output, the first uses the raw input parameter, the second does not.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import re&lt;br /&gt;
&lt;br /&gt;
re.match(r&amp;quot;\bhello world\b&amp;quot;,&amp;quot;hello world&amp;quot;).group()&lt;br /&gt;
&lt;br /&gt;
re.match(&amp;quot;\\bhello world\\b&amp;quot;,&amp;quot;hello world&amp;quot;).group()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== JavaScript ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=7dVfzg22ono&lt;br /&gt;
|time=3m58s&lt;br /&gt;
|desc=Basics of Regular Expressions.  Uses JavaScript as the language of focus.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Regular expressions in JavaScript are their own native data type, so native that they are expressed using literals surrounded with forward slashes and not even strings.&lt;br /&gt;
&lt;br /&gt;
To perform a simple match, call the '''test''' method on the regular expression:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
alert(/^\d+$/.test(&amp;quot;123&amp;quot;)); // true&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To find a match, call the '''exec''' method on the regular expression:&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=vpqV8n56J6w&lt;br /&gt;
|time=5m34s&lt;br /&gt;
|desc=Regular Expressions in JavaScript Part 2.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var emailRegex = /^[\w!#$%&amp;amp;'*+\/=?^_`{|}~-]+@([\w\-]+(?:\.[\w\-]+)+)$/&lt;br /&gt;
&lt;br /&gt;
function domainFromEmail(str){&lt;br /&gt;
	if(match=emailRegex.exec(str)){&lt;br /&gt;
		return match[1];&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(domainFromEmail(&amp;quot;sam@bbc.co.uk&amp;quot;)); // bbc.co.uk&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=WwsNPSO7J-I&lt;br /&gt;
|time=1m48s&lt;br /&gt;
|desc=Regular Expressions in JavaScript Part 3.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Continue calling the '''exec''' method to produce more matches:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var emailRegex = /\b[\w!#$%&amp;amp;'*+\/=?^_`{|}~-]+@([\w\-]+(?:\.[\w\-]+)+)\b/g&lt;br /&gt;
&lt;br /&gt;
function findAllEmailDomains(str){&lt;br /&gt;
	var matches = []&lt;br /&gt;
	while(match=emailRegex.exec(str)){&lt;br /&gt;
		matches.push(match[1]);&lt;br /&gt;
	}&lt;br /&gt;
	return matches;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(findAllEmailDomains(&amp;quot;sam@bbc.co.uk, julie@amazon.com, rick@wustl.edu&amp;quot;));&lt;br /&gt;
// bbc.co.uk,amazon.com,wustl.edu&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' In order to make the regular expression &amp;quot;searchable&amp;quot;, we need to add the '''g''' flag in its definition.  The flag goes after the closing forward slash.&lt;br /&gt;
&lt;br /&gt;
== Using Regular Expressions in Your Workflow ==&lt;br /&gt;
&lt;br /&gt;
Regular expressions aren't limited to use in programming languages.  In fact, you can use them ''right now'' in your text editor!&lt;br /&gt;
&lt;br /&gt;
In Komodo, go to '''File-&amp;gt;Find''', and in the dialog, select &amp;quot;Regex&amp;quot;.  Bam: whatever you type into the search box will be evaluated as a regular expression!  Here is an example where I find all end tags in my document:&lt;br /&gt;
&lt;br /&gt;
[[File:KomodoRegexSearch.jpg]]&lt;br /&gt;
&lt;br /&gt;
You can also do regular expression '''find and replace''' in Komodo.  You can use groups, too: in the &amp;quot;Replace with&amp;quot; box, a '''\1''' will insert your first group, a '''\2''' will insert your second group, and so on.  Nifty!&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 4]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Extensible_Calendar&amp;diff=1695</id>
		<title>Extensible Calendar</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Extensible_Calendar&amp;diff=1695"/>
		<updated>2014-01-04T07:39:05Z</updated>

		<summary type="html">&lt;p&gt;Shane: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page documents a tutorial for using the [http://ext.ensible.com/products/calendar/ Extensible Calendar Pro API] with Django as the back end.&lt;br /&gt;
&lt;br /&gt;
== REST ==&lt;br /&gt;
&lt;br /&gt;
The Extensible Calendar is going to connect to your server via AJAX calls.  These calls conform to a web application paradigm known as '''REST''', or ''REpresentational State Transfer''.  In particular, the application will automatically send requests with the following HTTP methods:&lt;br /&gt;
&lt;br /&gt;
* '''GET''' when it wants to read something&lt;br /&gt;
* '''POST''' when it wants to create something&lt;br /&gt;
* '''PUT''' when it wants to change something&lt;br /&gt;
* '''DELETE''' when it wants to remove something&lt;br /&gt;
&lt;br /&gt;
You recognize ''GET'' and ''POST'' from Module 2.  All along, there were actually more than just these two request methods.  REST simply takes advantage of all of them.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' In practice, since older browsers do not support the additional HTTP request methods required by REST, the actual implementation of ''PUT'' and ''DELETE'' will most likely be ''POST'' with an additional header defining the request type.  The frameworks takes care of this difference under the hood.&lt;br /&gt;
&lt;br /&gt;
== The Back End ==&lt;br /&gt;
&lt;br /&gt;
First, we will set up the back end.&lt;br /&gt;
&lt;br /&gt;
=== Creating the App with Source Control ===&lt;br /&gt;
&lt;br /&gt;
Start by making a new Django project and app.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ django-admin.py startproject cse330calendar&lt;br /&gt;
$ cd cse330calendar&lt;br /&gt;
$ python manage.py startapp cal&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Right now would be a good time to set up your IDE and source control.  Create a new Komodo project in the &amp;quot;cse330calendar&amp;quot; directory, and set up a repo on the &amp;quot;cse330calendar&amp;quot; in SourceTree.  Make frequent commits after each step of the process.&lt;br /&gt;
&lt;br /&gt;
=== Initial Configuration ===&lt;br /&gt;
&lt;br /&gt;
Go into ''settings.py'' and configure your database.&lt;br /&gt;
&lt;br /&gt;
Enable the admin panel, which requires editing both ''settings.py'' and ''urls.py''.  Add the ''cal'' application to the admin panel by creating ''cal/admin.py'' with the following content:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from django.contrib import admin&lt;br /&gt;
&lt;br /&gt;
# We will create these models in the next step&lt;br /&gt;
from cal.models import Cal, Event&lt;br /&gt;
&lt;br /&gt;
admin.site.register(Cal)&lt;br /&gt;
admin.site.register(Event)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, add &amp;quot;cal&amp;quot; to the INSTALLED_APPS list in ''settings.py''.&lt;br /&gt;
&lt;br /&gt;
=== Creating the Models ===&lt;br /&gt;
&lt;br /&gt;
Set up the models required for the Extensible Calendar.  We have already done this work for you.  Copy the following code into your ''cal/models.py'' file.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from django.db import models&lt;br /&gt;
&lt;br /&gt;
# Extensible wants two models: a &amp;quot;calendar&amp;quot; model and an &amp;quot;event&amp;quot; model.&lt;br /&gt;
# The &amp;quot;calendar&amp;quot; model represents a collection of events.  Note that the end&lt;br /&gt;
# application supports multiple calendars in the same view, with the events&lt;br /&gt;
# in each calendar having a different background color.&lt;br /&gt;
# &lt;br /&gt;
# First we will define our calendar model, `Cal`, and then we will define&lt;br /&gt;
# our event model, `Event`.&lt;br /&gt;
&lt;br /&gt;
class Cal(models.Model):&lt;br /&gt;
	# Title of the calendar&lt;br /&gt;
	title = models.CharField(max_length=50)&lt;br /&gt;
&lt;br /&gt;
	# Text description of the calendar&lt;br /&gt;
	description = models.CharField(max_length=200)&lt;br /&gt;
&lt;br /&gt;
	 # Color ID (1-32)&lt;br /&gt;
	color = models.IntegerField(default=1)&lt;br /&gt;
&lt;br /&gt;
	# Boolean for whether the calendar is hidden by default&lt;br /&gt;
	hidden = models.BooleanField(default=False)&lt;br /&gt;
&lt;br /&gt;
class Event(models.Model):&lt;br /&gt;
	# Declare a one-to-many relationship with Cal&lt;br /&gt;
	cal = models.ForeignKey(Cal)&lt;br /&gt;
&lt;br /&gt;
	# Title of the event&lt;br /&gt;
	title = models.CharField(max_length=50)&lt;br /&gt;
&lt;br /&gt;
	# DateTime of event start&lt;br /&gt;
	start = models.DateTimeField()&lt;br /&gt;
&lt;br /&gt;
	# DateTime of event end&lt;br /&gt;
	end = models.DateTimeField()&lt;br /&gt;
&lt;br /&gt;
	# Additional information that can be associated with an event:&lt;br /&gt;
	loc = models.CharField(max_length=50) # Location&lt;br /&gt;
	notes = models.CharField(max_length=200) # Notes&lt;br /&gt;
	url = models.CharField(max_length=100) # URL&lt;br /&gt;
	ad = models.BooleanField(default=False) # Is this an all-day event&lt;br /&gt;
	rem = models.CharField(max_length=200) # Reminder&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, sync the db.  After you do this, run the Django server and play around with the admin panel to make sure everything is in working order.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python manage.py syncdb&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Tastypie ===&lt;br /&gt;
&lt;br /&gt;
Django does not come with REST support out of the box, so we need to install an additional framework.  I have so far had success with '''[http://django-tastypie.readthedocs.org/en/latest/tutorial.html Tastypie]''', and I will be using Tastypie throughout this tutorial.&lt;br /&gt;
&lt;br /&gt;
Start by installing Tastypie.  There are instructions on the above link.&lt;br /&gt;
&lt;br /&gt;
Your ''cal/api.py'' file can contain simply:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from tastypie.resources import ModelResource&lt;br /&gt;
from tastypie.paginator import Paginator&lt;br /&gt;
from cal.models import Cal, Event&lt;br /&gt;
from tastypie.fields import ToOneField&lt;br /&gt;
&lt;br /&gt;
class CalResource(ModelResource):&lt;br /&gt;
	class Meta:&lt;br /&gt;
		queryset = Cal.objects.all()&lt;br /&gt;
		paginator_class = Paginator&lt;br /&gt;
&lt;br /&gt;
class EventResource(ModelResource):&lt;br /&gt;
	cid = ToOneField(CalResource, &amp;quot;cal&amp;quot;, full=True)&lt;br /&gt;
	class Meta:&lt;br /&gt;
		queryset = Event.objects.all()&lt;br /&gt;
		paginator_class = Paginator&lt;br /&gt;
		always_return_data = True&lt;br /&gt;
	def dehydrate_cid(self, bundle):&lt;br /&gt;
		return bundle.obj.cal.id&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above snippet, we also are installing the ''Paginator'' utility.  The Extensible Calendar requires that your data have pagination.&lt;br /&gt;
&lt;br /&gt;
You will be modifying this file later on in this tutorial.&lt;br /&gt;
&lt;br /&gt;
I also recommend making JSON the default output format for Tastypie.  To do this, add the following line to your ''settings.py'' file:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
TASTYPIE_DEFAULT_FORMATS = ['json']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
While you're inside ''settings.py'', go ahead and add the following line as well.  It may save you headaches down the road.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
APPEND_SLASH=True&lt;br /&gt;
TASTYPIE_ALLOW_MISSING_SLASH=False&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Routing ===&lt;br /&gt;
&lt;br /&gt;
Let's create an empty ''index.html'' for our site.  We will be modifying it later.  Create the file in ''cal/templates/cal/index.html''.  Then add it to ''cal/views.py'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from django.shortcuts import render&lt;br /&gt;
&lt;br /&gt;
def index(request):&lt;br /&gt;
    return render(request, 'cal/index.html', {})&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Also add it to ''cal/urls.py'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from django.conf.urls import patterns, url&lt;br /&gt;
&lt;br /&gt;
from cal import views&lt;br /&gt;
&lt;br /&gt;
urlpatterns = patterns('',&lt;br /&gt;
    url(r'^$', views.index, name='index')&lt;br /&gt;
)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, add ''cal'' to your core ''urls.py'' file, which by now should look something like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from django.conf.urls import patterns, include, url&lt;br /&gt;
from cal.api import CalResource, EventResource&lt;br /&gt;
&lt;br /&gt;
# Uncomment the next two lines to enable the admin:&lt;br /&gt;
from django.contrib import admin&lt;br /&gt;
admin.autodiscover()&lt;br /&gt;
&lt;br /&gt;
# RESTful setup:&lt;br /&gt;
cal_resource = CalResource()&lt;br /&gt;
event_resource = EventResource()&lt;br /&gt;
&lt;br /&gt;
urlpatterns = patterns('',&lt;br /&gt;
    # Admin page&lt;br /&gt;
    url(r'^admin/', include(admin.site.urls)),&lt;br /&gt;
&lt;br /&gt;
    # Templates&lt;br /&gt;
    url(r'^', include('cal.urls')),&lt;br /&gt;
&lt;br /&gt;
    # RESTful URLs&lt;br /&gt;
    url(r'^', include(cal_resource.urls)),&lt;br /&gt;
    url(r'^', include(event_resource.urls)),&lt;br /&gt;
)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Try launching [http://localhost:8000/cal/ http://localhost:8000/cal/] in your browser.  If everything is working properly, you should see a JSON representation of the data in your calendar.&lt;br /&gt;
&lt;br /&gt;
=== Additional Work on the Back End ===&lt;br /&gt;
&lt;br /&gt;
In the above example, we have implemented a read-only API for your calendar.  You will need to use Django Auth to add users and to only reveal those calendars associated with a user.  You will also need to implement the writing site of Tastypie.  Almost all of these steps are in the Tastypie documentation.&lt;br /&gt;
&lt;br /&gt;
== The Front End ==&lt;br /&gt;
&lt;br /&gt;
So far, all of our work has been setting up our database, models, and server API.  Now, we need to set up the front end that takes the JSON data and displays it in a GUI for the end user.&lt;br /&gt;
&lt;br /&gt;
=== Installing Extensible ===&lt;br /&gt;
&lt;br /&gt;
Start by downloading the Extensible library from the official web site.  Save the download in ''cal/static/vendor/extensible''.&lt;br /&gt;
&lt;br /&gt;
=== Extensible Config File ===&lt;br /&gt;
&lt;br /&gt;
Copy the file at ''cal/static/vendor/extensible/Extensible-config.js'' into the ''cal/static/cal'' directory.  Make the following changes:&lt;br /&gt;
&lt;br /&gt;
# Change the Ext JS version on line 59 from '''4.2.0''' to '''4.1.1'''&lt;br /&gt;
# Comment out the line that includes the ''examples.js'' file (around line 179)&lt;br /&gt;
&lt;br /&gt;
=== The Core Extensible Code ===&lt;br /&gt;
&lt;br /&gt;
The examples on the Extensible documentation are helpful, but if you have never used Ext.JS before, it is easy to get lost.  We have therefore written an ''index.html'' file and an ''app.js'' file to get you started.&lt;br /&gt;
&lt;br /&gt;
Put the following code in ''cal/templates/cal/index.html'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
{% load staticfiles %}&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
	&amp;lt;title&amp;gt;Calendar&amp;lt;/title&amp;gt;&lt;br /&gt;
	&amp;lt;script type=&amp;quot;text/javascript&amp;quot; src=&amp;quot;{% static 'cal/Extensible-config.js' %}&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;
	&amp;lt;script type=&amp;quot;text/javascript&amp;quot; src=&amp;quot;{% static 'cal/app.js' %}&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div id=&amp;quot;calbox&amp;quot; style=&amp;quot;width:600px; height:400px;&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;span id=&amp;quot;app-msg&amp;quot; class=&amp;quot;x-hidden&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Put the following code in ''cal/static/cal/app.js'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Demo Extensible Calendar App&lt;br /&gt;
// Created for CSE 330S by Shane Carr&lt;br /&gt;
// Washington University in St. Louis&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
// Ext.JS wants you to use `Ext.define` when making a custom component.&lt;br /&gt;
Ext.define(&amp;quot;CSE330.Calendar&amp;quot;, {&lt;br /&gt;
&lt;br /&gt;
	// List the classes we use inside this component.  This enables Ext.JS to load&lt;br /&gt;
	// the files containing the definitions for these classes more efficiently.&lt;br /&gt;
	requires: [],&lt;br /&gt;
&lt;br /&gt;
	// Main code for our component&lt;br /&gt;
	constructor: function(){&lt;br /&gt;
		// Set up the calendar store&lt;br /&gt;
		this.calendarStore = Ext.create(&amp;quot;Extensible.calendar.data.MemoryCalendarStore&amp;quot;, {&lt;br /&gt;
			autoLoad: true,&lt;br /&gt;
			storeId: &amp;quot;Calendars&amp;quot;,&lt;br /&gt;
			proxy: {&lt;br /&gt;
				type: &amp;quot;rest&amp;quot;,&lt;br /&gt;
				url: &amp;quot;/cal/&amp;quot;,&lt;br /&gt;
				startParam: &amp;quot;offset&amp;quot;,&lt;br /&gt;
				reader: {&lt;br /&gt;
					type: &amp;quot;json&amp;quot;,&lt;br /&gt;
					root: &amp;quot;objects&amp;quot;&lt;br /&gt;
				},&lt;br /&gt;
				writer: {&lt;br /&gt;
					type: &amp;quot;json&amp;quot;,&lt;br /&gt;
					nameProperty: &amp;quot;mapping&amp;quot;&lt;br /&gt;
				}&lt;br /&gt;
			}&lt;br /&gt;
		});&lt;br /&gt;
&lt;br /&gt;
		// Set up the event store&lt;br /&gt;
		this.eventStore = Ext.create(&amp;quot;Extensible.calendar.data.MemoryEventStore&amp;quot;, {&lt;br /&gt;
			autoLoad: true,&lt;br /&gt;
			storeId: &amp;quot;Events&amp;quot;,&lt;br /&gt;
			proxy: {&lt;br /&gt;
				type: &amp;quot;rest&amp;quot;,&lt;br /&gt;
				url: &amp;quot;/event/&amp;quot;,&lt;br /&gt;
				startParam: &amp;quot;offset&amp;quot;,&lt;br /&gt;
				reader: {&lt;br /&gt;
					type: &amp;quot;json&amp;quot;,&lt;br /&gt;
					root: &amp;quot;objects&amp;quot;,&lt;br /&gt;
				},&lt;br /&gt;
				writer: {&lt;br /&gt;
					type: &amp;quot;json&amp;quot;,&lt;br /&gt;
					nameProperty: &amp;quot;mapping&amp;quot;&lt;br /&gt;
				}&lt;br /&gt;
			}&lt;br /&gt;
		});&lt;br /&gt;
&lt;br /&gt;
		// Set up the panel (view)&lt;br /&gt;
		this.container = Ext.create('Extensible.calendar.CalendarPanel', {&lt;br /&gt;
			renderTo: Ext.get(&amp;quot;calbox&amp;quot;),&lt;br /&gt;
			title: &amp;quot;My CSE330 Calendar&amp;quot;,&lt;br /&gt;
			width: &amp;quot;100%&amp;quot;,&lt;br /&gt;
			height: &amp;quot;100%&amp;quot;,&lt;br /&gt;
			id: &amp;quot;ext-calendar-main&amp;quot;,&lt;br /&gt;
			eventStore: this.eventStore,&lt;br /&gt;
			calendarStore: this.calendarStore,&lt;br /&gt;
			monthViewCfg: {&lt;br /&gt;
				showHeader: true // show the days of the week&lt;br /&gt;
			}&lt;br /&gt;
		});&lt;br /&gt;
&lt;br /&gt;
	}&lt;br /&gt;
});&lt;br /&gt;
&lt;br /&gt;
Ext.onReady(function(){&lt;br /&gt;
	Ext.create(&amp;quot;CSE330.Calendar&amp;quot;);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You should be able to load [http://localhost:8000/ http://localhost:8000/] and see an empty calendar with all events you have thusfar put in your database.  Exciting!&lt;br /&gt;
&lt;br /&gt;
=== Additional Work on the Front End ===&lt;br /&gt;
&lt;br /&gt;
Again, right now you have a read-only calendar without any sort of authentication.  You need to tie these two pieces together.&lt;br /&gt;
&lt;br /&gt;
If you look at the web inspector, you can see the requests that Extensible sends to your server when you try to create or modify an event using the front-end GUI.  You need to make sure that your server and Extensible work together, both sending and receiving compatible formats.&lt;br /&gt;
&lt;br /&gt;
You can implement log in and log out over AJAX via the Tastypie API.  There are examples of how to do this in the documentation.&lt;br /&gt;
&lt;br /&gt;
== Help with Debugging ==&lt;br /&gt;
&lt;br /&gt;
Wrapping your head around Extensible, Django-Tastypie, and how to make the two frameworks talk to each other is a daunting task.  The goal of this section is to help you learn how to debug this process.&lt;br /&gt;
&lt;br /&gt;
=== Tutorial for Debugging the Create Event Mechanism ===&lt;br /&gt;
&lt;br /&gt;
Let's first take a look at what happens when you try to add a new event via the Extensible GUI.  When you click somewhere on the calendar, a little dialog opens, and in it you can specify the details of your event.  However, when you press &amp;quot;Save&amp;quot;, you see the following error in the console:&lt;br /&gt;
&lt;br /&gt;
[[File:Extensible-Debugging-Unauthorized.png]]&lt;br /&gt;
&lt;br /&gt;
Whoopsy daisy, we got a '''401 Unauthorized''' from the server!  This means that Django-Tastypie thinks that we don't have enough permissions to edit this resource.  We need to tell Tastypie that we do indeed have such permissions.&lt;br /&gt;
&lt;br /&gt;
Let's temporarily open up the event to be globally editable.  Refer to [http://django-tastypie.readthedocs.org/en/latest/tutorial.html#hooking-up-the-resource-s this section of the Tastypie guide] for an example of how to do this.  Try figuring it out on your own before reading on.&lt;br /&gt;
&lt;br /&gt;
You may have figured out that we need to specify these changes inside the ''cal/api.py'' file.  In particular, if we add the following line to the ''Meta'' of the ''EventResource'' class, we in effect open up the resource to be globally editable.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# Add to the Event meta&lt;br /&gt;
authorization = Authorization()&lt;br /&gt;
&lt;br /&gt;
# don't forget to put an import statement at the top of your file!&lt;br /&gt;
#      from tastypie.authorization import Authorization&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Great!  Now let's try sending our request again.  You'll see that you get a '''400 Bad Request''' error.  That sounds scary!  What's happening?&lt;br /&gt;
&lt;br /&gt;
Let's head on over to the &amp;quot;Network&amp;quot; panel of the web inspector.  Scroll to the bottom of the page to find the latest network request.  Click it, and then choose the &amp;quot;Response&amp;quot; tab.  You'll see something like this:&lt;br /&gt;
&lt;br /&gt;
[[File:Extensible-Debugging-Response-Error.png]]&lt;br /&gt;
&lt;br /&gt;
Hey, look!  There's an error that we can fix.  Let's look at it in more detail.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;&lt;br /&gt;
The 'cid' field was given data that was not a URI, not a dictionary-alike and does not have a 'pk' attribute: 1.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It sounds like Tastypie doesn't like whatever we're sending as the ''cid'' field.  Let's go check on what we're actually sending.  To do this, click on the &amp;quot;Headers&amp;quot; tab in the web inspector, and scroll down to &amp;quot;Request Payload&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
[[File:Extensible-Debugging-Request-Payload.png]]&lt;br /&gt;
&lt;br /&gt;
So we're clearly sending an integer calendar ID in the ''cid'' field.  Why wouldn't Tastypie like this?  I don't know; let's google the error!&lt;br /&gt;
&lt;br /&gt;
Note that when we google something, we need to take specific field names out of our search.  In our case, this is the &amp;quot;cid&amp;quot; field name as well as the value of &amp;quot;1&amp;quot;.  With that in mind, here are the hits:&lt;br /&gt;
&lt;br /&gt;
[[File:Extensible-Debugging-Google-Hits.png]]&lt;br /&gt;
&lt;br /&gt;
Look at that!  We're clearly not the first people to run into this error.&lt;br /&gt;
&lt;br /&gt;
The first Stack Overflow question looks verbose.  Let's try the second one.&lt;br /&gt;
&lt;br /&gt;
Hey, you find something that might provide you a clue!&lt;br /&gt;
&lt;br /&gt;
[[File:Extensible-Debugging-StackOverflow-Answer.png]]&lt;br /&gt;
&lt;br /&gt;
So we need to make our data field resemble one of those two options: either a dictionary with a &amp;quot;pk&amp;quot; field or a resource URL.&lt;br /&gt;
&lt;br /&gt;
But how can we change the data format?  We could do it from the Extensible side, or we could do it from the Tastypie side.  Since we have greater control over Tastypie than Extensible, let's do it on the Tastypie side.&lt;br /&gt;
&lt;br /&gt;
[http://django-tastypie.readthedocs.org/en/latest/resources.html The Resources guide for Tastypie] seems like a reasonable place to start.  Read it and try to find the method that enables you to modify incoming data before Tastypie puts it into the model.&lt;br /&gt;
&lt;br /&gt;
If you pinpointed the ''hydrate_FOO'' method, you were right!  We simply need to define this method to transform the incoming data into the format that Tastypie wants.&lt;br /&gt;
&lt;br /&gt;
Based on the &amp;quot;simple example&amp;quot; under ''hydrate_FOO'', the following definition seems reasonable.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# Part of the EventResource class&lt;br /&gt;
&lt;br /&gt;
	def hydrate_cid(self, bundle):&lt;br /&gt;
		bundle.data[&amp;quot;cid&amp;quot;] = &amp;quot;/cal/%d/&amp;quot; % bundle.data[&amp;quot;cid&amp;quot;]&lt;br /&gt;
		return bundle&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, we are transforming the incoming ''cid'' number to a resource URL.  For example, '''3''' will be transformed into '''/cal/3/''', the format that Tastypie wants according to the Stack Overflow post.&lt;br /&gt;
&lt;br /&gt;
Okay, great!  Let's save and see where we stand.  Try creating an event through the GUI.&lt;br /&gt;
&lt;br /&gt;
Hey, it looks like something happened!  We received a ''201'' request back from the server!  Let's take a peek at our database.  Enter a Django shell and enter the following commands.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# Run these commands inside a Django shell&lt;br /&gt;
from cal.models import Cal, Event&lt;br /&gt;
map(lambda v: &amp;quot;%d %s&amp;quot; % (v.id, v.title), Event.objects.all())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The first line imports your modules into the shell, and the second line queries them via ORM and displays a list of the events with an ID and a title.&lt;br /&gt;
&lt;br /&gt;
What do you see that's interesting?  Hey, the &amp;quot;Banana Event&amp;quot; that I just added has ID 0!  That's not cool.  How do we fix it?&lt;br /&gt;
&lt;br /&gt;
You may remember from the Django tutorial that Django will automatically assign the next available ID if you leave the ''id'' field empty in the new model.  So, let's go ahead and transform all '''0''' IDs in Tastypie to '''None'''.&lt;br /&gt;
&lt;br /&gt;
Try writing the necessary ''hydrate_id'' method.  You should get something like the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# Part of the EventResource class&lt;br /&gt;
&lt;br /&gt;
	def hydrate_id(self, bundle):&lt;br /&gt;
		if bundle.data[&amp;quot;id&amp;quot;] == 0:&lt;br /&gt;
			bundle.data[&amp;quot;id&amp;quot;] = None&lt;br /&gt;
		return bundle&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Save and try again.  What do you know, it works now!  Each new event is now assigned a unique ID.&lt;br /&gt;
&lt;br /&gt;
=== Next Steps ===&lt;br /&gt;
&lt;br /&gt;
So hopefully you now have the knowledge you need to complete the module.  In summary, when you need help, do the following:&lt;br /&gt;
&lt;br /&gt;
# Look at the web inspector console&lt;br /&gt;
# Look at the network activity&lt;br /&gt;
# Look at the server log&lt;br /&gt;
# When you find an error that looks useful, google it (remove application-specific terms)&lt;br /&gt;
# When fixing the problem, refer to documentation&lt;br /&gt;
# When the problem is fixed, commit your code!&lt;br /&gt;
&lt;br /&gt;
If you still need help, ask in class or come to office hours.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 6]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_3&amp;diff=1694</id>
		<title>Module 3</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_3&amp;diff=1694"/>
		<updated>2013-12-22T05:30:46Z</updated>

		<summary type="html">&lt;p&gt;Shane: Adding link to coderesponsibly.org&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__&lt;br /&gt;
In Module 3, you will learn about MySQL, a web application database.&lt;br /&gt;
&lt;br /&gt;
This article contains your assignments for Module 3.&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[Introduction to MySQL]]&lt;br /&gt;
* [[MySQL Schema and State]]&lt;br /&gt;
* [[PHP and MySQL]]&lt;br /&gt;
* [[Web Application Security, Part 2]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
You will create a simple grades database containing four tables.&lt;br /&gt;
&lt;br /&gt;
'''IMPORTANT:''' The individual assignment is to be done by writing queries by hand.  (You can use phpMyAdmin to run the queries, but '''do not let phpMyAdmin write your queries for you!''')  Writing your own queries gives you a greater understanding of the underlying mechanisms and databases in general.  Additionally, having SQL knowledge and experience is a very marketable trait.&lt;br /&gt;
&lt;br /&gt;
=== Install MySQL and phpMyAdmin ===&lt;br /&gt;
&lt;br /&gt;
Before you start, '''you need to install MySQL''' on your EC2 instance.  You may also install phpMyAdmin, a web frontend to MySQL, if you choose to do so.&lt;br /&gt;
&lt;br /&gt;
You may find the following article to be very helpful: [[Introduction to MySQL]]&lt;br /&gt;
&lt;br /&gt;
=== Set Up a Database ===&lt;br /&gt;
&lt;br /&gt;
You may find the following article to be very helpful: [[Introduction to MySQL]]&lt;br /&gt;
&lt;br /&gt;
# Create a database named '''wustl''' &lt;br /&gt;
# Create a user named '''wustl_inst''' and give them the password '''wustl_pass'''&lt;br /&gt;
&lt;br /&gt;
=== Create Tables ===&lt;br /&gt;
&lt;br /&gt;
You may find the following article to be very helpful: [[MySQL Schema and State]]&lt;br /&gt;
&lt;br /&gt;
When creating tables, keep the following items in mind:&lt;br /&gt;
&lt;br /&gt;
* You should create all tables such that they use the InnoDB storage engine, since we wish to make use of its support of foreign keys. In other database engines, foreign key constraints are not enforced.  (If you mess up, you can use ALTER TABLE to change the storage engine.)&lt;br /&gt;
* Where it is appropriate, you should take advantage of the ability to define fields NOT NULL so that you do not inadvertently insert incomplete data for a row.&lt;br /&gt;
&lt;br /&gt;
Create the following tables:&lt;br /&gt;
&lt;br /&gt;
# Create a table named '''students''' with the following fields:&lt;br /&gt;
#* '''id''' of an appropriately-sized unsigned integer type (we will never need to process more than a million students)&lt;br /&gt;
#* '''first_name''' of type '''VARCHAR(50)'''&lt;br /&gt;
#* '''last_name''' of type '''VARCHAR(50)'''&lt;br /&gt;
#* '''email_address''' of type '''VARCHAR(50)'''&lt;br /&gt;
#: The primary key should be on the '''id''' field.&lt;br /&gt;
# Create a table named '''departments''' with the following fields:&lt;br /&gt;
#* '''school_code''' of type '''ENUM''' (e.g. &amp;quot;L&amp;quot; for ArtSci and &amp;quot;E&amp;quot; for Engineering).  The options are as follows:&lt;br /&gt;
#*: 'L', 'B', 'A', 'F', 'E', 'T', 'I', 'W', 'S', 'U', 'M'&lt;br /&gt;
#* '''dept_id''' of an appropriately-sized unsigned integer type (in the foreseeable future there will never be more than 200 departments in a school)&lt;br /&gt;
#* '''abbreviation''' of type '''VARCHAR(9)''' (e.g. CSE, ChemE, etc)&lt;br /&gt;
#* '''dept_name''' of type '''VARCHAR(200)''' (e.g. Computer Science and Engineering)&lt;br /&gt;
#: The primary key should be on two fields: '''school_code''' and '''dept_id'''&lt;br /&gt;
#: '''Note:''' Why not just use the department ID for the primary key? The ID numbers are sometimes reused across schools. For instance, department 33 in The College of Arts and Sciences is Psychology while department 33 in The School of Engineering and Applied Sciences is Energy, Environmental and Chemical Engineering. Thus we must also include the school code to differentiate them  such that the record for  E33 is distinct from that of L33.&lt;br /&gt;
# Create a table named '''courses''' with the following fields:&lt;br /&gt;
#* '''school_code''' of type '''ENUM'''&lt;br /&gt;
#*: This should have the same letters in the same order as the '''school_code''' '''ENUM''' field in the '''departments''' table.&lt;br /&gt;
#* '''dept_id''' of the same size of integer as in the '''departments''' table&lt;br /&gt;
#* '''course_code''' of type '''CHAR(5)''' (this will hold course codes; e.g., '330S', '131', '2960')&lt;br /&gt;
#* '''name''' of type '''VARCHAR(150)'''&lt;br /&gt;
#: The appropriate fields in this table should make a foreign key reference to the corresponding fields in '''department'''.&lt;br /&gt;
#: In addition, it is up to you to determine the field(s) for the primary key.&lt;br /&gt;
#: '''Note:''' If you are unsure which fields to make the foreign keys and feel the need to beg your friends or the TAs to give you the answer, bang your head on your desk whilst repeating &amp;quot;I WILL EXERCISE REASON AND COMMON SENSE AND I WILL CURTAIL MY DESIRE TO BLINDLY FOLLOW DIRECTIONS&amp;quot;&lt;br /&gt;
#: ''Disclaimer: don't actually bang your head on your desk, the resulting head trauma may in fact make it harder for you to determine which fields should have associated foreign keys.''&lt;br /&gt;
# Create a table named '''grades''' with the following fields:&lt;br /&gt;
#* '''pk_grade_ID''' of an appropriately-sized unsigned integer type (should be larger than the one you chose for the '''students''' table)&lt;br /&gt;
#*: You should declare this field to be '''auto_increment''' and make it the primary key.&lt;br /&gt;
#*: This is called a ''surrogate key'' as opposed to a ''natural key'' because it doesn't arise &amp;quot;naturally&amp;quot; from the data; that is to say that it is not derived from application data. The use of surrogate keys vs. natural keys is a polemic issue amongst database designers.  For a decently unbiased take on the issue, see this page: http://www.agiledata.org/essays/keys.html#Comparison&lt;br /&gt;
#*: '''Food for thought:''' Aside from simply exposing you to the concept, can you think of any reasons why a surrogate key might be preferable for this table?  Alternatively, what attributes, if any, could you use as a natural key, and what might be the drawbacks of doing so?&lt;br /&gt;
#* '''student_id''' of the same integer (unsigned) type that you chose in the '''students''' table&lt;br /&gt;
#* '''grade''' of type '''decimal(5,2)'''&lt;br /&gt;
#* '''school_code''' of type '''ENUM'''&lt;br /&gt;
#*: Can you guess what entries to use for the enum?&lt;br /&gt;
#* '''dept_id''' of the same integer type that you've used for this field in other tables&lt;br /&gt;
#* '''course_code''' of the same type you chose for the course code in the '''courses''' table&lt;br /&gt;
#: The '''grades''' table should have foreign keys to both the '''students''' table and the '''courses''' table.&lt;br /&gt;
&lt;br /&gt;
=== Populate Tables ===&lt;br /&gt;
&lt;br /&gt;
Now, populate the tables by downloading the text files given below and loading them into the appropriate tables.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' Do not insert all the values manually; instead, use the MySQL's ability to load in data from text files.&lt;br /&gt;
&lt;br /&gt;
You may find the following article to be very helpful: [[MySQL Schema and State]]&lt;br /&gt;
&lt;br /&gt;
The files containing the data are:&lt;br /&gt;
* students: http://classes.engineering.wustl.edu/cse330/content/students_data.txt&lt;br /&gt;
* courses: http://classes.engineering.wustl.edu/cse330/content/courses.txt&lt;br /&gt;
* departments: http://classes.engineering.wustl.edu/cse330/content/departments_data.txt&lt;br /&gt;
* grades: http://classes.engineering.wustl.edu/cse330/content/grades_data.txt&lt;br /&gt;
&lt;br /&gt;
=== Insert More Data ===&lt;br /&gt;
&lt;br /&gt;
Insert the following data into the tables that you have created and populated:&lt;br /&gt;
&lt;br /&gt;
# Insert an entry for CSE 330&lt;br /&gt;
#: ''If you don't know CSE's department code, how can you find out using the tables in the database?''&lt;br /&gt;
# Insert the grades given for the students named below.  You may choose to make the entries for whichever classes you like, with the one condition that all of the students must have a grade for CSE 330 (who wouldn't want to take that class: I hear the professor and TAs are amazing!)&lt;br /&gt;
#* '''Ben Harper'''&lt;br /&gt;
#** E-mail: '''bharper@ffym.com'''&lt;br /&gt;
#** Student ID: '''88'''&lt;br /&gt;
#** Grades:&lt;br /&gt;
#*** 35.5 (CSE 330 grade)&lt;br /&gt;
#*** 0&lt;br /&gt;
#*** 95&lt;br /&gt;
#* '''Matt Freeman'''&lt;br /&gt;
#** E-mail: '''mfreeman@kickinbassist.net'''&lt;br /&gt;
#** Student ID: '''202'''&lt;br /&gt;
#** Grades:&lt;br /&gt;
#*** 100 (CSE 330 grade)&lt;br /&gt;
#*** 90.5&lt;br /&gt;
#*** 94.8&lt;br /&gt;
#* '''Marc Roberge'''&lt;br /&gt;
#** E-mail: '''mroberge@ofarevolution.us'''&lt;br /&gt;
#** Student ID: '''115'''&lt;br /&gt;
#** Grades:&lt;br /&gt;
#*** 75 (CSE 330 grade)&lt;br /&gt;
#*** 37&lt;br /&gt;
#*** 45.5&lt;br /&gt;
#: You may choose any 3 classes you'd like for them to be enrolled in, with at least one class, &amp;quot;CSE 330S&amp;quot;, in which they are all enrolled.&lt;br /&gt;
&lt;br /&gt;
=== Querying Your Database ===&lt;br /&gt;
&lt;br /&gt;
Now that you have a fully-functional, populated database, let's do some queries on it!&lt;br /&gt;
&lt;br /&gt;
Please take a screenshot of running the following '''select''' queries and show them to a TA (be sure to include your query command and the response:&lt;br /&gt;
&lt;br /&gt;
# Select the entire grades table.&lt;br /&gt;
# Select all fields describing the courses offered in the school of arts and sciences (school code L).&lt;br /&gt;
# The names, student IDs, and grades of the students who are in CSE330.&lt;br /&gt;
#: '''Note:''' This query should involve joins.  You don't need to use any aggregation functions.&lt;br /&gt;
# The names, e-mails, and average grades of any student with an average below 50 so that the dean can send them an email notification that they are now on academic probation.&lt;br /&gt;
#: ''You should be able to do this in only one query, without making any temporary tables.  You will need to use aggregation functions and the '''having''' keyword.''&lt;br /&gt;
# An individual report card for Jack Johnson, consisting of his student ID, e-mail address, and average grade.&lt;br /&gt;
#: ''Again, you should be able to do this in just one query, using the correct combination of aggregation functions and joins.''&lt;br /&gt;
#: '''Note:''' Your query must look for students with the name Jack Johnson instead of hard-coding the student ID.&lt;br /&gt;
&lt;br /&gt;
== Group Project ==&lt;br /&gt;
&lt;br /&gt;
You will work in pairs on this project.  You may work with the same partner from Module 2, or change to someone else.&lt;br /&gt;
&lt;br /&gt;
'''Important Reminder:''' frequently commit your work to your subversion repository as a backup!&lt;br /&gt;
&lt;br /&gt;
=== Simple News Web Site ===&lt;br /&gt;
&lt;br /&gt;
'''Examples:'''&lt;br /&gt;
* http://digg.com/&lt;br /&gt;
* http://slashdot.org/&lt;br /&gt;
&lt;br /&gt;
You should use '''PHP''' unless you get permission to use another web technology from the instructor.  You may also use phpMyAdmin to help set up databases.&lt;br /&gt;
&lt;br /&gt;
You may find this wiki article helpful: [[PHP and MySQL]]&lt;br /&gt;
&lt;br /&gt;
==== Requirements ====&lt;br /&gt;
&lt;br /&gt;
* Users can register for accounts and then log in to the website.&lt;br /&gt;
* Accounts should have both a username and a ''secure'' password.  '''NEVER store plaintext passwords in a database!'''&lt;br /&gt;
*: For more information on password security, refer to [[Web Application Security, Part 2#Password Security|the Web Application Security guide]].&lt;br /&gt;
* Registered users can submit story commentary and links to those stories.&lt;br /&gt;
*: You do not have to make a distinction between the two types of stories, although if you want to, you could do something with this for the creative portion of your project.&lt;br /&gt;
* Registered users can comment on any story.&lt;br /&gt;
* Unregistered users can only view stories and comments.&lt;br /&gt;
* Registered users can edit and delete their stories and comments.&lt;br /&gt;
* All data must be kept in a MySQL database (user information, stories, comments, and categories).&lt;br /&gt;
* Creative Portion&lt;br /&gt;
&lt;br /&gt;
=== Web Security and Validation ===&lt;br /&gt;
&lt;br /&gt;
No application is finished until much thought is put into web security and best practice.  Throughout this course, we heavily emphasize the dogma of [http://coderesponsibly.org/ responsible] coding.&lt;br /&gt;
&lt;br /&gt;
Read this week's Web Application Security guide: [[Web Application Security, Part 2]].  In particular, your project needs to:&lt;br /&gt;
&lt;br /&gt;
* '''Your application needs to be secure from SQL injection attacks'''. If you are using prepared queries, you should already be safe on this front.&lt;br /&gt;
* '''Your passwords need to be securely salted''' to prevent rainbow table attacks.&lt;br /&gt;
* '''You should pass tokens in forms''' to prevent CSRF attacks.&lt;br /&gt;
* '''You should check all preconditions on the server side''' to prevent Abuse of Functionality attacks.&lt;br /&gt;
&lt;br /&gt;
You shouldn't forget the practices you learned last week:&lt;br /&gt;
&lt;br /&gt;
* '''Your page should validate''' with no errors through the W3C validator.&lt;br /&gt;
* '''Filter Input and Escape Output''', but not the other way around.&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 100 points total.&lt;br /&gt;
&lt;br /&gt;
# '''MySQL Queries (25 Points):'''&lt;br /&gt;
#* A MySQL server is running on your instance (2 points)&lt;br /&gt;
#* Tables fields, including data types, are correct (4 points)&lt;br /&gt;
#* Foreign keys are correct (4 points)&lt;br /&gt;
#* The output of each of the five queries is correct (3 points each)&lt;br /&gt;
# '''News Site (60 Points):'''&lt;br /&gt;
#* '''''User Management (20 Points):'''''&lt;br /&gt;
#** A session is created when a user logs in (3 points)&lt;br /&gt;
#** New users can register (3 points)&lt;br /&gt;
#** Passwords are hashed using salted one-way encryption (3 points)&lt;br /&gt;
#** Users can log out (3 points)&lt;br /&gt;
#** A user can edit and delete his/her own stories and comments but cannot edit or delete the stories or comments of another user (8 points)&lt;br /&gt;
#* '''''Story and Comment Management (20 Points):'''''&lt;br /&gt;
#** Relational database is configured with correct data types and foreign keys (4 points)&lt;br /&gt;
#** Stories can be posted (3 points)&lt;br /&gt;
#** A link can be associated with each story using a separate database field (3 points)&lt;br /&gt;
#** Comments can be posted in association with a story (4 points)&lt;br /&gt;
#** Stories can be edited and deleted (3 points)&lt;br /&gt;
#** Comments can be edited and deleted (3 points)&lt;br /&gt;
#**: ''Note: Although there are only 6 points allocated for editing/deleting in this section, there are 8 more points at stake in the User Management section that cannot be earned unless editing/deleting is implemented.  Implementing editing but not deleting, or vice-versa, will result in earning half the points.''&lt;br /&gt;
#* '''''Best Practices (15 Points):'''''&lt;br /&gt;
#** Code is well formatted and easy to read (3 points)&lt;br /&gt;
#** Safe from SQL Injection attacks (2 points)&lt;br /&gt;
#** Site follows the FIEO philosophy (3 points)&lt;br /&gt;
#** All pages pass the W3C validator (2 points)&lt;br /&gt;
#** CSRF tokens are passed when creating, editing, and deleting comments and stories (5 points)&lt;br /&gt;
#* '''''Usability (5 Points):'''''&lt;br /&gt;
#** Site is intuitive to use and navigate (4 points)&lt;br /&gt;
#** Site is visually appealing (1 point)&lt;br /&gt;
# '''Creative Portion (15 Points)'''&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 3]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_8&amp;diff=1693</id>
		<title>Module 8</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_8&amp;diff=1693"/>
		<updated>2013-11-24T10:19:59Z</updated>

		<summary type="html">&lt;p&gt;Shane: Adding out-of-date disclaimer&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;''THIS PAGE IS OUT OF DATE AND IS HERE FOR REFERENCE ONLY.''&lt;br /&gt;
&lt;br /&gt;
Module 5 is your chance to complete a project of your own creation.  There's a reason this class has &amp;quot;Creative Programming&amp;quot; in the title.&lt;br /&gt;
&lt;br /&gt;
== Objective ==&lt;br /&gt;
&lt;br /&gt;
Your project should incorporate topics we have learned throughout this corse, but it should be focussed primarily on some new concept or concepts relating to web development.  You should continue the best practices and security protocols you have learned in previous modules as well.&lt;br /&gt;
&lt;br /&gt;
== Technologies ==&lt;br /&gt;
&lt;br /&gt;
We have looked through the projects submitted by all groups, and we have picked out a few technologies that turned up frequently.  Below is a short summary of these technologies and the TAs who can help answer questions about them.&lt;br /&gt;
&lt;br /&gt;
=== HTML5 Canvas ===&lt;br /&gt;
&lt;br /&gt;
The HTML5 '''&amp;lt;nowiki&amp;gt;&amp;lt;canvas&amp;gt;&amp;lt;/nowiki&amp;gt;''' element enables you to render dynamic graphics in real-time in the browser.  In many ways, you can think of HTML5 Canvas as a substitute for Flash Player: most tasks that Flash Player can do, '''&amp;lt;nowiki&amp;gt;&amp;lt;canvas&amp;gt;&amp;lt;/nowiki&amp;gt;''' can do just as well.&lt;br /&gt;
&lt;br /&gt;
Here are examples of some things you can do with the HTML5 Canvas: http://www.hongkiat.com/blog/48-excellent-html5-demos/&lt;br /&gt;
&lt;br /&gt;
You may want to consider using a dedicated JavaScript library for interfacing with the Canvas.  This will ensure better compatibility, and the documentation should be more helpful than trying to figure out the native Canvas methods.  Here are some promising Canvas libraries:&lt;br /&gt;
&lt;br /&gt;
* [http://kineticjs.com/ KineticJS]&lt;br /&gt;
* [http://fabricjs.com/ Fabric.JS]&lt;br /&gt;
* [http://calebevans.me/projects/jcanvas/index.php jCanvas (built on jQuery)]&lt;br /&gt;
&lt;br /&gt;
==== TAs Knowledgeable about Canvas ====&lt;br /&gt;
&lt;br /&gt;
* Paul&lt;br /&gt;
* Marc&lt;br /&gt;
&lt;br /&gt;
=== Node.JS and Socket.IO ===&lt;br /&gt;
&lt;br /&gt;
In Module 4, you learned how to use AJAX, which is a technology by which a client can communicate with the server asynchronously.  However, AJAX requires that a client '''''ask for data''''' from a server, and the server then sends a ''response''.  This approach fails in real-time applications: think chatrooms and online action games.&lt;br /&gt;
&lt;br /&gt;
Socket.IO is a technology that enables the server to send data to the client '''''without the client having to request it first'''''.  Node.JS is a server built from the ground up to handle real-time requests efficiently, more so than a server like Apache.&lt;br /&gt;
&lt;br /&gt;
It is important to understand that Socket.IO and Node.JS ''replace'' AJAX, PHP, and Apache in your web application.  You can use a technology like [http://expressjs.com/ express] to serve static files so that you don't even need to have Apache running.&lt;br /&gt;
&lt;br /&gt;
It is worth noting that Linux distributions based on Debian are more friendly to Node.JS than distributions based on RHEL.  If your main server is running the Amazon Linux AMI, you may want to consider launching a new EC2 instance running Ubuntu Server if you are using Node.JS in your project.&lt;br /&gt;
&lt;br /&gt;
==== TAs Knowledgeable about Node.JS ====&lt;br /&gt;
&lt;br /&gt;
* Shane&lt;br /&gt;
* Todd&lt;br /&gt;
&lt;br /&gt;
=== Maps ===&lt;br /&gt;
&lt;br /&gt;
It is common to see maps embedded in web sites.  [https://developers.google.com/maps/ Google Maps], [http://api.maps.nokia.com/en/overview.html Nokia Maps], and [http://developer.mapquest.com/ Mapquest] are three examples.&lt;br /&gt;
&lt;br /&gt;
Cendors like Google, Nokia, and Mapquest provide APIs that make it easy for you, the developer, to use their maps on your site.  For example, this is all the code you need to display a map of Wash U's campus using the Nokia Map API:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
map = new nokia.maps.map.Display(document.getElementById(&amp;quot;mapDiv&amp;quot;), {&lt;br /&gt;
   zoomLevel: 15,&lt;br /&gt;
   center: [38.648044, -90.304881]&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== TAs Knowledgeable about Maps ====&lt;br /&gt;
&lt;br /&gt;
* Sid&lt;br /&gt;
* Todd&lt;br /&gt;
&lt;br /&gt;
=== Alternate Authentication Methods ===&lt;br /&gt;
&lt;br /&gt;
You have probably used sites that allow you to log in using your Google, Yahoo, Facebook, Twitter, or some other account rather than making a new account with a new password.&lt;br /&gt;
&lt;br /&gt;
It is relatively easy to implement alternate authentication methods like this.  OpenID, which is a gateway to account providers like Google and Yahoo, is documented in [[Web Application Security, Part 2#OpenID]].&lt;br /&gt;
&lt;br /&gt;
==== TAs Knowledgeable about Alternate Authentication Methods ====&lt;br /&gt;
&lt;br /&gt;
* Paul&lt;br /&gt;
* Shane&lt;br /&gt;
* Todd&lt;br /&gt;
&lt;br /&gt;
=== HTML5 Video and Audio ===&lt;br /&gt;
&lt;br /&gt;
In the past, a plugin like Flash was required for viewing media on the web.  With HTML5 Video, these plugins are no longer necessary.&lt;br /&gt;
&lt;br /&gt;
In its simplest form, an HTML5 video can be loaded in one line of HTML:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;video src=&amp;quot;my_video.mp4&amp;quot; type=&amp;quot;video/mp4&amp;quot; controls&amp;gt;&amp;lt;/video&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Video formats are more complicated than image formats, however, and so it is necessary for you to define multiple source files for the same video, encoded in different formats.  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;video controls&amp;gt;&lt;br /&gt;
  &amp;lt;source src=&amp;quot;my_video.mp4&amp;quot; type=&amp;quot;video/mp4&amp;quot; /&amp;gt;&lt;br /&gt;
  &amp;lt;source src=&amp;quot;my_video.ogv&amp;quot; type=&amp;quot;video/ogg&amp;quot; /&amp;gt;&lt;br /&gt;
  &amp;lt;source src=&amp;quot;my_video.webm&amp;quot; type=&amp;quot;video/webm&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;/video&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
I highly recommend that you take the time to read this informative article about HTML5 Video if you choose to employ this technology in your project: http://diveintohtml5.info/video.html&lt;br /&gt;
&lt;br /&gt;
==== TAs Knowledgeable about HTML5 Video and Audio ====&lt;br /&gt;
&lt;br /&gt;
* Shane&lt;br /&gt;
* Sid&lt;br /&gt;
* Todd&lt;br /&gt;
&lt;br /&gt;
=== CSS 3 ===&lt;br /&gt;
&lt;br /&gt;
CSS 3 adds features to CSS that reduce the need for background images and JavaScript for layout purposes, resulting in a more centralized and robust stylesheet.  CSS 3 also enables developers to be more creative with their layouts and typography.&lt;br /&gt;
&lt;br /&gt;
Here are examples of some nifty things that you can do with CSS 3: http://webdesignerwall.com/trends/47-amazing-css3-animation-demos&lt;br /&gt;
&lt;br /&gt;
==== TAs Knowledgeable about CSS 3 ====&lt;br /&gt;
&lt;br /&gt;
* Sid&lt;br /&gt;
* Paul&lt;br /&gt;
* Shane&lt;br /&gt;
* Marc&lt;br /&gt;
&lt;br /&gt;
=== Other APIs ===&lt;br /&gt;
&lt;br /&gt;
Above, we mentioned the Map APIs provided by some vendors.  In reality, there are APIs provided for applications extending far beyond Maps.  Some of these additional APIs include:&lt;br /&gt;
&lt;br /&gt;
* [http://developer.yahoo.com/finance/ Yahoo Finance]&lt;br /&gt;
* [http://www.twilio.com/docs/libraries Twilio]&lt;br /&gt;
* [https://dev.twitter.com/docs/twitter-libraries Twitter]&lt;br /&gt;
* [http://developers.facebook.com/ Facebook]&lt;br /&gt;
&lt;br /&gt;
==== TAs Knowledgeable about Other APIs ====&lt;br /&gt;
&lt;br /&gt;
* Todd&lt;br /&gt;
* Marc&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
You should have already turned in a printed copy of your grade sheet.  We will grade everyone's projects in class on '''Wednesday, November 14'''.  Because of the nature of Module 5 and since everyone's grade sheets are different, '''''you MUST be in class on time and ready to demo, or you risk a severe late penalty (almost 2 letter grades per day).'''''  If you wish to demo early, you must do so either in class on Monday or in Marc's office hours on Tuesday.  Thanks for your understanding.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 8]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=CSE_330_Online_Textbook_-_Table_of_Contents&amp;diff=1692</id>
		<title>CSE 330 Online Textbook - Table of Contents</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=CSE_330_Online_Textbook_-_Table_of_Contents&amp;diff=1692"/>
		<updated>2013-11-24T10:19:16Z</updated>

		<summary type="html">&lt;p&gt;Shane: Adding Module 8&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;div style=&amp;quot;text-align:center;&amp;quot;&amp;gt;[[File:CSE330Banner.png]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__NOTOC__ &lt;br /&gt;
&amp;lt;div style=&amp;quot;column-width: 300px; -moz-column-width: 300px; -webkit-column-width: 300px;&amp;quot;&amp;gt;&lt;br /&gt;
{{FrontPageModule&lt;br /&gt;
|num=1&lt;br /&gt;
|subject=HTML and CSS Fundamentals&lt;br /&gt;
|links=&lt;br /&gt;
* [[HTML and CSS]]&lt;br /&gt;
* [[HTML Forms]]&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
{{FrontPageModule&lt;br /&gt;
|num=2&lt;br /&gt;
|subject=Linux, Apache, and PHP&lt;br /&gt;
|links=&lt;br /&gt;
* [[Linux]]&lt;br /&gt;
* [[Bash]]&lt;br /&gt;
* [[Amazon Web Services]]&lt;br /&gt;
* [[SSH]]&lt;br /&gt;
* [[Apache]]&lt;br /&gt;
* [[PHP]]&lt;br /&gt;
* [[Workflow]]&lt;br /&gt;
* [[Web Application Security, Part 1]]&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
{{FrontPageModule&lt;br /&gt;
|num=3&lt;br /&gt;
|subject=SQL Databases&lt;br /&gt;
|links=&lt;br /&gt;
* [[Introduction to MySQL]] (installation)&lt;br /&gt;
* [[MySQL Schema and State]] (queries)&lt;br /&gt;
* [[PHP and MySQL]] (using MySQL from PHP)&lt;br /&gt;
* [[Web Application Security, Part 2]]&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
{{FrontPageModule&lt;br /&gt;
|num=4&lt;br /&gt;
|subject=Scripting for Rapid Prototyping&lt;br /&gt;
|links=&lt;br /&gt;
* [[Python]]&lt;br /&gt;
* [[Regular Expressions]]&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
{{FrontPageModule&lt;br /&gt;
|num=5&lt;br /&gt;
|subject=Version Control Systems and Web Frameworks&lt;br /&gt;
|links=&lt;br /&gt;
* [[Git]]&lt;br /&gt;
* [[Web Frameworks]]&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
{{FrontPageModule&lt;br /&gt;
|num=6&lt;br /&gt;
|subject=JavaScript and APIs&lt;br /&gt;
|links=&lt;br /&gt;
* [[JavaScript]]&lt;br /&gt;
* [[AJAX and JSON]]&lt;br /&gt;
* [[Ext JS]]&lt;br /&gt;
* [[Extensible Calendar]]&lt;br /&gt;
* [[Web Application Security, Part 3]]&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
{{FrontPageModule&lt;br /&gt;
|num=7&lt;br /&gt;
|subject=Real-Time Web Applications&lt;br /&gt;
|links=&lt;br /&gt;
* [[Node.JS]]&lt;br /&gt;
* [[Socket.IO]]&lt;br /&gt;
* [[Pong Game]]&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
{{FrontPageModule&lt;br /&gt;
|num=8&lt;br /&gt;
|subject=Creative Project&lt;br /&gt;
|links=&lt;br /&gt;
* [[Choosing a Platform]]&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Reference ==&lt;br /&gt;
&lt;br /&gt;
Use this wiki as a starting place for your projects in CSE 330.  However, web development is a large field, so it is impossible for us to document everything you might need to know.  Here are some other places you should look when you need to find something:&lt;br /&gt;
&lt;br /&gt;
* [http://www.webplatform.org/ WebPlatform.org], a community-driven source containing documentation and tutorials for Web technologies&lt;br /&gt;
* [http://www.w3.org/community/webed/wiki/Main_Page The Web Education Community Group Wiki], also sponsored by the W3C.&lt;br /&gt;
* [http://reference.sitepoint.com/html SitePoint], which has a reference page as well as quality articles and tutorials&lt;br /&gt;
* Also take a look at [http://designfestival.com/13-time-saving-tools-for-web-designers/ this list of productivity tools] for web development.&lt;br /&gt;
&lt;br /&gt;
If you can't find what you need in any of these places, try using your favorite search engine.  '''Be wary of sites that come up on search engines.'''  Many HTML reference sites document bad practices and dated techniques.  If you're unsure whether a reference site you find is legitimate, ask a TA.&lt;br /&gt;
&lt;br /&gt;
== Want to Learn More? ==&lt;br /&gt;
&lt;br /&gt;
The limited amount of time in CSE 330 means that we can cover only a subset of the wide range of possible topics in the field of rapid prototyping and web development.  Indeed, the exact topics covered in CSE 330 change from year to year.&lt;br /&gt;
&lt;br /&gt;
Feel free to browse some of the topics that have previously been covered in CSE 330: [[:Category:Former Content|CSE 330 Former Content]]&lt;br /&gt;
&lt;br /&gt;
You should also consider following blogs like [http://www.sitepoint.com/ SitePoint] to keep up-to-date on the latest developments in the field of web development.&lt;br /&gt;
&lt;br /&gt;
== Content License ==&lt;br /&gt;
&lt;br /&gt;
The content of this wiki is copyright (c) 2013, Washington University in St. Louis, Department of Computer Science.  All rights reserved.&lt;br /&gt;
&lt;br /&gt;
=== Modified BSD License ===&lt;br /&gt;
&lt;br /&gt;
Redistribution and use in source and binary forms, with or without modification, by a Third Party who has not completed and is not in the process of completing CSE 330, of the code examples or concepts on this wiki, are permitted, provided that the following conditions are met:&lt;br /&gt;
&lt;br /&gt;
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.&lt;br /&gt;
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.&lt;br /&gt;
* Neither the name of the Washington University School of Engineering and Applied Science nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.&lt;br /&gt;
&lt;br /&gt;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS TO ALL PARTIES &amp;quot;AS IS&amp;quot; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.&lt;br /&gt;
&lt;br /&gt;
=== What it Means ===&lt;br /&gt;
&lt;br /&gt;
If you are a student in CSE 330, you may use the code from this wiki freely in your projects without the need for attribution.  If you are not a student in CSE 330, you may use the code from this wiki freely in your projects with attribution.  Either way, the code examples are provided &amp;quot;as is&amp;quot;, without any warranty, and Washington University holds no liability for problems arising from the use of the content in this wiki.&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Choosing_a_Platform&amp;diff=1691</id>
		<title>Choosing a Platform</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Choosing_a_Platform&amp;diff=1691"/>
		<updated>2013-11-24T10:18:33Z</updated>

		<summary type="html">&lt;p&gt;Shane: Creating with all new content&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;You've learned a large variety of platforms in this course.  Which one should you use?  This page summarizes some of the pros and cons of each platform.&lt;br /&gt;
&lt;br /&gt;
== PHP ==&lt;br /&gt;
&lt;br /&gt;
[[PHP]] is a language built for server-side web development.  You built a [[Module 2|file sharing application]] and a [[Module 3|news syndication site]] in PHP.&lt;br /&gt;
&lt;br /&gt;
=== PHP Pros ===&lt;br /&gt;
&lt;br /&gt;
* '''Largest support community:''' Easy to find help if you get stuck.&lt;br /&gt;
* '''Distribution:''' Runs on virtually any web server in existence.&lt;br /&gt;
&lt;br /&gt;
=== PHP Cons ===&lt;br /&gt;
&lt;br /&gt;
* '''Language:''' Few people will say that PHP is the most elegant language known to mankind.  The language makes it easy to fall into the trap of bad coding practices.&lt;br /&gt;
* '''Security:''' PHP does very little for you automatically in terms of web security.&lt;br /&gt;
&lt;br /&gt;
== Django ==&lt;br /&gt;
&lt;br /&gt;
[[Web Frameworks|Django]] is a web frameworks written in the [[Python]] scripting language.  In more ways than not, it is the Python equivalent of [[wikipedia:Ruby on Rails|Ruby on Rails]].&lt;br /&gt;
&lt;br /&gt;
=== Django Pros ===&lt;br /&gt;
&lt;br /&gt;
* '''Less Code:''' Implementing common web design patterns, like social login or commenting, is usually as easy as a ''pip install''.&lt;br /&gt;
* '''Conventions:''' Django forces you to write neat and organized code, leading to better software engineering practices and scalability down the road.&lt;br /&gt;
* '''Security:''' Django automatically implements common security practices, leading to a more robust web application.&lt;br /&gt;
&lt;br /&gt;
=== Django Cons ===&lt;br /&gt;
&lt;br /&gt;
* '''Difficult to Debug:''' Django's high level of abstraction is a double-edged sword, because bugs and errors are sometimes difficult to find and can take hours to fix.&lt;br /&gt;
* '''Heavyweight:''' Django is designed for larger web applications, and it is not suitable for smaller projects with just one or two controllers.&lt;br /&gt;
&lt;br /&gt;
== Bottle and Flask ==&lt;br /&gt;
&lt;br /&gt;
Bottle is a web ''microframework'' written in the [[Python]] scripting language.  Flask is similar option.  Although you did not explicitly use Bottle or Flask during a module, it's worth listing on this page.  In more ways than not, Bottle and Flask are the Python equivalents of the better-known [[wikipedia:Sinatra (software)|Sinatra]], a Ruby microframework.&lt;br /&gt;
&lt;br /&gt;
=== Bottle and Flask Pros ===&lt;br /&gt;
&lt;br /&gt;
* '''Lightweight:''' There are few enough files that you can find your way around and be in full control of your application logic.&lt;br /&gt;
* '''Access to Python Libraries:''' A lot of the things you do in Django you can do in Bottle and Flask, except that you have more control over the ways that they are implemented.&lt;br /&gt;
&lt;br /&gt;
=== Bottle and Flask Cons ===&lt;br /&gt;
&lt;br /&gt;
* '''Lack of Conventions:''' Bottle and Flask give you the tools you need to build maintainable code, but unlike Django, they don't force you to.  It's easy to end up with Python scripts containing hundreds of lines of unrelated application logic.&lt;br /&gt;
&lt;br /&gt;
== Node.JS and Express ==&lt;br /&gt;
&lt;br /&gt;
[[Node.JS]] is a low-level implementation of JavaScript that enables you to write networked and web applications.  Express is a Sinatra-like microframework that runs on top of Node.jS.&lt;br /&gt;
&lt;br /&gt;
It is also worth bringing your attention to [http://www.meteor.com/ Meteor], a bleeding-edge framework for Node.JS that abstracts away client-server communications.  (Watch the promo video; it's pretty awesome.)&lt;br /&gt;
&lt;br /&gt;
=== Node.JS Pros ===&lt;br /&gt;
&lt;br /&gt;
* '''Speed:''' Node.JS is the fastest of the options on this page.  It is easy to scale up your Node.JS applications.&lt;br /&gt;
* '''Modern:''' Node.JS is also the newest of the options on this page, so most of the plugins you find for it use the best and latest practices.&lt;br /&gt;
* '''Language:''' With Node.JS, you can use just one language for both your server-side and client-side logic.&lt;br /&gt;
* '''Real-Time Options:''' Node.JS enables you to write real-time applications with ease, for example, with Socket.IO.&lt;br /&gt;
&lt;br /&gt;
=== Node.JS Cons ===&lt;br /&gt;
&lt;br /&gt;
* '''Lack of Conventions:''' Like Bottle, Flask, and most other microframeworks, Node.JS and Express don't force you to stick to predefined conventions, giving the potential to build messy code.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 8]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Pong_Game&amp;diff=1690</id>
		<title>Pong Game</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Pong_Game&amp;diff=1690"/>
		<updated>2013-11-20T09:48:09Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* Connecting to Socket.IO */ Changing to conventional notation&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This article documents ''pong-game.js'', a pre-built JavaScript file that helps you implement your pong game.&lt;br /&gt;
&lt;br /&gt;
== Setup ==&lt;br /&gt;
&lt;br /&gt;
First thing first: set up a static file server running Node.JS.  We will need it in order to serve up our HTML and JavaScript content.&lt;br /&gt;
&lt;br /&gt;
=== File 1: pong-game.js ===&lt;br /&gt;
&lt;br /&gt;
The first file you can save in your ''static'' directory will be ''pong-game.js'', which you can download from here: http://classes.engineering.wustl.edu/cse330/content/pong-game.js&lt;br /&gt;
&lt;br /&gt;
We created the ''pong-game.js'' file for you to save you time and so that you can focus on the Node.JS and Socket.IO aspects of this module.  This file contains the core Pong engine, but it does ''not'' establish communication between users of any kind.&lt;br /&gt;
&lt;br /&gt;
=== File 2: client.js ===&lt;br /&gt;
&lt;br /&gt;
You should create an additional file, ''client.js'', which you include into ''client.html'' and which contains the client-side logic for your Pong game.  It should load after ''pong-game.js''.  You will be saving all of you client-side code in this file.&lt;br /&gt;
&lt;br /&gt;
=== File 3: client.html ===&lt;br /&gt;
&lt;br /&gt;
The third file you can save in your ''static'' directory should be an HTML file created from your favorite [[HTML and CSS#Quick and Easy Page Layout|Quick and Easy Page Layout]].  You need to add the following CSS rules:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;css&amp;quot;&amp;gt;&lt;br /&gt;
#gameContainer{&lt;br /&gt;
	margin: 0 auto;&lt;br /&gt;
	width: 960px;&lt;br /&gt;
	height: 500px;&lt;br /&gt;
}&lt;br /&gt;
#controls{&lt;br /&gt;
	height: 20px;&lt;br /&gt;
	text-align: center;&lt;br /&gt;
}&lt;br /&gt;
#game{&lt;br /&gt;
	width: 960px;&lt;br /&gt;
	height: 480px;&lt;br /&gt;
	border: 1px solid black;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Add the following HTML inside your ''main'' div; this is what will contain the Pong game canvas:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;div id=&amp;quot;gameContainer&amp;quot; style=&amp;quot;display:none;&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;div id=&amp;quot;game&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You also need to require ''pong-game.js'' and ''client.js''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;script src=&amp;quot;pong-game.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;script src=&amp;quot;client.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Connecting to Socket.IO ===&lt;br /&gt;
&lt;br /&gt;
Now that you have your static fileserver running that serves up your three files (''pong-game.js'', ''client.html'', and ''client.js''), we need to connect everything with Socket.IO.&lt;br /&gt;
&lt;br /&gt;
Set up a static fileserver by following the instructions in [[Node.JS|the Node.JS guide]].  When finished, add the following lines:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var io = socketio.listen(app);&lt;br /&gt;
io.sockets.on(&amp;quot;connection&amp;quot;, function(socket){&lt;br /&gt;
	// This closure runs when a new Socket.IO connection is established.&lt;br /&gt;
	&lt;br /&gt;
	// Listen for client messaging server:&lt;br /&gt;
	socket.on(&amp;quot;message&amp;quot;, function(content){&lt;br /&gt;
		// do stuff&lt;br /&gt;
	});&lt;br /&gt;
	&lt;br /&gt;
	// Send a message from the server to the client:&lt;br /&gt;
	socket.emit(&amp;quot;message&amp;quot;, {some:&amp;quot;data&amp;quot;});&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Don't forget to require socket.io at the top of your file!&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
socketio = require(&amp;quot;socket.io&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You also need to make sure to install ''socket.io'' from npm.&lt;br /&gt;
&lt;br /&gt;
Inside of the ''io.listen'' callback function is where most of your server-side code will go.&lt;br /&gt;
&lt;br /&gt;
On the client side, you need to include the Socket.IO library (put this above ''pong-game.js'' and ''client.js''):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&amp;lt;script src=&amp;quot;/socket.io/socket.io.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And finally, you need to connect your client to the Socket.IO server (put this in ''client.js''):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;var socket = io.connect(window.location.origin);&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
But enough of us giving you all the code!  It's time for you to start being creative.&lt;br /&gt;
&lt;br /&gt;
== The API ==&lt;br /&gt;
&lt;br /&gt;
For the remainder of this module, your work will be in three files:&lt;br /&gt;
&lt;br /&gt;
* app.js (or whatever you called your Node.JS file)&lt;br /&gt;
* client.html&lt;br /&gt;
* client.js&lt;br /&gt;
&lt;br /&gt;
What you need to do is to build a system that enables two players who are both viewing ''client.html'' to choose each other (e.g., from a lobby) and play a game of Pong.&lt;br /&gt;
&lt;br /&gt;
You should be wondering, &amp;quot;how do I interact with the Pong game?&amp;quot;  The public interface is as follows.&lt;br /&gt;
&lt;br /&gt;
=== Methods ===&lt;br /&gt;
&lt;br /&gt;
* '''pong.init()'''&lt;br /&gt;
*: Initialize the game client.&lt;br /&gt;
* '''pong.resetBall([x, y])'''&lt;br /&gt;
*: Arbitrarily set the position of the ball.  Defaults to the center if no arguments are given.  Cancels all animations currently acting on the ball.&lt;br /&gt;
* '''pong.launch(angle, direction)'''&lt;br /&gt;
*: Launch the ball ''from its current position'' in the specified ''angle'' (-89 to +89) and direction (-1 for left or 1 for right).&lt;br /&gt;
* '''pong.updateOpponentPaddle(position)'''&lt;br /&gt;
*: Set the position of the opponent paddle to ''position''.  (Hint: the ''position'' value should have been generated by the opponent's '''paddlemove''' event)&lt;br /&gt;
* '''pong.pauseOrResumeGame()'''&lt;br /&gt;
*: Set the game in a paused state, or remove the game from a paused state.&lt;br /&gt;
* '''pong.ready()'''&lt;br /&gt;
*: Returns true if the game is not in a &amp;quot;paused&amp;quot; state.&lt;br /&gt;
* '''pong.setScore(score)'''&lt;br /&gt;
*: Display score on the game canvas.  ''score'' is an object literal containing two fields: left and right.&lt;br /&gt;
&lt;br /&gt;
=== Events ===&lt;br /&gt;
&lt;br /&gt;
All events for the pong game are fired on the window.&lt;br /&gt;
&lt;br /&gt;
* '''paddlemove'''&lt;br /&gt;
*: The player's paddle has moved.&lt;br /&gt;
*: This event will fire only after the paddle has moved 15 pixels or more.&lt;br /&gt;
** '''event.detail.position'''&lt;br /&gt;
**: The new y coordinate of the paddle.&lt;br /&gt;
* '''paddlehit-left'''&lt;br /&gt;
*: The ball has hit the left side of the screen.&lt;br /&gt;
** '''event.detail.hit'''&lt;br /&gt;
**: True if the ball hit the player's paddle; false otherwise.&lt;br /&gt;
** '''event.detail.angle'''&lt;br /&gt;
**: If the ball was reflected, the new angle of the ball's rightward movement.&lt;br /&gt;
** '''event.detail.position'''&lt;br /&gt;
**: The position at which the ball hit the left side.&lt;br /&gt;
&lt;br /&gt;
=== Problems with Our Interface ===&lt;br /&gt;
&lt;br /&gt;
There are at least two major problematic issues with our API:&lt;br /&gt;
&lt;br /&gt;
* We are firing events on the window.  We should have taken the time to make our Pong class implement the EventTarget interface directly.&lt;br /&gt;
* We are putting more trust in the client than we should, because the client can fake any angle and position upon the '''paddlehit-left''' event and manipulate the game in his or her favor.  The trajectory should be computed on the Node.JS side.&lt;br /&gt;
&lt;br /&gt;
Just be aware of the above issues as you complete this lab.  You won't be required to fix them, although if you do (and if you recompile your modified code with Lime) you may be a candidate for extra credit.&lt;br /&gt;
&lt;br /&gt;
=== Enabling a Player to Pause ===&lt;br /&gt;
&lt;br /&gt;
''You do not need to implement pausing for the purposes of Module 7.  If you do, you can earn 5 points of creative portion.''&lt;br /&gt;
&lt;br /&gt;
Implementing a game pause is more difficult for a network game than it is for a game that runs on just one computer: you need to make sure that the game is in a state such that you won't run into any race conditions, etc.&lt;br /&gt;
&lt;br /&gt;
One situation during a Pong game when it makes sense to enable a user to pause the game is after a user has lost a round.  Since the game at that point in time is waiting for the player to launch the next ball, we shouldn't have any race conditions.&lt;br /&gt;
&lt;br /&gt;
If you implement pausing, the '''pong.pauseOrResumeGame()''' and '''pong.ready()''' functions will come in handy.&lt;br /&gt;
&lt;br /&gt;
== Examples ==&lt;br /&gt;
&lt;br /&gt;
=== Starting a Pong Game ===&lt;br /&gt;
&lt;br /&gt;
Once two players have formed a pair, one of them needs to initialize the game with a certain angle and direction for the ball.  Here is how you might go about doing this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// generate an initial angle between -60 degrees and +60 degrees:&lt;br /&gt;
var initAngle = -60 + 120*Math.random();&lt;br /&gt;
&lt;br /&gt;
// randomly choose the initial direction of the ball:&lt;br /&gt;
var initDirection = Math.random() &amp;lt; 0.5 ? -1 : 1;&lt;br /&gt;
&lt;br /&gt;
// show the game canvas:&lt;br /&gt;
document.getElementById(&amp;quot;gameContainer&amp;quot;).style.display = &amp;quot;block&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
// initialize the game canvas:&lt;br /&gt;
pong.init();&lt;br /&gt;
&lt;br /&gt;
// move the ball to the center:&lt;br /&gt;
pong.resetBall();&lt;br /&gt;
&lt;br /&gt;
// set the ball into motion:&lt;br /&gt;
pong.launch(initAngle, initDirection);&lt;br /&gt;
&lt;br /&gt;
// tell the server about the ball's initial angle and direction.  For example:&lt;br /&gt;
socket.emit(&amp;quot;launch&amp;quot;, {&lt;br /&gt;
	angle: initAngle,&lt;br /&gt;
	direction: initDirection&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== When a Player Reflects the Ball ===&lt;br /&gt;
&lt;br /&gt;
When the ball hits a player's side, the '''paddlehit-left''' event fires on the window.  Here is how you might listen for this event in your ''client.js'' and transmit this information over your socket:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
window.addEventListener(&amp;quot;paddlehit-left&amp;quot;, function(e){&lt;br /&gt;
	// e.detail.hit will be true if the client hit the ball with his/her paddle.&lt;br /&gt;
	if (e.detail.hit) {&lt;br /&gt;
		console.log(&amp;quot;HIT PADDLE.  New angle: %f&amp;quot;, e.detail.angle); // log a message to the console&lt;br /&gt;
		&lt;br /&gt;
		// Tell our opponent via Socket.IO about the ball's new angle and position:&lt;br /&gt;
		socket.emit(&amp;quot;reflect&amp;quot;, {&lt;br /&gt;
			angle: e.detail.angle,&lt;br /&gt;
			position: e.detail.position&lt;br /&gt;
		});&lt;br /&gt;
		&lt;br /&gt;
		// Note: The game automatically launches the ball and determines the angle based on the ball's position relative to the paddle position.  We therefore do not need to call pong.launch() in here (but our opponent will, as shown below).&lt;br /&gt;
	}else{&lt;br /&gt;
		console.log(&amp;quot;MISSED PADDLE&amp;quot;);&lt;br /&gt;
		&lt;br /&gt;
		// in here, we will update the score, check for victory condition, launch a new ball (perhaps after a timeout), etc.&lt;br /&gt;
	}&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is what you might have in ''app.js'' inside of your Socket.IO callback function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Listen for the &amp;quot;reflect&amp;quot; message from the client&lt;br /&gt;
socket.on(&amp;quot;reflect&amp;quot;, function(data){&lt;br /&gt;
	// Tell our opponent about the reflection.&lt;br /&gt;
	// Note: In this sample implementation, we store the opponent in `socket.opponent`.&lt;br /&gt;
	// You might use a different mechanism for storing the opponent's socket.&lt;br /&gt;
	socket.opponent.emit(&amp;quot;reflect&amp;quot;, data);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, here is what you might have on the opponent's end (hint: this is also in ''client.js''):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Listen for the &amp;quot;reflect&amp;quot; message from the server&lt;br /&gt;
socket.on(&amp;quot;reflect&amp;quot;, function(data){&lt;br /&gt;
	// In order to make up for any network lag, immediately move the ball to its correct position:&lt;br /&gt;
	pong.resetBall(960, data.position);&lt;br /&gt;
	&lt;br /&gt;
	// Finally, launch the ball on our local game client:&lt;br /&gt;
	pong.launch(data.angle, -1);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Flow Chart ==&lt;br /&gt;
&lt;br /&gt;
If you are a visual learner, this flow chart of the logic you need to build for the pong game might be useful.&lt;br /&gt;
&lt;br /&gt;
[[File:Module 7 Flow Chart.png]]&lt;br /&gt;
&lt;br /&gt;
== How We Built pong-game.js ==&lt;br /&gt;
&lt;br /&gt;
If you are curious, we used the [http://www.limejs.com/ LimeJS] framework as the backbone of ''pong-game.js''.  You can find the pre-compiled source code for the Pong game here:&lt;br /&gt;
&lt;br /&gt;
* http://classes.engineering.wustl.edu/cse330/content/pong.js&lt;br /&gt;
* http://classes.engineering.wustl.edu/cse330/content/ball.js&lt;br /&gt;
&lt;br /&gt;
We then used the [https://developers.google.com/closure/compiler/ Google Closure Compiler] to compile all of the libraries you need into the one modular JavaScript file.&lt;br /&gt;
&lt;br /&gt;
Just to be clear, ''for the purposes of Module 7, you do not need to bother with either LimeJS or Google Closure.''&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 7]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Socket.IO&amp;diff=1689</id>
		<title>Socket.IO</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Socket.IO&amp;diff=1689"/>
		<updated>2013-11-20T09:47:00Z</updated>

		<summary type="html">&lt;p&gt;Shane: /* The Chat Server */ Changing to conventional notation&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;AJAX is useful when one-way communication is satisfactory for your web application.  However, what happens when you need two-way communication, like a chat client or multiplayer game?  AJAX isn't the tool for the job.  This is where '''Socket.IO''' comes in.&lt;br /&gt;
&lt;br /&gt;
Built to work natively with Node.JS, Socket.IO enables asynchronous, two-way communication between the server and the client.  This means that the server can send messages to the client without the client having to ask first, as is the case with AJAX.  As you learn Socket.IO, Non-Blocking I/O will become your best friend!&lt;br /&gt;
&lt;br /&gt;
== Installing Socket.IO ==&lt;br /&gt;
&lt;br /&gt;
Before you install Socket.IO, you need to install [[Node.JS]] and NPM, which is often installed automatically when you install Node.JS.&lt;br /&gt;
&lt;br /&gt;
The NPM package manager is different from many of the package managers we've used in that you need to install remote packages for every project in which you use them.  This means that you need to '''cd''' to the working directory in which you want to keep your Node.JS JavaScript file, ''and then'' run the following command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm install socket.io&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' If you pass the ''-g'' to ''npm install'', then the package will be installed &amp;quot;globally&amp;quot; on your instance, so all Node.JS projects will be able to use it.  However, this is not recommended for all projects.  [http://blog.nodejs.org/2011/04/06/npm-1-0-link/ Read Node.JS's justification here.]&lt;br /&gt;
&lt;br /&gt;
== Messaging ==&lt;br /&gt;
&lt;br /&gt;
Socket.IO works by having clients send messages to the server and the server send messages to clients.  For example, consider the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Computer A:&lt;br /&gt;
socket.emit(&amp;quot;info&amp;quot;, {&lt;br /&gt;
	&amp;quot;hello&amp;quot;: &amp;quot;world&amp;quot;&lt;br /&gt;
});&lt;br /&gt;
&lt;br /&gt;
// Computer B:&lt;br /&gt;
socket.on(&amp;quot;info&amp;quot;, function (data) {&lt;br /&gt;
	console.log(data.hello);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Computer A could be ''either the client or the server'', and Computer B would be the other.  When '''socket.emit(name, data)''' is called on either end, the callback function in '''socket.on''' that listens for the message named ''name'' is called with the ''data'' from '''socket.emit'''.&lt;br /&gt;
&lt;br /&gt;
== A First Socket.IO Application: Chat Server and Client ==&lt;br /&gt;
&lt;br /&gt;
Building a chat client is surprising simple using Socket.IO and Node.JS, and it gives great insight into the workings of Socket.IO.  Take the time to understand how this example works, and ask questions; if you understand this, the group portion will be easy!&lt;br /&gt;
&lt;br /&gt;
=== The Chat Server ===&lt;br /&gt;
&lt;br /&gt;
You can make a file called ''chat-server.js'' with the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Require the packages we will use:&lt;br /&gt;
var http = require(&amp;quot;http&amp;quot;),&lt;br /&gt;
	socketio = require(&amp;quot;socket.io&amp;quot;),&lt;br /&gt;
	fs = require(&amp;quot;fs&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
// Listen for HTTP connections.  This is essentially a miniature static file server that only serves our one file, chat.html:&lt;br /&gt;
var app = http.createServer(function(req, resp){&lt;br /&gt;
	// This callback runs when a new connection is made to our HTTP server.&lt;br /&gt;
	fs.readFile(&amp;quot;chat.html&amp;quot;, function(err, data){&lt;br /&gt;
		// This callback runs when the chat.html file has been read from the filesystem.&lt;br /&gt;
		if(err) return resp.writeHead(500);&lt;br /&gt;
		resp.writeHead(200);&lt;br /&gt;
		resp.end(data);&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
app.listen(3456);&lt;br /&gt;
&lt;br /&gt;
// Do the Socket.IO magic:&lt;br /&gt;
var io = socketio.listen(app);&lt;br /&gt;
io.sockets.on(&amp;quot;connection&amp;quot;, function(socket){&lt;br /&gt;
	// This callback runs when a new Socket.IO connection is established.&lt;br /&gt;
	socket.on(&amp;quot;message&amp;quot;, function(content){&lt;br /&gt;
		// This callback runs when the client sends us a &amp;quot;message&amp;quot; event&lt;br /&gt;
		console.log(&amp;quot;message: &amp;quot;+content); // log it to the Node.JS output&lt;br /&gt;
		socket.broadcast.emit(&amp;quot;someonesaid&amp;quot;, content); // broadcast the message to other users&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code makes a simple HTTP server that responds to all connections with the contents of the file &amp;quot;chat.html&amp;quot;, which we will make in the next step.  We tell Socket.IO to listen for &amp;quot;message&amp;quot; events, and when it hears one, it should emit a new event called &amp;quot;someone said&amp;quot; back to the connected clients.&lt;br /&gt;
&lt;br /&gt;
=== The Chat Client ===&lt;br /&gt;
&lt;br /&gt;
Here is a front-end client that could work with our server, in ''chat.html'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
&amp;lt;title&amp;gt;Chat Client&amp;lt;/title&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!-- Include the Socket.IO and Ext libraries --&amp;gt;&lt;br /&gt;
&amp;lt;script src=&amp;quot;/socket.io/socket.io.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;script src=&amp;quot;//cdn.sencha.io/ext-4.1.1-gpl/ext-all-dev.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!-- Write our custom code --&amp;gt;&lt;br /&gt;
&amp;lt;script&amp;gt;&lt;br /&gt;
Ext.DomHelper.useDom = true; // prevent XSS&lt;br /&gt;
&lt;br /&gt;
var socket = io.connect();&lt;br /&gt;
socket.on(&amp;quot;someonesaid&amp;quot;, function(content){&lt;br /&gt;
	// This callback runs when the server sends us a &amp;quot;someonesaid&amp;quot; event&lt;br /&gt;
	Ext.fly(&amp;quot;messages&amp;quot;).createChild({&lt;br /&gt;
		tag: &amp;quot;li&amp;quot;,&lt;br /&gt;
		children: [content]&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
Ext.onReady(function(){&lt;br /&gt;
	Ext.fly(&amp;quot;send&amp;quot;).on(&amp;quot;click&amp;quot;, function(){&lt;br /&gt;
		// When the &amp;quot;send&amp;quot; button is clicked, emit a &amp;quot;message&amp;quot; event to the server containing a chat message&lt;br /&gt;
		socket.emit(&amp;quot;message&amp;quot;, Ext.fly(&amp;quot;comment&amp;quot;).getValue());&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/script&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
&amp;lt;ul id=&amp;quot;messages&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;/ul&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
	&amp;lt;textarea id=&amp;quot;comment&amp;quot;&amp;gt;&amp;lt;/textarea&amp;gt;&lt;br /&gt;
	&amp;lt;button id=&amp;quot;send&amp;quot;&amp;gt;Send Comment&amp;lt;/button&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' This example passes strings as the event data, but you can pass any JavaScript datatype, including object literals.&lt;br /&gt;
&lt;br /&gt;
To see this in action, save these two files in the same directory, cd over to the directory, and start the server:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;$ node chat-server.js&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Fire up your favorite browser and navigate to http://localhost:3456/.  Open the page in two windows.  Violà: you have your (very basic) chat client!&lt;br /&gt;
&lt;br /&gt;
== Resources ==&lt;br /&gt;
&lt;br /&gt;
The [http://socket.io/ Socket.IO web site] has concise examples that tell you pretty much all you need to know in order to build a functional Socket.IO web application.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 7]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Pong_Game&amp;diff=1688</id>
		<title>Pong Game</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Pong_Game&amp;diff=1688"/>
		<updated>2013-11-19T06:06:14Z</updated>

		<summary type="html">&lt;p&gt;Shane: Adding flow chart&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This article documents ''pong-game.js'', a pre-built JavaScript file that helps you implement your pong game.&lt;br /&gt;
&lt;br /&gt;
== Setup ==&lt;br /&gt;
&lt;br /&gt;
First thing first: set up a static file server running Node.JS.  We will need it in order to serve up our HTML and JavaScript content.&lt;br /&gt;
&lt;br /&gt;
=== File 1: pong-game.js ===&lt;br /&gt;
&lt;br /&gt;
The first file you can save in your ''static'' directory will be ''pong-game.js'', which you can download from here: http://classes.engineering.wustl.edu/cse330/content/pong-game.js&lt;br /&gt;
&lt;br /&gt;
We created the ''pong-game.js'' file for you to save you time and so that you can focus on the Node.JS and Socket.IO aspects of this module.  This file contains the core Pong engine, but it does ''not'' establish communication between users of any kind.&lt;br /&gt;
&lt;br /&gt;
=== File 2: client.js ===&lt;br /&gt;
&lt;br /&gt;
You should create an additional file, ''client.js'', which you include into ''client.html'' and which contains the client-side logic for your Pong game.  It should load after ''pong-game.js''.  You will be saving all of you client-side code in this file.&lt;br /&gt;
&lt;br /&gt;
=== File 3: client.html ===&lt;br /&gt;
&lt;br /&gt;
The third file you can save in your ''static'' directory should be an HTML file created from your favorite [[HTML and CSS#Quick and Easy Page Layout|Quick and Easy Page Layout]].  You need to add the following CSS rules:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;css&amp;quot;&amp;gt;&lt;br /&gt;
#gameContainer{&lt;br /&gt;
	margin: 0 auto;&lt;br /&gt;
	width: 960px;&lt;br /&gt;
	height: 500px;&lt;br /&gt;
}&lt;br /&gt;
#controls{&lt;br /&gt;
	height: 20px;&lt;br /&gt;
	text-align: center;&lt;br /&gt;
}&lt;br /&gt;
#game{&lt;br /&gt;
	width: 960px;&lt;br /&gt;
	height: 480px;&lt;br /&gt;
	border: 1px solid black;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Add the following HTML inside your ''main'' div; this is what will contain the Pong game canvas:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;div id=&amp;quot;gameContainer&amp;quot; style=&amp;quot;display:none;&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;div id=&amp;quot;game&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You also need to require ''pong-game.js'' and ''client.js''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;script src=&amp;quot;pong-game.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;script src=&amp;quot;client.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Connecting to Socket.IO ===&lt;br /&gt;
&lt;br /&gt;
Now that you have your static fileserver running that serves up your three files (''pong-game.js'', ''client.html'', and ''client.js''), we need to connect everything with Socket.IO.&lt;br /&gt;
&lt;br /&gt;
Set up a static fileserver by following the instructions in [[Node.JS|the Node.JS guide]].  When finished, add the following lines:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
io.listen(app).sockets.on(&amp;quot;connection&amp;quot;, function(socket){&lt;br /&gt;
	// This closure runs when a new Socket.IO connection is established.&lt;br /&gt;
	&lt;br /&gt;
	// Listen for client messaging server:&lt;br /&gt;
	socket.on(&amp;quot;message&amp;quot;, function(content){&lt;br /&gt;
		// do stuff&lt;br /&gt;
	});&lt;br /&gt;
	&lt;br /&gt;
	// Send a message from the server to the client:&lt;br /&gt;
	socket.emit(&amp;quot;message&amp;quot;, {some:&amp;quot;data&amp;quot;});&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Don't forget to require socket.io at the top of your file!&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
io = require(&amp;quot;socket.io&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You also need to make sure to install ''socket.io'' from npm.&lt;br /&gt;
&lt;br /&gt;
Inside of the ''io.listen'' callback function is where most of your server-side code will go.&lt;br /&gt;
&lt;br /&gt;
On the client side, you need to include the Socket.IO library (put this above ''pong-game.js'' and ''client.js''):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&amp;lt;script src=&amp;quot;/socket.io/socket.io.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And finally, you need to connect your client to the Socket.IO server (put this in ''client.js''):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;var socket = io.connect(window.location.origin);&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
But enough of us giving you all the code!  It's time for you to start being creative.&lt;br /&gt;
&lt;br /&gt;
== The API ==&lt;br /&gt;
&lt;br /&gt;
For the remainder of this module, your work will be in three files:&lt;br /&gt;
&lt;br /&gt;
* app.js (or whatever you called your Node.JS file)&lt;br /&gt;
* client.html&lt;br /&gt;
* client.js&lt;br /&gt;
&lt;br /&gt;
What you need to do is to build a system that enables two players who are both viewing ''client.html'' to choose each other (e.g., from a lobby) and play a game of Pong.&lt;br /&gt;
&lt;br /&gt;
You should be wondering, &amp;quot;how do I interact with the Pong game?&amp;quot;  The public interface is as follows.&lt;br /&gt;
&lt;br /&gt;
=== Methods ===&lt;br /&gt;
&lt;br /&gt;
* '''pong.init()'''&lt;br /&gt;
*: Initialize the game client.&lt;br /&gt;
* '''pong.resetBall([x, y])'''&lt;br /&gt;
*: Arbitrarily set the position of the ball.  Defaults to the center if no arguments are given.  Cancels all animations currently acting on the ball.&lt;br /&gt;
* '''pong.launch(angle, direction)'''&lt;br /&gt;
*: Launch the ball ''from its current position'' in the specified ''angle'' (-89 to +89) and direction (-1 for left or 1 for right).&lt;br /&gt;
* '''pong.updateOpponentPaddle(position)'''&lt;br /&gt;
*: Set the position of the opponent paddle to ''position''.  (Hint: the ''position'' value should have been generated by the opponent's '''paddlemove''' event)&lt;br /&gt;
* '''pong.pauseOrResumeGame()'''&lt;br /&gt;
*: Set the game in a paused state, or remove the game from a paused state.&lt;br /&gt;
* '''pong.ready()'''&lt;br /&gt;
*: Returns true if the game is not in a &amp;quot;paused&amp;quot; state.&lt;br /&gt;
* '''pong.setScore(score)'''&lt;br /&gt;
*: Display score on the game canvas.  ''score'' is an object literal containing two fields: left and right.&lt;br /&gt;
&lt;br /&gt;
=== Events ===&lt;br /&gt;
&lt;br /&gt;
All events for the pong game are fired on the window.&lt;br /&gt;
&lt;br /&gt;
* '''paddlemove'''&lt;br /&gt;
*: The player's paddle has moved.&lt;br /&gt;
*: This event will fire only after the paddle has moved 15 pixels or more.&lt;br /&gt;
** '''event.detail.position'''&lt;br /&gt;
**: The new y coordinate of the paddle.&lt;br /&gt;
* '''paddlehit-left'''&lt;br /&gt;
*: The ball has hit the left side of the screen.&lt;br /&gt;
** '''event.detail.hit'''&lt;br /&gt;
**: True if the ball hit the player's paddle; false otherwise.&lt;br /&gt;
** '''event.detail.angle'''&lt;br /&gt;
**: If the ball was reflected, the new angle of the ball's rightward movement.&lt;br /&gt;
** '''event.detail.position'''&lt;br /&gt;
**: The position at which the ball hit the left side.&lt;br /&gt;
&lt;br /&gt;
=== Problems with Our Interface ===&lt;br /&gt;
&lt;br /&gt;
There are at least two major problematic issues with our API:&lt;br /&gt;
&lt;br /&gt;
* We are firing events on the window.  We should have taken the time to make our Pong class implement the EventTarget interface directly.&lt;br /&gt;
* We are putting more trust in the client than we should, because the client can fake any angle and position upon the '''paddlehit-left''' event and manipulate the game in his or her favor.  The trajectory should be computed on the Node.JS side.&lt;br /&gt;
&lt;br /&gt;
Just be aware of the above issues as you complete this lab.  You won't be required to fix them, although if you do (and if you recompile your modified code with Lime) you may be a candidate for extra credit.&lt;br /&gt;
&lt;br /&gt;
=== Enabling a Player to Pause ===&lt;br /&gt;
&lt;br /&gt;
''You do not need to implement pausing for the purposes of Module 7.  If you do, you can earn 5 points of creative portion.''&lt;br /&gt;
&lt;br /&gt;
Implementing a game pause is more difficult for a network game than it is for a game that runs on just one computer: you need to make sure that the game is in a state such that you won't run into any race conditions, etc.&lt;br /&gt;
&lt;br /&gt;
One situation during a Pong game when it makes sense to enable a user to pause the game is after a user has lost a round.  Since the game at that point in time is waiting for the player to launch the next ball, we shouldn't have any race conditions.&lt;br /&gt;
&lt;br /&gt;
If you implement pausing, the '''pong.pauseOrResumeGame()''' and '''pong.ready()''' functions will come in handy.&lt;br /&gt;
&lt;br /&gt;
== Examples ==&lt;br /&gt;
&lt;br /&gt;
=== Starting a Pong Game ===&lt;br /&gt;
&lt;br /&gt;
Once two players have formed a pair, one of them needs to initialize the game with a certain angle and direction for the ball.  Here is how you might go about doing this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// generate an initial angle between -60 degrees and +60 degrees:&lt;br /&gt;
var initAngle = -60 + 120*Math.random();&lt;br /&gt;
&lt;br /&gt;
// randomly choose the initial direction of the ball:&lt;br /&gt;
var initDirection = Math.random() &amp;lt; 0.5 ? -1 : 1;&lt;br /&gt;
&lt;br /&gt;
// show the game canvas:&lt;br /&gt;
document.getElementById(&amp;quot;gameContainer&amp;quot;).style.display = &amp;quot;block&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
// initialize the game canvas:&lt;br /&gt;
pong.init();&lt;br /&gt;
&lt;br /&gt;
// move the ball to the center:&lt;br /&gt;
pong.resetBall();&lt;br /&gt;
&lt;br /&gt;
// set the ball into motion:&lt;br /&gt;
pong.launch(initAngle, initDirection);&lt;br /&gt;
&lt;br /&gt;
// tell the server about the ball's initial angle and direction.  For example:&lt;br /&gt;
socket.emit(&amp;quot;launch&amp;quot;, {&lt;br /&gt;
	angle: initAngle,&lt;br /&gt;
	direction: initDirection&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== When a Player Reflects the Ball ===&lt;br /&gt;
&lt;br /&gt;
When the ball hits a player's side, the '''paddlehit-left''' event fires on the window.  Here is how you might listen for this event in your ''client.js'' and transmit this information over your socket:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
window.addEventListener(&amp;quot;paddlehit-left&amp;quot;, function(e){&lt;br /&gt;
	// e.detail.hit will be true if the client hit the ball with his/her paddle.&lt;br /&gt;
	if (e.detail.hit) {&lt;br /&gt;
		console.log(&amp;quot;HIT PADDLE.  New angle: %f&amp;quot;, e.detail.angle); // log a message to the console&lt;br /&gt;
		&lt;br /&gt;
		// Tell our opponent via Socket.IO about the ball's new angle and position:&lt;br /&gt;
		socket.emit(&amp;quot;reflect&amp;quot;, {&lt;br /&gt;
			angle: e.detail.angle,&lt;br /&gt;
			position: e.detail.position&lt;br /&gt;
		});&lt;br /&gt;
		&lt;br /&gt;
		// Note: The game automatically launches the ball and determines the angle based on the ball's position relative to the paddle position.  We therefore do not need to call pong.launch() in here (but our opponent will, as shown below).&lt;br /&gt;
	}else{&lt;br /&gt;
		console.log(&amp;quot;MISSED PADDLE&amp;quot;);&lt;br /&gt;
		&lt;br /&gt;
		// in here, we will update the score, check for victory condition, launch a new ball (perhaps after a timeout), etc.&lt;br /&gt;
	}&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is what you might have in ''app.js'' inside of your Socket.IO callback function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Listen for the &amp;quot;reflect&amp;quot; message from the client&lt;br /&gt;
socket.on(&amp;quot;reflect&amp;quot;, function(data){&lt;br /&gt;
	// Tell our opponent about the reflection.&lt;br /&gt;
	// Note: In this sample implementation, we store the opponent in `socket.opponent`.&lt;br /&gt;
	// You might use a different mechanism for storing the opponent's socket.&lt;br /&gt;
	socket.opponent.emit(&amp;quot;reflect&amp;quot;, data);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, here is what you might have on the opponent's end (hint: this is also in ''client.js''):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Listen for the &amp;quot;reflect&amp;quot; message from the server&lt;br /&gt;
socket.on(&amp;quot;reflect&amp;quot;, function(data){&lt;br /&gt;
	// In order to make up for any network lag, immediately move the ball to its correct position:&lt;br /&gt;
	pong.resetBall(960, data.position);&lt;br /&gt;
	&lt;br /&gt;
	// Finally, launch the ball on our local game client:&lt;br /&gt;
	pong.launch(data.angle, -1);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Flow Chart ==&lt;br /&gt;
&lt;br /&gt;
If you are a visual learner, this flow chart of the logic you need to build for the pong game might be useful.&lt;br /&gt;
&lt;br /&gt;
[[File:Module 7 Flow Chart.png]]&lt;br /&gt;
&lt;br /&gt;
== How We Built pong-game.js ==&lt;br /&gt;
&lt;br /&gt;
If you are curious, we used the [http://www.limejs.com/ LimeJS] framework as the backbone of ''pong-game.js''.  You can find the pre-compiled source code for the Pong game here:&lt;br /&gt;
&lt;br /&gt;
* http://classes.engineering.wustl.edu/cse330/content/pong.js&lt;br /&gt;
* http://classes.engineering.wustl.edu/cse330/content/ball.js&lt;br /&gt;
&lt;br /&gt;
We then used the [https://developers.google.com/closure/compiler/ Google Closure Compiler] to compile all of the libraries you need into the one modular JavaScript file.&lt;br /&gt;
&lt;br /&gt;
Just to be clear, ''for the purposes of Module 7, you do not need to bother with either LimeJS or Google Closure.''&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 7]]&lt;/div&gt;</summary>
		<author><name>Shane</name></author>
		
	</entry>
</feed>