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))

Open Street Map(OSM)

OpenStreetMap (OSM) is a collaborative project to create a free editable map of the world.
The creation and growth of OSM has been motivated by restrictions on use or availability of map
information across much of the world, and the advent of inexpensive portable satellite navigation
devices.

OSM is considered a prominent example of volunteered geographic information.
Created by Steve Coast in the UK in 2004, it was inspired by the success of Wikipedia and
the predominance of proprietary map data in the UK and elsewhere. Since then, it has grown
to over 2 million registered users, who can collect data using manual survey, GPS devices, aerial
photography, and other free sources.

This crowdsourced data is then made available under the Open Database Licence. The site is supported by the OpenStreetMap Foundation, a non-profit
organisation registered in England and Wales.

Rather than the map itself, the data generated by the OpenStreetMap project is considered its
primary output. The data is then available for use in both traditional applications, like its usage
by Craigslist, OsmAnd, Geocaching, MapQuest Open, JMP statistical software, and Foursquare
to replace Google Maps, and more unusual roles like replacing the default data included with
GPS receivers. OpenStreetMap data has been favourably compared with proprietary datasources,
though data quality varies worldwide.

Map usage Map is available on the following platform.

  •  Web browser Data provided by the OpenStreetMap project can be viewed in a web browser
    with JavaScript support via Hypertext Transfer Protocol (HTTP) on its official website.
  • OsmAnd OsmAnd is free software for Android and iOS mobile devices that can use offline vector data from OSM. It also supports layering OSM vector data with prerendered raster map tiles from OpenStreetMap and other sources.

• Maps.me Maps.me is free software for Android and iOS mobile devices that provides offline
maps based on OSM data.
• GNOME Maps GNOME Maps is a graphical front-end written in JavaScript and intro-
duced in GNOME 3.10. It provides a mechanism to find the user’s location with the help of
GeoClue, finds directions via GraphHopper and it can deliver a list as answer to queries.
• Marble Marble is a KDE virtual globe application which received support for OpenStreetMap.
• FoxtrotGPS FoxtrotGPS is a GTK+-based map viewer, that is especially suited to touch
input. It is available in the SHR or Debian repositories.
• Emerillon Another GTK+-based map viewer.
• The web site OpenStreetMap.org provides a slippy map interface based on the Leaflet
JavaScript library (and formerly built on OpenLayers), displaying map tiles rendered by
the Mapnik rendering engine, and tiles from other sources including OpenCycleMap.org.
• Custom maps can also be generated from OSM data through various software including Jawg
Maps, Mapnik, Mapbox Studio, Mapzen’s Tangrams.
• OpenStreetMap maintains lists of online and offline routing engines available, such as the
Open Source Routing Machine. OSM data is popular with routing researchers, and is also
available to open-source projects and companies to build routing applications (or for any
other purpose).

Importance of logging in python

Not in the mood of writing much today so will probably leave the link which I found useful and will definitely help us if we want to know more about logging.

https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/

There’s only one thing that they have not explained properly and that is the use of “`__name__. Basically, this will tell the name of the file and improve the log message. This helps us to make more sense of the logging message and we can tell where the error occurred during the program execution.

Serialization: A week long struggle

Hello folks,

I have been away from my blog because there was nothing really to discuss. I was constantly trying to do some stuff and was constantly failing. But, after a week long struggle and some help I was able to get over this struggling period and now shifted to the next task in my task list.

So as a whole, this month was well spent learning new stuff, first unit tests and then serializers. Those who have worked with Django Rest Framework will get what I am trying to say in the post.

First things first, Why do we need serializers?

To answer this question, we need to know why were the serializers created anyway.

According to some reliable sources like Wikipedia, serialization is the process by which we convert the data into such a format so that it can be transferred easily through the different layers of electronic components.

We know that our data is present in the models. We also know that we cannot ship that data easily to different formats through our models. So, we use the simple concept of serialization that converts the models’ data or any other data into JSON, XML or YAML format which can be easily transmitted over the network.

Easy, right?

Let’s dive in and see some code snippets.

class ScanInfo(models.Model):
    def __str__(self):
        return self.scan_type

    scan_types = (
        ('URL', 'URL'),
        ('Local Scan', 'localscan'),
    )

    scan_type = models.CharField(max_length=20, choices=scan_types, default='URL')
    is_complete = models.BooleanField()

class UserInfo(models.Model):
    def __str__(self):
        return self.user.username

    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    scan_info = models.ForeignKey(ScanInfo)

class URLScanInfo(models.Model):
    def __str__(self):
        return self.URL

    scan_info = models.ForeignKey(ScanInfo)
    URL = models.URLField(max_length=2000)

class LocalScanInfo(models.Model):
    def __str__(self):
        return self.folder_name

    scan_info = models.ForeignKey(ScanInfo)
    folder_name = models.CharField(max_length=200)

class CodeInfo(models.Model):
    def __str__(self):
        return self.total_code_files

    scan_info = models.ForeignKey(ScanInfo)
    total_code_files = models.IntegerField(null=True, blank=True)
    code_size = models.IntegerField(null=True, blank=True, default=0)

Well, that’s not the all of the models, but you got the idea, right? So, we have multiple levels of inheritance between all those models( Well not really inheritance but in simple words, we can say this). Now the real test is to write the serializers about them.

I decided to use the simple ModelSerializers.

class ScanInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = ScanInfo
        fields = '__all__'
class UserInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserInfo
        fields = '__all__'
class URLScanInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = URLScanInfo
        fields = '__all__'
class LocalScanInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = LocalScanInfo
        fields = '__all__'
class CodeInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = CodeInfo
        fields = '__all__'

Now I checked the sample outputs of these serializers and to my surprise, I was not able to get the desired result. The JSON output created by them was totally opposite from what we were expecting it to be.

So, I did an experiment to create a GodSerializer( Which was the literal name of the serializer) along with a helper for it. The helper will tell the serializer in the way that it was going to work.

class GodSerializer(serializers.Serializer):
    """
    Another good serializer to handle all the serialization activities
    """
    code_info = CodeInfoSerializer()
    url_scan = UrlScanInfoSerializer()
    local_scan = LocalScanInfoSerializer()
    scan_result = ScanResultSerializer()
    scan_file_info = ScanFileInfoSerializer(many=True)
    license = LicenseSerializer(many=True)
    matched_rule = MatchedRuleSerializer(many=True)
    matched_rule_license = MatchedRuleLicenseSerializer(many=True)
    copyright = CopyrightSerializer(many=True)
    copyright_holder = CopyrightHolderSerializer(many=True)
    copyright_statement = CopyrightStatementSerializer(many=True)
    copyright_author = CopyrightAuthorSerializer(many=True)
    package = PackageSerializer(many=True)
    scan_error = ScanErrorSerializer(many=True)

After this, I created the GodSerializerHelper that helped the Serializer the way things were going to work. Here is the code for the helper.

class GodSerializerHelper(object):
    def __init__(self, scan_info):
        self.scan_info = scan_info
        self.code_info = CodeInfo.objects.get(scan_info=scan_info)
        self.url_scan = URLScanInfo.objects.get(scan_info=scan_info)
        self.local_scan = None
        self.scan_result = ScanResult.objects.get(code_info=self.code_info)
        self.scan_file_info = ScanFileInfo.objects.filter(scan_result=self.scan_result)
        self.license = License.objects.filter(scan_file_info__in=(self.scan_file_info))
        self.matched_rule = MatchedRule.objects.filter(license__in=(self.license))
        self.matched_rule_license = MatchedRuleLicenses.objects.filter(matched_rule__in=(self.matched_rule))
        self.copyright = Copyright.objects.filter(scan_file_info__in=(self.scan_file_info))
        self.copyright_holder = CopyrightHolders.objects.filter(copyright__in=(self.copyright))
        self.copyright_statement = CopyrightStatements.objects.filter(copyright__in=(self.copyright))
        self.copyright_author = CopyrightAuthor.objects.filter(copyright__in=(self.copyright))
        self.package = Package.objects.filter(scan_file_info__in=(self.scan_file_info))
        self.scan_error = ScanError.objects.filter(scan_file_info__in=(self.scan_file_info))

See the proper usage __in, this is used to remove a big error of calling a model by using multiple rows of the ForeignKey. This might seem weird explanation. But that’s it. Let me try it once more. We know when we use objects.filter it return more than one row. Now as the variable is storing more than one row, it cannot be passed to next objects.filter because it has more than one rows itself.

After this, for testing, I used the following code to see if the things are looking well.

s = GodSerializerHelper(ScanInfo.objects.get(pk=51))
s = GodSerializer(s)
s.data

Hope this post helps someone in future. Still, in some dilemma, join the conversation in the comments.

Have a good day.

Writing unit tests for the models

You must have heard about the term test-driven-development if you are into the developmental works. It is the development in which you write tests before writing the logic. That means first you write the stuff that can break the code and then you write the real code that doesn’t break which is unbreakable from that point of view.

I hope this makes sense. If not, keep on reading for some time and you will come to know more about the stuff.

Why do we need tests?

At the intermediate level of development, where I am right now, we merely write tests for our code. But it is regularly said that

Untested code is broken code.

That being said, I found a great presentation that will eventually strengthen my argument of writing automatic tests.

https://www.slideshare.net/wooda/philipp-von-weitershausen-untested-code-is-broken-code

No need to go beyond first 7-8 slides.

So the basic idea of automatic testing is to save someone from breaking our code in future. This also helps us to find some issues in the code that were not visible when we coded them. The logical errors in the repository having thousands of lines of code are hard to detect. That is why the good people introduced testing for the developers.

Similarly in future, if someone codes something for us and we add that to our main repository without testing, it can break everything for us. So automatic testing is there to save us. Run the tests before adding the new stuff into the main repository and go forward without worrying about your code.

What happens during testing?

During testing, we are given certain cases which are applied on the code. The output of the code is calculated and is compared with some recommended output that developer wants. If both the outputs are same then test passes otherwise it fails. As simple as that.

In the GSoC project, we wrote tests using the unittest module of python. The unit test is a software engineering term which means to test each and every module separately. This is the default testing module used by Django.

For the beginning, we used the module to write tests for the models in the code. Here is the commit for the code.

https://github.com/singh1114/scancode-server/commit/99a36d8fe0c9289a5fac608f02cbf34171abdf28

After applying the tests I found a few errors in the code that I removed in the same commit.

What should we test in models?

While testing models we should test all the custom methods in the models. We should also test that we cannot add stuff when the field is not given. Django takes care of most of the rest stuff.

As all the things are provided in Django by default so there is very less need of test most of the things in the recent versions. But you should test __str__ and plural name of the models visible in the admin panel.

As your tests start taking shape you will feel more confident about your code.

Let’s have a coding sample:

from django.test import TestCase
class ScanInfoTestCase(TestCase):
    def test_scan_info_added(self):
        scan_info = ScanInfo.objects.create(scan_type='URL', is_complete=True)
        self.assertTrue(scan_info.is_complete)
        self.assertEqual(scan_info.scan_type, str(url_scan_info))
        self.assertEqual('Scan Info', scan_info._meta.verbose_name_plural)

In the first line, we import the TestCase from django.test. After that, in the ScanInfoTestCase we inherited this TestCase and used assertTrue and assertEqual method to check if the tests pass or not. The assertTrue method is used to check if the value is True or not. Similarly, assertEqual checks if the two variables are equal or not.

For running tests in Django, apply:

$ python manage.py test

Conclusion

It is not difficult to write automatic tests for your code. You just have to be patient with tests. It takes some time to write tests and many times it feels useless. But in longer runs, it will benefit you and save a lot of your time.