2009年11月30日 星期一

Exercises : C++ How to Program, Fifth Edition

Developement Environment: Dev-C++ 4.9.9.2


  • 3.11

  • (Modifying Class GradeBook) Modify class GradeBook (Figs. 3.113.12) as follows:
    a. Include a second string data member that represents the course instructor's name.
    b. Provide a set function to change the instructor's name and a get function to retrieve it.
    c. Modify the constructor to specify two parametersone for the course name and one for the instructor's name.
    d. Modify member function displayMessage such that it first outputs the welcome message and course name, then outputs "This course is presented by: " followed by the instructor's name.
    Use your modified class in a test program that demonstrates the class's new capabilities.

    • GradeBook.h


    • #include
      using std::string;

      class GradeBook
      {
      public:
      GradeBook(string, string);
      void setCourseName(string);
      string getCourseName();
      void setCourseInstructorName(string);
      string getCourseInstructorName();
      void displayMessage();

      private:
      string courseName;
      string courseInstructorName;
      };

    • GradeBook.cpp


    • #include
      using std::cout;
      using std::endl;

      #include "GradeBook.h"

      GradeBook::GradeBook(string name, string insName)
      {
      setCourseName(name);
      setCourseInstructorName(insName);
      }

      void GradeBook::setCourseName(string name)
      {
      courseName = name;
      }

      string GradeBook::getCourseName()
      {
      return courseName;
      }

      void GradeBook::setCourseInstructorName(string insName)
      {
      courseInstructorName = insName;
      }

      string GradeBook::getCourseInstructorName()
      {
      return courseInstructorName;
      }

      void GradeBook::displayMessage()
      {
      cout << "Welcome to the grade book for\n" << getCourseName() << "!" <<
      "\nThis course is presented by:" << getCourseInstructorName()
      << endl;
      }

    • main.cpp


    • #include
      using std::cout;
      using std::endl;

      #include "GradeBook.h"

      int main(int argc, char *argv[])
      {
      GradeBook gradeBook1("CS101 Instroduction to C++ Programming", "John");

      gradeBook1.displayMessage();

      system("PAUSE");
      return EXIT_SUCCESS;
      }

    • Output


    • Download Source from here.

  • 3.12

  • (Account Class) Create a class called Account that a bank might use to represent customers' bank accounts. Your class should include one data member of type int to represent the account balance. [Note: In subsequent chapters, we'll use numbers that contain decimal points (e.g., 2.75)called floating-point valuesto represent dollar amounts.] Your class should provide a constructor that receives an initial balance and uses it to initialize the data member. The constructor should validate the initial balance to ensure that it is greater than or equal to 0. If not, the balance should be set to 0 and the constructor should display an error message, indicating that the initial balance was invalid. The class should provide three member functions. Member function credit should add an amount to the current balance. Member function debit should withdraw money from the Account and should ensure that the debit amount does not exceed the Account's balance. If it does, the balance should be left unchanged and the function should print a message indicating "Debit amount exceeded account balance." Member function getBalance should return the current balance. Create a program that creates two Account objects and tests the member functions of class Account.

    • Account.h


    • #include
      using std::string;

      class Account
      {
      public:
      Account(int);
      void credit(int);
      void debit(int);
      int getBalance();

      private:
      int balance;
      };

    • Account.cpp


    • #include
      using std::cout;
      using std::endl;

      #include "Account.h"

      Account::Account(int initAmount)
      {
      if(initAmount < 0)
      {
      balance = 0;
      cout << "ERROR!!! The initial balance was invalid.\n";
      }
      else
      balance = initAmount;

      }

      void Account::credit(int amount)
      {
      balance += amount;
      }

      void Account::debit(int amount)
      {
      if(amount > balance)
      {
      cout << "ERROR!!! Debit amount exceeded account balance.\n";
      return;
      }
      balance -= amount;
      }

      int Account::getBalance()
      {
      return balance;
      }

    • main.cpp


    • #include
      using std::cout;
      using std::endl;

      #include "Account.h"

      int main(int argc, char *argv[])
      {
      Account acct1(-10);
      cout << "Acct 1, Balance => $" << acct1.getBalance() << "\n";
      acct1.credit(100);
      cout << "Acct 1, Balance => $" << acct1.getBalance() << "\n";


      Account acct2(1000);
      cout << "Acct 2, Balance => $" << acct2.getBalance() << "\n";
      acct2.debit(2000);
      cout << "Acct 2, Balance => $" << acct2.getBalance() << "\n";

      system("PAUSE");
      return EXIT_SUCCESS;
      }

    • Output


    • Download source from here.

  • 9.6

  • (Rational Class) Create a class called Rational for performing arithmetic with fractions. Write a program to test your class.
    Use integer variables to represent the private data of the classthe numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it is declared. The constructor should contain default values in case no initializers are provided and should store the fraction in reduced form. For example, the fraction

    would be stored in the object as 1 in the numerator and 2 in the denominator. Provide public member functions that perform each of the following tasks:

    a. Adding two Rational numbers. The result should be stored in reduced form.
    b. Subtracting two Rational numbers. The result should be stored in reduced form.
    c. Multiplying two Rational numbers. The result should be stored in reduced form.
    d. Dividing two Rational numbers. The result should be stored in reduced form.
    e. Printing Rational numbers in the form a/b, where a is the numerator and b is the denominator.
    f. Printing Rational numbers in floating-point format.

    • TBD


2009年11月27日 星期五

WPF DataGrid

1. Create a WPF Application through Visual Studio 2008 SP1 and Dot Net Framework 3.5 SP1.

In Windows1.xaml

< Window x:Class="WpfDataGrid.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dg="http://schemas.microsoft.com/wpf/2008/toolkit"
Title="Window1" Height="300" Width="600">




< dg:DataGridTextColumn Header="First Name" Binding="{Binding Path=FirstName}"/>
< dg:DataGridTextColumn Header="Last Name" Binding="{Binding Path=LastName}"/>
< dg:DataGridTextColumn Header="Address" Binding="{Binding Path=Address}"/>
< dg:DataGridCheckBoxColumn Header="New?" Binding="{Binding Path=IsNew}"/>
< dg:DataGridCheckBoxColumn Header="Subscribed?" Binding="{Binding Path=IsSubscribed}"/>







In Windows1.xaml.cs
First, define a class to generate data to display.

public class Customer
{
public String FirstName { get; set; }
public String LastName { get; set; }
public String Address { get; set; }
public Boolean IsNew { get; set; }

// A null value for IsSubscribed can indicate
// "no preference" or "no response".
public Boolean? IsSubscribed { get; set; }

public Customer(String firstName, String lastName,
String address, Boolean isNew, Boolean? isSubscribed)
{
this.FirstName = firstName;
this.LastName = lastName;
this.Address = address;
this.IsNew = isNew;
this.IsSubscribed = isSubscribed;
}

public static ObservableCollection GetSampleCustomerList()
{
return new ObservableCollection (new Customer[4] {
new Customer("A.", "Zero",
"12 North Third Street, Apartment 45",
false, true),
new Customer("B.", "One",
"34 West Fifth Street, Apartment 67",
false, false),
new Customer("C.", "Two",
"56 East Seventh Street, Apartment 89",
true, null),
new Customer("D.", "Three",
"78 South Ninth Street, Apartment 10",
true, true)
});
}
}


By this way, we could see the simple WPF DataGrid.


Run this program, one problem occured. If you would like to change the status of the checkbox, you have to click twice. First click will focus on the row, and second click will change the state of the checkbox.
The solution is to use DataGridTemplateColumn to replace the DataGridCheckBoxColumn.

















At this moment, everything seems to be ok. But in practice, if we could not make sure how many columns we have, what should we do?
So we need to create DataGrid programmatically.

In Windows1.xaml, we don't need the defination of the columns, just leave the declaration of < dg:DataGrid/>.

< Window x:Class="WpfDataGrid.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dg="http://schemas.microsoft.com/wpf/2008/toolkit"
Title="Window1" Height="300" Width="600">


< dg:DataGrid AutoGenerateColumns="False" Margin="22,24,20,26" Name="dataGrid"/>





In Windows.xaml.cs, I wrote a method InitDataGrid and put it after InitializeComponent().

private void InitDataGrid()
{
dataGrid.ItemsSource = Customer.GetSampleCustomerList();

dataGrid.Columns.Clear();

dataGrid.Columns.Add(GetTextColumn("First Name", "FirstName"));
dataGrid.Columns.Add(GetTextColumn("Last Name", "LastName"));
dataGrid.Columns.Add(GetTextColumn("Address", "Address"));
dataGrid.Columns.Add(GetCheckBoxColumn("New?", "IsNew"));
dataGrid.Columns.Add(GetCheckBoxColumn("Subscribed?", "IsSubscribed"));
}


private DataGridTextColumn GetTextColumn(string _header, string _binding)
{
DataGridTextColumn col = new DataGridTextColumn();
col.Header = _header;
if (_binding != null && _binding != "")
col.Binding = GetBinding(_binding, BindingMode.OneWay);
return col;
}


private DataGridTemplateColumn GetCheckBoxColumn(string _header, string _binding)
{
DataGridTemplateColumn col = new DataGridTemplateColumn();
col.Header = _header;

Dictionary values = new Dictionary();
//values.Add(CheckBox.StyleProperty, FindResource("DataGridCheckBoxStyle"));

Dictionary bindings = new Dictionary();
bindings.Add(CheckBox.IsCheckedProperty, GetBinding(_binding, BindingMode.TwoWay));

col.CellTemplate = GetDataTemplate(typeof(CheckBox), values, bindings);
return col;
}


private DataTemplate GetDataTemplate(Type _t, Dictionary _values,
Dictionary _bindings)
{
DataTemplate dt = new DataTemplate();
FrameworkElementFactory factory = new FrameworkElementFactory(_t);
dt.VisualTree = factory;
//SetValue
foreach (KeyValuePair kvp in _values)
{
factory.SetValue(kvp.Key, kvp.Value);
}
//SetBinding
foreach (KeyValuePair kvp in _bindings)
{
factory.SetBinding(kvp.Key, kvp.Value);
}
return dt;
}


private Binding GetBinding(string _path, BindingMode _mode)
{
Binding binding = new Binding();
binding.Path = new PropertyPath(_path);
binding.Mode = _mode;
return binding;
}


You could download the solution from here.
If you use Firefox, you may see strange syntax. If so, try to use IE or just download the source code.

2009年11月26日 星期四

C# Timestamp

1.Define a class, HiResDateTime

public class HiResDateTime
{
private static DateTime _startTime;
private static System.Diagnostics.Stopwatch _stopWatch = null;
private static TimeSpan _maxIdle = TimeSpan.FromSeconds(10);

public static DateTime UtcNow
{
get
{
if ((_stopWatch == null) ||
(_startTime.Add(_maxIdle) < DateTime.UtcNow))
{
Reset();
}
return _startTime.AddTicks(_stopWatch.Elapsed.Ticks);
}
}

private static void Reset()
{
_startTime = DateTime.UtcNow;
_stopWatch = System.Diagnostics.Stopwatch.StartNew();
}
}


2.How to use:

Console.WriteLine("{0}", HiResDateTime.UtcNow.ToString("yyyyMMddHHmmssffff"));

2009年11月21日 星期六

WRONG HOLE with DJ Lubel, Taryn Southern and Scott Baio



I took her on a date things seemed so bright
I knew I would not need my youporn tonight
We go to her place and we fooled around
We throw all our clothes to the ground

We begin as she turns out the lights
I start but feel something so very extra tight
I hear her cry and I see her frown
I look at the condom it is all brown

Last night I stuck it in the wrong hole
I'm so sorry from the bottom of my soul
Cause I stuck it in the wrong hole

Try some preparation H it'll make you feel better
In my defense those holes are so close together
Oh baby baby don't feel defiled
It's a common accident during doggy style

It was so dark I couldn't see so good
I had no idea where I put my wood
I want to make things better want to make it alright
If you want you can put on a strap on and give it back to me all night ( I'd rather if she didn't)

Last night I stuck it in the wrong hole
I'm so sorry from the bottom of my soul

I never ever want to make you feel hurting
I guess that's why God made that hole not for inserting
Tell me how you feel baby please don't pause
Now I know how they feel in that HBO show OZ
Maybe take some advit your pain it will fix
From the way you are walking you can compete in the special olympics
If this was Alabama we would be on trial
That's how my mom took my temperature when I was a child

I've got a confession and I think you wont mind
I kinda liked when you put it in my behind
I don't know baby I'm no Sodomite
Can't we just try it again tonight?

Alright!

Every night I stick it in the wrong hole
It's so much fun and we don't need no birth control
When we stick it in the wrong hole.

I stuck in your ass.

2009年11月13日 星期五

C# Thread Implementation

I will demonstrate 3 types of thread implementations in C#. They are ThreadPool.QueueUserWorkItem(), Thread, and Win32 thread.

1. ThreadPool.QueueUserWorkItem

class Program
{
static void Main(string[] args)
{
string message = "Hi";
ThreadPool.QueueUserWorkItem(DoSomething, message);
}

//The method to be used in ThreadPool.QueueUserWorkItem, must has one parameter
//with object
static void DoSomething(object stateInfo)
{
Console.WriteLine("DoSomething: stateInfo={0}", stateInfo.ToString());
}
}


2. Thread
First, create a Daemon class. This class has a constructor with values. Besides, it has a delegate callback function.

public class Daemon
{
private string title;
private int val;

private DelegateCallbackFunc callback;

public Daemon(string _title, int _val, DelegateCallbackFunc _callback)
{
title = _title;
val = _val;
callback = _callback;
}

public void DoSomething()
{
try
{
Console.WriteLine("DoSomething: _title={0}, _val={1}", title, val);
title = title + " Dude!";
val = val + 1;

//Callback
if (callback != null)
callback(title, val);
}
catch (ThreadAbortException ex)
{

}
finally
{

}

}
}

//Declare a delegate callback method
public delegate void DelegateCallbackFunc(string _title, int _val);

Second, create and start the thread.

class Program
{
static void Main(string[] args)
{
Daemon d = new Daemon("Hi", 0, new DelegateCallbackFunc(CallbackFunc));
Thread t = new Thread(new ThreadStart(d.DoSomething));
t.Start();
}

public static void CallbackFunc(string _title, int _val)
{
Console.WriteLine("CallbackFunc: _title={0}, _val={1}", _title, _val);
}
}

3. Use win32 thread
First, create a class with extern declaration.

public class Win32
{
[DllImport("kernel32.dll", SetLastError = true)]
public static extern int CreateThread(ref SECURITY_ATTRIBUTES lpThreadAttributes,
int dwStackSize, Delegate lpStartAddress, ref object lpParameter,
int dwCreationFlags, ref int lpThreadId);

[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}
}

public delegate void ExecuteFunc();

Second, use this Win32 class in main program.

class Program
{
static void Main(string[] args)
{
Daemon d = new Daemon("Hi", 0, new DelegateCallbackFunc(CallbackFunc));
ExecuteFunc ef = new ExecuteFunc(d.DoSomething);

Win32.SECURITY_ATTRIBUTES sa = new Win32.SECURITY_ATTRIBUTES();
object lpParameter = new object();
int lpThreadId = 0;
Win32.CreateThread(ref sa, 0, ef, ref lpParameter, 0, ref lpThreadId);
}
}


Source code is here.