I searched the net but didn't get the code so publishing it here.
class OracleTimeStamp
{
public:
static Timestamp ToTimestamp(Oracle::ENV env, const struct timeval &tv);
static void ToEpoch(const Timestamp& ts, struct timeval &tv);
};
Timestamp
OracleTimeStamp::ToTimestamp(Oracle::ENV env, const struct timeval &tv)
{
char buffer[100] = {0};
time_t curtime = tv.tv_sec;
strftime(buffer,30,"%Y %m %d %H %M %S",localtime(&curtime));
stringstream strstream;
strstream.clear();
strstream << buffer << " " << tv.tv_usec;
int year;
int month;
int day;
int hour;
int minute;
int seconds;
long int millisec;
strstream >> year;
strstream >> month;
strstream >> day;
strstream >> hour;
strstream >> minute;
strstream >> seconds;
strstream >> millisec;
millisec *= 1000;
Timestamp ts(env, year, month, day, hour, minute, seconds, millisec);
return ts;
}
void
OracleTimeStamp::ToEpoch(const Timestamp& ts, struct timeval &tv)
{
string date_time = ts.toText("yyyy mm dd hh24:mi:ss.FF", 6);
date_time.replace(13, 1, " ");
date_time.replace(16, 1, " ");
date_time.replace(19, 1, " ");
stringstream date_time_stream;
date_time_stream.clear();
date_time_stream << date_time;
struct tm time_val;
date_time_stream >> time_val.tm_year;
time_val.tm_year -= 1900;
date_time_stream >> time_val.tm_mon;
time_val.tm_mon -= 1;
date_time_stream >> time_val.tm_mday;
date_time_stream >> time_val.tm_hour;
date_time_stream >> time_val.tm_min;
date_time_stream >> time_val.tm_sec;
date_time_stream >> tv.tv_usec;
// Assign the values to struct tm
// Then get the microsecond value directly into tv.tv_usec
time_t time_in_sec;
time_in_sec = mktime(&time_val);
tv.tv_sec = time_in_sec;
return;
}
Programming Puzzles and Tricks
Come up with your puzzles in programming and get the answers.
Tuesday, March 30, 2010
C++ function overloading on Return Type
It is possible to overload the functions based on return type.
I am not talking about the functions with 'CV' qualifier.
For e.g,
class C
{
public:
void foo() const;
int foo() volatile;
double foo() const volatile;
};
This way we can have overloading. But in reality they are not overloaded for same object. It depends on what kind of object. For eg, when you create const object of C, it will call void foo(), similarly for volatile , it is int foo() etc...
So in real sense they are not overloaded.
Where as if you use template, you can overload the functions based on the return type.
class OverLoad
{
public:
template < T > // just declaration , no definition
T GetMe();
};
template <>
int
OverLoad::GetMe()
{
return int;
}
template <>
std::string
OverLoad::GetMe()
{
return std::string();
}template <>
double
OverLoad::GetMe()
{
return 2.2;
}
etc...
These functions can be called by the same object.
I am not talking about the functions with 'CV' qualifier.
For e.g,
class C
{
public:
void foo() const;
int foo() volatile;
double foo() const volatile;
};
This way we can have overloading. But in reality they are not overloaded for same object. It depends on what kind of object. For eg, when you create const object of C, it will call void foo(), similarly for volatile , it is int foo() etc...
So in real sense they are not overloaded.
Where as if you use template, you can overload the functions based on the return type.
class OverLoad
{
public:
template < T > // just declaration , no definition
T GetMe();
};
template <>
int
OverLoad::GetMe()
{
return int;
}
template <>
std::string
OverLoad::GetMe()
{
return std::string();
}template <>
double
OverLoad::GetMe()
{
return 2.2;
}
etc...
These functions can be called by the same object.
Friday, March 28, 2008
Template Metaprogramming
We must have seen that C++ has incorporated template metaprogramming.
It also mentions that it gets calculated at compile time ( Wow! ).
This saves the execution time of a program which is great.
So lets see the standard example give in C++ Templates book by Vandevoorde/Josuttis.
template <int N>
class Pow3 {
public:
enum { result = 3 * Pow3<N-1>::result };
};
template <>
class Pow3<0> {
public:
enum { result = 1 };
};
Now when you write the program like :
int main() try {
cout << " 3 to power 3 is : " << Pow3<3>::result << endl;
return 0;
} catch(...) {
cout << "Uncaught exception..." << endl;
}
It prints : 27.
Conceptually enums are constants and constants are to be given value at compile time only.
Therefore, we can assume that Pow3<3>::result was having 27 as value.
But how will you prove that compiler did the actual calculation for you ???
If you are not sure check out the reply for this blog.
It also mentions that it gets calculated at compile time ( Wow! ).
This saves the execution time of a program which is great.
So lets see the standard example give in C++ Templates book by Vandevoorde/Josuttis.
template <int N>
class Pow3 {
public:
enum { result = 3 * Pow3<N-1>::result };
};
template <>
class Pow3<0> {
public:
enum { result = 1 };
};
Now when you write the program like :
int main() try {
cout << " 3 to power 3 is : " << Pow3<3>::result << endl;
return 0;
} catch(...) {
cout << "Uncaught exception..." << endl;
}
It prints : 27.
Conceptually enums are constants and constants are to be given value at compile time only.
Therefore, we can assume that Pow3<3>::result was having 27 as value.
But how will you prove that compiler did the actual calculation for you ???
If you are not sure check out the reply for this blog.
Thursday, March 6, 2008
Depth First Search without writing code
I am going to show how depth first search ( DFS ) without using any algorithm.
Actually I am making use of the algorithm which compilers already have implemented :-)
The virtual inheritance property is compiler makes sure that it follows the depth first search logic to instantiate the virtual base classes.
Here is the code and output:
/*
* =====================================================================================
*
* Filename: DepthFirstSearch.cpp
*
* Description: Without writing code DFS implementation
* A B C D
* \ / \ /
* E F
* \ /
* \ /
* G
* Version: 1.0
* Created: 03/06/2008 11:21:34 AM IST
* Revision: none
* Compiler: gcc
*
* Author: Siddhartha Singh :
* Company:
*
* =====================================================================================
*/
#include
using std::cout;
using std::endl;
class A {
public:
A() {
cout << "A()" << endl;
}
};
class B {
public:
B() {
cout << "B()" << endl;
}
};
class C {
public:
C() {
cout << "C()" << endl;
}
};
class D {
public:
D() {
cout << "D()" << endl;
}
};
class E : public virtual A, virtual public B {
public:
E() {
cout << "E()" << endl;
}
};
class F : public virtual C, virtual public D {
public:
F() {
cout << "F()" << endl;
}
};
class G : virtual public E, virtual public F {
public:
G() {
cout << "G()" << endl;
}
};
int main() try {
G g;
return 0;
} catch(...) {
cout << "Uncaught exception..." << endl;
}
--------------------------------------------------------
Output :
A()
B()
E()
C()
D()
F()
G()
So no need to write algo to find how DFS works ( Short cut to success ;-)
Actually I am making use of the algorithm which compilers already have implemented :-)
The virtual inheritance property is compiler makes sure that it follows the depth first search logic to instantiate the virtual base classes.
Here is the code and output:
/*
* =====================================================================================
*
* Filename: DepthFirstSearch.cpp
*
* Description: Without writing code DFS implementation
* A B C D
* \ / \ /
* E F
* \ /
* \ /
* G
* Version: 1.0
* Created: 03/06/2008 11:21:34 AM IST
* Revision: none
* Compiler: gcc
*
* Author: Siddhartha Singh :
* Company:
*
* =====================================================================================
*/
#include
using std::cout;
using std::endl;
class A {
public:
A() {
cout << "A()" << endl;
}
};
class B {
public:
B() {
cout << "B()" << endl;
}
};
class C {
public:
C() {
cout << "C()" << endl;
}
};
class D {
public:
D() {
cout << "D()" << endl;
}
};
class E : public virtual A, virtual public B {
public:
E() {
cout << "E()" << endl;
}
};
class F : public virtual C, virtual public D {
public:
F() {
cout << "F()" << endl;
}
};
class G : virtual public E, virtual public F {
public:
G() {
cout << "G()" << endl;
}
};
int main() try {
G g;
return 0;
} catch(...) {
cout << "Uncaught exception..." << endl;
}
--------------------------------------------------------
Output :
A()
B()
E()
C()
D()
F()
G()
So no need to write algo to find how DFS works ( Short cut to success ;-)
Wednesday, February 20, 2008
Diamond Ring formation is Not a problem But a solution
Many a times in C++ people ( mostly interviewers ) ask : What is Diamond Ring problem?
The reply should be : It is not a problem rather a solution.
Scenario : When there is a common base class inherited by a child from immediate base classes. It leads to ambiguity. For e.g., Consider this situiation
class B : public A {};
class C : public A {};
class D : public B, public C {} //this leads to two instances of A in D , one from B another from C
The diagram looks like :
A A
\ /
B C
\ /
D
This causes two instances of A to be in D. Which leads to ambiguity problem the moment you create an instance of D.
The way to resolve is A should be inherited to B and C virtually.
i.e
class B : virtual public A {}
class C : public virtual A {}
class D : public B, public C {}
When it is virtual inheritance, it differs from normal inheritance. Standard doesn't talk about how to implement it. But the behavior is when you create any child class' object in the hierarchy what is guaranteed is the A class' constructor gets called directly from the child class ( I will write another post as how to create final class in C++ using virtual inheritance ).
In case of virtual inheritance the diagram would look like (diamond ring). This solves the ambiguity problem by having reference to A in B and C and not the instance of A.
A
/ \
B C
\ /
D
Final wordings : Diamond ring is actually a solution and not a problem.
The reply should be : It is not a problem rather a solution.
Scenario : When there is a common base class inherited by a child from immediate base classes. It leads to ambiguity. For e.g., Consider this situiation
class B : public A {};
class C : public A {};
class D : public B, public C {} //this leads to two instances of A in D , one from B another from C
The diagram looks like :
A A
\ /
B C
\ /
D
This causes two instances of A to be in D. Which leads to ambiguity problem the moment you create an instance of D.
The way to resolve is A should be inherited to B and C virtually.
i.e
class B : virtual public A {}
class C : public virtual A {}
class D : public B, public C {}
When it is virtual inheritance, it differs from normal inheritance. Standard doesn't talk about how to implement it. But the behavior is when you create any child class' object in the hierarchy what is guaranteed is the A class' constructor gets called directly from the child class ( I will write another post as how to create final class in C++ using virtual inheritance ).
In case of virtual inheritance the diagram would look like (diamond ring). This solves the ambiguity problem by having reference to A in B and C and not the instance of A.
A
/ \
B C
\ /
D
Final wordings : Diamond ring is actually a solution and not a problem.
Monday, October 15, 2007
Is Strategy Pattern any different than Polymorphism of OOPs
I am not sure if Strategy ( or Policy ) pattern is any different than simple use of Polymorphism with Encapsulation of OOPs theory.
So why should it be a part of GoF Design Pattern.
Comments welcome
Cheers,
Siddhartha
So why should it be a part of GoF Design Pattern.
Comments welcome
Cheers,
Siddhartha
Thursday, October 4, 2007
Item 10 of More Effective C++ in an easy way
Though Scott's view is that I don't have RAII, but my approach saves un-necessary complications of using auto_ptr / smart_ptr. I respect Scott's view at the same time many people are not aware of the advantages of auto_ptr / smart_ptr and why to have more learning curve when a user doesn't want it at that time.
Basically I have initialized the pointers and then allocated memory to prevent resource leak during construction in the initialization list.
#include <iostream>
#include <string>
#include <list>
using namespace std;
class Image {
public:
Image(const string& imageDataFileName) {
fileName = imageDataFileName;
}
~Image() {
cout << "~Image()..." << endl;
}
private:
string fileName;
};
class AudioClip {
public:
AudioClip(const string& audioDataFileName) {
fileName = audioDataFileName;
throw exception();
}
~AudioClip() {
cout << "~AudioClip()..." << endl;
}
private:
string fileName;
};
class PhoneNumber {
public:
PhoneNumber(const int number) {
phNumber = number;
}
private:
int phNumber;
};
class BookEntry {
public:
BookEntry(const string& name,
const string& address = "",
const string& imageFileName = " ",
const string& audioClipFileName = " ") try : theName(name),theAddress(address),
// theImage(0),theAudioClip(0), // so sad that multiple initialization is not allowed
theImage(imageFileName != ""
? theImage=0, new Image(imageFileName) //This is the trick ',' operator does the job
: 0),
theAudioClip(audioClipFileName != ""
? theAudioClip = 0,new AudioClip(audioClipFileName)
: 0) {
} catch(...) {
cout << "exception caught during construction of BookEntry..." << endl;
if(theImage) delete theImage;
if(theAudioClip) delete theAudioClip;
throw;
}
~BookEntry() {
delete theImage;
delete theAudioClip;
}
void addPhoneNumber ( const PhoneNumber& number);
private:
string theName;
string theAddress;
list < PhoneNumber> thePhones;
Image *theImage;
AudioClip *theAudioClip;
};
int main() try {
cout << "Hello World!" << endl;
BookEntry bookEntry("sid");
return 0;
}
catch(exception &e) {
cout << " exception caught " << endl;
}
catch(...) {
cout << "Uncaught exception..." << endl;
}
Basically I have initialized the pointers and then allocated memory to prevent resource leak during construction in the initialization list.
#include <iostream>
#include <string>
#include <list>
using namespace std;
class Image {
public:
Image(const string& imageDataFileName) {
fileName = imageDataFileName;
}
~Image() {
cout << "~Image()..." << endl;
}
private:
string fileName;
};
class AudioClip {
public:
AudioClip(const string& audioDataFileName) {
fileName = audioDataFileName;
throw exception();
}
~AudioClip() {
cout << "~AudioClip()..." << endl;
}
private:
string fileName;
};
class PhoneNumber {
public:
PhoneNumber(const int number) {
phNumber = number;
}
private:
int phNumber;
};
class BookEntry {
public:
BookEntry(const string& name,
const string& address = "",
const string& imageFileName = " ",
const string& audioClipFileName = " ") try : theName(name),theAddress(address),
// theImage(0),theAudioClip(0), // so sad that multiple initialization is not allowed
theImage(imageFileName != ""
? theImage=0, new Image(imageFileName) //This is the trick ',' operator does the job
: 0),
theAudioClip(audioClipFileName != ""
? theAudioClip = 0,new AudioClip(audioClipFileName)
: 0) {
} catch(...) {
cout << "exception caught during construction of BookEntry..." << endl;
if(theImage) delete theImage;
if(theAudioClip) delete theAudioClip;
throw;
}
~BookEntry() {
delete theImage;
delete theAudioClip;
}
void addPhoneNumber ( const PhoneNumber& number);
private:
string theName;
string theAddress;
list < PhoneNumber> thePhones;
Image *theImage;
AudioClip *theAudioClip;
};
int main() try {
cout << "Hello World!" << endl;
BookEntry bookEntry("sid");
return 0;
}
catch(exception &e) {
cout << " exception caught " << endl;
}
catch(...) {
cout << "Uncaught exception..." << endl;
}
Sunday, September 30, 2007
Subtraction in Binary
What do you use to subtract two binary numbers?
two's compliment?
Why to have so complicated approach ( of course on Paper )
Just use our basic decimal system approach and subtract the number normally.
For e.g.,
binary decimal
100 4
011 3
subtract 4-3 = 1
Just think that 4 is hundred in binary and 3 is eleven ( as it looks like visually ).
Now subtract 11 from 100 , you will get 89. Now replace 8 by 0 and 9 by 1
you will get 1 as the answer in binary.
When you subtract two binary numbers as decimal numbers, you have four possible numbers 0,1 , 8 and 9. Now since the answer should be in binary, 8 is even so replace by 0 ( as 8 mod 2 = 0) and 9 is odd so replace by 1 ( as 9 mod 2 = 1 ).
See how easy it goes !
two's compliment?
Why to have so complicated approach ( of course on Paper )
Just use our basic decimal system approach and subtract the number normally.
For e.g.,
binary decimal
100 4
011 3
subtract 4-3 = 1
Just think that 4 is hundred in binary and 3 is eleven ( as it looks like visually ).
Now subtract 11 from 100 , you will get 89. Now replace 8 by 0 and 9 by 1
you will get 1 as the answer in binary.
When you subtract two binary numbers as decimal numbers, you have four possible numbers 0,1 , 8 and 9. Now since the answer should be in binary, 8 is even so replace by 0 ( as 8 mod 2 = 0) and 9 is odd so replace by 1 ( as 9 mod 2 = 1 ).
See how easy it goes !
Thursday, September 27, 2007
Singly linked list as Doubly
With the linked list the major concern is the space consumed by the pointer in the structure.
For singly linked list, there is one extra pointer in each node to point to the next node.
Similarly in doubly linked list, there are two extra pointers in each node, one point to previous node and other point to next node.
Now depending upon the machine word size, if it is 32 bit, the pointer consume 4 bytes and in 64 bit machine it consumes 64 bits. Which is quite a bit.
I have written a code in C++, which just take the space of a singly linked list but it can be used to traverse both ways like doubly linked list.
#include
using std::cout;
using std::endl;
template
class NODE {
public:
NODE() {
next = NULL;
}
NODE(const TYPE data) : data(data), next(NULL) { }
TYPE getData() {
return data;
}
NODE *getNext() {
return next;
}
void setNext(long next) {
this->next = reinterpret_cast(next);
}
private:
TYPE data;
NODE *next;
};
template
class LIST {
public:
LIST() {
XORdata = head = tail = NULL;
}
void add(TYPE data);
void traverseForward();
void traverseBackward();
private:
NODE *head;
NODE *tail;
NODE *XORdata;
};
template
void LIST::traverseBackward() {
NODE *tempTail = tail;
NODE *tempTail1 = tail;
NODE *tempXOR = XORdata;
while(tempTail) {
cout << "Data : " <<>getData() << p1 =" reinterpret_cast<"> (tempTail->getNext());
long p2 = reinterpret_cast<> (tempXOR);
tempTail = reinterpret_cast *>(p1^p2);
tempXOR = tempTail1;
tempTail1 = tempTail;
}
}
template
void LIST::traverseForward() {
NODE *tempHead = head;
NODE *tempHead1 = head;
NODE *tempXOR = NULL;
while(tempHead) {
cout << "Data : " <<>getData() <<>getNext()) break;
long p1 = reinterpret_cast<> (tempHead->getNext());
long p2 = reinterpret_cast<> (tempXOR);
tempHead = reinterpret_cast *>(p1^p2);
tempXOR = tempHead1;
tempHead1 = tempHead;
}
}
template
void LIST::add(TYPE data) {
if(NULL == head) {
tail = head = new NODE(data);
} else {
NODE *temp = new NODE(data);
long p1 = reinterpret_cast(XORdata);
long p2 = reinterpret_cast(temp);
tail->setNext(p1^p2);
XORdata = tail;
tail = temp;
}
}
int main(int argc, char **argv, char **arge) try {
LIST list;
for(int i = 10; i < 16; ++i )
list.add ( i);
list.traverseForward();
cout << "Now moving backward !!!" << endl;
list.traverseBackward();
return 0;
} catch(...) {
cout << "Uncaught exception!" << endl;
}
For singly linked list, there is one extra pointer in each node to point to the next node.
Similarly in doubly linked list, there are two extra pointers in each node, one point to previous node and other point to next node.
Now depending upon the machine word size, if it is 32 bit, the pointer consume 4 bytes and in 64 bit machine it consumes 64 bits. Which is quite a bit.
I have written a code in C++, which just take the space of a singly linked list but it can be used to traverse both ways like doubly linked list.
#include
using std::cout;
using std::endl;
template
class NODE {
public:
NODE() {
next = NULL;
}
NODE(const TYPE data) : data(data), next(NULL) { }
TYPE getData() {
return data;
}
NODE *getNext() {
return next;
}
void setNext(long next) {
this->next = reinterpret_cast
}
private:
TYPE data;
NODE *next;
};
template
class LIST {
public:
LIST() {
XORdata = head = tail = NULL;
}
void add(TYPE data);
void traverseForward();
void traverseBackward();
private:
NODE
NODE
NODE
};
template
void LIST
NODE
NODE
NODE
while(tempTail) {
cout << "Data : " <<>getData() << p1 =" reinterpret_cast<"> (tempTail->getNext());
long p2 = reinterpret_cast<> (tempXOR);
tempTail = reinterpret_cast
tempXOR = tempTail1;
tempTail1 = tempTail;
}
}
template
void LIST
NODE
NODE
NODE
while(tempHead) {
cout << "Data : " <<>getData() <<>getNext()) break;
long p1 = reinterpret_cast<> (tempHead->getNext());
long p2 = reinterpret_cast<> (tempXOR);
tempHead = reinterpret_cast
tempXOR = tempHead1;
tempHead1 = tempHead;
}
}
template
void LIST
if(NULL == head) {
tail = head = new NODE
} else {
NODE
long p1 = reinterpret_cast
long p2 = reinterpret_cast
tail->setNext(p1^p2);
XORdata = tail;
tail = temp;
}
}
int main(int argc, char **argv, char **arge) try {
LIST
for(int i = 10; i < 16; ++i )
list.add ( i);
list.traverseForward();
cout << "Now moving backward !!!" << endl;
list.traverseBackward();
return 0;
} catch(...) {
cout << "Uncaught exception!" << endl;
}
Tuesday, September 25, 2007
Cricket Puzzle
Contrary to an Indian, I don't like cricket at all ( at least before twenty 20 ).
Though when I came through the below mentioned cricket puzzle and having interest in solving puzzles. I somehow gained interest in knowing the rules. So people who know cricket should have a look.
Here it goes:
There are last 2 balls to bowl. Both the batsman are on 94 each.
The team require 7 runs to win. Both has to score century as well.
How will they help their team to win.
Though when I came through the below mentioned cricket puzzle and having interest in solving puzzles. I somehow gained interest in knowing the rules. So people who know cricket should have a look.
Here it goes:
There are last 2 balls to bowl. Both the batsman are on 94 each.
The team require 7 runs to win. Both has to score century as well.
How will they help their team to win.
Thursday, September 20, 2007
Atomic Compare and Swap algorithm
Is there anyone who knows how to make CSA in C/C++ to make it atomic ?
This would help in having producer-consumer lock free.
This would help in having producer-consumer lock free.
Why VTABLE is required for Abstract class in C++
I am not sure why VTABLE is required in C++ after all it is just an interface and it always refer to its derived classes only. One can manipulate the pointer to upcast but that has got no meaning ( logical ).
Therefore, my main question is why not optimize it and remove the VTABLE from abstract class.
I am looking for a satisfying answer.
Therefore, my main question is why not optimize it and remove the VTABLE from abstract class.
I am looking for a satisfying answer.
Subscribe to:
Posts (Atom)