- Prison Code Breaker Diary -

=> aka: Nhật Kí Code Tù

Categories

Showing posts with label How-to. Show all posts

Let's start unit-test journey using this simple class, in which we want to test whether this class returns all passes or failures.


using System;
using System.Collections.Generic;
using System.Text;

namespace UnitTest
{
    enum CalculatingType
    {
        Addition,
        Subtraction,
        Multiplication,
        Division
    }
    class Calculator
    {
        private List List;
        private CalculatingType cType;

        public Calculator() { }

        public Calculator(List list, CalculatingType type)
        {
            this.List = list;
            this.cType = type;
        }

        public List CList
        {
            get { return this.List; }
            set { this.List = value; }
        }

        public CalculatingType CType
        {
            get { return this.cType; }
            set { this.cType = value; }
        }

        public double GetResult()
        {
            double result = this.List[0];

            for (int i = 1; i < this.List.Count; ++i)
            {
                if (cType == CalculatingType.Addition)
                    result += this.List[i];
                else if (cType == CalculatingType.Subtraction)
                    result -= this.List[i];
                else if (cType == CalculatingType.Multiplication)
                    result *= this.List[i];
                else
                    result /= this.List[i];
            }

            return result;
        }

    }
}

That's it, there have 'Calculator' class containing a list of double values and a enumeration type indicating what kind of computing. Right now, you should have installed NUnit before moving on. Let's create a new class named 'CalculatorTest' to test our created-class 'Calculator'. So what do we want to test? It can be, and should be: + constructors + properties + methods Since this class is quite simple, so testing constructors and properties can be considered alike; in other words, we will test properties and methods of class 'Calculator' In the current project, add a new class named 'CalculatorTest'. Add Reference to NUnit.Framework.Dll, which is located in installed NUnit directory. First of our test code
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;

namespace UnitTest
{
    [TestFixture]
    class CalculatorTest
    {
        [Test]
        public void TestCListA()
        {
            Calculator calc = new Calculator(new List { 1, 2, 3 }, CalculatingType.Addition);
            Assert.AreEqual(new List { 1, 2, 3 }, calc.CList);            
        }
    }
}

Build project, then call NUnit from VS, click button 'Run'.
You've got a pass! (list picture below)


So far so good, let's go into some explanation.
Since you've added NUnit Framework, you can add attribute to the classes or methods to indicate you want to test them.
To indicate a class test, [TestFixture] is used before the class declaration, and [Test] is used before methods'.
Simple enough?
Try the next test function to test whether our expected result and actual result are the same

        [Test]
        public void TestCListB()
        {
            Calculator calc = new Calculator(new List { 1, 2, 3 }, CalculatingType.Addition);            
            Assert.AreEqual(new List { 2, 3, 1 }, calc.CList);
        }

We've got a fail here
UnitTest.CalculatorTest.TestCListB:
  Expected and actual are both  with 3 elements
  Values differ at index [0]
  Expected: 2.0d
  But was:  1.0d

So that means the numbers at index 0 are different. We may understand like both lists containing the same number but arranged in different order, but in facts, it isn't; they're compared one-by-one iterate through index of each list.

Try a different list
        [Test]
        public void TestCListC()
        {
            Calculator calc = new Calculator(new List { 1, 2, 3 }, CalculatingType.Addition);
            Assert.AreEqual(new List { -1, 2, 3 }, calc.CList);
        }

It's certainly a fail because the first value of each list is different.

Let's test the other property, CalculatingType
        [Test]
        public void TestCTypeA()
        {
            Calculator calc = new Calculator(new List { 1, 2, 3 }, CalculatingType.Addition);
            Assert.AreEqual(CalculatingType.Addition, calc.CType);
        }

        [Test]
        public void TestCTypeB()
        {
            Calculator calc = new Calculator(new List { 1, 2, 3 }, CalculatingType.Addition);
            Assert.AreEqual(CalculatingType.Subtraction, calc.CType);
        }
It's easy to see that TestCTypeA() passes and TestCTypeB() fails logically.

Similarly, we will create test function for the GetResult(). Since there're 4 kind of computing, so we will divide into 4 small test functions to check each kind of computing,

        [Test]
        public void TestAddition()
        {
            Calculator calc = new Calculator(new List { 1, 2, 3 }, CalculatingType.Addition);
            Assert.AreEqual(6, calc.GetResult());
        }


        [Test]
        public void TestSubtraction()
        {
            Calculator calc = new Calculator(new List { 1, 2, 3 }, CalculatingType.Subtraction);                      
            Assert.AreEqual(-4, calc.GetResult());
        }

        [Test]
        public void TestMultiplication()
        {
            Calculator calc = new Calculator(new List { 1, 2, 3 }, CalculatingType.Multiplication);
            Assert.AreEqual(6, calc.GetResult());
        }

        [Test]
        public void TestDivisionA()
        {
            Calculator calc = new Calculator(new List { 1, 2, 3 }, CalculatingType.Division);
            Assert.AreEqual(0.1666667, calc.GetResult());
        }

We have passed at function TestAddition(), TestSubtraction(), TestMultiplication(), but failed at function TestDivisionA().
The reason is the floating point not match. Well, it's kinda of trick here.
Luckily that we have first operation 1/2 = 0.5 limited so we can write like

        [Test]
        public void TestDivisionB()
        {
            Calculator calc = new Calculator(new List { 1, 2, 3 }, CalculatingType.Division);
            Assert.AreEqual( 0.5/3, calc.GetResult());
        }
Good trick! We pass TestDivisionB().
Not happy yet, what if the input for Division containing 0 (zero)?
It is an exception, isn't it?
NUnit provides an attribute to test whether an exception is called out.

        [Test,ExpectedException(typeof(DivideByZeroException))]
        public void TestDivisionC()
        {
            Calculator calc = new Calculator(new List { 1, 2, 0 }, CalculatingType.Division);
            throw new DivideByZeroException();
        }

As you see above, we expect to get an exception type DivideByZeroException, a .NET class.

Software testing is quite a complicated task and consumes a lot of time. Well, this post just demonstrate a very very simple introduction to unit test.
Hope you learn something from this tutorial.

Linux bash shell provides 2 types of test:
+ ( -ot ) : is other than
+ ( -nt ) : is newer than


#!/bin/sh

if [ "$file1" -nt "$file2" ]
then
    echo -e "$file1 is newer than $file2"
else
    echo -e "$file1 is older than $file2"
fi

I write this bash script to automate the process of creating Linux libraries in C/C++

#!/bin/bash

clear

echo -e "##########################################"
echo -e "#     LIBRARY AUTO-CREATOR by [JaPh]     #"
echo -e "#========================================#"
echo -e "Usage: `basename $0` lib_name type path   "
echo -e "Example: "
echo -e " + creating libraries from hello.c in current directory"
echo -e " `basename $0` hello C . "
echo -e " + creating libraries from bye.cpp to '/opt/lib' directory"
echo -e "   `basename $0` bye C++ /opt/lib"
echo -e "Feel free to contact, pete.houston.17187@gmail.com\n"

ARG=3

if [ "$#" -ne "$ARG" ]
then
 echo -e "[?] wrong input arguments!"
 exit
fi

libname=lib"$1"

if [ "$2" == "C" ]
then
 filename="$1.c"
 compiler="gcc"
elif [ "$2" == "C++" ]
then
 filename="$1.cpp"
 compiler="g++"
else
 echo -e "[?] unknown filetype"
 exit
fi

echo -e "< Static Library: $libname.a >"
command="$compiler -Wall -c $filename"
echo -e "\$ $command"
if [ !`$command` ]
then
 echo -e ".created: $1.o"
else
 echo -e ".[?] cannot create object $1.o"
 exit
fi

echo -e "\$ ar -cvq $libname.a $1.o"
ar -cvq $libname.a $1.o
echo -e ".created: $libname.a"
echo -e "< Static Library '$libname.a' created ! >"

rm -f $1.o
echo -e "< Shared Object Library: $libname.so.1.0 >"
command="$compiler -Wall -fPIC -c $1.c"
echo -e "\$ $command"
if [ !`$command` ]
then
 echo -e ".created: $1.o"
else
 echo -e ".[?] cannot create object $1.o"
 exit
fi

command="$compiler -shared -Wl,-soname,$libname.so.1 -o $libname.so.1.0 $1.o"
echo -e "\$ $command"
if [ !`$command` ]
then
 echo -e ".created: $libname.so.1.0"
else
 echo -e ".[?] cannot create shared object $libname.so.1.0"
 exit
fi

ln -sf $libname.so.1.0 $libname.so
ln -sf $libname.so.1.0 $libname.so.1

echo -e "< Shared Object Library '$libname.so.1.0' created ! >"

if [ "$3" != "." ]
then
 mv $libname.* "$3"
 echo -e "[!] All files moved to $3"
fi


STATIC LIBRARY (.a)

+ Compile

$ gcc -Wall -c *.c
+ Create library
$ ar -cvq libtest *.o
+ List files in library
$ ar -t libtest.a
+ Linking with library
$ gcc -o executable-name prog.c libtest.a
$ gcc -o executable-name prog.c -L/path/to/library-dir -ltest


Shared Object: DYNAMICALLY LINKED LIBRARY

+ Compile object
$ gcc -Wall -fPIC -c *.c
+ Create shared object
$ gcc -shared -Wl,-soname,libtest.so.1 -o libtest.so.1.0 -o *.o
+ Move library to destination
$ mv libtest.so.1.0 /path/to/lib-dir
+ Allow naming convention like -ltest
$ ln -sf /path/to/lib-dir/libtest.so.1.0 /path/to/lib-dir/libtest.so
+ Allow run-time binding to work
$ ln -sf /path/to/lib-dir/libtest.so.1.0 /path/to/lib-dir/libtest.so.1
+ Testing executable file dependencies
$ ldd executable-file


Reference: Yo-Linux

libcurl - the multiprotocol file transfer library

libcurl is a free and easy-to-use client-side URL transfer library, supporting FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS, FILE, IMAP, SMTP, POP3 and RTSP. libcurl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, Kerberos4), file transfer resume, http proxy tunneling and more!

libcurl is highly portable, it builds and works identically on numerous platforms, including Solaris, NetBSD, FreeBSD, OpenBSD, Darwin, HPUX, IRIX, AIX, Tru64, Linux, UnixWare, HURD, Windows, Amiga, OS/2, BeOs, Mac OS X, Ultrix, QNX, OpenVMS, RISC OS, Novell NetWare, DOS and more...

libcurl is free, thread-safe, IPv6 compatible, feature rich, well supported, fast, thoroughly documented and is already used by many known, big and successful companies and numerous applications.

Homepage: http://curl.haxx.se/libcurl/

First, download and install cURL library package.
Then, use the utility 'curl-config' to get the compile options need for cURL program

$ curl-config --cflags
$ curl-config --libs

This is a simple program that retrieve a web page:

#include <stdio.h>
#include <curl/curl.h>
int main()
{
 CURL *curl;
 CURLcode res;
 
 curl = curl_easy_init();
 if(curl) {
  curl_easy_setopt(curl, CURLOPT_URL, "xjaphx.blogspot.com");
  res = curl_easy_perform(curl);
  
  curl_easy_cleanup(curl);
 }
 return 0;
}

Try to compile with this option:

$ gcc -o curl_simple curl_simple.c `curl-config --libs`
$ ./curl_simple

The header is needed in program `#include `, you can find its location by this


$ whereis curl
$ whereis curl.h

Probably, it will be /usr/bin/curl /usr/include/curl
While compile, you need to specify the linking library, that's why I set option `curl-config --libs`.
If you run this command alone


$ curl-config --libs
-lcurl
That's the result. Instead, you can compile like this

$ gcc -o curl_simple curl_simple.c -lcurl

Which gives the same result.

It's possible. Yes, it is!

NOTE: this guide is for education purposes only, not promoting for illegal actions

Requirements:
1. Crossover Linux Professional 7.0: get it here: Download

2. Installation package for Ms Office 2007.

How-to:

1. From menu, choose CrossOver -> Install Windows Software. Pick Microsoft Office 2007, locate the setup.exe file, then install it as in Windows.

2. After all installation done, we need to crack it though.
a. Get this file: Proof.XML
b. Replace the old one located under:

/home/[YOUR_USER_NAME]/.cxoffice/MSOffice/drive_c/Program Files/Common Files/Microsoft Shared/OFFICE12/Office Setup Controller/Proof.en
c. From CrossOver menu -> Run a Windows Command, type: regedit
d. Find the key: HKLM\Software\Microsoft\Office\12.0\Registration\DigitalProductID, and delete it.
e. Close all CrossOver-related program.
d. Under main menu: Applications, you can see Windows Application menu, and enjoy !


Enjoy !

It's really itchy to have menu list cover half of your screen, they're way too biggggg!!!
I've googled to find the solution but it's like impossible @@!
Finally, I got the answer. This is how-to make it better look for you.

Choose a theme to use in order to edit that theme, example, I use 'Is Ora Smooth'.
Then I locate to its settings at: /usr/share/themes/Is Ora Smooth/gtk-2.0/gtkrc
Run gEdit or any text editor under root permission to edit this file.

Add this option into the file:

gtk-icon-sizes = "panel-menu=16,16"

I'm not sure if you want to make it smaller but the size is often like 16, 24 or 32.
Choose the one that best fits for you.
Logout and apply that theme, you'll see how beautiful it is!

Here's the trick, using the -o, and L option we can search for what we need to print out

ps -opid -A

The End!

Oh yes, it took me time to search for this.
Here's the trick:


ps -o"%C" -p #PID

or simplified version

ps -opcpu -p #PID

The End :D

All information about the environment variable is stored in '$env'.
When you want to retrieve info about any variable, you can follow the syntax

$env:<variable_name>

Here's an example how to use it:


PS C:\> $env:windir
C:\Windows

PS C:\> $env:path
C:\Perl\site\bin;C:\Perl\bin;C:\Program Files\ActiveState Perl Dev Kit 8.0\bin;
C:\Program Files\Borland\Delphi7\Bin;C:\Program Files\Borland\Delphi7\Projects\
Bpl\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;c:\Program Files\M
icrosoft SQL Server\90\Tools\binn\;C:\Web\PHP;C:\Web\PHP\ext;C:\Web\MySQL\bin;C
:\Program Files\QuickTime\QTSystem\;C:\GTK\bin;C:\Program Files\Microsoft Visua
l Studio 8\VC\bin;C:\Program Files\Java\jdk1.6.0_18\bin;C:\GTK2-16\bin;C:\Windo
ws\System32\WindowsPowerShell\v1.0\;C:\Program Files\GTK2-Runtime\bin;C:\BC5\BI
N;C:\Program Files\Nmap;C:\Program Files\Common Files\Nero\Lib\

It's a damn cool thing when you want to save something into HTML format.
Windows PowerShell provides this function through [ConvertTo-HTML] Cmdlets.

Example, if I want to save my list of current processes into HTML format

PS > Get-Process | ConvertTo-HTML | Out-File ProcessHTML.html

Another great thing is that it provides the way how you can format the output the HTML file through these 3 arguments: -head, -body, and -title.
Here, another example of formatting the output

$format_head = "<title> PROCESS LIST </title>"
$format_head += "<style>
"
$format_head += "TABLE { border-width:2px;border-style:solid}"
$format_head += "TH {border-width:1px;border-style:solid}"
$format_head += "TD {border-width:2px;border-style:solid}"
$format_head += "</style>"

$format_body = "<center> PROCESS LIST </center>"

Get-Process | ConvertTo-HTML -head $format_head -body $format_body | Out-File processHTML.html

There're 2 ways to run your VBScript or JScript under Windows, either through CScript.exe or WScript.exe
What's the difference about those two?
- They are all almost the same, just different in the way displaying the output. While CScript.exe displays output in a Console, WScript.exe display the output in a Dialog.

Well, when you run the script, the default host will be chosen certainly. But you can switch between them.

If you want CScript.exe to be the default host

cmd> CScript //H:CScript

or WScript to be the default one

cmd> WScript //H:WScript

By default, you cannot execute any remote PowerShell script (extension: PS1).
However, you can set execution right to run any script on your system by calling the Set-ExecutionPolicy command

PS C:\Data> Set-ExecutionPolicy RemoteSigned

Execution Policy Change
The execution policy helps protect you from scripts that you do not
trust. Changing the execution policy might expose you to the security
risks described in the about_Execution_Policies help topic. Do you want
 to change the execution policy?
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): Y
PS C:\Data>


After that, you can run any .ps1 script as you like.

Menu Preferences | Appearances

  • Theme | Customize
    1. Controls | Is Ora Smooth
    2. Window Border | evil_mac - Download
    3. Icons | Ultimate Gnome - Download
    4. Pointer | Wonderland
  • Fonts
    1. Application Font | Segoe UI | 11
    2. Document Font | Segoe UI | 11
    3. Desktop Font | Trebuchet MS Bold | 9
    4. Window Title Font | Segoe UI | 11
    5. Fixed Width Font | Monospace | 10
    6. Rendering | Best Shapes
    7. Details | Resolution
    • Resolution | 75 dots per inch
    • Smoothing | Grayscale
    • Hinting | Medium
    • Subpixel Order | RGB
  • Background - Download Corlorful Pack

This is my new shot of command prompt.

Right click then select "Properties".

$ Option -> Command History -> Buffer Size -> 500
$ Option -> Command History -> Discard Old Duplicates -> True
$ Option -> Edit Options -> QuickEdit Mode -> True
$ Layout -> Screen Background -> Height -> 999
$ Layout -> Window Size -> Height -> 50
$ Color -> Screen Text -> RGB: 0 255 0
$ Color -> Screen Background -> RGB: 0 55 0

Change the title using TITLE utility


C:/> title "[JaPh] - Shell"

Have fun!

Access this key in Registry Editor:
HKEY_CURRENT_USER \ Software \ Microsoft \ Command Processor
Create a new String name it Autorun with value: "CD /d your_new_default_path"

Example:


CD /d C:\


It applies right away, you don't need to restart or log-off, just restart to new session.

Have fun!

Would you like to have your command prompt like mine?













OK! Let's open Registry Editor (regedit.exe) utility for some add-ons.
First, export your current registry settings for the sake of your life (menu File->Export).
Then, access this key: Computer\HKLM\SYSTEM\CurrentControlSet\Control\SessionManager\Environment
Right click to create a new string value, name it PROMPT with value: "[JaPh]@$P~$P$$$P"
Then log-off or reboot to apply new settings to environment. You'll see the change in your command prompt, just like Unix-shell.

However, if you just want to have this style temporarily, means that for current session only, you need to use "prompt" utility to set up.
Example:


C:\> prompt [JaPh]@$P~$$$P

After session, everything changes back to default.

Here some special value if you want differences:

$A & (Ampersand)
$B | (pipe)
$C ( (Left parenthesis)
$D Current date
$E Escape code (ASCII code 27)
$F ) (Right parenthesis)
$G > (greater-than sign)
$H Backspace (erases previous character)
$L < (less-than sign) $N Current driveprompt [%USERNAME%@%COMPUTERNAME%$S~]$$
$P Current drive and path
$Q = (equal sign)
$S (space)
$T Current time
$V Windows XP version number
$_ Carriage return and linefeed
$$ $ (dollar sign)

Have fun!

Language: Perl
Presiquisite: XML::Simple

Assuming we have a xml file like this: data.xml

<?xml version="1.0" encoding="UTF-8"?>
<database>
<user>
<uname>Pete Houston</uname>
<upass>123456</upass>
<email>pete.houston.17187@gmail.com</email>
<id>1</id>
</user>
<user>
<uname>Bach Van Kim</uname>
<upass>987654</upass>
<email>bvkvn06@gmail.com</email>
<id>2</id>
</user>
</database>
We will dump this XML tree using XML::Simple and Dumper package:

#!C:\perl\bin\perl.exe -w
use strict;
use XML::Simple;
use Data::Dumper;

print Dumper( XML::Simple->new()->XMLin("data.xml"));

The result shows:

$VAR1 = {
'user' => {
'1' => {
'email' => 'pete.houston.17187@gmail.com',
'uname' => 'Pete Houston',
'upass' => '123456'
},
'2' => {
'email' => 'bvkvn06@gmail.com',
'uname' => 'Bach Van Kim',
'upass' => '987654'
}
}
};

The method: XML::Simple->new() will create an object to handle XML file, and then input file will be called through method XMLin("filename.xml");
A very simple way!

Here the instruction on how to install Gtk+ for Perl on Windows.
There are two options:

1. Simply download and setup CamelBox:

2. Using ActivePerl:
+ Download and install ActivePerl: https://www.activestate.com/activeperl/downloads/
+ Download and install Gtk+ Environment for Windows: http://cdnetworks-kr-2.dl.sourceforge.net/project/gladewin32/gtk%2B-win32-runtime/2.8.20/gtk-2.8.20-win32-1.exe
+ Open command and type:


ppm repo add http://www.lostmind.de/gtk2-perl/ppm/
ppm install Gtk2

+ Finally, restart your Windows

There are many ways but those two are the best options of all that I prefer.

Have fun!

Under Windows, it's best to use ActiveState Perl.
In order to manage your Perl package, you might want to use either:

1. Command-line approach:


C:\>perl -MCPAN -e shell;


2. Easier management through GUI:

C:\>ppm

PPM is Perl Package Manager provided by ActiveState.

Have fun!