12/31/2014

LiveCoder-r4 Application : Interactive environment to easily learn Coffee-Script, Jade and Stylus

# LiveCoder-r4 Application
     written for Web and JavaScript developers to easily learn and understand concept using an Interactive Environment for Coffee-Script, Jade and Stylus, ( If you want you can add other Languages too, Its FREE, Open-Source and Full-Portable), Just Download Extract and Run.

# This is not an IDE for Coffee-Script/Jade/Stylus, This just helps you to play and learn them very effectively.

#DOWNLOAD
    https://sourceforge.net/p/livecoder-r4/
    Currently I have upload binary file only for Windows Operating system, But As This tool is written using JavaFX ( Basic4Java) this will seamlessly run on any platform.

# Simple GUI Design

# Introduction to Features
     # Interactive Environment for Coffee-Script, Jade and Stylus CSS pre-processor.
    # No need to Download other binary or extra file.
    # Free, Portable and open-source, just download and install.
    # Embedded node.js binary and node package manager so that you can easily extend its features.
    # If You want, You can add support for other languages like, ( TypeScript, etc..)
    # Cross-Platform support ( Built using JavaFX ( and B4J ))

# Why use?
    # Have you ever used Coffee-Script/Jade/Stylus Language before, These are complete languages or you can say they just extends the features of their parent Languages.

    # LiveCoder gives you power to use this languages with installing and configuring anything else, Just download and extract the content to your defined Directory and you are ready to go.

    # Now browse into ${PROJECT_HOME} directory, there will be some executable files, each Built using AutoIT for Windows Operating system, these are based on my previous project ( jLauncher -> gives power to package your Java application in Fully portable manner, so that your user just download and use them, This is about running your Java application even without installing and configuring JRE . )

    # LiveCoder-r4.exe -> for running LiveCoder without CMD
    # LiveCoder-r4D.exe -> for running LiveCoder with CMD
        Helps you debug your application if anything goes wrong..
    # LiveCoder-r4-x64.exe -> for running LiveCoder without CMD  for 64-bit System.

# Getting Started
    # First download pre-built binary from sourceforge.net
    # Extract its content to any directory you want
    # Now run the executable for Livecoder as your needs.
    # Select your Language by clicking on Checkbox
        # Now click on "OPEN" button to load sample files into workspace
        # Now you can clear contents ( Using "CLEAR" button) if you want and write your own code and you can see the compilation results on fly, there is no need to save and then compile LiveCoder will Do that for you.


# So, It was so easy.

12/25/2014

All about Jade: Template Engine for Node

# What is Jade?
    # Jade is a Template Engine for Node.js
    # Jade is default Template Engine for Express ( Node.js web framework)
    # Jade is a high performance template engine heavily influenced by Haml (http://haml-lang.com)
       and implemented with JavaScript for [ Node ].
    # You can imagine a Jade Template as a View for your Node.JS application, for example,
        You can put all of your JavaScript Code/Logic inside a index.js file, This file can export
        JavaScript Objects, Variable, and other data type,
        and Your Jade Template can use those things to setup/generate a static HTML web page, using optional
        export data from node.js app (In this case, index.js)
    # If you are familiar with Python/Haskell/Coffee-script etc,, they use Indentation for nesting of expressions,
        same as for Jade, Here we use 2 white-space as indentation for Jade expressions to nest them into one another.

# How to Install?
    # Using node package manager ( npm )
        npm install jade -g

# Jade API ( using jade inside Node project )
     # import jade using require() function

    # All API options that can be used while compiling or rendering Jade Template
{
    filename:  'string',
    doctype: 'string',
    pretty:  'boolean|string',
    self:  'boolean',
    debug:  'boolean',
    compileDebug:  'boolean',
    compiler:  'class',
    globals: Array<string>
}

       var jade = require('jade')

> require('jade')
{ selfClosing:
[ 'area',
'base',
'br',
'col',
'embed',
'hr',
'img',
'input',
'keygen',
'link',
'menuitem',
'meta',
'param',
'source',
'track',
'wbr' ],
doctypes:
{ default: '<!DOCTYPE html>',
xml: '<?xml version="1.0" encoding="utf-8" ?>',
transitional: '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
strict: '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
frameset: '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
'1.1': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">',
basic: '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">',
mobile: '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">' },
filters: [Function: filter],
utils:
{ merge: [Function],
walkAST: [Function: walkAST] },
Compiler: [Function: Compiler],
Parser: [Function: Parser],
Lexer: [Function: Lexer],
nodes:
{ Node: [Function: Node],
Tag: [Function: Tag],
Code: [Function: Code],
Each: [Function: Each],
Case: { [Function: Case] When: [Function: When] },
Text: [Function: Text],
Block: [Function: Block],
MixinBlock: [Function: MixinBlock],
Mixin: [Function: Mixin],
Filter: [Function: Filter],
Comment: [Function: Comment],
Literal: [Function: Literal],
BlockComment: [Function: BlockComment],
Doctype: [Function: Doctype] },
runtime:
{ merge: [Function: merge],
joinClasses: [Function: joinClasses],
cls: [Function: cls],
attr: [Function: attr],
attrs: [Function: attrs],
escape: [Function: escape],
rethrow: [Function: rethrow] },
cache: {},
compile: [Function],
compileClient: [Function],
compileFile: [Function],
render: [Function],
renderFile: [Function],
compileFileClient: [Function],
__express: [Function] }


# compile
    var fn = jade.compile('string of jade', options);
    var html = fn(locals);
ssp@ssp-pc ~ $ node
    > var jade = require('jade')
    > var fn = jade.compile('doctype html')
    > var html = fn()
    > html
        '<!DOCTYPE html>'

# render
    var html = jade.render('string of jade', merge(options, locals));

    > var html = jade.render('doctype html\nhtml(lang="eng")')
    > html
        '<!DOCTYPE html><html lang="eng"></html>'

# render jade file
    var html = jade.renderFile('filename.jade', merge(options, locals));

    # demo.jade
doctype html
html
  head
    title #{title}
  body
    h1 This is #{title}
    p This is very simple paragraph


    # jade template rendering
> var html = jade.renderFile('demo.jade', ('pretty', {title: 'Simple Node jade template'}))
> console.log(html)
<!DOCTYPE html>
<html>
<head>
<title>Simple Node jade template</title>
</head>
<body>
<h1>This is Simple Node jade template</h1>
<p>This is very simple paragraph</p>
</body>
</html>


# Using jade from Command line
# jade Synopsis
  Usage: jade [options] [dir|file ...]

  Options:

    -h, --help         output usage information
    -V, --version      output the version number
    -O, --obj <str>    javascript options object
    -o, --out <dir>    output the compiled html to <dir>
    -p, --path <path>  filename used to resolve includes
    -P, --pretty       compile pretty html output
    -c, --client       compile function for client-side runtime.js
    -n, --name <str>   The name of the compiled template (requires --client)
    -D, --no-debug     compile without debugging (smaller functions)
    -w, --watch        watch files for changes and automatically re-render
    --name-after-file  Name the template after the last section of the file path (requires --client and overriden by --name)
    --doctype <str>    Specify the doctype on the command line (useful if it is not specified by the template)

  Examples:

    # translate jade the templates dir
    $ jade templates

    # create {foo,bar}.html
    $ jade {foo,bar}.jade

    # jade over stdio
    $ jade < my.jade > my.html

    # jade over stdio
    $ echo 'h1 Jade!' | jade

    # foo, bar dirs rendering to /tmp
    $ jade foo bar --out /tmp 


# compile Jade template using command line
jade --client --no-debug filename.jade

which will produce filename.js containing the compiled template.

ssp@ssp-pc ~ $ /usr/local/bin/jade --pretty demo.jade

  rendered demo.html

ssp@ssp-pc ~ $ cat demo.html
<!DOCTYPE html>
<html>
  <head>
    <title></title>
  </head>
  <body>
    <h1>This is </h1>
    <p>This is very simple paragraph</p>
  </body>
</html>ssp@ssp-/usr/local/bin/jade demo.jade

  rendered demo.html

ssp@ssp-pc ~ $ cat demo.html
<!DOCTYPE html><html><head><title></title></head><body><h1>This is </h1><p>This is very simple paragraph</p></body></html>ssp@ssp-pc ~ $ 


# Document type declaration inside Jade document

doctype html
<!DOCTYPE html>

doctype xml
<?xml version="1.0" encoding="utf-8" ?>

doctype transitional
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

doctype strict
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

doctype frameset
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">

doctype 1.1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

doctype basic
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">

doctype mobile
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">

    =>Custom Doctypes
You can also use your own literal custom doctype:

doctype html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN">

    => Using doctype as an Option while compiling and rendering, and see its effect.
The doctype affects compilation in some other cases, for example self closing tags and boolean attributes).
For this reason, you might sometimes want to specify it manually. You can do this via the doctype option. e.g.

var jade = require('jade');    // importing Jade module as jade variable

// Compile a function, with doctype as XML
var fn = jade.compile('img(src="foo.png")', {doctype: 'xml'});

// Render the function
var html = fn({});
    '<img src="foo.png"></img>'

// Compile a function, with doctype as HTML
var fn = jade.compile('img(src="foo.png")', {doctype: 'html'});

// Render the function
var html = fn({});
    '<img src="foo.png">'


# Writing comments for either Jade Template or for generated HTML document
    => Single line comments look the same as JavaScript comments and must be
           placed on their own line.

// just some paragraphs
p foo
p bar
<!-- just some paragraphs -->
<p>foo</p>
<p>bar</p>

    => Jade also supports un-buffered comments, by simply adding a hypen

- // This is a JavaScript expression comment
//- Simple java-script


    => Block Comments ( means a multi-line comment for HTML document)

body
  //
    As much text as you want
    can go here

<body>
  <!--
  As mush text as you want
  can go here
  -->
</body>

    => Conditional Comments
Jade does not have any special syntax for conditional comments. If your line begins with <
then it is treated as plain text. So just use normal HTML style conditional comments

<!--[if IE 8]>
<html lang="en" class="it-ie9">
<![endif]-->


# Writing Plain text for Jade, that will not be processed by Jade Compiler
    => Jade provides three common ways of getting plain text,

    => Piped Text, prefix the line with  |  character.

body
  | Plain text can include <strong>HTML</strong>
  br
  | because This piped text will be passed as it was.
  p
    | It must always be on its own line


<body>Plain text can include <strong>HTML</strong><br/>because This piped text will be passed as it was.
  <p>It must always be on its own line</p>
</body>

    => Inline in a Tag
since it's a common use case, you can put text in a tag just by adding it inline after a space

p Plain text can include <strong>html</strong>

<p>Plain text can include <strong>html</strong></p>

    => Block in a Tag, useful for writing JavaScript and CSS rules inside Jade Template.
Often you might want large blocks of text within a tag. A good example is with inline scripts or styles.
To do this, just add a  .  after the tag (with no preceding space)

script(src="java.js").
  if (usingJade())
    console.log("you are awesome")
  else
    console.log("use Jade")

<script src="java.js">
  if (usingJade())
    console.log("you are awesome")
  else
    console.log("use Jade")
</script>


# Using HTML tags inside Jade document
By default, text at the start of a line (or after only white space) represents an HTML tag.
Indented tags are nested, creating the tree like structure of html.

ul
  li Item A
  li Item B
  li Item C

<ul>
  <li>Item A</li>
  <li>Item B</li>
  <li>Item C</li>
</ul>

    => Jade also knows which elements are self closing with the help of DOCTYPE declaration.

img

<img />

    => Block expansion, ( for nesting of HTML elements we generally use Indentation, but their is one more syntax, you can use
           :    to nest one or more HTML elements. ). To save space, jade provides an inline syntax for nested tags.

a: img

<a><img /></a>

    => Self Closing Tags, ( define your own self-closing tag)
Tags such as  img, meta, link and so on are automatically self-closing (unless you use the xml doctype).
You can also explicitly self close a tag by simply a[[ending the  /  character.
Only do this if you know what you are doing.

foo/
foo(bar='baz')/

<foo/>
<foo bar='baz'/>


# Using Attributes with HTML elements
    => Tag attributes look similar to HTML, however their values are just regular JavaScript, means you need a key and put its values inside a
          parenthesis, and If you have multiple attributes than separate them using comma.

a(href='google.com') Google
<a href="google.com">Google</a>

    => All the JavaScript expressions work fine too, You are allowed to write any custom JavaScript code, and that might help you generate custom html.
          use a     -    before the JavaScript expression, so that Jade Compiler treats that line as a JavaScript Expression.

- var authenticated = true
body(class=authenticated ? 'authed' : 'anon')
<body class="authed"></body>

    => If you have many attributes, you can also spread them across many lines, and there is no need to use comma to separate them.
input(
  type="checkbox"
  name="agreement"
  checked
)

    => Unescaped Attributes, ( So, you define a value for attribute and then you want to use that value as it is, tell the Jade Compiler do not worry about this value.)
By default, all attributes are escaped (replacing special characters with escape sequences) to prevent attacks such as cross site scripting.
If you need to use special characters you can use != instead of =

div(escaped="<code>")
<div escaped="&lt;code&gt;"></div>

div(unescaped!="<code>")
<div unescaped="<code>"></div>
// Danger, You must be sure to sanitize any user inputs to avoid Cross Site Scripting

    => Boolean Attributes
Boolean attributes are mirrored by jade, and accept bools, like,  true or false as in JavaScript.
When no value is specified, true is assumed.

input(type='checkbox', checked)
<input type="checkbox" checked="checked">

input(type='checkbox', checked=true)
<input type="checkbox" checked="checked">

input(type='checkbox', checked=false)
<input type="checkbox">

input(type='checkbox', checked=true.toString())
<input type="checkbox" checked="true">

doctype html
<!DOCTYPE html>
input(type='checkbox', checked)
<input type="checkbox" checked>

input(type='checkbox', checked=true)
<input type="checkbox" checked>

input(type='checkbox', checked=false)
<input type="checkbox">

input(type='checkbox', checked=true && 'checked')
<input type="checkbox" checked="checked">

    => Style Attributes
The style attribute can be a string, but it can be an object, which is handy when parts of the style are generated by JavaScript.

a(style="color:red;background:greenl") This is that simple text
<a style="color: red; background: green;">This is that simple text</a>

    => Class Attributes
The  class  attributes can ba a string, but it can be an array of class names, which is handy when generated from Java-script.

- var classes = ['foo', 'bar', 'baz'];
a(class=classes)
<a class="foo bar baz"></a>

a(class=classes class=['bing'])
<a class="bing foo bar biz"></a>

    => Class Literal, ( easy and Simple way to define classes for any HTML element), If no HTML element is used with .class than a DIV is assumed.

a.button
<a class="button"></a>

.content
<div class="content"></div>

    => ID Literal, (simple and easy way to define ID for HTML elements), If no HTML element is used with #ID than DIV is assumed.

a#main-link
<a id="main-link"></a.

#content
<div id="content"></div>

    => &attributes (and attributes) can be used to explode an object into attributes of an element

div#foo(data-bar="foo")&attributes({'data-foo': 'bar'}) Lets talk with me
<div id="foo" data-bar="foo" data-foo="bar">Lets talk with me</div>

Danger: Attributes applied using  &attributes are not automatically escaped, You must be sure to sanatize any user inputs to avoid
Cross Site Scripting. This is done for you if you passing in attributes from a mixin call.


# Case ( Generate HTML based on different cases defined by JavaScript equivalent code)

- var friends = 10;     // This is JavaScript variable
case friends
  when 0
    p You have no friends
  when 1
    p You have a friend
  default
    p You have #{friends} friends

<p>You have 10 friends<p>

    => Case Fall Through
You can use fall through just like in a select statement in JavaScript.

- var friends = 0
case friends
  when 0
  when 1
    p You have very few friends
  default
    p You have #{friends} friends

<p>You have very few friends</a>

    => Block Expansion
Block expansion may also be used

- var friends = 1
case friends
  when 0: p you have no friends
  when 1: p you have a friend
  default: p you have #{friends} friends

<p>You have a friend</a>


# Code and Text Interpolation
Jade makes it possible to write inline JavaScript code in your templates,
There are three types of code,

    => Unbuffered Code
Unbuffered code starts with a  -  does not add any output directly:

- for (var x=0; x < 3; x++)
  li item

<li>item</li>
<li>item</li>
<li>item</li>

    => Buffered Code
Buffered code starts with  =  and output the result of evaluating the JavaScript expression in the template,
For security, it is first HTML escaped:

p
  = 'This code is <escaped>!'

<p>This code is &lt;escaped&gt;!</p>

p
  'This is very Simple'
p
  This is very Simple

-var user = { description: 'foo bar baz'}
-var authorized = false
#user
  if user.description
    h2 Description
    p.description user.description
    p.description= user.description


<div id="user">
  <h2>Description</h2>
  <p class="description">user.description</p>
  <p class="description">foo bar baz</p>
</div>


    => Unescaped Buffered Code
Unescaped buffered code starts with  !=  and output the result of evaluating the JavaScript expression in the template.
It is not safe for user input:

p
  != 'This code is <strong>not<strong> !escaped'

<p>This code is <strong>not<strong> escaped!</p>

    => Interpolation
Both plain-text and piped-text support interpolation.

- var user = {name: 'Hello world!'}
p Welcome #{user.name}

<p>Welcome Hello world!</p>

    => Unescaped Interpolation
You can also use unescaped interpolation in output HTML:

-var user = {name: '<strong>Hello world!<strong>'}
p Welcome #{user.name}
p Welcome !{user.name}

<p>Welcome &lt;strong&gt;Hello world!&lt;/strong&gt;</p>
<p>Welcome <strong>Hello world!</strong></p>


# Conditionals, ( generate HTML code based on if-else statements )
Jade's first-class conditional syntax allows for optional parenthesis, and you may now omit the leading - otherwise it's identical, still just regular javascript:

- var user = { description: 'foo bar baz' }
- var authorised = false
#user
  if user.description
    h2 Description
    p.description= user.description
  else if authorised
    h2 Description
    p.description.
      User has no description,
      why not add one...
  else
    h1 Description
    p.description User has no description

<div id="user">
  <h2>Description</h2>
  <p class="description">foo bar baz</p>
</div>

    => Jade also provides a negated version   unless   (the following are therefore equivalent):

unless user.isAnonymous
  p You're logged in as #{user.name}

if !user.isAnonymous
  p You're logged in as #{user.name}


# Iteration over JavaScript objects using each and while statements

    => each
jade's first-class iteration syntax makes it easier to iterate over arrays and objects within a template:

ul
  // Don't use white-space before = sign
  each val in [1,2,3,4,5]
    li= val

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

    => You can also get the index as you iterate:

ul
  each val, index in ['zero', 'one', 'two']
    li= index + ': ' + val

<ul>
  <li>0: zero</li>
  <li>1: one</li>
  <li>2: two</li>
</ul>

    => Jade also lets you iterate over the keys in an object:

ul
  each val, index in {1: 'one', 2: 'two', 3: 'three'}
    li= index + ': ' + val

    => The object or array to iterate over is just plain JavaScript so it can be a variable or the result of a function call or almost anything:

- var values = []
ul
  each val in values.length ? values: ['There are no values']
    li= val

<ul>
  <li>There are no values</li>
</ul>

    => while
You can also use  while to create a loop

- var n = 0
ul
  while n < 4
    li = n++


# Extends - Template Inheritance ( Using extends and block keyword )
The  extends  keyword allows a template to extend a layout or parent template.
It can then override certain pre-defined blocks of content.

//-FILE:  layout.jade
doctype html
html
  head
    //- So this is a block named title,
    //- you can extend this into another template.
    block title
  body
    //- This block name is content
    block content

//- FILE:  index.jade
extends layout.jade

//- Time to use our pre-defined blocks
block title
  title Simple Node Application

block content
  h1 Welcome to my first Node Application

//- FILE:  index.html
<!DOCTYPE html>
<html>
  <head>
    <title>Simple Node Application</title>
  </head>
  <body>
    <h1>Welcome to my first Node Application</h1>
  </body>
</html>


# Filters
Filters let you use other languages (like, HTML, XML,,,) within a jade template. They take a block of plain text as an input.

//- FILE:  index.jade
:markdown
  # Markdown

  I Often like including markdown documents

script(type="text/coffeescript")
  :coffee
      console.log 'This is coffee script'

//- FILE:  index.html

<h1 id="markdown">Markdown</h1>
<p>I Often like including markdown documents</p>

<script type="text/coffeescript">(function() {
  console.log('This is coffee script');

}).call(this);

</script>


# Includes ( Similar to require()  or  include()  function in PHP Language )
    => Includes allow you to insert the content of one jade file into another.

//- FILE:  index.jade
doctype html
html
  include ./includes/head.jade
  body
    h1 My Site
    p Welcome to my super lame site
    include ./includes/foot.jade

//- FILE:  includes/head.jade
head
  title My Simple Node Application
  script(type="text/javascript", src="js/jquery.min.js")
  script(type="text/javascript", src="js/app.js")

//- FILE:  includes/foot.jade
#footer
  p Copyright 1990-2014 (c) foobar


//- FILE:  index.html  (generated using Jade)
<!DOCTYPE html>
<html>
  <head>
    <title>My Simple Node Application</title>
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="js/app.js"></script>
  </head>
  <body>
    <h1>Welcome to my Simple website</h1>
    <p>this is cool</p>
    <div id="footer">
      <p>Copyright 1990-2014 (c) foobar</p>
    </div>
  </body>
</html>


    => Including filtered text
You can combine filters with includes to filter things as you include them.

//- FILE:  index.jade
doctype html
html
  head
    title A Simple Article
  body
    include:markdown article.md

//- FILE:  article.md
This is an article written in markdown.
In order to apply the transform markdown you must install one of "marked","supermarked","markdown-js","markdown"

<!DOCTYPE HTML>
<html>
  <head>
    <title> An Article</title>
  </head>
  <body>
    <h1>article.md</h1>
    <p>This is an article written in markdown</p>
  </body>
</html>

//- FILE:  index.html ( generated file using Jade)
<!DOCTYPE html>
<html>
  <head>
    <title>A Simple Article</title>
  </head>
  <body><p>&lt;!DOCTYPE HTML&gt;</p>
<html>
  <head>
    <title> An Article</title>
  </head>
  <body>
    <h1>article.md</h1>
    <p>This is an article written in markdown</p>
  </body>
</html>

  </body>
</html>


# Template Inheritance
Jade supports inheritance via the Keywords  block  and  extends. Jade block can provide default content
    => A block is simply a "block" of jade that may be replaced within a child template. This process is recursive

//- FILE:  layout.jade
html
  head
    title My Site - #{title}
    block scripts
      script(src='/jquery.js')
  body
    block content
    block foot
      #footer
        p some footer content

Now we do not want to use the defaul content of blocks  scripts and content, so lets re-define them.
//- FILE:  page-a.jade
extends ./layout.jade

block scripts
  script(src='/jquery.js')
  script(src='/pets.js')

block content
  h1= title
  each pet in pets
    include pet

This is possible to override a block to provide additional blocks. Here we are extending layout.jade but we are re-defining the content block.
//- FILE:  sub-layout.jade
extends ./layout.jade

block content
  .sidebar
    block sidebar
      p nothing
  .primary
    block primary
      p nothing

//- FILE:  page-b.jade
extends ./sub-layout.jade

block content
  .sidebar
    block sidebar
      p nothing
  .primary
    block primary
      p nothing

    => Block append / prepend
Jade allows you to replace (default), prepend, or append blocks. Suppose for example, you have default scripts in a
"head" block that you wish to utilize on every page and there are also some custom scripts that might be diffrent for a diffrent web pages.

//- FILE:  layout.jade
html
  head
    block head
      link(rel="stylesheet", href="style/bootstrap.min.css")
      script(type="text/javascript", src="js/jquery.js")
      script(type="text/javascript", src="js/bootstrap.min.js")

    body
      block content

Now you are extending this template for your website game/application page, and you need to add some more scripts,
This is why, you don't want to replace the default content of  scripts block, This is where 'append' can help you.

//- FILE:  index.jade
extends layout.jade

block append head
  script(type="text/javascript", src="js/app.js")
  script(type="text/javascript", src="js/game.js")

block content
  h1 Welcome to my game page

//- FILE:  index.html (Generated from index.jade file)

<html>
  <head>
    <link rel="stylesheet" href="style/bootstrap.min.css"/>
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/bootstrap.min.js"></script>
    <script type="text/javascript" src="js/app.js"></script>
    <script type="text/javascript" src="js/game.js"></script>
    <body>
      <h1>Welcome to my game page</h1>
    </body>
  </head>
</html>


# Mixins  ( Jade function ) ( and two global objects,   attributes  , and   &attributes )
Mixins allow you to create reusable blocks of jade

//- Declaration of a Jade mixins
mixin list
  ul
    li Simple
    li Hello
    li world

// using mixins
+list
+list

<ul>
  <li>Simple</li>
  <li>Hello</li>
  <li>world</li>
</ul>
<ul>
  <li>Simple</li>
  <li>Hello</li>
  <li>world</li>
</ul>

    => Mixins are compiled to functions and can take arguments just like JavaScript functions.

mixin pet(name)
  li.pet= name

ul
  +pet('cat')
  +pet('dog')
  +pet('pig')

<ul>
  <li class="pet">cat</li>
  <li class="pet">dog</li>
  <li class="pet">pig</li>
</ul>

    => Mixin BlocksMixins can also take a block of jade to act as the content

//- FILE:  index.jade
mixin article(title)
  .article
    .article-wrapper
      h1= title
      if block
        block
      else
        p No content provided

+article('Hello world')
+article('Hello World')
  p This is my
  p Amazing article

//- FILE:  index.html ( generated HTML code)
<div class="article">
  <div class="article-wrapper">
    <h1>Hello world</h1>
    <p>No content provided</p>
  </div>
</div>
<div class="article">
  <div class="article-wrapper">
    <h1>Hello world</h1>
    <p>This is my</p>
    <p>Amazing article</p>
  </div>
</div>

    => Mixin Attributes
Mixins also get an implicit attributes argument taken from the attributes passed to the mixin:

mixin link(href, name)
  //- attributes == {class: "btn"}
  a(class!=attributes.class, href=href)= name

+link("/demo.html", "Demo to link")(class="btn")

<a href="/demo.html" class="btn">Demo to link</a>

    => You can also use with  &attributes

mixin link(href,name)
  a(href=href)&attributes(attributes)= name

+link("/demo.html", "demo to link")(class="btn", id="button")

<a href="/demo.html" class="btn" id="button">demo to link</a>

    => Rest Arguments
You can write mixins that take an unknown number of arguments using the 'rest arguments' syntax

mixin list(id, ...items)
  ul(id=id)
    each item in items
      li= item

+list('my-list', 1, 2, 3, 4)

<ul id="my-list">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>


12/23/2014

Managing web projects dependencies using Bower: Package manager for web

Bower - A package manager for web



# What is Bower?
    #  Bower helps us to make front-end web development easier.
    # So, Bower is a package manager for web,
        If you familiar with npm (Node package manager), We use npm to
        download and Install node packages from its repository.
        Basically these packages are required by server side, and server is Node.js
        server, based on Google chrome JavaScript engine (v8) .


# Why use Bower?
    #  As we know that websites are not a simple page, we use a lot of stuff
         like , JavaScript libraries, Frameworks and many other things.
         These are required for proper rendering or functioning of our
          website, so there is a problem to manage all of that stuff if you are
          really working with a big web project. I am assuming that there must
          be a lot of dependencies that you have download.

# How this tool can help us?
    #  OK, Lets us assume that you are not using Bower for your web project.
         So, now your web project is complete, and this is the time when you
         want to distribute your web project to others or you want to deploy that
         Git-hub so that others can download and use/test your project.

    # first way is you have to manually manager your project dependencies.
        means, either you are going to package all dependencies with your
        web project, or you can manually list them in documentation so that
        your project user can download and install them your defined directory.
        so that your project can work well.

    # Now, take a look at Bower, how this can help us?
        for your web project, first you have to init Bower, so that this will create
        a config file ( bower.json ), where it can put project configuration settings.
        Now you can tell Bower, hey this is a Project dependency, and why
        not download and install that for me.

# How to install Bower?
    # Bower comes as a package of Node.js
    # This is why, first you have to install Node as well as npm
    # You can Download  Node installer from http://nodejs.org/

    # Once you installed, Node you can now install bower using npm.
   
     npm install bower -g

    # now you can use Bower directly from command line.


# Getting started with Bower.
    # Creating a Bower configuration file for your web project.

     bower init


    # This will create a  bower.json  file, which contains the project
        name, version, keywords, main file name, dependencies and more.

    # simple bower.json file.




    # Installing Packages
        bower install jquery

             or

        bower install jquery --save

 
    # If you are passing a  --save flag for bower than bower will update the
        bower.json file and make that package as dependency for our project.
        without --save flag Bower will just download and install that package
        into  bower_components/  directory.

    # Installing packages from Git-hub using Bower.

        bower install desandro/masonry

        bower install git://github.com/user/package.git

    # Download and Install from given URL
  
        bower install http://example.com/script.js

    # Search for a Package or Library using Bower.
        ( This will only look for packages registered in Bower registry. )

        bower search polymer






    # Playing with  bower.json file.
        # this is sample bower.json file.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
{
  "name": "nodeFilePlayer",
  "version": "0.0.0",
  "description": "Simple polymer project with node",
  "keywords": [
    "node",
    "express",
    "polymer"
  ],
  "authors": [
    "ssp"
  ],
  "license": "MIT",
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components",
    "test",
    "tests"
  ],
  "dependencies": {
    "core-component-page": "Polymer/core-component-page#^0.5.0",
    "platform": "~1.3.0",
    "polymer-elements": "~0.3.0",
    "polymer-platform": "~0.4.2",
    "polymerangular": "*"
  }
}

    # There you can explicitly define version number for any dependencies,
        then Bower will look for that dependencies in bower.json file
        and download + install that for you.
        if you don't define a version number for any dependencies, than Bower
        will install the latest package from its repository.

    # last thing is about when you have a bower.json configuration file, and
        you want to download and install all dependencies listed inside of it.

        bower install

    # this will parse bower.json file and install listed dependencies for you
        inside  bower_components/  directory. So you don't have to look for
        each and every dependencies that are required for your web project
        over Internet and download and install one by one.


10/27/2014

working with Linux OS behind proxy server (Linuxmint 17)

# Configuring proxy servers when you are using Linux/Windows operating system.

# In this case i am using Linux mint 17 - XFCE x64bit

# There are mostly two ways to configure proxy for Linux operating system tools.
    #1. First you can look for tool configuration file, that can be found in Linux System /etc directory,
    For example: If you are using WGET (Linux download manager) that its configuration file in
        /etc/wgetrc
        ~ And you need to edit this file to setup proxy for wget,
   
        #NOTE
                ~ This proxy will be configured for wget will be used every time you run wget.
           So, if you are using proxy for a while than you should avoid this method.

    #2. Second method for configuring proxy is using console/Terminal environment variable.

----------------------------------NOTE------------------------------------------------------------
Environment variables are very important and allows you to directly communicate with another 
command line application or look for any configuration file where that defined for your specific
Application.
A simple example is, So you have installed JAVA_JDK or you are going to install java into your SYSTEM,
How your SYSTEM is going to find that you have installed JAVA_JDK installed,
    -> You can say that path can be defined using windows registry. ok but what about linux?

Their is one another way to use it even without installing it,

    -> This is using Environment variables, these are specific for two scopes
        -> LOCAL Environment Variables
        -> GLOBAL Environment Variables    => need admin privileges
    -> export JAVA_HOME environment variable for that Directory where you have installed/extract
        java_jdk contents.
    -> And you are ready to go ..
----------------------------------------------------------------------------------------------------

         ~  for BASH shell on Linux mint17-XFCE-x64
         ~ I have used this command-
              $ export http_proxy=http://172.16.200.3:3128
          
              ~ So, what actually this is going to do?
                   ~ This actually create a new environment variable using :
                             KEY = http_proxy
                             VALUE= http://172.16.200.3:3128

            ~ If you want to see Environment variable, use env  command,
                   ~ $ env
                    # This is going to print every environment variable KEY and corresponding
                       key VALUES.

    # If you are using Linux tools using CYGWIN package
     https://www.cygwin.com/
     http://x.cygwin.com/

      ~You can set environment variable using set command on windows, 
            ~ There is Syntax
              >set http_proxy=http://172.16.200.3:3128
              >wget http://www.google.co.in 



    # Linux == export ( to define environment variables temporarily)
        ~ And to view them use == env  command
         http://www.computerhope.com/unix/uenv.htm

    # Windows == set ( to define environment variables temporarily on windows OS  )
        ~ And to view all of them use   == set command
        http://www.computerhope.com/sethlp.htm
       http://ss64.com/nt/set.html

# Some examples:
    #1. using wget command line download manager for UNIX like systems.
        ~LINUX
        $ export http_proxy=http://172.16.200.3:3128
       $ wget -o home.html http://python.org

                               OR

       $ http_proxy=http://172.16.200.3:3128 wget -o home.html http://python.org

                              OR

      ~ Use wget  configuration, edit and define proxy server and port for http, https, ftp protocol.
         # nano /ect/wgetrc

    #2. using pip python modules/packages management tool
        ~ LINUX
        $  export http_proxy=http://172.16.200.3:3128
        $ sudo pip install ipython[test, notebook, zmq, qtconsole]
        # This is how we can install IPython with notebook, qtconsole, zmq dependencies.

                                OR

        $ http_proxy=http://172.16.200.3:3128 pip install ipython[test, notebook, zmq, qtconsole]

                                 OR

        # use pre-defined option for proxy server
            $ sudo pip --proxy http://172.16.200.3:3128 install ipython

    #3. using apt-get to install Linux packages form console/terminal
    ~ Although you can use Synaptic package manager or GDebi package manager which are GUI
         for Linux package management, yet apt-get is most basic tool for managing packages on
         debian based Linux operating systems.

         ~ LINUX
         $ export http_proxy=http://172.16.200.3:3128
         $ sudo apt-get install ipython

                               OR

         # http_proxy=http://172.16.200.3:3128 apt-get install ipython

                               OR

       ~ edit configuration file for apt-get tool
          ~ which is apt.conf
          ~ PATH == /etc/apt/apt-conf
               # and now define proxy for this file, note that you can not edit this file untill
                  you have root user privileges.

                  #
         Acquire::http::Proxy "http://172.16.200.3:3128";
         #
 
    # edit your BASH configuration file that can be found in your HOME directory.
       ~/.bachrc 
 
       # Time to edit this file, nano is my favorite command line editor.
       # nano ~/.bashrc
         # go to the bottom of file and this line of code,
           of-course you are familiar with this code. 

         #
         http_proxy=http://172.16.200.3:3128
         export http_proxy
         # 

             # Save using ( CTRL+O )  and exit using ( CTRL+X )

    #4. Using easy_install behind proxy server
        $ export http_proxy=http://172.16.200.3:3128
        $ sudo -E easy_install  ipython



6/10/2014

First Step with Python ..-->> 001






# What is Python :-                                                                                                                                   
>> General Purpose Language and full object Oriented Programming Language
>> Portable, runs on almost every Operating System available Today
>> High Quality Apps can be rapidly developed and Maintained Easily

<Source:  https://en.wikipedia.org/wiki/Python_(programming_language) >

# Programmer aspects from a Language : -                                                                                            
>> Dynamic and general Purpose
>> Easy to learn and remember
>> Readability and easier to maintain codes
>> High level Interpreted Language
>> Built-in documentation
>> high Quality modules
>> Easier to make your own modules
>> object oriented Programming Language
>> large set of Python Modules or Libraries
>>

# Why you should learn Python :-                                                                                                        


# Primary Resource to learn about python :-                                                                                      
1.> https://wiki.python.org/moin/BeginnersGuide  # Beginners guide

2.> https://www.python.org/about/apps                  # choose popular python module according to your Interest.

3.> http://pypi.python.org/pypi                               # Python module index

# Getting started Python : -                                                                                                                       


## Installing on linux :-
sudo apt-get install python
sudo apt-get install python3
sudo apt-get install python-dev
sudo apt-get install python3-dev
sudo apt-get install python-numpy
sudo apt-get install python-matplotlib
sudo apt-get install python-scipy
sudo apt-get install python-pillow
sudo apt-get install python-pygame
sudo apt-get install python-django

and so on..

## Installing on Windows :-
### Download and Install Python from https://www.python.org/downloads/


### Use Portable Python :- ( BEST )
http://portablepython.com/wiki/Download/
>>> Personally, I like this Project Because of Large set of third party python libraries -
 NumPy, SciPy, Matplotlib, PyWin32, Django, PIL, wxPython, PyQt, PyGame, etc. code editors
- PyScripter and IDLE all packaged in a single installer.
- NumPy == Numerical python
- SciPy   == for scientific calculations
- Matplotlib == for graph plotting and many more cool stuff
- PyWin32  == Python script to exe
- Django    == Python based popular Web FrameWork
- PIL           == Python imaging Library
- wxPython  == GUI apps development using python
- PyGame  == Rapid Game Developement using python
- IDLE  == Interactive IDE for Python
- PyQt == GUI Framework for Python based UPON Qt
- Tkinter == GUI Framework







>>> So you do not need to Install Python Again and Again, Install Python to USB drive and take it anywhere you want.




## Installing Python Modules :-                                                                                                                
### For Windows :-
>>> Unofficial Windows Binaries for Python Extension Packages
http://www.lfd.uci.edu/~gohlke/pythonlibs/

### For Linux :-
>>> You can use PIP or easy_install
for example :-
sudo pip install numpy
sudo pip install pandas

>>> OR use your system package manager
for example for Ubuntu( Debian based)
sudo apt-get install python-numpy
sudo apt-get install python-mmtk


## Interactive Python :-

    IPython
    IDLE
    WinPython

## IDE for Python :-
    PyDev for eclipse
    Spider
    Eric
    IDLE

or You can use:
    NotePad++
    gEdit
    kWrite
    Notepad itself.

# Online Python Interpreters :-                                                                                                                  
1.> http://www.compileonline.com/execute_python_online.php
2.> https://www.learnstreet.com/lessons/study/python
3.> http://www.pythonanywhere.com/
4.> http://repl.it/languages/Python    

## Books You Must read, and Recommended Books for Python:-                                                          
1:: A Byte of Python ( C. Swaroop )
2:: Learn Python the hard way ( Zad A. Shaw)
3:: Building Skills in Python ( Steven F. Lott )
4:: Beginning Game Development with Python and Pygame  ( Will McGugan )
5:: Making use of Python ( R. gupta )
6:: The Definitive Guide to Jython - Python for the Java Platform 
( Josh Juneau, Jim Baker, Victor Ng, Leo Soto, Frank Wierzbicki )
7:: Programming Computer vision with Python :: ( Jan Erik Solem )
8::  Mysql for Python ( Albert Lukaszewski )
9:: Python Pocket Refrence ( Mark Lutz )
10:: Natural Language Processing with Python
( Steven Bird, Ewan Klein, and Edward Loper ) 
11:: Begining Python ( James Payne )
12:: A Primer on Scientific Programming with Python
( Hans Petter Langtangen ) 
13:: Rapid GUI Programming with Python and Qt
( Mark Summerfield )
14:: Python Web Development with Django®
( Jeff Forcier, Paul Bissex, Wesley Chun )
15:: Matplotlib for Python Developers
( Sandro Tosi )
16:: Head First Python  ( Paul Barry )
17:: Tkinter Refrence :: A GUI for Python ( John W. Shipman )
18:: Gray hat Python ( Justin Seitz )
19:: Core Python Programming ( y Wesley J. Chun )
20:: Fundamentals of Python 
( MartinKenneth A. LambertOsborne )



##


5/17/2014

My Python Project :: FFplayer a Fastest Video Player Using FFMPEG Library..

Go To https://sourceforge.net/projects/ffplayer-and-converter/
           ## For Binary Download
           ## fastest Video player Build Using Python and Tkinter and FFMPEG + FFPLAY

#FFplayer Python code
###@ http://pastebin.com/RGqeup3A
    #!/usr/bin/env python
    # file name = ffplayer ( build using ffmpeg multimedia library )
    # developer :: Shishtpal
    import os, glob, shutil, sys, tempfile, subprocess, ctypes, time
    import Tkinter as tk
    import tkFileDialog
    vlist = set()
    index_no = 0
    # < Program Code #10001@ >
    # Code Block used to add files to vlist, that we use as an argument with this script.
    try:
            if len(sys.argv) == 1:
                    cwd = ''
            else:
                    cwd = sys.argv[1:]
            for i in cwd:
                    print i
                    vlist.add(i)
            print "\n\n"
    except:
            print "Error in Program Code #10001@"
    def tk_gui():
            global root, cwd
            global  index_no
           
            root = tk.Tk()
            root.wm_geometry(newGeometry='250x0+10+10')  
            root.wm_title("Ffplayer ( Video Player )")
            menubar = tk.Menu(root)
            root.config(menu=menubar)
            # Creating a menu button
            filemenu1 = tk.Menu(menubar)
            filemenu2 = tk.Menu(menubar)
            filemenu3 = tk.Menu(menubar)
            menubar.add_cascade(label='Player', menu=filemenu1)
            menubar.add_cascade(label='Control', menu=filemenu2)
            menubar.add_cascade(label='Help', menu=filemenu3)
           
            def button1Click():    
                    """
                    this code block is used to play a single video file,
                    this video file will be added to vlist playlist
                    """
                    global cwd, vlist
                    print "Opening Video File :-)\n\n"
                    openfilename = tkFileDialog.askopenfilename(title="Select Video/Mp3 File..", initialdir="C:\\")
                    cwd = openfilename
                    vlist.add(cwd)
                    vid_player(cwd)
            def button2Click():
                    """
                    this code block is used to open a window dialog box asked you to select
                    a folder and filter all video files in your defined location,
                    and add all of them to your vlist
                    """
                    global cwd
                    print "Open a folder with Video File :-)\n\n"
                    openfoldername = tkFileDialog.askdirectory()
                   
                    b = openfoldername.split("/")
                    cwd = ''
                    for i in range(len(b)):
                            cwd = cwd + "\\" + b[i]
                    cwd = cwd[1:]
                    print cwd
                    vid_player(cwd)
                    play_video()
                   
            """                    
            def button3Click():
                    print "Open Settings Panel :-)\n\n\n"
                    #p1 = subproecess.call([])
            """
           
            def button4Click():
                    print "Bye Bye!!"
                    sys.exit()
            # create action for button 'Quit'
            filemenu1.add_command(label='Open File (o)', command=button1Click)
            filemenu1.add_command(label='Open Folder (f)', command=button2Click)
            #filemenu1.add_command(label='Settings', command=button3Click) 
            filemenu1.add_separator()
            filemenu1.add_command(label='Quit (q)', command=button4Click) # bind a event using command method
           
            #
            root.bind("<o>", lambda e: button1Click()) # bind a shortcut using lambda method
            root.bind("<O>", lambda e: button1Click())
           
            root.bind("<f>", lambda e: button2Click())
            root.bind("<F>", lambda e: button2Click())
           
            root.bind("<Q>", lambda e: button4Click())
            root.bind("<q>", lambda e: button4Click())
            #
            def next_video():
                    global p1
                    try:
                            p1.kill()
                    except:
                            print "\n\nThere is NO ffplay.exe subprocess Exists!!\n\n"
                    play_video()
                   
            def play_video():
                    global index_no, p1
                    print "\n", "##"*35
                    print "vlist contents :: ", len(vlist)
                    print "    # Current Video file Index Number Is :: ", index_no, "\n"
                    if len(vlist) > 0:
                            try:
                                    print "##"*35, "\n\n"
                                    p1 = subprocess.Popen(["ffplay.exe", "-autoexit", list(vlist)[index_no]])
                            except:
                                    pass
                    else:
                            print "\n\nHello, There is no Video File in your PlayList !!!\n\n\n"
                    if index_no <= len(vlist):
                           
                            index_no += 1
            def read_manual():
                    try:
                            subprocess.call(["notepad.exe", "source\\ffplay.help.txt"])
                    except:
                            print "Manual for ffplay Not Exists!!!"
                           
            def start_ffmpeg_web():
                    root1 = tk.Tk()
                    myContainer2 = tk.Frame(root1)
                    myContainer2.pack()
                    myLabel1 = tk.Label(myContainer2)
                    myLabel1.configure(text="Go to http://trac.ffmpeg.org", background="yellow")
                    myLabel1.pack()
                    button1 = tk.Button(myContainer2)
                    button1.configure(text="OK", background="green")
                    button1.pack()
                    root1.update()
                    time.sleep(2)
                    root1.destroy()
           
            def about_ffplayer():
                    print "\n  FFPLAYER is a video player build using ffmpeg library..\n\t Build By ( Shishtpal )"
                    root1 = tk.Tk()
                    myContainer2 = tk.Frame(root1)
                    myContainer2.pack()
                    myLabel1 = tk.Label(myContainer2)
                    myLabel1.configure(text="\n  FFPLAYER is a video player build using ffmpeg library..\n\t Build By ( Shishtpal )", background="cyan")
                    myLabel1.pack()
                    button1 = tk.Button(myContainer2)
                    button1.configure(text="OK", background="green")
                    button1.pack()
                    root1.update()
                    time.sleep(4)
                    root1.destroy()
                   
            def explore_video_folder():
                    loop_player()
                    global index_no, vlist, cwd, p1
                    print "\n##"*10
                    print "\n    ## After Exploring Video Folder I Found", len(vlist), "Files.."
                    print "    # Current Video file Index Number Is :: ", index_no
                    print "    # Your Working Directory is ::", cwd, "\n\n"
                   
                    if len(vlist) > 0:
                            index_no = 0
                            if p1.poll() == None:
                                    p1.kill()
                            if True:
                                    for i in range(len(vlist)):
                                            print "\n", "##"*35
                                            print "\n   #Playing Video File :: ", list(vlist)[index_no], "\n"
                                            p1 = subprocess.Popen(["ffplay.exe", "-autoexit", list(vlist)[index_no]])
                                            print "\n    # Current Video file Index Number Is :: ", index_no, "\n"
                                            print "\n", "##"*35
                                            index_no += 1
                                            p1.wait()
                            else:
                                    pass
                                   
            def loop_video():
                    global index_no, p1, vlist
                    try:
                           
                            if p1.poll() == None:
                                    p1.kill()
                                    print "\n", "##"*35
                                    print "\n    # Current Video file Index Number Is :: ", index_no-1, "\n\n"
                                    p1 = subprocess.Popen(["ffplay.exe", "-autoexit", list(vlist)[index_no-1]])
                            elif len(vlist) == 1:
                                    print "\n", "##"*35
                                    print "\n    # Current Video file Index Number Is :: ", index_no, "\n\n"
                                    p1 = subprocess.Popen(["ffplay.exe", "-autoexit", list(vlist)[index_no]])
                            else:
                                    print "\n", "##"*35
                                    print "\n    # Current Video file Index Number Is :: ", index_no-1, "\n\n"
                                    p1 = subprocess.Popen(["ffplay.exe", "-autoexit", list(vlist)[index_no-1]])
                           
                    except:
                            print "  # Error in loop_video Function. #"
           
            def previous_video():
                    global index_no, p1, vlist
                    if index_no > 1:
                            try:
                                    if p1.poll() == None:
                                            p1.kill()
                                            p1 = subprocess.Popen(["ffplay.exe", "-autoexit", list(vlist)[index_no-2]])
                                           
                                    else:
                                            p1 = subprocess.Popen(["ffplay.exe", "-autoexit", list(vlist)[index_no-2]])
                                    print "\n    # Current Video file Index Number Is :: ", index_no-2, "\n"
                                    print "##"*35, "\n"
                                   
                                    if index_no != 0:
                                            index_no -= 1
                            except:
                                    print "Error While playing Previous Video File.."
                    else:
                            print "There is No Previous Video File Exists..."
                            index_no = 0
                   
            root.bind("<m>", lambda e: play_video())
            root.bind("<M>", lambda e: play_video())
           
            root.bind("<n>", lambda e: next_video())
            root.bind("<N>", lambda e: next_video())
           
            root.bind("<k>", lambda e: previous_video())
            root.bind("<K>", lambda e: previous_video())
           
            root.bind("<l>", lambda e: loop_video())
            root.bind("<L>", lambda e: loop_video())
           
            filemenu2.add_command(label='Play Video (m)', command=play_video)
            filemenu2.add_command(label='Next Video (n)', command=next_video)
            filemenu2.add_command(label='Previous Video (k)', command=previous_video)
            filemenu2.add_command(label='Loop Video (l)', command=loop_video)
            filemenu2.add_separator()
           
            def print_playlist():
                    print "\n", "@#"*30
                    print "Play-list Contents :: ", "\n"
                    for i, j  in enumerate(vlist, 1):
                            print i, j
                    print "@#"*30, "\n"
            filemenu2.add_command(label='Print Playlist', command=print_playlist)
           
            def open_playlist_file():
                    global vlist, index_no, p1
                    print "Opening Play-list File :: "
                    try:
                            openfilename = tkFileDialog.askopenfilename(filetypes=[("PLT", "*.plt" )], title="Select Your Playlist File..", initialdir="C:\\")
                            print "\n", "@#"*30
                            print "You Select :: \n(", openfilename, ") \n\tPlay-list File..", "\n"
                            y = open(openfilename)
                            while True:
                                    a = y.readline()[:-1]
                                    if len(a) == 0:
                                            break
                                    else:
                                            vlist.add(a)
                            y.close()
                            print "\n", "@#"*30, "\n"
                    except:
                            print "No Play-List has been Selected..\n"
            filemenu2.add_command(label='Open Playlist File', command=open_playlist_file)
           
            def write_playlist_file():
                    global vlist
                    print "\n", "**"*30
                    print "We have Write your Current Play-List File To Disk.."
                    print "ffplayer_current_playlist.plt", "\n"
                    x = open("ffplayer_current_playlist.plt", "w")
                    for i in vlist:
                            w = i+"\n"
                            x.write(w)
                    x.close()
                    print "**"*30, "\n"
            filemenu2.add_command(label='Write Playlist File', command=write_playlist_file)
           
            def custom_playlist():
                    print "Customizing Play-list Contents :: "
                   
            #filemenu2.add_command(label='Custom Playlist', command=custom_playlist)
            filemenu2.add_separator()
            filemenu2.add_command(label='Explore Video Folder', command=explore_video_folder)
           
            filemenu3.add_command(label='Manual', command=read_manual)
            filemenu3.add_command(label='About FFMPEG', command=start_ffmpeg_web)
           
            def ffmpeg_howto():
                    try:
                            subprocess.Popen(["notepad.exe", "source\\ffmpeg.howto.txt"])
                    except:
                            print "FFMPEG How To Documentation File Not Exists.."
            filemenu3.add_command(label='FFMPEG How TO ', command=ffmpeg_howto)    
            filemenu3.add_command(label='About ffplayer', command=about_ffplayer)
    def screen_resolution():
            """
            this code block is used to get Screen resolution of your desktop Screen.       
            """
            global screensize
            user32 = ctypes.windll.user32
            screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
            print "Screen Resolution is :: ", screensize, "\n\n"
    screen_resolution()
    def vid_filter(filename):
            if os.path.isdir(filename) | filename.endswith(".jpg") | \
                    filename.endswith(".png") | filename.endswith(".jpeg") | \
                    filename.endswith(".JPG") | filename.endswith(".PNG") | \
                    filename.endswith(".JPEG") | filename.endswith(".txt") | \
                    filename.endswith(".tar.gz") | filename.endswith(".zip") | \
                    filename.endswith(".7z") | filename.endswith(".exe") | \
                    filename.endswith(".pdf") | filename.endswith(".htm") | \
                    filename.endswith(".html") | filename.endswith(".mhtm") | \
                    filename.endswith(".mhtml") | filename.endswith(".lnk") | \
                    filename.endswith(".mht") | filename.endswith(".ini") | \
                    filename.endswith(".db") | filename.endswith(".img") | \
                    filename.endswith(".iso") | filename.endswith(".pkg") | \
                    filename.endswith(".sh") | filename.endswith(".tgz") | \
                    filename.endswith(".css") | filename.endswith(".gif") | \
                    filename.endswith(".c4d") | filename.endswith(".xml") | \
                    filename.endswith(".apk") | filename.endswith(".dat") | \
                    filename.endswith(".doc") | filename.endswith(".docx") | \
                    filename.endswith(".ppt") | filename.endswith(".pptx") | \
                    filename.endswith(".xls") | filename.endswith(".xlsx") | \
                    filename.endswith(".py") | filename.endswith(".pyw") | \
                    filename.endswith(".pyc") | filename.endswith(".pyo") | \
                    filename.endswith(".chm") | filename.endswith(".js")  | \
                    filename.endswith(".gz") | filename.endswith(".cfg")  | \
                    filename.endswith(".inf") | filename.endswith(".sys")  | \
                    filename.endswith(".dll"):
                    return True
    def vid_player(cwd):
            global p1, vlist
            if os.path.isfile(cwd):
                    vlist.add(cwd)
                    p1 = subprocess.Popen(["ffplay.exe", "-autoexit", cwd])
                   
            elif os.path.isdir(cwd):
                    for i in os.listdir(cwd):
                            try:
                                    filename = os.path.join(cwd, i)
                                    if vid_filter(filename):
                                            pass
                                    else:
                                            vlist.add(filename)
                            except:
                                    print "Error While Filtering File Formats..\n\t In vid_player Function..\n"
                                    pass
                                   
            else:
                    print "Hi, I Do not Know, what you Defined !!\n\t as a video file or a folder which contains video files..\n"
    def loop_player():
            """
            This code Block create a list of each and every file recursively,
            But we have used a filter So that wrong File Formats will not be used with
            ffplayer, because this just gives you an error,
            we can also use ffrpobe to know if supplied file is a video file, but this is just
            time consuming process, this would be great if you just use a filter.
            """
            global files, vlist, index_no, cwd
            files = []  
            for i in zip(os.walk(cwd)):
                    files.append(i)
            for i in range(len(files)):
                    for j in files[i][0][2]:
                            try:
                                    filename = os.path.join(files[i][0][0], str(j))
                                    if vid_filter(filename):
                                            pass
                                    else:
                                            vlist.add(filename)
                            except:
                                    print "Error While Filtering File Formats !! In explore video folder Function !!"
                                    pass
    #
    tk_gui()
    root.mainloop()

## FFconverter Python Code
    ##@ http://pastebin.com/gixzxeuj

    #!/usr/bin/env python
    # filename :: video converter using Python ( Based Upon FFMPEG Library )
    print "##"*35
    print "Video Converter Build using Python and FFMPEG library.."
    import os
    import sys
    import tempfile
    import glob
    import subprocess
    import Tkinter as tk
    cwd = ''                # Input file to convert
    cwd21a = ''             # Output file to Convert
    vlist = set()   # Used to create a playlist for converting multiple files simultaneously
    format = ''             # file format or extension to which you want to convert
    duration = ''
    size_of_video = ''
    frame_per_sec = ''
    z = 0
    ffmpeg_command = ''
    def tk_gui():
            root = tk.Tk()
            #root.wm_geometry(newGeometry='250x250+10+10')  
            root.wm_title("Ffconverter ( Video Converter )")
           
            # Container Number 1
            myContainer1 = tk.Frame(root)
            myContainer1.pack()
           
            myLabel1 = tk.Label(myContainer1)
            myLabel1.configure(text="  Select File To Convert  ::   ", background="yellow")
            myLabel1.pack(side=tk.LEFT)
           
            entry1 = tk.Entry(myContainer1)
            entry1.configure(width=100)
            entry1.pack(side=tk.LEFT)
           
            def select_file():
                    """
                    this code block is used to play a single video file,
                    this video file will be added to vlist playlist
                    """
                    global cwd, vlist
                    print "Opening Video File :-)\n\n"
                    openfilename = tkFileDialog.askopenfilename()
                    cwd = openfilename
                    print "You Have Select :: ", cwd
                    entry1.insert(0, cwd)
                    root.update()
            button1 = tk.Button(myContainer1)
            button1.configure(text="Select", background="green", command=select_file)
            button1.pack(side=tk.LEFT)
           
            ## Container Number 3
            myContainer3 = tk.Frame(root)
            myContainer3.pack()
           
            myLabel3 = tk.Label(myContainer3)
            myLabel3.configure(text="Enter Format Name to Convert ::", background="yellow")
           
            myLabel3.pack(side=tk.LEFT)
            entry3 = tk.Entry(myContainer3)
            entry3.configure(width=20)
            entry3.pack(side=tk.LEFT)
           
            def get_format():
                    global format
                    format = tk.StringVar()
                    print "Retrieving File Format.."
                    entry3.index(0)
                    format = entry3.get()
                    print "You want to Convert to :: ", format
                    print "##"*40, "\n"
                   
            button3 = tk.Button(myContainer3)
            button3.configure(text="OK  ", background="cyan", command=get_format)
            button3.pack(side=tk.LEFT)
            ##
            myLabel5 = tk.Label(myContainer3)
            myLabel5.configure(text="Duration, Frame Size, Frame Rate ", background="yellow")
            myLabel5.pack(side=tk.LEFT)
            entry4 = tk.Entry(myContainer3)
            entry4.configure(width=50)
            entry4.pack(side=tk.LEFT)
            def get_size():
                    global cwd, duration, size_of_video, frame_per_sec
                    print "Checking for Oroginal Size of Video File.."
                    filename = cwd
                    result = subprocess.Popen(["ffprobe.exe", filename], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
                    duration0 = [x for x in result.stdout.readlines() if "Duration" in x]
                    duration = duration0[0].split()[1]
                    result = subprocess.Popen(["ffprobe.exe", filename], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
                    size_of_video0 = [x for x in result.stdout.readlines() if "Video:" in x]
                    size_of_video1 = size_of_video0[0].split()
                    for i in size_of_video1:
                            if "x" in i:
                                    size_of_video = i
                    frame_per_sec0 = size_of_video0[0].split()
                    print frame_per_sec0
                    frame_per_sec1 = frame_per_sec0.index("fps,")
                    frame_per_sec = frame_per_sec0[frame_per_sec1 - 1]
                   
                    print "\n", "##"*35
                    print "Duration of Video File :: ", duration
                    print "Size of Video Frame :: ", size_of_video
                    print "Frame Rate of Video :: ", frame_per_sec
                    print "\n", "##"*35, "\n"
                    contents = duration + " " + size_of_video + " " +frame_per_sec
                    entry4.insert(0, contents)
                   
            button5 = tk.Button(myContainer3)
            button5.configure(text="OK  ", background="cyan", command=get_size)
            button5.pack(side=tk.LEFT)
           
            ## Conatiner Number 2
            myContainer2 = tk.Frame(root)
            myContainer2.pack()
            myLabel2 = tk.Label(myContainer2)
            myLabel2.configure(text=" File Converted to     ::      ", background="yellow")
            myLabel2.pack(side=tk.LEFT)
           
           
            entry2 = tk.Entry(myContainer2)
            entry2.configure(width=100)
            entry2.pack(side=tk.LEFT)
           
            def Converted_file():
                    global cwd, vlist, format, cwd21a
                    cwd1 = os.path.split(cwd)[0]
                    cwd2 = os.path.split(cwd)[1]
                    cwd21 = cwd2[:-4]
                    cwd21a = cwd1 + cwd21 + "__converted__." + str(format)
                    print "File will be Converted to :: ", cwd21a
                    entry2.index(0)
                    entry2.insert(0, cwd21a)
                   
                    text1.index(1.0)
                    ffmpeg_command_1 = "ffmpeg.exe" + " -i" + " \""+str(cwd)+"\"" + " \""+str(cwd21a)+"\""+"\n"
                    text1.insert(1.0, ffmpeg_command_1)
                   
                   
            button2 = tk.Button(myContainer2)
            button2.configure(text="Save  ", background="green", command=Converted_file)
            button2.pack(side=tk.LEFT)
           
            button7 = tk.Button(myContainer2)
            def clear_entry():
                    entry1.delete(0, tk.END)
                    entry2.delete(0, tk.END)
                    entry3.delete(0, tk.END)
                    entry4.delete(0, tk.END)
                   
            button7.configure(text="Clear ", background="red", command=clear_entry)
            button7.pack(side=tk.LEFT)
           
            ## Container Number 4
            myContainer4 = tk.Frame(root)
            myContainer4.pack()
           
            #myLabel4 = tk.Label(myContainer4)
            #myLabel4.configure(text="Run Custom FFMPEG Commands", background="red")
            #myLabel4.pack(side=tk.LEFT)
            text1 = tk.Text(myContainer4)
            text1.configure(width=100)
            text1.pack(side=tk.LEFT)
           
            def get_ffmpeg_command():
                    global format, cwd, cwd21a, z, ffmpeg_command
                    format = tk.StringVar()
                    print "Retrieving File Format.."
                    text1.index(1.0)
                    #z = 0
                   
                    try:
                            start = str(z+1)+"."+str(0)
                            end = str(z+1)+"."+str("end")
                            try:
                                    if len(text1.get(start, end)) == 0:
                                            #break
                                            print "There is No Custom FFMPEG Commands Exists in This Line..!!"
                                            print "Value of video Index Number z == ", z
                                            pass
                                    else:
                                            z += 1
                                            ffmpeg_command = text1.get(start, end) # one FFMPEG command must be without a new line character
                                            print "\n", "@#"*35
                                            print "You want to run This FFMPEG Command >> \n", ffmpeg_command
                                            print "\n", "@#"*35
                                            print "\n\n"
                                            os.system(ffmpeg_command)
                                            #p1 = subprocess.Popen([ffmpeg_command])
                            except:
                                    print "No More FFMPEG Custom Commands Found In Text Box.."
                                    pass
                    except:
                            print "Error While Running Custom FFMPEG codes.."
                            z += 1
                            pass
                   
            button4 = tk.Button(myContainer4)
            button4.configure(text="Run Custom FFMPEG Command", background="cyan", command=get_ffmpeg_command)
            button4.pack()
           
            button5 = tk.Button(myContainer4)
            def ffmpeg_manual():
                    print "Opening FFMPEG Manual .."
                    try:
                            subprocess.Popen(["notepad.exe", "source\\ffmpeg.help.txt"])
                    except:
                            print "FFMPEG Manual Not Exists.."
                            pass
            button5.configure(text="  Help?  ", background="green", command=ffmpeg_manual)
            button5.pack()
           
            button6 = tk.Button(myContainer4)
            def ffmpeg_examples():
                    print "Opening FFMPEG Examples .."
                    try:
                            subprocess.Popen(["notepad.exe", "source\\ffmpeg.examples.txt"])
                    except:
                            print "FFMPEG Manual Not Exists.."
                            pass
            button6.configure(text="Examples", background="green", command=ffmpeg_examples)
            button6.pack()
           
            ##
           
    tk_gui()
    while True:
            try:
                    exec(raw_input(":: "))
            except:
                    pass