Backbone.js the Basics

Backbone is a JavaScript front-end framework that is used to solve down the purpose of modular programming in JavaScript. Whenever a programmer starts to build nice apps in JavaScript with some functionality the code starts to become more and more cumbersome with more and more functions working with one another and returning values from one function to other. Backbone provides a platform that makes the code of the application more standardized by using some build in methods and structures of writing code.

I decided to work on this framework because one of the project on which I was working had it’s code written in this platform and it was whole lot of code( somewhat around 45000 lines of code). After opening the main file, sometimes my editor starts to hang. Here is the code of that project: https://github.com/singh1114/converse.js

Backbone doesn’t works like many of the MVC( Models, Views, Controllers) frameworks like ruby on rails. The code of backbone consist of four major classes:

  • Models
  • Views
  • Collections
  • Controllers

Sometimes Routers are also considered as the main part but if you want to build a SPA( single page application) then you don’t have to think of them.

Dependencies

Backbone has a soft dependency on jquery and hard dependency on Underscore.js. So, if you want to build a application then create a folder with your app name and then download the newest production version of these three softwares and then add them as a script in the order as follows :

  • Jquery
  • underscore.js
  • backbone.js

See an example here which includes CDN format of these files included:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js">
<script type="text/javascript" src="https://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js">
<script type="text/javascript" src="https://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js">

Now let’s talk about all the major things in Backbone one by one:

  • Models

Models are the single row in the database in this case. Each time you create a model in the app you create a set of rules in which the user can provide some data to the app.


var Person = Backbone.Model.extend({
initialize: function(){
console.log("This works as constructor");;
},
defaults:{
Name: 'Ranvir Singh',
Age: 21,
}
});
var sahil = new Person({Name: "Sahil", Age: 23});

var ranvir = new Person();

var name = sahil.get(‘Name’);
document.write(name);

var sahil.set({Name: ‘Sahil Sharma’}) ;

sahil.save();

Person is the type of class which has an initialize function and some default values which tells us what kind of data can arrive from some place. There are many functions like get and set which can be used to provide further functionalities. You can find some of them on this link.

get and set functions are used so that we have less probability to change the values by chance. save function is used to permanently change the changes to the particular

  • Collections

We will discuss the rest part in the next tutorial and I will tell you when it’s out.

Simplifying the construction of graphs made using amcharts

I was given a task by sir to simplifying the work of construction of graphs using amcharts. My sir had already constructed a graph by making use of an equation.

For making graphs, we have to look into the way using which the graphs are created.

For a simple 2-D graph we have an equation y = f(x). This equation is followed at every point on the graph. The simplest way to create a path is by interpolation i.e. for each point of x we try to find out the corresponding value of y using the equation and finally put the point on the graph. This the most basic and most useful method for creating the graph.

The equation can further be extended into y = f(x) + c1 + c2…. where c1, c2…. are the constants. So what we have to do now is that we have to pass a set of constants too to complete the calculations.

So, my college senior Manpreet Kaur, who created the original version of this made use of this logic and created a function that calculated the value of the equation when all the constants and each value of x was passed into the function.

amchart graph using a equation

Now my task was to simplify the work of the construction by making use of some other equation. I decided to make a .json file and define everything in that file and try to take the variables from the JSON file. So that all the initialization must be on one occasion. I was able to make the same graph by making the JSON file and importing the variables from the JSON file.

I was able to make the graph but code is not full proof i.e. the support of some technical person is required to make the graph completely. I decided to use three or four more equations.

How to contribute to the open source and improve the way you write code

Contributing to open-source is something that most people don’t try to do when they are starting out in the development career. Due to this reason, people are leaving a lot on the table.

Open-source can be advantages to the career of a developer at any level.

A full-length blog was posted on my website lately. Please give a look and let me know if you liked it.

GraphFrames

GraphFrames is a package for Apache Spark which provides DataFrame-based Graphs. It provides
high-level APIs in Scala, Java, and Python. It aims to provide both the functionality of GraphX
and extended functionality taking advantage of Spark DataFrames. This extended functionality
includes motif finding, DataFrame-based serialization, and highly expressive graph queries.
What are GraphFrames? GraphX is to RDDs as GraphFrames are to DataFrames.
GraphFrames represent graphs: vertices (e.g., users) and edges (e.g., relationships between
users). If you are familiar with GraphX, then GraphFrames will be easy to learn. The key differ-
ence is that GraphFrames are based upon Spark DataFrames, rather than RDDs.
GraphFrames also provide powerful tools for running queries and standard graph algorithms.
With GraphFrames, you can easily search for patterns within graphs, find important vertices, and
more. Refer to the User Guide for a full list of queries and algorithms.
creating nodes using pagerank algorithm

# Create a Vertex DataFrame with unique ID column “id”
v = sqlContext.createDataFrame([
(“a”, “Alice”, 34),
(“b”, “Bob”, 36),
(“c”, “Charlie”, 30),
], [“id”, “name”, “age”])
# Create an Edge DataFrame with “src” and “dst” columns
e = sqlContext.createDataFrame([
(“a”, “b”, “friend”),
(“b”, “c”, “follow”),
(“c”, “b”, “follow”),
], [“src”, “dst”, “relationship”])
# Create a GraphFrame
from graphframes import *
g = GraphFrame(v, e)
# Query: Get in-degree of each vertex.
g.inDegrees.show()
# Query: Count the number of “follow” connections in the graph.
g.edges.filter(“relationship = ’follow’”).count()
# Run PageRank algorithm, and show results.
results = g.pageRank(resetProbability=0.01, maxIter=20)
results.vertices.select(“id”, “pagerank”).show()

NetworkX

NetworkX
Figure 4.2: NetworkX logo
NetworkX is a Python package for the creation, manipulation, and study of the structure, dy-
namics, and functions of complex networks.
Features
• Data structures for graphs, digraphs, and multigraphs• Many standard graph algorithms
• Network structure and analysis measures
• Generators for classic graphs, random graphs, and synthetic networks
• Nodes can be ”anything” (e.g., text, images, XML records)
• Edges can hold arbitrary data (e.g., weights, time-series)
• Open source 3-clause BSD license
• Well tested with over 90% code coverage
• Additional benefits from Python include fast prototyping, easy to teach, and multi-platform
Installation
sudo apt-get install python-pip python-virtualenv
virtualenv venv
source venv/bin/activate
pip install networkx
Algorithm PageRank computes a ranking of the nodes in the graph G based on the structure
of the incoming links. It was originally designed as an algorithm to rank web pages.
Graph types
• Undirected Simple
• Directed Simple
• With Self-loops
• With Parallel edges

OSMnX

OSMnx
Figure 4.1: OSMnx map of manhattan
OSMnx: retrieve, construct, analyze, and visualize street networks from OpenStreetMap.
OSMnx is a Python package that lets you download spatial geometries and construct, project,
visualize, and analyze street networks from OpenStreetMaps APIs. Users can download and con-
struct walkable, drivable, or bikable urban networks with a single line of Python code, and then
easily analyze and visualize them.
Features
• Download street networks anywhere in the world with a single line of code
• Download other infrastructure network types, place polygons, or building footprints as well• Download by city name, polygon, bounding box, or point/address + network distance
• Get drivable, walkable, bikable, or all street networks
• Visualize the street network as a static image or leaflet web map
• Simplify and correct the networks topology to clean and consolidate intersections
• Save networks to disk as shapefiles or GraphML
• Conduct topological and spatial analyses to automatically calculate dozens of indicators
• Calculate and plot shortest-path routes as a static image or leaflet web map
• Plot figure-ground diagrams of street networks and/or building footprints
• Download node elevations and calculate edge grades
• Visualize travel distance and travel time with isoline and isochrone maps
• Calculate and visualize street bearings and orientations
Installation
sudo apt-get install python-pip python-virtualenv
virtualenv venv
source venv/bin/activate
pip install osmnx
Usage
import osmnx as ox
G = ox.graph_from_place(’Punjab, India’, network_type=’drive’)
ox.plot_graph(ox.project_graph(G))

Django: Keeping your directory structure clean

Hello there!

If you have worked with Django before, then you might know the way you organise your files is very important in making your code reusable. These days I have been trying to DRF( Django’s REST Framework). Along with learning, I am trying to complete a minor project.

So, I found a great article that explained a lot about the way you should keep your files in a project that is built using Django. Here is the link if you want to read it.

http://www.revsys.com/blog/2014/nov/21/recommended-django-project-layout/

In this post, I am going to discuss the discrepancies that I discovered while following the tutorial.

  • After dividing the settings into some parts, your code breaks down. For running the code again you have to make changes in two places. One at the manage.py and other at wsgi.py.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings.dev")

After doing this, you will get rid of the empty secret code error.

  • After this, you may face the ‘module not found’ error. For solving this, just use a dot before the name of the module that you are importing.
from .base import *

After this, the runserver command will work.

Thanks for reading. Do comment your views.

Sorting the messages in the _postMessage function

I am trying to sort the messages that I am receiving when I used the getHistory function in the Message Archiving. But till now I haven’t found a success.

They say failures are the greatest teachers. I hope they are true because yet again, I have failed.

A lot of tough words up there. Let’s simplify the situation a little. So from last few posts, I have been talking about XMPP- The protocol for chatting( or message sharing). I did posted them because I was working on a chatting web-client called JSXC. I tried it and found that the client never retrieved messages from the server. So my work was to implement this feature.

With the help of the main developer, I was able to make some progress and made the messages appear into the chat box. As the developer told me that the messages are not going to be sorted so I have to make some changes in the function such that the sorted messages can appear in the chat window.

In this post I want to discuss the way in which I wrote the function without showing the real code so that we can keep everything simple. First of all, I wrote the getHistory function such that if there is message in the server for a particular person( we call it jid in terms of XMPP), make a object having everything about the message and send it into the function named postMessage which in return is responsible of printing these messages into the chat box.

Now, I did checked personally that the messages are stored properly on the server and they are retrieved properly one at a time. Whenever a message is retrieved from the server the message is given to the function for printing. But to my surprise the messages order does not remain intact and messages printed in the chat box are in no particular order.

So I decided to make some changes to my function. I changed the function and now the function saves all the messages for a partcular person in an array and when all the messages are retrieved they are sent to the function for printing. I used a loop to make it work but as far as I think it is not working. I don’t know why.

For more details stay tuned. Also this week was great in terms for my typing speed. I wrote whole of this post without giving a single look to the keyboard. Also the speed have reached a new level of 30 wps. Which is a great progress.

converse.js and candy.js Functionalities

I have tried both converse.js and candy for creating a chat application on the browser for some use. Both of them provide very good functionality. Both converse.js and candy are based on XMPP client and pull data from the ejabberd server and render it on the screen on the browser.

But somehow we ended up not using both of them. In this post, I am going to discuss the things that helped us to move forward leaving behind these clients.

converse.js

The client is very good and a lot of development is being done by the developers. Also, the interface of the client is very great and is similar to the interface of facebook messaging client. But there were some things that were not well in the client like:-

  • There is no file transfer
  • All of the groups were shown( even the once that were not required by the user)

Candy

This client is also very good. The best thing is that they have built everything as different plugins and if you want to install any of them you can do that separately. This gives a choice to everyone. But the things that were not great about this were:-

  • history saving is not there
  • Interface is not that great

Maybe we have not checked them properly so these points might change with the time. I am going to look into them properly.

PHP : The Basics

What is PHP?

php stands for Hypertext Preprocessor. We have posted a lot about the python web development framework Django. It is somewhat similar to Django. PHP is the most widely used language for the server. It is used for handling the server. It is also used to interact with your database so that you can save the data for future use. PHP is also open source and free to use. PHP is very easy to learn that is why many developers believe that every new developer ;learn this as the first language.

Installation

Installation of PHP is very simple and can be done easily. Just go to this link( http://php.net).

Usage

You have to insert starting and ending PHP tags in the html where ever you want to run some PHP script. Whenever you want to run some php code save the file with the .php extension. For eg:- save this file as new.php and run using the server.

STARTING TAG : <?php

ENDING TAG : ?>

Variables

Variables are the most important thing that any language must have. Variables in PHP are assigned without specifying the type of the variable.

<?php

$age = 20;

$name = ‘Ranvir Singh’;

?>

This will assign $x as the value of 10. For printing you can use both echo or print. Both of them have very small difference. echo function does not return anything while print does return 1. For this reason echo is faster than print.

echo $name;

This will print out the ‘Ranvir Singh’ on the browser.

String handling funtions 

String data type has many build in functions which can be used to make our work easier. For studying such functions see this post.

CONSTANTS

Constants are the variables whoes values never change during the execution of the program. Similarly PHP constants are used for similar purposes. define keyword is used to declare a constant.

SYNTAX:

define(“variable_name”, “Value_of_the_variable”, “case-insensitive( true/false)”);

<?php

define(“PI”, “3.14”);

echo PI;

?>

case-insensitive is used if you want to make it case insensitive.

Conditional statements

  • if
  • if-else
  • if-elif
  • nested if
  • switch statements

These statements are all similar to the statements in any other language.

LOOPS

  • while
  • do while
  • for
  • for each

All other loops are similar but foreach is somewhat different.

<?php

$numbers = array(‘1’, ‘2’, ‘3’, ‘4’);

foreach($number as $value){

echo ‘$value + <br>’;

}

?>

Function

Functions are also similar to other languages.

SYNTAX:

function functioname(){

//…. Somestuff

return some_variable;

}

echo functionname();

Arrays

There are three types of arrays in PHP.

  • Indexed Array : Accessed using the numbers
  • Associative Array : Elements are accessed using the programmer given values
  • Multi-dimensional Array : Similar to matrices.

echo count($arrayname);

This function will print the total number of elements in an array. That’s it for now. With the provided knowledge you can easily build anything that you want. Think of something that you want to build. If you get any problem ask below.