May 27, 2013

Python IF Statement

Python IF Statement

False Values:
None, 0, empty string, empty list, empty dictionary

Boolean False:
True, False
1, 0

Operators:
==, !=, <, <=, >, >=

and
or
not

Important:
Python doesn't have ! operator,

IDLE 2.6.6    
>>> st = 'my non empty string'
>>> if(!st):

SyntaxError: invalid syntax
>>>



>>> if(not st):
 print "Empty String"
else:
 print "Non Empty String"


Non Empty String
>>>


May 18, 2013

Python Strings - III

1)
Pythonic way to copy a string/list
s[:]

IDLE 2.6.6    
>>> s = 'my new string'
>>> s
'my new string'
>>> s1 = s[:]
>>> s1


2)
Python % and Strings

python comes up with printf like % things.

IDLE 2.6.6    
>>> str = " I am learning %s since %d days " % ('python',5 )
>>> str
' I am learning python since 5 days '
>>>


After %, we need to provide tupple.


3).

Python Unicode Strings:

  
IDLE 2.6.6    

>>> str = u' Python Unicode \u018e '
>>> str
u' Python Unicode \u018e '
>>> s = str.encode('utf-8')
>>>
>>> s
' Python Unicode \xc6\x8e '
>>>

Python Strings - II

Python String Part -II
------------------------

String Methods:
-------------------

Difference between method and function is that, method is called on an 'object'
while function is called independant.

some of the methods:

s.upper() : converts to upper-case
s.lower() : converts to lower-case

s.strip() : trims spaces


s.isalpha() : whether the string is alpha numeric or not


IDLE 2.6.6     

>>> s = 'd'
>>> s.isalpha
<built-in method isalpha of str object at 0x0039ECE0>
>>> s.isalpha()
True


>>> s = 'd3('
>>> s.isalpha()
False


>>> s = '3'
>>> s.isdigit
<built-in method isdigit of str object at 0x003AF580>
>>> s.isdigit()
True

May 17, 2013

Python Strings

Python Strings:

1)
Stings can be enclosed by " ( double quotes ) or  ' ( single quotes )
escaping works on both single quotes and double quotes

2)
Also, we can have multi-line strings.
- But for multiline strings, it has to be escaped by \
- Or we can use """ or '''

example:

a = " this is \
multinline string "

a = """ this is
multine string """


3)
String in python are immutable. i.e. once assigned, it can't be changed.
i.e. all manipulative operations are resulted into new string

4)
we can use [] operator to access string characters
starting from 0 index

s = 'hello'
s[1] will be 'e'

len function returns lenght of the string


4).
There is no ++ operator in python


May 16, 2013

Python Modules and Packages

python module
- module __name__
- a module can contain executable statements as well as functional statements
- those are executed only once
- modules has its private symbol table
- modules can import other modules
- if you include __name__ == __main__ -> then, it will execute
- otherwise, module can be imported too

python module search path
- module is first searched into module path
- then, module is searched in sys.path
- sys.path same as PATH variable in shell


what is python compiled file
- byte compiled.
- modification time

python standard modules
- python comes up with standard modules
- that is called python library reference
- dependant of system implementation

python packages:
- module namespace - by using dotted module names i.e. A.B
- import * = must be in __init__.py file  : 

Python: Dynamic and Strongly Typed Language


Python is both dynamically and strongly typed language.

Dynamic:
- i.e. Types are checked at run-time

Strongly:
- i.e. We can't intermingle variables with different type
         Javascript: var b = 'x' + 3, This will assign 'x3' into b
         While in python, you it would throw an exception



More into Dynamic Nature of Language:

When we declare a variable, we usually associate a type with that.
i.e. integer, float

For Example:

int a
float b

In STATICALLY typed language, variable type is fixed through out life cycle of program execution.

Assigning a = 's', ( integer typed variable to string would throw compile time error )

But, in python, it's dynamic nature.

Variable can hold any type of data through-out the life-cycle of program execution.

a = {'key':'value'} # first as dictionary
a = 'a' # now as String


So, during compile-time, type checks are skipped, Although, as its strongly typed language,
we can't intermingle two different type of variables.

It is up-to programmers test-suite to detect type errors.








Python Basics


Why Python ?

 - Efficient High-Level Data-structures.
    - Tupples
    -  Lists
    - Dictionaries
    - Sets


- Simple Object Oriented Approach

- Elegant Syntax
   a = "hi %s" % "Dave"

- Dynamic Typing
  - i.e. type-checks are performed at run time


sys.exit(0)

March 29, 2013

Bootstrap modal in center

Showing up bootstrap.js modal dialog into center, when we dont use default width.
 
here is the hack:
 

        $("#headerPreview").modal('show').css(
        {
            'margin-top': function () {
                return -($(this).height() / 2);
            },
            'margin-left': function () {
                return -($(this).width() / 2);
            }
        })



Source: https://github.com/twitter/bootstrap/issues/374


Cheers!

March 23, 2013

Zend Framework Basics

Zend Framework, is basically, collection of component,
when put together, we can build web-app relatively faster and stronger.

While, we can use indiviual component too.



Comes up with basic componanents:

Zend_Controller
Zend_Layout
Zend_Config
Zend_Db
Zend_Db_Table
Zend_Registry

September 30, 2012

PHP - Create Vertical Text Image

Create vertical text image in PHP

Please visit Gist

cheers!!

September 20, 2012

PHP MVC Part - I

MVC:

Model
View
Controller

What is MVC?
MVC is a way of coding. how do we distribute functions/classes/files. 

What MVC is not ?
MVC is not any programming language, rather it is a framework/architecture/design schema.
MVC architecture, we can implement in PHP, JAVA, C# and also JavaScript

Analogy:
1. How do you keep things in your kitchen. ?
2. We can keep all tools and utilities scattered on one table - ( No Pattern )
3. We can keep tools categorized by use. i.e. knife,spoon in one box, Plates near sink   - ( some pattern )

Real world example:
1. We have to build Book Store
2. We need to add/remove books
3. Show users list of books
4. Registered user can see preview

Here, we have some logic, lets call them, business logic:
i.e. add/remove books:

Also, we have some-thing to show user
i.e. List of books

Also, we have one rule
i.e. Registered user can see preview


All classes/functions of business logic, we can call: MODEL
All classes/files which helps to render product list, we can call:VIEW
All classes/files/functions which helps to decide/implement rule, we can call: CONTROLLER


Technically:
Model: Encompasses business logic ( Mostly base classes )
View: Helps to present/render data ( Mostly template files + classes which helps to render )
Controller: Helps to decide some rule. like, which page to render, which page not to render

Prime Example of MVC architecture:
Zend
Magento - way to complex to understand

End of part one.

Cheers!!




September 14, 2012

PHP MVC Singleton pattern

What is Singleton pattern ?
- A simple design schema, in which, we instantiate object only once in a page life cycle.

Explanation with analogy.
- Lets say, you went to restaurant and ordered 3 types of Soup.
- Each Soup comes up with Bowl + Spoon
- Now, you have 3 spoons.
- Normal pattern : you use 3 spoons for each bowl
- problem in that: wastage of 3 spoons
-Singleton pattern: each time, you use: same spoon to drink soup.
- Thats it.

Real-time example:
- DB Object.
- We invoke DB object in page life cycle only once.
- Each time, we need to run query, we use same object.

Example with code:

class db{

publis static $_instance;

public static _getInstance(){
       // Lets check, do we have object already instantiated ?
        if(self::$_instance){
             // return already instantiated object
             return self::$_instance
        }
        else{
             // else instantiate and return object
             return self::$instance = new db();
        }
}

}


Seems so easy :)

cheers!!!

September 12, 2012

Javascript Closure

Good way in javascript to have dynamic content using closure

Lets say, we have to use the string:

" content has been posted 1 times"
" content has been posted 2 times"

we can use below code

var message = function(count){
return " content has been posted " + count + times ";
}
console.log(message(1));
console.log(message(2));

Cheers!!

September 11, 2012

jQuery $.ajax IE and Cross Domain

jQuery $.ajax fails in IE for cross-domain request, even-though we have allowed origin on server configuration.

Basically AJAX is an transport mechanism, with few rules. we can have our own transport too. Here is how we can override $.ajax transport and allow cross-domain AJAX request in IE.

Add below code at the end of page.

$.ajaxTransport("+*", function( options, originalOptions, jqXHR ) {
    if(jQuery.browser.msie && window.XDomainRequest) {
        var xdr;
        return {
            send: function( headers, completeCallback ) {
                // Use Microsoft XDR
                xdr = new XDomainRequest();
                xdr.open("get", options.url);
                xdr.onload = function() {
                    if(this.contentType.match(/\/xml/)){
                        var dom = new ActiveXObject("Microsoft.XMLDOM");
                        dom.async = false;
                        dom.loadXML(this.responseText);
                        completeCallback(200, "success", [dom]);
                    }else{
                        completeCallback(200, "success", [this.responseText]);
                    }
                };
                xdr.ontimeout = function(){
                    completeCallback(408, "error", ["The request timed out."]);
                };
                xdr.onerror = function(){
                    completeCallback(404, "error", ["The requested resource could not be found."]);
                };
                xdr.send();
          },
          abort: function() {
              if(xdr)xdr.abort();
          }
        };
      }
    });
 
 
Cheers!! 

June 09, 2012

Bugs in software

Most painful things about software application are Bugs:

That has created virtually more than Billion Dollar Industry. ( Literally... ). For example, QA, QTP, Selenium and lots more...

After working on few iterations of same product.. old adage is powerful.

It is better to prevent rather than cure.

Use-cases:
1. Our client had virtually no patience during first iteration of consumer internet product.
2. He would present a page of ebay and ask to replicate it ... ASAP.

3. Poor developer, under pressure of project manager, recession and client tries hard to code
    fast and works on SATISFIABLE deliverable. After seeing that...client says okay.

4. Next day, Client asks the same to replicate for other type of classified of same page.
5. Again, under pressure -- poor developer with sheer force of his job security
    copies the module and in one case, it was so intense that, developer may not care about
    changing variable names either.

....these are the points, where i think, system becomes less and less usable. we had then, another 2 iterations at the cost of time and nonetheless to mention $$$$$.

Get to the market fast would be a good thing to follow, but, that has to be modified like

Get to the market fast in usable form. 


Lessons Learned:
1. Avoid working for clients with blind deadlines and rigidity of output/delivery
2. Avoid off-topic discussions in order to stay focused and keep shipping

3. Preset all use-cases in order to avoid possible unknown bugs.
4. Listen carefully and grasp N+2 level of requirement.
     i.e. if client wants to put a button with some operation.. try to understand,
           what exactly he wants to accomplish.
5. Avoid bugs from start :) it is better to prevent than cure.


Cheers!!

 

June 08, 2012

Optimism amidst 'recessionary fears'

Nice point to learn in Donald R. Keough's : Top 10 commandments for business failure"

We move slowly, but progress is being made at even the most hidebound bastions of what some politely call "traditionalism"

Father Ted Hesburgh at Notre Dame calls it: " Reactionary Pigheadedness".

Like, 1900 or 1929 or 1998 or 2007, we slowly progress for sure...

Get past the past.

Nicely written..

June 07, 2012

Web scrapping using python and beautifulsoup

BeautifulSoup is nicely written utility in python to parse the web page using.

It follows css selector style. Thus developer who is used to jquery selectors will find it very easy to parse the HTML/XML tags.

Here is sample example to get all the links.

Python:
 
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc)
 
soup.find_all('a')
#returns all links as nested data-structure
 
soup.find(id="link3")
#return node whose id is link3   

very Awesome.

Cheers!

 

May 30, 2012

Agile Development

Learned a big lesson today being in software development.

 -- Delivery is more important than coding elegance.


Today, we had a interim release of quasi consumer product i am working on for USA based client.

We have had third ( yes, third ) rewrite of code base. and each time we missed the delivery targets by few weeks. But, now everything is on burner. 16 hours of coding streak in a day.

Biggest lessons learned:
1. Delivery is more important. That means, less time spent of decisions on coding elegance
2. Keeping things simple should given more priority.
3. Meetings are simply waste of time.

4. Get things done is better than perfect. we can come later and fix trivial things.
5. Keep Shipping is like life line.