Install Wagtail – Linux Dependencies

I was trying to install wagtail which gets annoying if you are using something ike a Vagrant Box or Linux machine. Follow the following steps :

  1. Install pip
  2. Install  libjpeg-dev
  3. Install  zlib1g-dev
  4. Install  python-dev (if not 2 and 3  and 2 and 3 are in 4, still try just 2 and 3)
  5. Install pillow
  6. 6. Install wagtail

If you do not want to follow all the steps every time you set up an environment, make a vagrant box with these preinstalled and share it.

Matching DateTime objects in test cases with Django Rest Framework

If your model has a date_created or modified etc. kind of object(s) probably you will face a datetime object mismatch issue while asserting equality of your dictionary object with the rendered response dictionary. So, I have created a small function which will help you resolve it.

 

DATETIMEHELPER = lambda x : str(x.isoformat().split('.')[0])+'Z'

 

Now, you can call your data object as :

data = {...,"date_created":DATETIMEHELPER(self.model_name.date_created),...}
response.render()
self.AssertEqual(json.dumps(response.content), data)

Implementation of Graph DS using Python and BFS,DFS covered with iteration

This post will be mostly code. Please use proper indenting cuz Python otherwise will make your life hell. If you’re using Sublime go to, set Convert Indentation to tabs.

Gist : I have used the collections.defaultdict dict DT for implementing a dict of sets.
Vertices have been stored as adjacency list kind of elements as a dictionary. The code is raw and may have errors ( though no compilation error as of the post’s writing). Please comment for additional details. This is purely for testing purposes.


 

graph            A Graph.

 



from collections import defaultdict

#The Graph will be a dictionary of sets
class Graph():

def __init__(self, connections, directed = False):
self.graph = defaultdict(set)
self.directed = directed
self.add_connections (connections)

def add_connections(self, connections):
for node1,node2 in connections:
self.add_connection(node1,node2)

def add_connection(self, node1, node2):
self.graph[node1].add(node2)
if not self.directed:
self.graph[node2].add(node1)

def remove(self, node):
#removes all references to the node
#Use iteritems for dict items like k,v in dictname.iteritems():
for n,cons in self.graph.iteritems():
try:
#Removing from a set involves setname.remove(element)
cons.remove(node)
except KeyError:
pass
try:
#Removing from a dictionary involves rem dict_element_name
del self.graph[node]
except KeyError:
pass

def isconnected(self, node1, node2):
if node1 in self.graph[node2] or node2 in self.graph[node1]:
return True
return False

def dfs(self,start):
#If start node does not exist, return None (search is futile)
if start not in self.graph:
return None
#Start with an empty set
visited = set()

#To return unse ( which is not a set
unset = []
#Initially fill stack with start vertex
stack = [start]

#While stack is not empty keep repeating this algorithms
while stack:
#Take the first element of stack (pop means last inserted , aggressive)
vertex = stack.pop()
#If vertex has not been visited yet, add it to visited and look for all the element in graph[vertex]
if vertex not in visited:
visited.update(vertex)
unset.append(vertex)
stack.extend(self.graph[vertex] - visited)
return unset

def bfs(self, start):
if start not in self.graph:
return None
visited = set()
queue = [start]
unset = []
while queue:
vertex = queue.pop(0)
if vertex not in visited:
visited.update(vertex)
unset.append(vertex)
queue.extend(self.graph[vertex] - visited)
return unset

#Should work but not tested
def findpath(self,v1, v2):
m = bfs(v1)
if v2 in m:
return m[:m.index(v2)+1]
return None

 

Promises (and async prog) in JavaScript – To be continued..

For those living under a rock in the world of Web Dev and who missed the big buzz when Promises in JavaScript were the talk of the town. I present this article. Yeah, I am one of you and did not really bother to check them out because most of my routine tasks were being performed using Callbacks. Now, since I think I have some time to look into it ( free from my BackEnd work) I am interested in writing about them.

Notes to self : I Promise that this won’t be a long post. I Promise that this post will give only an elementary idea of Promise in JS because I myself found it very difficult to find something, giving you a very elementary idea of the same. I also Promise that I will not keep your hanging and add all the relevant context that you need to know/understand in order to understand JavaScript Promises, like async. 


 

promise

What is ‘Asynchronous Programming’ in JS ?
console.log("A");
jQuery.get("X.html",function(){
console.log("B");
});
console.log("C");

The mentioned code extract may or may not return the Alphabet output A B and C in order. It may be A C B too. Why? Because B is executed asynchrnously. Because loading the X.html page may take time and is executed as soon as its available and the extract console.log("C"); does NOT wait for it to complete.
See this code extract :

tweet = A(); //Line1
//Do something with tweet
doSomeImportantThings; //Line2

So, line number 2 will not be able to execute until Line 1 is done and the next things are done as JavaScript is single threaded.

But, now check this code :

A(function(){ //Line 1
//Do something with tweet
});
doSomethingWithTweet(); //Line 2

Here, A does stuff asynchronously and Line2 will not wait for A to finish. This is the beauty of Asynchronous execution. But, at times, when things are asynchronous it may lead to trouble if we exactly need the things to happen in some order.

Consider the scenario below :

  1. Load a Loading GIF file to indicate page is loading
  2. Load Images
  3. Load Fonts
  4. Load Everything else relevant
  5. Only if all are loaded, remove the GIF Loader and display the content

Due to JavaScript’s synchronous execution and single-threadedness the above order may not be executed as we desire. Say, Images and Fonts are from third party websites like Google and hence, asynchronous loading is necessary. So, it will take a while. Not sure how much though and the Loader will also not know what is the finishing time. This is sad. Check Pseudo code :


loadLoaderGif();
getImages{function('url'){
//load the images from the URL
})();
getFonts(function('fontsurl'){
//Load fonts
})();
//etc. etc.
//unloadLoaderGif();

As you can tell, based on your internet speed and mostly any damn internet speed, loadLoaderGif() and unloadLoaderGif(); will execute almost immediately whereas the async functions will take their own time for fetching images and laying them at the right places etc. So, the whole purpose has been defeated yeah ? Ok. To solve this our forefathers already included callbacks in JS.

Check this pseudo-code extract :

loadLoaderGif();
n = function('fontsurl'){
//Load fonts
UnloadLoaderGif();
}
m = function('url' , getFonts, n){
//load the images from the URL
getFonts(n);
}
(function(getImages, m){
getImages(m);
}());

Oh. Callback hell!

Now, how about this???

loadLoaderGif();
//I am a magical block of code and I ensure you that I will execute
//All of the loaing n crying, ranting stuff and then only let the function next
//to me execute
unloadLoaderGif();

See the middle block of comments !!!!
Yeah, Promises come into the picture now.

INCOMPLETE ( To be continued )