over 2 years ago

According to wikipedia, a closure is:

a technique for implementing lexically scoped name binding in languages with first-class functions.

I don't think this mouthful definition is comprehensible to anybody learning the language. So I decide to break it down and explain it in plain language.

Lexical Scope

Lexical scope = static scope, it refers to

determining a variable's scope based solely on its position within the textual corpus of code.

An example to illustrate this concept:

foo = 1; //a global variable that can be accessed from anywhere within the program


function log()
{
    var bar = 2; //a local variable can be only accessed by the function log itself

}

We can determine where foo and bar can be accessed within the program by looking at the code. Thus, the scopes of the variables are determined statically.

To contrast it with dynamic scope:

function log() {
    console.log(x); //resolve variable x at runtime (i.e. dynamically)
}

function print(){
    var x = getUserInput();
    log(); 
}

The value of x is not determined until runtime. Thus, console.log(x) has no idea what will be printed out. Also, x is neither a globally variable nor is defined within the log function. But log has access to it.

Note: this example above does not work in Javascript because JS does not support dynamic scoping.

So now we understand what the fancy term lexical scope means, let's take a look at the definition of first-class function

First-Class Function

A language supports:

  • passing functions as arguments to other functions
  • returning them as the values from other functions
  • assigning them to variables
  • storing them in data structures.

This one is easy to understand:

function isBigEnough(value) {
  return value >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); // the filter function expects a function being passed in as a parameter

I am not going to provide an example for each bullet point. But you get the idea. Passing, storing and returning functions are very common in Javascript.

Closure

According to this explanation,

Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created.

function outer(){
    var x = 5;  // the so called 'free' variable that can be accessed by inner()

    function inner(){
        console.log(x);
    }
    return inner;
}

var test = outer(); // outer() actually returns inner(), thus exposing inner() to the outside world

test(); // output 5

Highlights of this example:

  • inner() has access to variable x, which is defined outside of it
  • var test = outer() is equivalent of var test = inner() but test has no access to x
  • The value of x is stored in memory so that any subsequent call of test() will print 5

So to summarize what a closure is:

  • A function f that is nested within another function

- f accesses variables defined in the outer function

During the research of closure, another term comes up often:

Higher-order function

A function that does at least one of the following:

  • takes one or more functions as an input
  • outputs a function

So outer() is an example of a higher-order function because it outputs a function. The Mapfunction of a Javascript array is also a higher-order function because it takes a function as input.

 
over 2 years ago

I was given a task to randomly generate usernames and passwords for 80 users in Django. Here is how I did it:

Thanks to this excellent StackOverflow post, generating random characters become very easy:

import string
import random

def generate(size=5, numbers_only=False):
    base =  string.digits if numbers_only else string.ascii_lowercase + string.digits
    return ''.join(random.SystemRandom().choice(base) for _ in range(size))

I want to use lowercase characters for usernames and digits only for passwords. Thus, the optional parameter numbers_only is used to specific which format I want.

Then, open up the Django shell:

./manage.py shell

and Enter the following to the interactive shell to generate a user:

from django.contrib.auth.models import User
from note import utils

User.objects.create_user(utils.generate(), password=utils.generate(6, True))

I saved the generate() inside utils.py which is located inside a project named note. Modify from note import utils to suit your needs.

 
over 2 years ago

Use the --log-file=- option to send error messages to console:

gunicorn --log-file=-

After debugging is complete, remove this option and output the error message to a log file instead.

 
over 2 years ago

I have found a tool that allows you to write and test Javascript quickly in iPython Notebook. The tool is called IJavascript. The project page has a very detailed installation guide for differet OS.

To install it on Mac:

1) Install ijavascript itself via npm:

npm install -g ijavascript

2) Install the dependencies via pip:

sudo pip install --upgrade ipython jinja2 jsonschema pyzmq

3) to run:

ipython ijs

Here is a screenshot of it running:

 
almost 3 years ago

The default npm list command not only list the packages installed locally but also the packages they depend on. To most users, showing packages dependency is not necessary, as most of the time, we only want to know what is installed. To fix this, the --depth=0 option can be used:

npm ls --depth=0

So we get the list on the left instead of on the right:

dir_name@1.0.0 /path/blah/blah                 dir_name@1.0.0 /path/blah/blah
|-- babel-core@5.8.3                           |-- babel-core@5.8.3
                                                   |- babel-plugin-constant-folding@1.0.1
                                                   |- babel-plugin-eval@1.0.1
                                                   ...

However, this is not enough. Because if you have installed a package either

You are likely to see these errors:

npm ERR! max depth reached: webpack@*, required by babel-loader@5.3.2   // this error is caused by installing webpack globally
npm ERR! extraneous: file-loader@0.8.4 /blah/file-loader   // this error is caused by using npm install instead of npm install --save

To ignore these errors, a solution provided by this blog works:

npm ls --depth=0 "$@" 2>/dev/null

To create a proper shorcut, open your .bash_profile (for Mac):

alias nl="npm ls --depth=0 "$@" 2>/dev/null"
alias nlg="npm ls -g --depth=0 "$@" 2>/dev/null"  #for listing global packages

Reload the .bash_profile file and that's it!

. .bash_profile
 
almost 3 years ago

To reference globally installed NPM packages (i.e. packages installed with the "-g" option, like npm install -g webpack), a NODE_PATH has to be set in your environment. I used NVM to manage node.js and here is my setting (for Mac):

export NODE_PATH=/Users/cheng/.nvm/versions/node/v0.12.7/lib/node_modules

Now, you can reference these packages from anywhere.

If you use other OS, check out this post on StackOverflow.

 
almost 3 years ago

Use Jquery to get DOM elements

React.js injects code into HTML block like this:

React.render(
    <EditorForm />,
    document.getElementById('content)
);

To use Jquery to accomplish the samething:

React.render(
    <EditorForm />,
    $("#content")[0]
);

$("#content") along is not enough, because it returns a jquery object instead of a DOM object.

Why does React.js render function's return statement is surrounded by a parenthese?

This is because JavaScript does automatic semicolon insertion

When the following line is entered:

var test = 'str1'
           'str2'
           'str3';

The output is not an error, but instead str1 is assigned to variable test. This is because a semicolon has been inserted by js automatically like this:

var test = 'str1';

When working with React.js, this is what a typical render() looks like:

    return (
        <div className="form-group hovering-textarea-container">
            <input className="form-control input-lg" type="text" />
        </div>
    );

To make sure the entire div block is returned as a whole instead of just the first line, the parenthese are needed.

 
almost 3 years ago

The following ST3 plugins are need for React development:

  1. babel - for jsx syntax highlighting
  2. sublime-jshint - for linting your js code
  3. sublime-jsxhint - for linting your jsx code

Install babel

This one is very straight forward, just find babel in package control and install it. To use the Babel's JSX syntax highlight whenever a .jsx file is opened:

  • open up a .jsx file in ST3
  • Goto 'View -> Syntax -> Open all current extention as ... > Babel > Javascript (Babel)'

Linting JSX

I have written a blog about Linting react code here. Follow the instructions in that blog, it will give you real time linting as you code in sublime.

Install React Chrome plugin

Install this plugin if you use Chrome for development, go to this link and install.

Once installed, open up Extensions find the React plugin and check the Allow access to file URLS. This is important if you want to test React files locally.

If you have a webpage using React opened, such as this page, an extra tab named React should appear in your Developer Tools

Convert JSX files to JS files

React uses a syntax called JSX. To use it in your webpage, you have to convert it to regular JS format first. There are two ways to do it:

  1. Use the 'JSXTransformer.js' (which comes with React.js download) to do the conversion
  2. Use the 'react-tools' npm package to perform the conversion

Which one should you choose?

If you want to write your JSX code inside the HTML page, then use JSXTransformer.js like this:

<html>
<body>
    <script src="js/vendor/react.min.js"></script>
    <script src="js/vendor/JSXTransformer.js"></script>

    <script type="text/jsx">
            ...React code inside...
    </script>
</body>
</html>

This is good for debugging but not good for production. Because compiling from .jsx to .js takes time, you want to precompile the .jsx files to regular .js files before serving them to your customers.

So, how to compile .jsx files?

Install the 'react-tools' package via npm:

npm install -g react-tools

Once finished, go into your dev directory and use this command:

Assuming this is the structure of your dev directory

dev_dir/
    js/ 
        src/
        build/
cd dev_dir/js
jsx -w src/ build/

This command means watching all .js files inside the src folder and compile them if modified to regular .js files and save them to the build folder.

WARNING: This command works only if you saved the JSX files with .js extension, if you saved your JSX files with the .jsx extension, then you need to use this command:

jsx -x jsx -w src/ build/

If the command has been executed successfully, you should see a message like this:

built Module("your_js_or_jsx_filename")
["your_js_or_jsx_filename"]

You can import the compiled js files like this (without the need of JSXTransformer.js):

<html>
<body>
    <script src="js/vendor/react.min.js"></script>
    <script type="text/javascript" scr="js/build/precompiled.js"></script>
</body>
</html>

XMLHttpRequest cannot load

Just when you thought you can import a .jsx file like regular .js file locally like this:

<html>
<body>
    <script src="js/react.min.js"></script>
    <script src="js/JSXTransformer.js"></script>

    <script type="text/jsx" src="react_module.jsx"></script>
</body>
</html>

You will see an error in Chrome's console: XMLHttpRequest cannot load, this is because the JSXTransformer.js loads jsx files via XHR which is prohibited for local files.

There are a few ways to overcome this problem which is explained in the StackOverflow link above, but the easiest way to deal with it is to precompile your .jsx files into regular .js files and import them. (which has been explained in the previous section)

A very good React tutorial link

Reactjs Introduction for People Who Know Just Enough JQuery to Get by

This is about it to kickstart your React project using ST3.

 
almost 3 years ago

There are a few services that enable you to create responsive HTML email if you don't know how (with a price tag):

If you know how to write HTML & CSS, you might think writing a responsive HTML email would be simple. WRONG !!! There is reason why such services exists. How to make sure your email look the same on ALL email clients is the first & most difficult problem you will run into. Have a look at this test page provided by Email on Acid

I attempted to write a simple responsive HTML email with the following feature:

  1. Have an banner image on the top
  2. The rest of the body is just text

I found this tutorial and followed it, the first thing I noticed is that:

Everything should be inside a table tag

Because mail clients like outlook would ignore a few important CSS properties: background-image, float, margin and display.reference here

CSS Style in the header section will be ignored

You have to use inline style for all of the elements. MailChimp is really nice because they provides a tool to convert all styles inside the header section to inline style.

I don't know how to reference image files

You can add the image as attachment but I have no idea how to get a reference id to that attachment. So I had to upload the image to a web server (or to your dropbox and make it public).

Outlook makes my image unresponsive

Depending on how you send the email, outlook may add the width and height of the image file to the image tag's style. This makes the image unresponsive. To overcome this problem, do this:

<head>
    <style type="text/css" media="screen">
        body.outlook img {
          width: 100% !important;
          max-width: 100% !important;
        }
    </style>
</head>

Then, in your body tag:

<body class="outlook">
    ...

Once the fix is applied, Outlook will not ignore the style in the head section anymore.

Validate your HTML using W3C's validator

Link to W3C's HTMl validator

How to send HTML mail using Mac's Mail app?

  1. Open your HTML file locally in Safari
  2. Press 'command + i' (now the Mail app should pop up with the HTML content in it)
  3. Send it

DO NOT use 'command + a' to select the entire HTML page and copy and paste it into the Mail app. This works, but during this process, certain css attribute will be changed and you are likely to lose the responsiveness of your site!

This is only the beginning of the headaches. After you overcome the compatibility issure, you have to think about spam. Will your mass email pass the spam filter is another tricky topic.

I can see why you may want to pay for those email services now.

 
almost 3 years ago

When you have large number of models, it is eaiser to understand their relationships by looking at a graph, Django extensions has a handy command to convert these relationships into an image file:

  1. Install Django extension by:
pip install django-extensions

 2. Enable Django extensions in your settings.py:

  INSTALLED_APPS = (
    ...
    'django_extensions',
  )

 3. Install graph packages that Django extensions relies on for drawing:

pip install pyparsing==1.5.7 pydot

 4. Use this command to draw:

./manage.py graph_models -a -g -o my_project_visualized.png

For more drawing options, please refer to the offical doc.