Why Is a Derived Class Also Known As “Sub-class” When It Has More Properties Than Its Base Class (Aka Super-class)?

April 3rd, 2013

A common query of programmers new to object-oriented programming (OOP) is why is a derived class known as a “sub-class” when, by definition, it contains more member properties/functions than the base class (aka super-class) than it inherited from?

The trick to understanding this concept is to remember that Computer Science has Mathematics as its roots, and “class” is synonymous with “set” in set theory. Thus, when you declare a class, you’re really declaring a set of instances with the defined properties; when you declare a derived class, you introduce additional criteria (properties), thus effectively declaring a specialization of the base class – i.e. a sub class.

E.g.

class Mammal{
  ...
}

class Dog: public Mammal{
  public:
    void bark();
  ...
}

The above code could be represented as the below Venn diagram:

Venn diagram depicting a class and its sub-class

Venn diagram depicting a class and its sub-class

Bookmark and Share

- Lem

Opera to Change Engine – Switching to Webkit

February 17th, 2013

Opera has announced its plans to ditch its Presto rendering engine in favor of Webkit in order to allow it to focus its engineering resources to developing new features and user-friendly solutions.

Webkit, according to Wikipedia, is the most popular web browser rendering engine; prominent users include Google Chrome as well as Apple’s Safari browsers.

Other major rendering engines are Internet Explorer’s Trident and Firefox’s Gecko engine.

Credits: Wikipedia

Bookmark and Share

- Lem

WebRTC new Milestone Reached – Firefox & Chrome’s WebRTC RTCPeerConnection Now Interoperable

February 9th, 2013

Chrome and Firefox have jointly announced that their WebRTC RTCPeerConnection implementations are now interoperable, implying that it is possible to create direct peer-to-peer video calls.

WebRTC stands for Web Real Time Communications, and is an open project supported by Google, Mozilla and Opera to enable web browsers with Real-Time Communications capabilities via Javascript APIs, without the use of plugins.

Firefox-Chrome call demonstration between Mozilla’s Chief Innovation Officer, Todd Simpson, and Google’s Director of Product Management, Hugh Finnan:

Even though the implementations are interoperable, there still exists differences in their Javascript API, implying that you may need to deploy different sets of codes for each browser.
Example difference:

Credits: http://www.webrtc.org/interop

Credits: http://www.webrtc.org/interop

Further info could be found on WebRTC.org website

Bookmark and Share

- Lem

Commonly Used Python Modules/Functions Cheatsheet

January 19th, 2013

See also Python Syntax Cheatsheet

  1. sys/os module
  2. String functions &amps Regexp
  3. File I/O functions
  4. HTTP & SMTP
  5. Misc
    1. math & random modules
    2. Date/time
    3. Compression

sys/os module

import sys

sys.argv # list of args. note that the first item is the name of this script

import os

os.getcwd()
os.chdir(path)
os.mkdir(path)
os.listdir(path=’.’) # note: does not return “.” and “..”

os.environ # map of environment variables. Can be modified directly.
os.system(command)
os.execle(path, arg0, arg1, …, argn, env)
os.execve(path, list-of-args, env)

os._exit(n)

 

File I/O Functions

To open a file, use the “open()” native function:
myFile = open(filename, mode=”r”)

myFile.read() # Reads in the entire file and returns as string
myFile.read(n)
myFile.readline() # Note: the “\n” is read in as well
myFile.readlines() # list of lines

myFile.write(string)

To write binary data, use the struct module:

import struct

myBytes = struct.pack(“>i”,10); # writes i as a big endian integer
Other format rules:

> Big endian
< Small endian
h short
h short
H unsigned short
i integer
I unsigned integer
f float
s string

myFile.seek(offset, fromWhere)
fromWhere could be 0 (beginning), 1 (current pos), 2 (end of file)

myFile.close();
 

String functions & Regexp

String methods:

string.find(substring, start, end)
“The sum of 1 + 2 is {0}”.format(1+2)
string.index(substring, start, end)
replace(old,new,count)
isnumeric(), rfind(), rindex(), splitlines(), split(separator-string)

import re

re.find(r’\bf[a-z]*’, “foot hand fish”) # returns ["foot", "fish"]

re.split(‘[a-f]+’, ’0a3B9′, flags=re.IGNORECASE) # ['0', '3', '9']

myMatch = re.match(pattern, string) # match is an instance of class MatchObject

>>> myMatch.group(0) # The entire match
>>> myMatch.group(1) # The first parenthesized subgroup.
>>> myMatch.group(2) # The second parenthesized subgroup.

Note: match() vs search(). match() matches ONLY from the start of the string.

re.sub(pattern, replacement, string) # replaces all patterns in string with the replacement

 

HTTP & SMTP

Accessing a Webpage

from urllib.request import urlopen

for line in urlopen(“http://….”):
  line = line.decode(‘utf-8′)
  if ‘hello’ in line:
    print(line)

Sending Emails

import smtplib

server = smtplib.SMTP(“localhost”)
server.sendmail(fromAddr, toAddrs, msg);
– fromAddr and toAddrs are SMTP envelope headers
server.quit()

 

Misc

Math & Random

import math
import random

random.random()

Date/time

from datetime import date

now = date.today()
myDateString = now.strftime(“%Y-%m-%d %H:%M:%S”)

birthday = date(1970,6,30)
age = now – birthday # timedelta object

print age.days

Compression
Modules: zlib, gzip, bz2, zipfile, tarfile

E.g. myBytes = zlib.compress(string)
myBytes = zlib.decompress(string)

 

Bookmark and Share

- Lem

Rumour: NTT Docomo to Build Phone on Tizen OS

January 1st, 2013

According to non-official sources, it seemed that NTT Docomo, the largest mobile telco in Japan, has joined Samsung and Intel to build a phone based on Tizen OS, and will supposedly bring the first Tizen OS phone to market in 2013.

https://www.tizen.org

https://www.tizen.org

Tizen is a Linux-based OS that is being touted as a more open alternative to Android, iOS and Windows Phone OSes, which could also run in other devices such as smart TVs and in-vehicle entertainment systems.

Just like Mozilla’s Firefox OS project, Tizen OS provides HTML5-based SDK to its application developers, instead of the usual “native” APIs used by the current mobile OS providers.

Bookmark and Share

- Lem

Python Syntax Cheatsheet

December 25th, 2012

See also: Commonly Used Python Modules/Functions Cheatsheet

Created a cheat sheet for my Python scripting work :D :

Basic Syntax

# this is a comment

Variables:

myVar = 100
myVar = 0×64
myVar = 0o144 #octal
myVar = 0b01100100
intDiv = 11 // 2 #equals 5
powerVal = 2 ** 2 #equals 4

myString = ‘hello’ “world”
myString = ‘hello’ + “world”
myString = r“Special chars will not be escaped, e.g. \r\n”
world = myString[5:]
wo = myString[5:7]
myUnicodeString = “\u3041″ #code-point in hex
var1, var2 = “hello”, “World”

Flow Control:

if :
  do something
elif :
  do something
else:
  do something

for i in range(10):
  print(i)
else:
  print(“looped to the end!”)

while :
  do something
else:
  print(“looped to the end!”)
 

Functions

Function definitions

def myFunction(arg1, arg2):
  # do something
  return 123 # optional return statement

def defaultArgs(arg1=”hello”, arg2=”work”):
  # do something

def varArgs(*myVarArgs): # note that myVarArgs will be wrapped in tuple
  # do something

Function invocations

Keyword Arguments:
myFunc(arg1 = 1, arg2= 2)

Unpacking arguments list:
myList = [1,2]
myFunc(*myList)

Unpacking arguments dictionary:
myDict = {‘arg1′: 1, ‘arg2′: 2}
myFunc(**myDict)
 

Classes

Class definitions

class MyClass(Base1,Base2):
  myClassVar = 1

  def myClassFunc(arg1, arg2):
    #do something

  def __init__(self):
    super()
    self.instance_var_data = []

  …

#Note: there’s no private var in Python

Class Instantiation

var1 = MyClass()

Misc

isinstance(obj, int)

issubclass(bool, int)

 

Iterators & Generators

Iterators are classes that define the __iter__() and next() functions.

Iterators allow your class to be iterated via for …. in … statements

class MyIter:
  def __iter__(self):
    return self

  def next(self):
  #do something

Generators can also be used in for .. in .. statements, but they use the yield keyword to pass control instead. I.e. “automatic” state saving.

def reverse(data):
  for index in range(len(data)-1,-1,-1):
    yield data[index]

for char in reverse(‘golf’):
  print(char)

 

Data Structures

Tuples

Tuples are immutable ordered sequences

myTuple = ()
myTuple = a, b, c
myTuple = (a, b, c)

myTuple[0] #a

Lists

myList = []
myList = [a,b,c,d]
myList.append(d)
myList2 = myList[:] # copy all elements
myList2 = myList[1:2] # copy the 2nd element
myList2 = myList[1:-1] # b,c

List comprehension:

mySquares = [x**2 for x in range(10)]
evenNumbers = [x for x in range(100) if x % 2 ==0]

Sets

Unordered collection with no duplicates

mySet = {a,b,c}
mySet = set() # NOTE: “mySet = {}” CREATES AN EMPTY DICTIONARY INSTEAD!!

Set operations: a – b, a | b, a & b, a ^ b (xor)

Dictionaries

Dictionaries are hash maps

myDict = dict()
myDict = {}
myDict = {“hello”: 123, “World”: “LOL”}
myDict["hello"] # 123

myDict.keys()

for k,v in myDict.items():
  print(k + “: ” + v)

Dict Comprehension: mySquares = {x:x**2 for x in range(10) if x % 2 == 0}

len(myList)

 

Exception Handling

try:
  #do something
  raise SomeException()
except ValueError:
  #do something
except ZeroDivisionError as err:
  #do something
except:
  #default event handling logic
else:
  #when no exception occurs
finally:
  #execute regardless if exception occurred or not

Exceptions derive from the Exception class:
class MyException(Exception):

 

Modules & Packages

“import” statement brings the module into the current scope

import sys
sys.byteorder #valid call

from sys import byteorder
byteorder #valid call

if __name == “__main__”:
  #this py file was executed directly
  import sys
else:
  #this py file was loaded as a module

Module search path:

  1. built-in module
  2. current dir
  3. PYTHONPATH env var

dir() #lists all the modules loaded and variables defined
dir(modulename) #lists all symbols defined in the module

Package is a specialized form of modules.
Any module that contains a __path__ attribute is considered a package
Subpackages are separated by “.”

 

Misc

str() and repr() returns the string representation of an obj.

classes can define the __str__() function

string.rjust(2)

Formatting strings

‘{0} and {1}’.format(‘spam’, ‘eggs’)
‘The {food} was {adj}’.format(‘food’='spam’, ‘adj’='delicious’)

‘The value of pi is ~ %5.3f’ % (math.pi) #note: tuple

Serialization

Use the Pickle module:
  pickle.dump(x, fileobj)
 x = pickle.load(fileobj)

 

Bookmark and Share

- Lem

Using Facebook Messenger Without a Facebook Account – Facebook Gets Serious About Mobile Messaging

December 5th, 2012

Oops, currently only available on Android in India, Indonesia, Australia, Venezuela, and South Africa. But would most prob be coming to other OSes and regions in due time.

Facebook has revealed that it has released an update that will allow Android users in the said regions connect to Facebook Messenger using just their phone number. This move highlighted Facebook’s mobile messaging ambitions and puts it in direct competition with mobile messaging veterans – WhatsApp, Kik, Line, KakaoTalk. Facebook would be a formidable rival, not just because of it vast user base, but also because, unlike the mobile messaging veterans, Facebook Messenger allows its mobile users to cross-chat with their friends on desktops as well.

Credits: Facebook

Bookmark and Share

- Lem

HTTPS Strict Transport Security Officially a Standard

November 24th, 2012

HTTPS Strict Transport Security or HSTS, has graduated from “draft” status, and is now an official standard – RFC6797.

HTTPS Strict Transport Security (HSTS) is a proposed mechansim for websites to communicate to the browser that all embedded content, such as images and Ajax requests, on a https-encrypted webpage should be accessed via https as well. The browser, in turn, should take note of this request and should ensure, and change if neccessary, that all connections to the website are via https.

Overview:

  1. Browser navigates to a HSTS website via HTTPS.
  2. The HSTS website responds with the requested content. In its HTTP Response, there is a HTTP header “Strict-Transport-Security”, which would indicate to the browser that it is a HSTS website and also specify the duration for which this header is valid via the “max-age” attribute. The maximum value for “max-age” is 778000 sec = 90 days
  3. The browser will take note and remember this website as HSTS. During the valid duration, the browser would check that all HTTP connections to the website are via HTTPS and modifies if necessary, i.e. change “http://abc.com/myimage.png” to “https://abc.com/myimage.png”. In addition, if there are any errors in accessing the content via HTTPS, such as an invalid SSL Cert, the request would fail.

Note that HTTPS Strict Transport Security was designed as a second line of defense in case of human (programming) errors, to mitigate the risks of passive attacks (packet sniffing), by ensuring that all sensitive data such as cookies are transmitted through secured channels. HSTS is not designed to protect against active hackers; you’ll still need your standard security tools – firewalls, anti-viruses – for that.

Browsers that support HSTS include Google Chrome and Firefox. The NoScript Firefox extension also enforces HSTS for (older versions of) Firefox.

An example of a website that supports HSTS is Paypal:

Bookmark and Share

- Lem

What is HTML5?

November 1st, 2012

HTML5 had undergone a natural evolution process


My take – the term “HTML5″ had undergone a natural evolution process and now refers to any new proposed browser capabilities that had not existed in HTML4.

HTML5 refers to any new browser capabilities that had not existed in HTML4


Strictly speaking, HTML5 should only refer to the set of features outlined by WHATWG or W3C.

However, in my opinion, the term “HTML5″ had been shaped by market forces – in the form of marketing misuse and mis-interpretation, and perhaps over-optimism – and have now come to refer to any new HTML tags, Javascript APIs, and CSS features that were not part of HTML4.

The below diagram (credits: Wikipedia), while not comprehensive (e.g. WebRTC not inside), echoed my thoughts in considering new features that were not part of WHATWG or W3C’s list as HTML5:


Credits: Wikipedia – http://en.wikipedia.org/wiki/HTML5


Additionally, I also thought that http://www.html5rocks.com/en/ shared a similar idea of what HTML5 is, as this website also showcased articles on “HTML5″ features that were not part of WHATWG or W3C.


Credits: Wikipedia – http://en.wikipedia.org/wiki/HTML5


Note: I had previously written a short description of HTML5, but that was based on my previous interpretation of HTML5, which had since changed. However, the examples that I had quoted are still valid =)

Bookmark and Share

- Lem

Enough of Cloud Computing! Time for Paper Computing!

October 31st, 2012

Interesting article on DigInfo regarding research that will make it possible for computers to draw and erase on paper, effectively allowing paper to dual-function as both a computer screen as well as a “printed” hardcopy.

“The idea is to do computing on paper. But in the future, we’d like to enable several people to create one document, like with Google Docs, actually using real-world paper while far apart. We’d also like to enhance the rendering that’s possible through collaboration between people and computers. For example, by giving more detailed access than you get by hand, and enabling you to draw large areas at once.”

Bookmark and Share

- Lem