python %s

replaced by given string.

given_string = "I think %s is a perfectly normal thing to do in public."
def sub1(s):
     return given_string % s
given_string2 = "I think %s and %s are perfectly normal things to do in public."
def sub2(s1, s2):
    return given_string2 % (s1, s2)

string substitution

given_string2 = "I'm %(nickname)s. My real name is %(name)s, but my friends call me %(nickname)s."
def sub_m(name, nickname):
    return given_string2 % {"nickname": nickname, "name" : name}
    
print sub_m("Mike", "Goose") 

replacement

def escape_html(s):
   for (i, o) in (("&", "&"),
                (">", ">"),
                ("<", "&lt;"),
                ('"', "&quote;")):
        s = s.replace(i, o)
    return s

 print escape_html('>')
import cgi
def escape_html(s):
   return cgi.escape(s, quote = True)

 print escape_html('"hello, & = &amp;"')

validation

str.capitalize(): returns a copy of the string with only its first character capitalized.

months = ['January',
          'February',
          'March',
          'April',
          'May',
          'June',
          'July',
          'August',
          'September',
          'October',
          'November',
          'December']
          
def valid_month(month):
    if month:
        cap_month = month.capitalize()
        if cap_month in months:
            return cap_month

use dictionary to restrict only three character.

month_abbvs = dic((m[:3].lower(), m) for m in months)
          
def valid_month(month):
    if month:
        short_month = month[:3].lower()
        return month_abbvs.get(short_month)

checking day

def valid_day(day):
    if day and day.isdigit():
     day = int(day)
     if day > 0 and <= 31:
         return day

telnet

[vagrant@localhost]$ sudo yum -y install telnet
Trying 35.160.185.106...
Connected to www.udacity.com.
Escape character is '^]'.
GET / HTTP/1.0
Host: www.example.com

HTTP/1.1 302 Found
Cache-Control: no-cache
Location: https://www.example.com/
Content-Length: 0
Connection: Close

input form

<form action="http://www.google.com/search">
  <input name="q">
  <input type="submit">
</form>

play.py

import webapp2

class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Hello, webapp World!')

app = webapp2.WSGIApplication([('/', MainPage)],
    debug=True)

ダブルクォーテーション3つでくくると、複数行に渡る文字列を記述することができる。

import webapp2

form="""
<form action="http://www.google.com/search">
  <input name="q">
  <input type="submit">
</form>
"""

class MainPage(webapp2.RequestHandler):
    def get(self):
        #self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Hello, webapp World!')

app = webapp2.WSGIApplication([('/', MainPage)],
    debug=True)

form parameter

<form>
  <input type="radio" name="q" value="one">
  <input type="radio" name="q" value="two">
  <input type="radio" name="q" value="third">
  <br>
  <input type="submit">
</form>
<form>
    <label>
        one
        <input typ\e="radio" name="q" value="one">
    </label>
    <label>
        two
        <input type="radio" name="q" value="two">
    </label>
    <label>
        three
        <input type="radio" name="q" value="third">
    </label>
  <br>
  <input type="submit">
</form>

select

<form>
    <select name="q">
        <option value="1">the number one</option>
        <option>two</option>
        <option>three</option>
    </select>
  <br>
  <input type="submit">
</form>

User validation

import webapp2

form="""
<form method="post">
  What is your birthday?
  <br>
  <label>Month
  <input type="text" name="month">
  </label>
  <label>Day
  <input type="text" name="day">
  </label>
  <label>Year
  <input type="text" name="year">
  </label>

  <br>
  <br>
  <input type="submit">
</form>
"""

class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.out.write(form)

    def post(self):
        self.response.out.write("Thanks! That's a totally valid day!")

app = webapp2.WSGIApplication([('/', MainPage),('/testform', TestHandler)],
    debug=True)

gulp sass

npm install gulp-sass

var gulp = require('gulp');
gulp.task('default', function(){
  console.log("hello, gulp!");
});

gulp.task('styles', function(){
  gulp.src('sass/**/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./css'));
});

gulp.task('default', function(){
  gulp.watch('sass/**/*.scss',['styles']);
});

Linting is the process of running a program that will analyse code for potential errors.
ESLint

[vagrant@localhost rss24]$ sudo npm install -g eslint

span:inline
div:block

parameter
?name=value

fragment
#fragment

gulp

gulp is inmemory stream.

1. Install gulp globally:

If you have previously installed a version of gulp globally, please run npm rm –global gulp to make sure your old version doesn’t collide with gulp-cli.

$ npm install –global gulp-cli
2. Initialize your project directory:

$ npm init
3. Install gulp in your project devDependencies:

$ npm install –save-dev gulp
4. Create a gulpfile.js at the root of your project:

var gulp = require(‘gulp’);

gulp.task(‘default’, function() {
// place code for your default task here
});
5. Run gulp:

$ gulp

gulpfile.js

var gulp = require('gulp');
gulp.task('default', function(){
  console.log("hello, gulp!");
});
[vagrant@localhost rss24]$ gulp
[12:35:58] Using gulpfile ~/gulpfile.js
[12:35:58] Starting 'default'...
hello, gulp!
[12:35:58] Finished 'default' after 109 μs

Run python server

shell command

python -m http.server 8000

write with canvas

<!DOCTYPE html>
<html>
<head>
</head>
<body>
	<canvas id="c" width="500" height="500"></canvas>
	<script>
		var c = document.querySelector("#c");
		var ctx = c.getContext("2d");

		ctx.fillRect(100, 100, 100, 100);
		ctx.strokeRect(50, 50, 50, 50);

	</script>
</body>
</head>
</html>
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer


class WebServerHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        if self.path.endswith("/hello"):
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            message = ""
            message += "<html><body>Hello!</body></html>"
            self.wfile.write(message)
            print message
            return

        if self.path.endswith("/hola"):
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            message = ""
            message += "<html><body> &#161 Hola ! <a href='/hello'>back to hello</a></body></html>"
            self.wfile.write(message)
            print message
            return

        else:
            self.send_error(404, 'File Not Found: %s' % self.path)


def main():
    try:
        port = 8080
        server = HTTPServer(('', port), WebServerHandler)
        print "Web Server running on port %s" % port
        server.serve_forever()
    except KeyboardInterrupt:
        print " ^C entered, stopping web server...."
        server.socket.close()

if __name__ == '__main__':
    main()
from flask import Flask
app = Flask(__name__)


@app.route('/')
@app.route('/hello')
def HelloWorld():
    return "Hello World"

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=5000)

Canvas

<!DOCTYPE html>
<html>
<head>
</head>
<body>
	<canvas id="c" width="200" height="200"></canvas>s
	<script>
		var c = document.querySelector("#c");
		var ctx = c.getContext("2d");

		var image = new Image();

		image.onload = function(){
			console.log("Loaded image");
			ctx.drawImage(image, 0, 0, c.width, c.height);
		}

		image.src = "fry_fixed.jpg";
	</script>
</body>
</head>
</html>

jQuery

var navList, firstItem, link;

navList = $('.nav-list');
firstItem = navList.children().first();
link = firstItem.find('a');
link.attr('href','#');
var articleItems;

articleItems = $('.article-item');
articleItems.css('font-size','20px');
$('#input').on('change', function(){
  var val;
  var = $('#input').val();
  h1 = $('.articles').children('h1');
  h1.text(val);
});
var articleItems;

articleItems = $('.article-item');
ul = articleItems.find('ul');
ul.remove();
var family1, family2, bruce, madison, hunter;

family1 = $('#family1');
family2 = $('<div id="family2"><h1>Family 2</h1></div>');
bruce = $('<div id="#bruce"><h2>Bruce</h2></div>');
madison = $('<div id="#madison"><h3>Madison</h2></div>');
hunter = $('<div id="#hunter"><h3>Hunter<h3></div>');
  family2.insertAfter(family1);
  family2.append(bruce);
  bruce.append(madison);
  bruce.append(hunter);
function numberAdder(){
    var text, number;
    text = $(this).text();
    number = text.length;

    $(this).text(text + "" + number);
}
$('p').each(numberAdder);
$('#my-input').on('keypress', function(){
  $('button').remove();
});

cowsay

Redhat and CentOS users: sudo yum install cowsay
[vagrant@localhost rss]$ cowsay all is not better
 ___________________
< all is not better >
 -------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

-manual
man cowsay

var home etc tmp

min jQuery is much faster than usual jQuery.