Thursday, July 11, 2019

Debug Django code in Docker ( Vscode)

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.~ Brian Kernighan

This is well known fact. Most of the time developers spend there time on debugging code rather than implementing new stuffs. however it's worth it. the reason is we can't write a piece of code that covers every aspect of the  requirement at the first time. modern day software development is not sole work.It's team work.hence most of the time we need to work with a code someone else has written. And last not the least ever thing in the world not reliable 100% then how could it possible that something work on top of silicon chips.

Vscode 

vscode is text editor, not an IDE, It's not cool or smart in python as pychram at the first appearance.However the best thing about VS code is It's highly customizable . Therefore if we can dedicate some time we can easily configured it to shopisticated IDE. I'm not going to spend time on how we can make VScode more beast for python development. In here you can find good article 


Django and Docker 


According to official website Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source.
Truly it is. it's robust and feature rich framework and it has large community .

Then what are Dockers . A  container  (docker) is a standard unit of software that packages up code and all its dependencies so the application runs quickly and reliably from one computing environment to another.You can assume it as another OS on top of your OS, but that is really not the case.it's kind of bundle your application and it's dependccis and if it's works on your machine then it's works any other computer , cloud server or any other plat from which supports dockers. You can find more information from official website.

one downside of  Dockers is it's hard to debug ,because our application runs on docker container we have to connect that remote docker container in order to debug our code. Pycharm professional version has debugger for dockers however it's not wallet friendly.we need to buy licence. but we have alternative and it's 100% free. we can use VScode to connect docker and debug our application.



Prerequisites

As of this stage you need the following installed
  • Python 3
  • Docker

Installation of Prerequisite

Install dockers (if your already have dockers you may skip this step)
Here I'm not going to explain you have to make django docker container you can find comprehensive tutorial in here 

Project folder structure is like bellow



Docker file 

Docker compose file 
Then modify your mange.py file like bellow

We need to add three new lines as mentioned above to manage.py 
Next we need to start vscode and open our project 
next we need to add this configuration to vscode launch.json  file
we can add configuration to vscode by 
debug->open configuration 
launch.json looks  like this



Next we need build and start out docker container 
docker-compose build
then 
docker-compose run -p 3000:3000 -p 8000:8000 --rm web sh -c 'DJANGO_DEBUGGER=Tr python manage.py runserver --noreload --nothreading 0.0.0.0:8000'
Finally we need to start debug view in vscode ( CTRL+SHIFT+D )
select runserver as debug environment then hit play button



now you can add breakpoint and debug your code



That's it. Now you can enjoy your cool django project 
You can find full source code here  https://github.com/Nipuna-saga/django-docker-debugger-vscode


Wednesday, August 16, 2017

How to Transfer files between local machine and remote machine

Hello Guys, After long time I'm going to explain small trick that will help you to transfer files between local machine and remote machine using pscp. You can download it from putty website.It's better to install putty that will bundle with PSCP.

After install putty open command prompt
    run->cmd

then set path variable 

set PATH=C:\Program Files\PuTTY

Send a file


after that you can send file (sample.txt) using this command

pscp c:\Users\Saga\sample.txt  USERNAME@REMOTE_SERVER_ADDRESS:/home/folder1

then you have to enter password for remote server .after that file will be transferred. 

This is the  location of  sample.txt   c:\Users\Saga\sample.txt 
This is the location of destination    /home/folder1

Receive a file


To receive a file you need to enter bellow command 

pscp   USERNAME@REMOTE_SERVER_ADDRESS:/home/folder1/sample2.txt  c:\Users\Saga\.

make sure to enter . (dot) after the destination path

Thank you very much if you have any question please post a comment bellow . I'll try my best to help you

Wednesday, June 29, 2016

Xamarin Tutorial -Xamarin Forms Designer

Hi Guys ,Today I'm going to show you something that every Xamarin developer will love,because time that i'm writing this post there is no inbuilt UI designer for Xamarin forms.But for Xamarin android and Xamarin IOS do have that UI designer,But a technology like Xamarin real benefit is use cross-platform approach rather than using native approach.
                                            Idea of Xamarin Forms having a shared code base for Android IOS and Windows then write few custom renders to get platform specific features.
                                                          According to my idea real pain of Xamarin forms is design a nice UI ,If we do a small change like color replacement we need to build it and deploy it in device to see the results.After going here and there in internet I found a medicine for that pain.And now I'm going to share that threat with you.

To make this we need few ingredients
  • Android or IOS Emulator/Device
  • Gorilla Player 
I'll show you how to do it in Android Emulator
  • First If you don't have Android Emulator you can download and install Android Emulator from   here  (This is the Fastest Android emulator I have tested and also Genymotion  is also better                 alternative which has large variety of devices unless it's don't have restriction in free version)
  • Next we need Gorilla player.You can download it from here,but before download and install it in your system it's better to Register on that site because later stages that credentials will require for login to that player  After complete of Gorilla installer you will have pop up like this
       After complete Gorilla installer you will see pop up like this


     Make sure to mark the check box for install samples and player
     Then enter login details that we registered previously
    Then you will see a screen like this


Then click on Opening Player.sln and you will get VS/XS project
Then run that project in your Emulator,and you will get App like this in your Emulator


Then open your Application and you will see some gorilla face on top right corner on your XAML page that mean your xaml page connect with your gorilla player



And if you going through xaml pages or if you change anything in that page you will see the UI view in your emulator

                                                 So Welcome to Gorilla  Family 


Troubleshooting

When you trying to run Player sometimes you will get error like this 
'Resource.Attribute' does not contain a definition for 'actionBarSize'
To fix this issue we can simple delete Xamarin folder located in
C:\Users\{User}\AppData\Local  And rebuild your application again

If it's not work you can change your JAVA version and see the results (you must restart your VS after change JAVA version and after changing JAVA version it's better if you can delete Xamarin folder and rebuild)

Ok If you have any question or feed back please post a comment bellow then Happy Hunting  until next time


Sunday, May 22, 2016

Xamarin Tutorial - How to Add Dynamic Pages

Hi guys ,after long time I'm back with new technology .This is cross platform mobile development technology called Xamarin. We can create  Android,IOS and Windows Native mobile apps same time using single code base.In this language we written using c#.Good thing about Xamarin is we can reach native performance and features more than other cross platform mobile technologies.

Today I'm going to show you how to add dynamic pages in Xamarin .This is important when we need to change our views dynamically. Trick that we using here is Content views  in Xamarin as sub pages not ContentPages.

First we create Content  Page called MainPage and 2 content views called Page1 and Page2  That pages looks like this

MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="DynamicPages.MainPage">
  <StackLayout Padding="20">
    <StackLayout Orientation="Horizontal" HorizontalOptions="Center" >
      <Button Text="Page1" Clicked="onPage1ButtonClick"/>
      <Button Text="Page2" Clicked="onPage2ButtonClick"/>
    </StackLayout>
    <StackLayout HorizontalOptions="FillAndExpand" 
                VerticalOptions="FillAndExpand" x:Name="DynamicPageView">
    </StackLayout>
  </StackLayout>
</ContentPage>

In Main page I added 2 Buttons and Stack Layout named "DynamicPageView" .

Page1.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="DynamicPages.Page1">
  <StackLayout>
    <Label Font="20" Text="This is page 1"/>
  </StackLayout>
</ContentView>

Page2.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="DynamicPages.Page2">
  <StackLayout>
    <Label Font="20" Text="This is page 2"/>
  </StackLayout>
</ContentView>

In Page1 and Page2 we use Content views not Content Pages and we added only Labels on each pages

MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;

namespace DynamicPages
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        public void onPage1ButtonClick(object o, EventArgs e)
        {
            DynamicPageView.Children.Clear();
            DynamicPageView.Children.Add(new Page1());
        }

        public void onPage2ButtonClick(object o, EventArgs e)
        {
            DynamicPageView.Children.Clear();
            DynamicPageView.Children.Add(new Page2());

        }

    }
}

In MainPage.cs we add 2 functions for button clicks

DynamicPageView.Children.Clear();
DynamicPageView.Children.Add(new Page1());

In here we add children to our StackLayout in MainPage.xaml .It's important to clear Children before add new one.otherwise it will add redundant pages.

Final views look like this


Important :- we have to use Content views as Page 1 and Page 2

If you have any question feel free to post a comment bellow.Thank you very much see you soon.Happy Hunting

Friday, June 19, 2015

Digital Audio processing with c++ ( Chapter 1 ) - Configure Aquila Digital signal processing Library in Visual Studio

Aquila is  Digital signal processing Library that work with C++.And it has lots of features to analyze and process signals like audio.You can learn more about this library from official  website.

Today I'm going to show how to configure it visual studio programming environment.

Working environment

Windows 8.1
Visual studio 11

Development Tools



  • cmake     Download   (make sure to download binary distributions)


Library Configuration

  1. Install MinGW C++ compiler. During installation , select “C++ Compiler” and “MSYS Basic System” for installation
  2. Add system PATH to "c:/mingw/bin" (Right click on my computer-> Properties->Advance system settings->Environment variable -> select path and click edit) example
  3. Install Cmake
  4. unzip Aquila to C:\Aquila-src
  5. Run cmake GUI tool
  6. Choose C:\Aquila-src\ as source
  7. Choose the destination, C:\Aquila-build ,This is where to build the binaries
  8. Press Configure button, choose MinGW Makefiles as the generator.(then in red highlighted area We can choose many options but it's better to use default options if you are beginner)
  9. Press the Configure button again then press the Generate button
  10. Exit the cmake program when the generating is done
  11. Run the command line mode (cmd.exe) and go to the destination directory Aquila-build (type :- cd /Aquila-build)
  12. Type "mingw32-make". You can see a progress of building binaries. If the command is not found error occur problem is in system path (step 2)
  13. Then type "mingw32-make install" (you can see install path .we need it in next step)
In addition to this we need to do small one thing .That is we need to add these 2 files to your install directly (default directly C:\Program Files (x86)\Aquila\lib) 

**I try this few days and this is not work for me .then I found this 2 files need to place in that directly for work this library

Create Project 


  1. Open Visual Studio IDE
  2. Create new Console Application
  3. Go to project properties (Project-> Properties)
  4. Go to C/C++ -> General then add path of  "include" to Additional Include Directories  (example :- C:\Program Files (x86)\Aquila\include)
  5. Go to linker-> General then add path of  "lib" to Additional Library Directories  (example:- C:\Program Files (x86)\Aquila\lib)
  6. Go to linker-> input then add library files to Additional Dependencies (Add Aquila.lib ,Ooura_fft.lib )

Implementation


Then run this code

#include "aquila/global.h"
#include "aquila/source/generator/SineGenerator.h"
#include "aquila/transform/FftFactory.h"
#include "aquila/tools/TextPlot.h"

int main()
{
    // input signal parameters
    const std::size_t SIZE = 64;
    const Aquila::FrequencyType sampleFreq = 2000;
    const Aquila::FrequencyType f1 = 125, f2 = 700;

    Aquila::SineGenerator sineGenerator1 = Aquila::SineGenerator(sampleFreq);
    sineGenerator1.setAmplitude(32).setFrequency(f1).generate(SIZE);
    Aquila::SineGenerator sineGenerator2 = Aquila::SineGenerator(sampleFreq);
    sineGenerator2.setAmplitude(8).setFrequency(f2).setPhase(0.75).generate(SIZE);
    auto sum = sineGenerator1 + sineGenerator2;

    Aquila::TextPlot plt("Input signal");
    plt.plot(sum);

    // calculate the FFT
    auto fft = Aquila::FftFactory::getFft(SIZE);
    Aquila::SpectrumType spectrum = fft->fft(sum.toArray());

    plt.setTitle("Spectrum");
    plt.plotSpectrum(spectrum);

    return 0;
}


and you will get an output if you get error about "LNK2019 error c++ unresolved external symbol"
Go to BUILD->Configuration Manager and change platform to 64 bit

If  have any question please post a comment .This post written by using my experience.so sometimes there can be simple approach than this.Please be kind enough to mention that one also Thank you :)

***Update If you have a trouble with building an own library you can try my pre-build library . I have only tested 64bit lib files but I already added 32bit versions.Try and please kind enough to mentioned is this library works fine or not

Reference official website

Wednesday, April 1, 2015

Digital Image processing with c++ ( Chapter 7 ) - Image Smoothing (Gaussian filter)

Hi My dear friends.Today i'm going to show how to implement Gaussian Smoothing filter using C++ and openCV .Theory behind this Gaussian filter is you can learn by using this reference and it clearly mention how to make Gaussian weight matrix.And I'm going to show how I implement this code by using above mention links theory.



#include "stdafx.h"
#include <iostream>

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>

using namespace cv;
using namespace std;


int main()
{

 /* start producing Gaussian filter kernel*/
 const double PI = 4.0*atan(1.0) ;
 double sigma=  2;
 const int kernalWidth=5;
 const int kernalHeight=5;

 float kernalArray[kernalWidth][kernalHeight];

 double total=0;

 //calculate each relavant value to neighour pixels and store it in 2d array
 for(int row=0;row<kernalWidth;row++){

  for(int col=0;col<kernalHeight;col++){

   float value=(1/(2*PI*pow(sigma,2)))*exp(-(pow(row-kernalWidth/2,2)+pow(col-kernalHeight/2,2))/(2*pow(sigma,2)));

   kernalArray[row][col]=value;

   total+=value;
  }
 }

 //Scale value in 2d array in to 1
 for(int row=0;row<kernalWidth;row++){
  for(int col=0;col<kernalHeight;col++){

   kernalArray[row][col]=kernalArray[row][col]/total;

  }
 }

 /*End producing Gaussian filter kernel*/

 Mat RGBImage;

 RGBImage =imread("C:\\stripeys-big-red-eyes-sharp.jpg");

 Mat grayScaleImage(RGBImage.size(),CV_8UC1);
 Mat openCvGaussianFilterImage(RGBImage.size(),CV_8UC1);

 Mat FinalImage(RGBImage.size(),CV_8UC1);
 cvtColor(RGBImage,grayScaleImage,CV_RGB2GRAY);



 int rows=grayScaleImage.rows;
 int cols=grayScaleImage.cols;


 int verticleImageBound=(kernalHeight-1)/2;
 int horizontalImageBound=(kernalWidth-1)/2;

 //Assian Gaussian Blur value of the center point.Repeating this process for all other points through image

 for(int row=0+verticleImageBound;row<rows-verticleImageBound;row++){

  for(int col=0+horizontalImageBound;col<cols-horizontalImageBound;col++){

   float value=0.0;

   for(int kRow=0;kRow<kernalHeight;kRow++){
    for(int kCol=0;kCol<kernalWidth;kCol++){
     //multiply pixel value with corresponding gaussian kernal value
     float pixel=grayScaleImage.at<uchar>(kRow+row-verticleImageBound,kCol+col-horizontalImageBound)*kernalArray[kRow][kCol];
     value+=pixel;
    }
   }
   //assign new values to central point
   FinalImage.at<uchar>(row,col)=cvRound(value);

  }

 }

 //Genarate same GaussianBlur image using inbuilt openCv function
 GaussianBlur( grayScaleImage, openCvGaussianFilterImage, Size( 5, 5 ), 0 ,0 );

 namedWindow("Original Image",1);
 imshow("Original Image",grayScaleImage);

 namedWindow("Filtered Image",1);
 imshow("Filtered Image",FinalImage);

 namedWindow("openCvGaussianFilterImage",1);
 imshow("openCvGaussianFilterImage",openCvGaussianFilterImage);
 waitKey();
 return 0;
}

You can download image from this link

You can see results like this

This is our original image

This is open CV generated Gaussian blur image

This is our implemented algorithm's Gaussian blur image


Please note this .I'm not an expert on these things.Still i'm learning Image processing. This code is written according to my understand about the concepts of Gaussian smooth filter.If I did some mistake, missed something or if you have any question please leave a comment bellow.
Thank you :)

Saturday, March 28, 2015

Digital Image processing with c++ ( Chapter 6 ) - Image Smoothing (Median filter)

Hi All Today i'm going explain you how to add median filter to image

#include "stdafx.h"
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>

using namespace cv;
using namespace std;


int main()
{
 Mat RGBImage;

 RGBImage =imread("c:/Pictures/noisy.jpg");

 Mat grayScaleImage(RGBImage.size(),CV_8UC1);
 grayScaleImage=Scalar(0);
 Mat FinalImage(RGBImage.size(),CV_8UC1);
 cvtColor(RGBImage,grayScaleImage,CV_RGB2GRAY);
 int kernalWidth=3;
 int kernalHeight=3;
 int kernalSize=kernalHeight*kernalWidth;
 int rows=grayScaleImage.rows;
 int cols=grayScaleImage.cols;
 int pixelArray[9];

 int verticleImageBound=(kernalHeight-1)/2;
 int horizontalImageBound=(kernalWidth-1)/2;

 for(int row=0+verticleImageBound;row<rows-verticleImageBound;row++){

  for(int col=0+horizontalImageBound;col<cols-horizontalImageBound;col++){


   int pixelArrayIndex=0;
   for(int kRow=0;kRow<kernalHeight;kRow++){
    for(int kCol=0;kCol<kernalWidth;kCol++){
     pixelArray[pixelArrayIndex]=grayScaleImage.at<uchar>(kRow+row-verticleImageBound,kCol+col-horizontalImageBound);
     pixelArrayIndex++;
    }
   }


   int elements = sizeof(pixelArray) / sizeof(pixelArray[0]); 
   sort(pixelArray, pixelArray + elements);
   FinalImage.at<uchar>(row, col)=pixelArray[(kernalSize+1)/2];

  }

 }


 namedWindow("Original Image",1);
 imshow("Original Image",grayScaleImage);

 namedWindow("Filtered Image",1);
 imshow("Filtered Image",FinalImage);

 waitKey();
 return 0;
}




When you run this code you see results like this