Wednesday, October 18, 2017

Fix error "Invalid data set: 0" in Perl module GD::Graph

Error Message:
Invalid data set: 0 at D:\New\TOOL\ line 24.

Problem Code:

my @a1;
my @a2 = [-9,8,0,1,-2,-5,6,-4,3,7];

foreach my $i (1..10)
    push @a1, $i;

my @data = (


my @a1;
my @a2 = [-9,8,0,1,-2,-5,6,-4,3,7];

foreach my $i (1..10)
    push @a1, $i;

my @data = (

Fix error "Not a valid source data structure" in Perl module GD::Graph

Error Message:
Not a valid source data structure at D:\New\TOOL\ line 24.

Problem Code:
my $gd = $graph->plot(@data) or die $graph->error;

my $gd = $graph->plot(\@data) or die $graph->error;

Complete working code:
#!/usr/bin/env perl
use strict;
use warnings;
use GD::Graph;
use GD::Graph::bars;

Monday, October 16, 2017

Windows 10 Fall Creators Update and Microsoft Launcher (Preview)

Fall Creators Update is the latest version of the Windows 10 Operating System by Microsoft. It is now available as beta release. To get this update you need to register your Windows 10 account as an Windows Insider. To join the program go to:

Windows 10 PC Version History:

Version Code Name Marketing Name
1507 Threshold 1
1511 Threshold 2 November Update
1607 Redstone 1 Anniversary Update
1703 Redstone 2 Creators Update
1709 Redstone 3 Fall Creators Update

Windows 10 version 1507, codenamed "Threshold 1", is the first release of Windows 10. It carries the build number 10.0.10240; while Microsoft has stated that there was no designated release to manufacturing (RTM) build of Windows 10, 10240 has been described as an RTM build by various media outlets.

Windows 10 Fall Creators Update, or Windows 10 version 1709, codenamed "Redstone 3", is the fourth major update to Windows 10 and the third of the four major updates planned under the Redstone codenames. The first preview was released to Insiders on April 7, 2017. It will be available generally on October 17, 2017.

Windows 10 version 1803, codenamed "Redstone 4", is the fifth major update to Windows 10 and the last of four major updates planned under the Redstone codenames. The first preview was released to Insiders on August 31, 2017. It will be available in early 2018.

Friday, October 06, 2017

Monoalphabetic Substitution Cipher in Python

import random

plain_text = "devharsh_T @ $01.2"
cipher_text = ''
decipher_text = ''

alphabets = [chr(a) for a in range(0,127)]
mappings = [chr(a) for a in range(0,127)]



for i in range(len(plain_text)):
  for j in range(127):
    if(plain_text[i] == alphabets[j]):
      cipher_text += mappings[j]

for i in range(len(cipher_text)):
  for j in range(127):
    if(cipher_text[i] == mappings[j]):
      decipher_text += alphabets[j]

Wednesday, October 04, 2017

Monoalphabetic Substitution Cipher in C++

#include <iostream>
#include <string>
#include <ctime>
#include <chrono>
#include <thread>

int main()

  char plain[100] = "devharsh";
  char cipher[100];
  char alphabets[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
  char mappings[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
  alphabets[26] = '\0';
  mappings[26] = '\0';
  std::cout << alphabets << "\n";
  std::cout << mappings << "\n";
  for (int i=0; i<26; i++)
    int irand = rand() % 26;
    char temp = mappings[i];
    mappings[i] = mappings[irand];
    mappings[irand] = temp;
  std::cout << alphabets << "\n";
  std::cout << mappings << "\n";
  for (int i=0; i<sizeof(plain) / sizeof(char); i++)
      for (int j=0; j<26; j++)
          if (plain[i] == alphabets[j])
              cipher[i] = mappings[j];
  std::cout << plain << "\n";
  std::cout << cipher << "\n";


Monday, October 02, 2017

Mozilla Firefox Quantum 57+ Legacy Extensions And Alternatives

If you are a Firefox fan than you must have experienced periodical out-dating and temporary unavailability of your favorite extension every time you update your browser. Same thing is going on with the upcoming release of Firefox which is Firefox 57. It will release from November 2017 but if you are on beta channel you can upgrade to it now, from October 2017. If you have upgraded you will notice many extensions are not compatible and since disabled by-default and there is no option available to enable them. These extensions are listed as "Legacy Extensions" which used to be listed as incompatible extensions in previous versions.

From Firefox Official Blog:

In the past, extensions often stopped working each time a new version of Firefox was released, because developers had to update them every six weeks to keep them compatible. Since extensions could also modify Firefox internal code directly, it was possible for bad actors to include malicious code in an innocent-looking extension. To address these issues, and as part of broader efforts to modernize Firefox as a whole, we’ve transitioned to a new framework for developing Firefox extensions. Outside of rare instances, extensions created with the new standard won’t break in new Firefox releases. You can still personalize Firefox with extensions the same way you do now, except they won’t break in new Firefox releases.

I found couple of essential extensions in this list like Adblock Plus and Browsec VPN. I did some lookup and the alternatives you can use are AdBlock for Firefox ( and Best Proxy Switcher ( 

To find alternatives click on "Find a Replacement" button next to the extension and you will be redirected to Firefox add-on pages listing alternative extensions listed under that category.

Java Standard Edition 9 Features And Download Links

Java SE 9

At JavaOne 2011, Oracle discussed features they hoped to release for Java 9 in 2016. Java 9 should include better support for multi-gigabyte heaps, better native code integration, a different default garbage collector (G1, for "shorter response times") and a self-tuning JVM. In early 2016, the release of Java 9 was rescheduled for March 2017, later again postponed four more months to July 2017, and changed again to be finally available on September 21, 2017, due to controversial acceptance of the current implementation of Project Jigsaw by Java Executive Committee, which led Oracle to fix some open issues and concerns, and to refine some critical technical questions.

End of Public Updates for Oracle JDK 8

Oracle will not post further updates of Java SE 8 to its public download sites for commercial use after September 2018. Customers who need continued access to critical bug fixes and security fixes as well as general maintenance for Java SE 8 or previous versions can get long term support through Oracle Java SE Advanced, Oracle Java SE Advanced Desktop, or Oracle Java SE Suite. For more information, and details on how to receive longer term support for Oracle JDK 8, please see the Oracle Java SE Support Roadmap.

Thursday, September 21, 2017

Extract Audio from Video with FFmpeg and Format Factory


FFmpeg is a free software project that produces libraries and programs for handling multimedia data.

Format Factory:

FormatFactory is an ad-supported freeware multimedia converter that can convert video, audio, and picture files. It is also capable of ripping DVDs and CDs to other file formats, as well as creating .iso images. It can also join multiple video files together into one.

How to extract audio from video using FFmpeg:

If you just want to copy the audio stream without re-encoding just do:

ffmpeg -i input-video.avi -vn -acodec copy output-audio.aac

-vn is no video.
-acodec copy says use the same audio stream that's already in there.

Read the output to see what codec it is, to set the right filename extension.

Sunday, September 17, 2017

Getting started with SQLite database in Perl

SQLite is an in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. The code for SQLite is in the public domain and is thus free for use for any purpose, commercial or private. SQLite is the most widely deployed database in the world with more applications than we can count, including several high-profile projects. []

Following program demonstrates how to Create a new SQLite database, how to connect to a database with credentials, how to create a table, how to insert values and how to select values.

use DBI;
use strict;
use warnings;

my $dsn = "DBI:SQLite:test.db";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1, AutoCommit => 0})
   or die $DBI::errstr;

print "Opened database successfully\n";

Thursday, September 14, 2017

Plot colored node graph with networkx in Python


NetworkX is a Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. URL:


import networkx as nx
import matplotlib.pyplot as plt

color_map = ['blue','green','red']


nx.draw(G,node_color = color_map,with_labels = True)


Wednesday, September 13, 2017

Create HTML dashboard of Jenkins jobs status

Perl script to fetch live jobs' status from Jenkins server and generate and display HTML dashboard from it.

use strict;
use warnings;
use autodie;
use REST::Client;
use MIME::Base64;
use JSON;

my $api_proto = 'http';               #HTTP/HTTPS
my $api_url = 'localhost';       #Server IP
my $api_port = '8080';                #Port number
my $api_user = 'admin';           #Jenkins account username
my $api_pass = 'password';          #Jenkins account password
my $client = REST::Client->new();    #Perl Rest Client Object

$client->addHeader('Authorization', 'Basic '.encode_base64($api_user . ':' . $api_pass));

my $html = "";
$html = $html."<!DOCTYPE html><html><head><title></title></head><body><table style='width:100%'>";
$html = $html."<tr><th>NAME</th><th>COLOR</th><th>URL</th></tr>";

if ($client->responseCode() == 200)
    my $data = decode_json($client->responseContent());
    my @jobs = @{$data->{'jobs'}};
    print("\nTotal ".scalar(@jobs)." jobs found..\n\n");
    foreach my $job (@jobs)
        $html = $html."<tr>";
        $html = $html."<td><font color='".$job->{'color'}."'>".$job->{'name'}."</font></td>";
        $html = $html."<td><font color='".$job->{'color'}."'>".$job->{'color'}."</font></td>";
        $html = $html."<td><a href=".$job->{'url'}."><font color='".$job->{'color'}."'>".$job->{'url'}."</font></a></td>";
        $html = $html."</tr>";

    print("\ncould not connect to jenkins server... :( :(\n");

$html = $html."</table></body></html>";

open (my $fh, ">Jenkins Dashboard.html") or die("Could not open file. $!");
print $fh $html;
close $fh;

system("Jenkins Dashboard.html");

Sunday, September 10, 2017

Parse DICOM Image in Python | Convert DICOM to PNG in Python


Digital Imaging and Communications in Medicine (DICOM) is a standard for storing and transmitting medical images. It includes a file format definition and a network communications protocol.


PNG (pronounced ping as in ping-pong; for Portable Network Graphics) is a file format for image compression that, in time, is expected to replace the Graphics Interchange Format (GIF) that is widely used on today's Internet. Portable Network Graphics (PNG /ˈpɪŋ/) is a raster graphics file format that supports lossless data compression. PNG was created as an improved, non-patented replacement for Graphics Interchange Format (GIF), and is the most widely used lossless image compression format on the Internet.


You need to install following python packages: pydicom, pylab, pypng

To install these modules you can type following commands in console:
pip install pydicom
pip install pylab
pip install pypng

Build Jenkins Job Remotely | Fix: Error 403 No valid crumb was included in the request

In case you are a newbie with Jenkins read through this article:

Build Jenkins Job Remotely

I have found two ways in which you can trigger a build on job remotely via scripting.

Both methods are simple HTTP Get/Post requests, nothing fancy here. Along with these Requests we need to pass login credentials.

Method 0: No protection enabled

=> This is the case when you are in a secure environment and have disabled all additional protection mechanism like CSRF (Method 1) and Authentication Token (Method 2). If this is the case then you can simply trigger a HTTP Request like this:


e.g. http://admin:pass@localhost:8080/job/job1/build

Jenkins: Trigger build remotely via script using Authentication Token


$acctname = "admin"
$password = "password"
$server = "localhost"
$port = "8080"
$jobName = "test02"
$jobToken = "test02_authentication_token"
$params = @{uri = "http://${server}:${port}/job/${jobName}/build?token=${jobToken}";
            Method = 'Get';
            Headers = @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$(${acctname}):$(${password})"));}}
Invoke-RestMethod @params

Jenkins: Trigger build remotely via script using crumb


import requests
api_proto = 'http'
api_url = 'localhost'
api_port = '8080'
api_job = 'test01'
api_user = 'admin'
api_pass = 'password'

api_crumb = requests.get(api_proto + '://' + api_user + ':' + api_pass + '@' + api_url + ':' + api_port + '/crumbIssuer/api/json')
if api_crumb.status_code == 200 :
    api_crumb = api_crumb.json()['crumb']

resp = + '://' + api_url + ':' + api_port + '/job/' + api_job + '/build', auth=(api_user, api_pass), headers={"Jenkins-Crumb":api_crumb})
if resp.status_code == 201:
    print(api_job + ' was triggered successfuly..')

Saturday, September 09, 2017

"No connection adapters were found for '%s'" % url [Solved]


Traceback (most recent call last):

  File "C:\Users\310211146\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\", line 110, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "C:\Users\310211146\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\", line 56, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\310211146\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\", line 475, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\310211146\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\", line 590, in send
    adapter = self.get_adapter(url=request.url)
  File "C:\Users\310211146\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\", line 672, in get_adapter
    raise InvalidSchema("No connection adapters were found for '%s'" % url)
requests.exceptions.InvalidSchema: No connection adapters were found for 'localhost:8080/'

Problem Code:

resp ="localhost:8080", auth=("user","pass"), headers={"key":"value"}) 


resp ="http://localhost:8080", auth=("user","pass"), headers={"key":"value"}) 


Getting up and running with Jenkins 2.60.3 on Windows [How to solve Error: no workspace]

The leading open source automation server, Jenkins provides hundreds of plugins to support building, deploying and automating any project. Jenkins is a Continuous Integration server. Basically Continuous Integration is the practice of running your tests on a non-developer machine automatically every-time someone pushes new code into the source repository.

Java Development Kit (JDK)
Java Run-time Environment (JRE)

Count number of items and sum of the items in a column in R


mydf <- data.frame(Key=c('a','b','c','d','a','a','a','a','b','c','d','c','c','d','b','b','a'), Values=c(4,6,3,4,5,6,2,1,3,4,5,6,4,2,4,5,6))
mydf_keys <- unique(mydf$Key)
mydf_vals <- c(nrow(mydf_keys))
for (i in mydf_keys)
    mydf_vals <- c(mydf_vals, nrow(mydf[mydf$Key %in% i, ]))

#mydf_count gives count of items i.e. how many times they appear
mydf_count <- data.frame(item=mydf_keys, count=mydf_vals)

#mydf_sum gives sum of values of items in the column you specify
mydf_sum <- setNames(aggregate(mydf$Values, by = list(item=mydf$Key), FUN = sum, na.rm = TRUE), c('item', 'sum'))


If you have a better approach for this then please share in comments below or email me. :)

Friday, September 08, 2017

Run Microsoft R Open Script From Command Prompt

Microsoft R Open is Multi-core environment developed on Core R. Microsoft R Open (MRO), formerly known as Revolution R Open (RRO), is the enhanced distribution of R from Microsoft Corporation. It is a complete open source platform for statistical analysis and data science. Microsoft R Open 3.4.1 is coming September 11th.

MRO comes with Microsoft R Open GUI and you can also use it in RStudio IDE. But in case you want to run it from command prompt, it is pretty easy.

First you need to set Path in environment variable.

For 32-bit version path would be like: C:\Program Files\Microsoft\R Open\R-3.4.0\bin
For 64-bit version path would be like: C:\Program Files\Microsoft\R Open\R-3.4.0\bin\x64

Now save it and restart command prompt if already open or open a new command prompt window.

Type command "where rscript" and check whether it returns a correct path.

Now you can type command "rscript your_script.r" and it will get executed. Note that RStudio commands like "show" won't work from Rscript and only R/MRO commands will work.

Thursday, September 07, 2017

Xiaomi Mi A1 vs Motorola Moto G5S Plus Price and Comparison

Xiaomi Mi A1

The Xiaomi Mi A1 is a dual-SIM (Nano-SIM) smartphone that runs Android 7.1.2 Nougat. It features a 5.5-inch full-HD (1080x1920 pixels) display. It is powered by an octa-core Qualcomm Snapdragon 625 SoC coupled with 4GB of RAM. In terms of optics, the dual rear camera setup of the Xiaomi Mi A1 bears two 12-megapixel sensors, with one featuring a wide-angle lens with a 1.25-micron pixel sensor and f/2.2 aperture, and the other sporting a telephoto lens, 1-micron pixel sensor, an f/2.6 aperture, and capable of delivering 2x optical zoom. The smartphone bears a 5-megapixel front camera with a real-time beautification mode. The Xiaomi Mi A1 comes with 64GB of inbuilt storage, which is expandable via microSD card (up to 128GB) in a hybrid dual-SIM configuration. It houses a 3080mAh battery.

Motorola Moto G5S Plus

The dual-SIM (Nano) Moto G5S Plus runs Android 7.1 Nougat out of the box, and it sports a 5.5-inch full-HD (1080x1920 pixels) IPS LCD display. It is powered by a Qualcomm Snapdragon 625 octa-core SoC clocked up to 2GHz, coupled with 4GB of RAM. In terms of optics, the smartphone comes with a dual rear camera setup with two 13-megapixel sensors with an f/2.0 aperture, depth editing software, and colour correcting dual-LED flash. On the front, it bears an 8-megapixel sensor with an f/2.0 aperture, wide-angle lens, and an LED flash. The Moto G5S Plus bears 64GB of inbuilt storage, expandable via microSD card (up to 128GB). The handset houses a 3000mAh battery.

Wednesday, September 06, 2017

Perl Subroutine Arguments


1. Retrieving arguments to a subroutine with shift:

A subroutine's arguments come in via the special @_ array. The shift without an argument defaults to @_.

   sub volume {
my $height = shift;
my $width = shift;
my $depth = shift;

        return $height
* $width * $depth;

C/C++ Parameter Passing

C parameter passing:-

1. Pass by Value:

- The value of a variable is sent to function.
- The actual parameter cannot be changed by function.
- Duplicate Copy of Original Parameter is Passed.
- No effect on Original Parameter after modifying parameter in function.


void interchange(int number1,int number2)
    int temp;
    temp = number1;
    number1 = number2;
    number2 = temp;

int main() {

    int num1=50,num2=70;

    printf("\nNumber 1 : %d",num1);
    printf("\nNumber 2 : %d",num2);


Saturday, August 05, 2017

Campagna T-Rex

Campagna T-Rex
From Wikipedia, the free encyclopedia

The Campagna T-REX is a two-seat, three-wheeled motor vehicle created by the Campagna Motors, located in Quebec, Canada. Its powered a 1.6 L, straight-six engine. Although it is usually registered as a motorcycle, the interior can accommodate the driver and a single passenger seated side-by-side, with adjustable seat backs, a foot-pedal box, and retractable three-point seat belts. The manual transmission, controlled by hand, more closely resembles a motorcycle's transmission than that of a car. The T-REX has been commercially available since the early 1990s. The Campagna T-REX was designed and styled by Deutschman Design.

Polaris Slingshot

Polaris Slingshot
From Wikipedia, the free encyclopedia

The Polaris Slingshot is a three-wheeled motor vehicle. It was introduced in 2014 as a 2015 model. The Slingshot is manufactured by Polaris Industries, which claims "It's a three-wheeled motorcycle!" It has a tilt-adjustable steering wheel, side-by-side bucket seats, and does not lean. Three-point seat belts are fitted, however it has no airbags or crumple zone, and driver and passenger must wear motorcycle helmets in certain jurisdictions. It has no roof, doors, or side windows. A small windshield is an optional extra on the base model, and fitted as standard on the SL model. The steering wheel, gear stick, and brake, clutch, and throttle pedals have a conventional automobile layout.

Payments Bank in India

Payments banks is a new model of banks conceptualized by the Reserve Bank of India (RBI). These banks can accept a restricted deposit, which is currently limited to ₹1 lakh per customer and may be increased further. These banks cannot issue loans and credit cards. Both current account and savings accounts can be operated by such banks. Payments banks can issue services like ATM cards, debit cards, net-banking and mobile-banking. Airtel has launched India's first live payments bank. Paytm is the second such service to be launched in the country. India Post Payments Bank is the third entity to receive payments bank permit after Bharti Airtel and Paytm. Aditya Birla group earned payments bank permit on 3 March 2017. [source:]

Android 8.0 Oreo list of supported Devices

Here are the Google devices which will receive the Android Oreo 8.0 update.

    Google Pixel (Developer Preview available to download)
    Google Pixel XL (Developer Preview available to download)
    Google Pixel 2
    Google Pixel C (Developer Preview available to download)
    Google Nexus Player (Developer Preview available to download)


Here is the list of Samsung phones getting Android 8.0 O update.

    Samsung Galaxy S8(G950F, G950W)
    Samsung Galaxy Note 8 (Upcoming)
    Samsung Galaxy S8 Plus(G955,G955FD)
    Samsung Galaxy S7 Edge(G935F, G935FD, G935W8)
    Samsung Galaxy S7(G930FD, G930F, G930, G930W8)
    Samsung Galaxy A3( 2017)(A320F)
    Samsung Galaxy A5( 2017)(A520F)
    Samsung Galaxy A7 ( 2017)(A720F, A720DS)
    Samsung Galaxy A8 ( 2017)(A810F, A810DS)
    Samsung Galaxy C9 Pro
    Samsung Galaxy J7v
    Samsung Galaxy J7 Max (2017)
    Samsung Galaxy J7 Pro(2017)
    Samsung Galaxy J7 Prime(G610F, G610DS, G610M/DS)
    Samsung Galaxy A9 (2016)(SM-A9100)
    Samsung Galaxy A7 (2016)(A710F, A710DS)
    Samsung Galaxy A5 (2016)(A510F, A510F)
    Samsung Galaxy A8 (2016)(A810F, A810DS)
    Samsung Galaxy Note FE

Android 8.0 Oreo list of unsupported Devices

  • Google:
  1. Google Nexus 5
  2. Google Nexus 4
  3. Google Nexus 3
  • HTC:
  1. HTC Desire 728
  2. HTC One E9s
  3. HTC Butterfly 3
  4. HTC A9
  5. HTC One M9
  6. HTC One M9 Plus
  7. HTC One M8
  8. HTC One M8s
  • Huawei:
  1. Huawei Honor 8 (Controversial)
  2. Huawei Honor 5A
  3. Huawei Honor 5c
  4. Huawei Y3II
  5. Huawei Y5II
  6. Huawei Mate 8 (Controversial)
  7. Huawei Y6
  8. Huawei Honor 7
  9. Huawei Y3( L02/03/L22/L23 U00)
  10. Huawei Y7
  11. Huawei Y6
  12. Huawei Y5

Sunday, February 19, 2017

Edit photo - Picture frame - Image effects in Python

from skimage import data, io
import sys
from skimage.color import gray2rgb

    rgb_image = data.imread(sys.argv[1])
    height = rgb_image.shape[0]
    width = rgb_image.shape[1]

    if(len(rgb_image.shape) < 3):
        rgb_image = gray2rgb(rgb_image)
    for i,j in zip(range(int(width/8)), range(int(width/8),0,-1)):
        rgb_image[i, 0:j, :] = 0
    for i,j in zip(range(int(7*(height/8)),height), range(0,int(width/8))):
        rgb_image[i, 0:j, :] = 0

Edit photo - Square crop - Image resizing in Python

from skimage import data, io
import sys
from skimage.color import gray2rgb

    rgb_image = data.imread(sys.argv[1])
    height = rgb_image.shape[0]
    width = rgb_image.shape[1]

    if height == width:
        print("already square image")
        if(len(rgb_image.shape) < 3):
            rgb_image = gray2rgb(rgb_image)
        right_image = rgb_image.copy()
        left_image = rgb_image.copy()
        center_image = rgb_image.copy()

Edit photo - Oil painting effect - Image manipulation in Python

from skimage import data, io
import random
import sys
from skimage.color import gray2rgb

    rgb_image = data.imread(sys.argv[1])
    height = rgb_image.shape[0]
    width = rgb_image.shape[1]

    if(len(rgb_image.shape) < 3):
        rgb_image = gray2rgb(rgb_image)
    for i in range(height):
        for j in range(width):
            for k in range(rgb_image.shape[2]):

Edit photo - Pencil sketch effect - Image processing in Python

from skimage import data, io, util
import random
import sys
from skimage.color import rgb2gray

    rgb_image = data.imread(sys.argv[1])
    height = rgb_image.shape[0]
    width = rgb_image.shape[1]
    if(len(rgb_image.shape) == 3):
        rgb_image = util.img_as_ubyte(rgb2gray(rgb_image))

Python: Count occurences in List

1. Histogram

>>> mylist = [1,3,2,5,4,4,2,2,4,2,4,2,4,6,4,5,2]

>>> import matplotlib.pyplot as plt

>>> plt.hist(mylist)
(array([ 1.,  0.,  6.,  0.,  1.,  0.,  6.,  0.,  2.,  1.]), array([ 1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ,  4.5,  5. ,  5.5,  6. ]), <a list of 10 Patch objects>)


Edit photo - Change color effects - Image filtering in Python


from skimage import data, io
import random

    rgb_image = data.imread("Collage.jpg")
    red_image = rgb_image.copy()
    green_image = rgb_image.copy()
    blue_image = rgb_image.copy()
    red_image[:, :, (1, 2)] = 0
    io.imsave("red_output_image.jpg", red_image)
    green_image[:, :, (0, 2)] = 0
    io.imsave("green_output_image.jpg", green_image)
    blue_image[:, :, (0, 1)] = 0
    io.imsave("blue_output_image.jpg", blue_image)

Saturday, February 18, 2017

Bar plot in Python using Bokeh

import pandas as pd
from collections import Counter
from datetime import datetime, timedelta
from bokeh.charts import Bar, output_file, show
from bokeh.models.layouts import Column
import numpy as np

    data = pd.read_csv('new.csv')
    scan_col = Counter(data['Scan'])
    values = list()
    keys = list()
    for s in scan_col.keys():
        scan_time_total = datetime.strptime("00:00:00","%H:%M:%S")
        scan_time_total = timedelta(hours=scan_time_total.hour, minutes=scan_time_total.minute, seconds=scan_time_total.second)

Bar plot in Python using Matplotlib

import pandas as pd
from collections import Counter
from datetime import datetime, timedelta
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

    data = pd.read_csv('new.csv')

    srn_col = Counter(data['SRN'])
    month_col = Counter(data['Month'])
    scan_col = Counter(data['Scan'])

    scan_dict = {}

Bar plot in Python using Plotly

Step 1: Install plotly package if you haven't.

Follow this article:

Step 2: Set up your online credentials for plotly account.

2.1: Go to
2.2: Sign in/sign up.
2.3: Open (API Settings page) and click on Regenerate Key button. Copy the API key.

Install Plotly package in Python

You need pip package manager to install Plotly package in Python.

Use this command to install plotly with python:
pip install plotly


Sunday, January 08, 2017

Find difference between two text files in Python

import difflib, sys

file1 = sys.argv[1]
file2 = sys.argv[2]

diff = difflib.unified_diff ( open(file1).readlines(), open(file2).readlines(), fromfile=file1, tofile=file2 )

strings = list()

for line in diff:
    strings.append(line.replace('\n', ''))

for string in strings:

Find difference between two text files in Perl

#!/usr/bin/env perl
use strict;
use warnings;
use Text::Diff;

my $file1 = $ARGV[0];
my $file2 = $ARGV[1];

my $diffs = diff $file1,$file2;
my @strings = split("\n",$diffs);

    print $_."\n";