- Prison Code Breaker Diary -

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

Categories

Showing posts with label Tricks 'n Tips. Show all posts

Opem XTerm and type

bash$ sudo passwd root

Then type a new password for root.
That's all!

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.

#include 

#define CreateFunction( FunctionName, Operator, Type ) \
  Type FunctionName( Type a, Type b ) \
  { \
   return a Operator b; \
  }

CreateFunction( Add, +, int )
CreateFunction( Sub, -, float )
CreateFunction( Mul, *, long )

using std::cout;
using std::endl;

int main( )
{

 cout << "CreateFunction(Add, +, int)"    << endl
   << "10 + 15 = "   << Add( 10, 15 )    << endl
   << "CreateFunction(Sub, -, float)"   << endl
   << "12.4 - 4.34 = " << Sub( 12.4, 4.34 )  << endl
   << "CreateFunction(Mul, *, long)"    << endl
   << "40 * 123 = "   << Mul( 40, 123 )   << endl;

 return 0;
}
The 3 lines
CreateFunction( Add, +, int )
CreateFunction( Sub, -, float )
CreateFunction( Mul, *, long )

will be expanded during compile time.

A well-known trick under GNU/C.

#!/bin/bash
#Valentin Heinitz, www.heinitz-it.de, 2008-11-13
#Reader for MS Windows 3.1 Ini-files
#Usage: inireader.sh
# e.g.: inireader.sh win.ini ERRORS DISABLE
# would return value "no" from the section of win.ini
#[ERRORS]
#DISABLE=no
INIFILE=$1
SECTION=$2
ITEM=$3
cat $INIFILE | sed -n /^\[$SECTION\]/,/^\[.*\]/p | grep "^[:space:]*$ITEM[:space:]*=" | sed s/.*=[:space:]*//

I got it from here.

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

Original Discussion -> [Cviet]

Code Relax #3 [ by rox_rook ]

- Write a class that allows operator overloading as long as possible and no syntax error.
Example, the following expression must be evaluated:

+++++++++++++++++++++++++++++++x; // must be valid and evaluated
- Language in use: C++

Solution [ by me ]

#include <iostream>

using namespace std;

template< typename X >
class MyOperator {
    private:
        X value;
    public:
        MyOperator( X _value = 0 ) : value(_value) { };
       
        MyOperator& operator+() {
            ++value;
        }
        MyOperator& operator++() {
            ++value;
        }

        X getValue() const { return value; }
};

int main( )
{
    MyOperator<int> x(7);
    ++++++++++++++++++++++++++++++++++x;
    cout << x.getValue() << endl;
   
    MyOperator<double> j(1.4);
    +++++++++++++++j;
    cout << j.getValue() << endl;

    return 0;
}


Evaluation
- The keyword 'operator' in C++ can be use to make cool things. I just found out about this 'til today testing it.

Original Discussion: -> [Cviet]

Code Relax #2 [ by rox_rook  ]

Given a template to get sum below

template< typename T >
inline
T calculate_sum_of_element( const T* i, const T* e )
{
    T sum = T( ); // a zero value for any type
    while( i != e )
    {
        sum += *i;
        ++i;
    }

    return sum;
}

Try this on int and char array

#include <iostream>

using namespace std;

template< typename T >
inline
T calculate_sum_of_element( const T* i, const T* e )
{
    T sum = T( ); // a zero value for any type
    while( i != e )
    {
        sum += *i;
        ++i;
    }

    return sum;
}

int main( )
{
    int int_ary[ 3 ] = { 1, 2, 3 };
    cout << calculate_sum_of_element( int_ary, int_ary + 3 ) << endl;
    
    char char_ary[ 3 ] = { 'a', 'b', 'c' };
    cout << calculate_sum_of_element( char_ary, char_ary + 3 ) << endl;
    return 0;
}

The result for int is 6 as expected; however, for char it supposed to be 97 + 98 + 99 = 294, but the character '&' is printed out.

Requirement
+ Re-write the given template function to make char data type return an int value
+ Language in use: C++

Solution [ by author, rox_rook ]

#include <iostream>
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

template< typename T >
class Trait;

template< >
class Trait< char >
{
public :
    typedef int SumType;
    static SumType zero( )
    {
        return 0;
    }
};

template< >
class Trait< short >
{
public :
    typedef short SumType;
    static SumType zero( )
    {
        return 0;
    }
};

template< >
class Trait< unsigned >
{
public :
    typedef unsigned SumType;
    static SumType zero( )
    {
        return 0;
    }
};

template< >
class Trait< double >
{
public :
    typedef double SumType;
    static SumType zero( )
    {
        return 0;
    }
};

template< >
class Trait< int >
{
public :
    typedef int SumType;
    static SumType zero( )
    {
        return 0;
    }
};

template< typename T >
inline
typename Trait< T >::SumType calculate_sum_of_element( const T* i, const T* e )
{
    typedef typename Trait< T >::SumType SumType; // create shortcut, less typo
    SumType sum = Trait< T >::zero( );
    while( i != e )
    {
        sum += *i;
        ++i;
    }

    return sum;
}

int main( )
{
    char char_ary[ 3 ] = { 'a', 'b', 'c' };
    cout << calculate_sum_of_element( char_ary, char_ary + 3 ) << endl;
    double d_ary[ 3 ] = { 1.1, 2.2 , 3.3 };
    cout << calculate_sum_of_element( d_ary , d_ary + 3 ) << endl;    
    int i_ary[ 3 ] = { 1, 2 , 3 };
    cout << calculate_sum_of_element( i_ary , i_ary + 3 ) << endl;      
}


Evaluation
- It's freaking unthinking of....lol

Original Topic Discussion => [Cviet]

Relax #1 [ by me ]

Given 3 functions:

int add( int _a, int _b ) { return _a + _b; }
int sub( int _a, int _b ) { return _a - _b; }
int mul( int _a, int _b ) { return _a * _b; }

Implement the following program:
+ Prompt user to input 1 of 4 strings: "add", "sub", "mul" or "end"; otherwise, start program again; "end" to exit.
+ Then, prompt user to input 2 numbers
+ Output result in this form

A [operator] B = [result]

Operator must be one of the following '+', '-' and '*', according to its own function, which means string "add" match add() function ....

Requirement
+ Must use function pointer
+ Call function according to its name, call add() if user prompt "add"....so on.
+ Language to use: C, C++

Demo output

> type 'add', 'sub', 'mul' or 'end': add
 a = 1
 b = 2
 1 + 2 = 3
> type 'add', 'sub', 'mul' or 'end': sub
 a = 6
 b = 4
 6 - 4 = 2
> type 'add', 'sub', 'mul' or 'end': mul
 a = 12
 b = 1
 12 * 1 = 12
> type 'add', 'sub', 'mul' or 'end': end

PROGRAM ENDED ! 


Solution #1 [ by me ]


Code in C as following:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_SIZE    1024

//
// #struct JFUNC
//
struct JFUNC {
    char *name;                 // function name
    int (*func)(int, int);      // pointer to function
    char sign;                  // sign of function, '+', '-', '*'
};

//
// #function        say()
// #purpose         format output with given params
//
void say( int (*func)(int,int), int _a, int _b, char _ )
{
    printf(" %d %c %d = %d\n", _a, _, _b, func( _a, _b ) );
}

//
// #function        input()
// #purpose         get input from user
//
void input( int *a, int *b ) {
    printf(" a = "); scanf("%d%*c", a);
    printf(" b = "); scanf("%d%*c", b);
}

//
// #function        add(),sub(),mul()
// #purpose         provide regular calculation
//
int add( int _a, int _b ) { return _a + _b; }
int sub( int _a, int _b ) { return _a - _b; }
int mul( int _a, int _b ) { return _a * _b; }
//int div( int _a, int _b ) { return _a / _b; }

/* ENTRY POINT */
int main( )
{
    // init array of 3 structs
    struct JFUNC calc[3] = {
        { "add", add, '+' },
        { "sub", sub, '-' },
        { "mul", mul, '*' }
    };
    int a, b; // input from user
    int idx; // index of struct JFUNC array
    char *key = (char *)malloc( MAX_SIZE * sizeof(char) ); // string to get from user
    do {
   
        printf("> type 'add', 'sub', 'mul' or 'end': " );
        // get input, exactly 4 bytes
        fgets( key, MAX_SIZE, stdin );     

        // iterate through array to get correct function
        for( idx = 0; idx < 3; ++idx ) {
            // if function name is matched
            if( strcmp(calc[idx].name, key) == 0 ) {
                // get input
                input( &a, &b );
                // output
                say( calc[idx].func, a, b, calc[idx].sign );
            }
        }
    // end program if "end" prompted
    } while ( strcmp(key, "end") != 0 );
   
    // free memory
    free( key );
   
    printf(" PROGRAM ENDED!\n");
    // program return
    return 0;
}

Code in C++ as following

#include <iostream>

using namespace std;

//
// #struct JFUNC
//
struct JFUNC {
    string name;                    // function name
    int (*func)(int, int);      // pointer to function
    char sign;                  // sign of function, '+', '-', '*'
};

//
// #function        say()
// #purpose         format output with given params
//
void say( int (*func)(int,int), int _a, int _b, char _ )
{
    cout << " " << _a << " " << _ << " " << _b << " = " << func( _a, _b ) << "\n";
}

//
// #function        input()
// #purpose         get input from user
//
void input( int *a, int *b ) {
    cout << " a = "; cin >> *a;
    cout << " b = "; cin >> *b;
}

//
// #function        add(),sub(),mul()
// #purpose         provide regular calculation
//
int add( int _a, int _b ) { return _a + _b; }
int sub( int _a, int _b ) { return _a - _b; }
int mul( int _a, int _b ) { return _a * _b; }
//int div( int _a, int _b ) { return _a / _b; }

/* ENTRY POINT */
int main( )
{
    // init array of 3 structs
    struct JFUNC calc[3] = {
        { "add", add, '+' },
        { "sub", sub, '-' },
        { "mul", mul, '*' }
    };
    int a, b; // input from user
    int idx; // index of struct JFUNC array
    string key; // string to get from user
    do {
   
        cout << "> type 'add', 'sub', 'mul' or 'end': ";
        // get input, exactly 4 bytes
        cin >> key;

        // iterate through array to get correct function
        for( idx = 0; idx < 3; ++idx ) {
            // if function name is matched
            if( calc[idx].name == key ) {
                // get input
                input( &a, &b );
                // output
                say( calc[idx].func, a, b, calc[idx].sign );
            }
        }
    // end program if "end" prompted
    } while ( key != "end" );
   

    cout << " PROGRAM ENDED!\n";
    // program return
    return 0;
}

Solution #2 [ by tauit_dnmd ]

/*
  UITs:UITstudent.com
  Coder:tauit_dnmd.
*/
#include<iostream>
#include<string>
using namespace std;
typedef int (*MyType)(int,int);

int  add( int _a, int _b ) { return _a + _b; }
int sub( int _a, int _b ) { return _a - _b; }
int mul( int _a, int _b ) { return _a * _b; }

int (*GetFunctionVerSion1(string s,char &oper))(int,int) 
{
        if(s=="add"){oper='+'; return &add;}
        if(s=="sub"){oper='-';return ⊂}
        if(s=="mul"){oper='*'; return &mul;}
}

MyType GetFunctionVerSion2(string s,char &oper)
{
        if(s=="add"){oper='+'; return &add;}
        if(s=="sub"){oper='-';return ⊂}
        if(s=="mul"){oper='*'; return &mul;}
}

int main()
{
    int (*uitstudent)(int,int)=NULL;//define 
    int a,b;
    string myoperator;//operator
    char UITs;
    do
    {
        do
        {
            cout<<"type 'add' 'sub' 'mul' or 'end':"; 
            cin>>myoperator;
            if(myoperator=="add"||myoperator=="sub"||myoperator=="mul"||myoperator=="end") break;
        }while(1);
        if(myoperator!="end")
        {
            uitstudent=GetFunctionVerSion1(myoperator,UITs);//Or uitstudent=GetFunctionVerSion2(myoperator,UITs);
            cout<<"a= ";cin>>a;
            cout<<"b= ";cin>>b;
            cout<<"a "<<UITs<<" b = "<<(*uitstudent)(a,b)<<endl;
        }
    }while(myoperator!="end");
    cout<<"UITs:PROGRAM END!"<<endl;
    return 0;
}  


Solution #3 [ by QuangHoang ]

#include <iostream>
#include <string>
#include <map>
using namespace std;

typedef int (*func)( int, int );

int add( int _a, int _b ) { return _a + _b; }
int sub( int _a, int _b ) { return _a - _b; }
int mul( int _a, int _b ) { return _a * _b; }

map <string, func> fmap;
map <string, func>::iterator it;

void initMap()
{
    fmap["add"] = add;
    fmap["sub"] = sub;
    fmap["mul"] = mul;
}

bool result(string oper)
{
    bool ok = false;
    for ( it=fmap.begin() ; it != fmap.end(); it++ )
        if ( oper == (*it).first ) ok = true;

    if ( !ok ) return false;
   

    int a, b;
    cout << "a = "; cin >> a;
    cout << "b = "; cin >> b;

    cout << a << " " << oper << " " << b << " = " << fmap[oper]( a,b ) << endl;
   
    cin.ignore();
    return true;
}

string label()
{
    string lbl;

    for ( it=fmap.begin() ; it != fmap.end(); it++ )
        lbl += "'" + (*it).first + "', ";

    return lbl;
}

int main()
{
    initMap();
    string oper;

    cout << "> type " << label() << "or 'end': ";
    do
    {
        getline(cin,oper);
        if (oper == "end") break;  

        if (!result(oper))
            cout << "> retype " << label() << "or 'end': ";
        else cout << "> type " << label() << "or 'end': ";

    } while (true);

    cout << "\nPROGRAM ENDED !";
    return 0;
}


Solution #4 [ by rox_rook ]

#include <iostream>
#include <map>
#include <string>


int add( int a, int b ) { return a + b; }
int sub( int a, int b ) { return a - b; }
int mul( int a, int b ) { return a * b; }
int end( int a, int b ) { return 0;     } // dummy func

typedef int( *FUNC )( int , int );

int main()
{
    std::map< std::string, std::pair< char, FUNC > > _func;

    _func[ "add" ] = std::make_pair< char, FUNC >( '+', add );
    _func[ "sub" ] = std::make_pair< char, FUNC >( '-', sub );
    _func[ "mul" ] = std::make_pair< char, FUNC >( '*', mul );
    _func[ "end" ] = std::make_pair< char, FUNC >( ' ', end );

    std::string user_repl;
    int a, b;

    do {
        std::cout << "> type 'add', 'sub', 'mul' or 'end' : ";
        std::cin >> user_repl;
        if( user_repl == "end" )
            break;
        std::cout << "> 'a' 'b' : ";
        std::cin >> a >> b;
        std::cout << a << _func[ user_repl ].first << b << "=" << _func[ user_repl ].second( a, b ) << "\n";
    }
    while( 1 );

    return 0;
}


Evaluation

- Solution #1: My approach follows the traditions of C, calling function by name through a structure, which is mentioned in C-faq under section 20.6 ( Read C-Faq 20.6 )
- Solution #2: It's kinda handy in matching strings.
- Solution #3: mapping, but not really satisfy requirements.
- Solution #4: mapping using value of pair template, it's short, clear and understandable. I think it's the best solution under C++.

I accidentally found it here: http://bytes.com/topic/c/answers/561589-print-1-100-without-loops-c-c

#include 
#include 

void (*f[2])(int);

void
printnum(int n)
{
        printf("%d\n", n);
        int i;
        i = ++n <= 100;
        (*f[i])(n);
}

void
done(int n)
{
        exit(0);
}

int
main(void)
{
        int n = 1;

        f[0] = &done;
        f[1] = &printnum;

        printnum(n);

        return 1;
}


These functions are usually used when dealing with binary data: open, read, write, close, seek and binmode.

I've written this perl script to generate a random binary file:

#!/bin/perl -w

use strict;

use constant RANGE => 0xFF;

if( $#ARGV != 1 ) {
    print "Error: no argument input!\n";
    print "Usage: > perl $0 FILE_NAME MAX_BYTES\n";
    print "Example: > perl $0 data.bin 255\n";
    exit;
}

my $file = $ARGV[0];
my $max_bytes = $ARGV[1];

my $cnt = 0;

open FILE,">", $file or die $!;

while( $cnt < $max_bytes ) {
    print FILE chr(int(rand(RANGE)));
    ++$cnt;
}

close FILE;

print "Binary file '$file' ($max_bytes bytes) generated!\n";

binmode() is not in used, so how does it work? Because I generate random value in ASCII so I can easily convert it into its according character, then simply write into file. It does sound weird but it actually works! The case of using binmode() and just print the number, it doesn't write the binary as expected. I don't understand why ???? The next script is to read a binary file and print out the hex code of each character inside.
#!/bin/perl -w

use strict;

if( @ARGV != 2 ) {
    print
     "Error: wrong arguments input!\n",
 "Usage: > perl $0 FILE BYTES\n",
 "Example: > perl $0 data.bin 255\n";
    exit;
}

my $file = $ARGV[0];
my $bytes = $ARGV[1];

open FILE, "<", $file or die $!;
#binmode FILE;

my $cnt = 0;
while( $cnt < $bytes ) {
    read FILE, my $byte, 1;
    print  sprintf("%02X", ord($byte)). " ";
    ++$cnt;
}
close FILE;
print "\n";


I use read() to get each byte then re-format into hex then print().
I don't use binmode() but it still does work well.

So I think I just don't need binmode() even though it's a binary case.

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

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

On exponentiation, don't take the number too big like: 10 ** 99999 ... otherwise, u will get unexpected result or 1.#INF

The remainder operator doesn't apply for floating-point number, but if you do then they all will be round-off into the closest integers, then apply the operator.

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!

By using the utility netsh, you may find it easily to manage your network. Yes, it's pretty much convenient.

1. Show network information:


netsh interface ip show config


2. Change setting of ip address, mask and gateway

netsh interface ip set address name="Network Name" static ip_address subnet_mask gateway 1


Sample: set Local Area Connection to static address 192.111.215.96, mask = 255.255.255.252, gateway = 192.111.215.1

netsh interface ip set address name="Local Area Connection" static 192.111.215.96 255.255.255.252 192.111.215.1 1


2. Change DNS setting
+ set DNS

netsh interface ip set dns "Network Name" static dns_address

+ add DNS

netsh interface ip add dns "Network Name" dns_address index=2


3. Export IP setting to file:

netsh -c interface dump > C:\setting.txt


4. Import IP setting from file:

netsh -f C:\setting.txt

or

netsh exec C:\setting.txt


5. Using DHCP
+ Simply add 'dhcp' at the end of your command :D

netsh interface ip set address "Local Area Connection" dhcp
netsh interface ip set dns "Local Area Connection" dhcp



Have fun!