Monday, May 14, 2007
Converting Numbers to Strings and Strings to Numbers in C++
http://www.parashift.com/c++-faq-lite/misc-technical-issues.html
Saturday, March 24, 2007
Managing C++ Objects
http://billharlan.com/pub/papers/Managing_Cpp_Objects.html
Managing C++ Objects
Here are some guidelines I have found useful for writing C++ classes. There are many good books on the subject, but they have not been sufficient to keep me out of trouble. The first time I returned to writing C++ after a year of writing Java, I was appalled at how much my design was constrained by managing the lifetime of objects. When C++ classes share objects, then they must negotiate who owns the object. Garbage collection is not available, and smart pointers often fall short.
§ Simple constructors
If your preferred constructor takes arguments, then define a default constructor (no arguments) and make it protected. Derived classes will require this method.
Define protected initialization methods void init(...) with arguments, and call them from your preferred constructors. Each initialization method should set all member variables to a valid state, without relying on constructor initialization blocks. Use these initialization methods from your public copy constructor and assignment operator, if required.
Remove everything from constructor initialization blocks except the simplest constructor of a superclass (preferably a default constructor). Call protected superclass initialization methods from the subclass initialization methods. Make initialization methods non-virtual to avoid hiding by derived classes (since the name will always be init(...).)
All init(...) methods should first call the init() equivalent of a default constructor, to initialize all member pointers, perhaps to nulls. If your constructor fails and throws an exception, then the destructor can be called safely.
Your constructors will now be much more flexible and robust. Derived class constructors can manipulate their arguments before initializing the superclass. (Superclass constructors can only be called in initialization blocks.) Within a single class, you can share more initialization between alternative constructors. You need not worry about the order of initialization blocks.
§ Implement "The Big Three"
Always define a copy constructor and an assignment operator. Don't let anyone use the default implementations. If your class contains pointers to objects which your class does not plan to delete, then just make these two methods private, without an implementation. Do not implement versions that make shallow copies. You do not want a user to accidentally make copies on the stack if required to call a non-copy constructor or clone method instead. Making copies of objects should be a very deliberate step Conversion operators (single-argument constructors) can be dangerous for the same reason.
Define a virtual destructor unless you never want anyone to derive from your class. Define a protected non-virtual void dispose() method that deletes the object's resources, then call this method from your destructor. (This is the destructor equivalent of an init() method.) You can use this method in assignment operators, initialization, and derived classes.
§ No references as members
A class member should never be a reference, whether const or non-const. A member's object reference can only be set in the initialization block of a constructor. You will not be able to set a reference member in an initialization method. A reference permanently prevents your class from replacing the object dynamically.
§ Optional ownership
If a constructor or initialization method takes a non-const object as an argument, then you must decide whether this wrapper class will assume ownership of this object. The destructor of a Bridge or Decorator class might need to delete the contained object. Or maybe not. If you have any doubt, then the constructor should allow the user to choose.
§ No pointers as arguments
Pass all objects to class methods and constructors as references. There is absolutely no advantage to passing objects as pointers. This rule is equally valid whether the objects are const or not.
I've already recommended that all class members be saved as pointers. You can easily take the address of an argument reference (with an ampersand) and assign it to your member pointer. Some C++ programmers do not seem to realize that the address of a reference is the same as the address of the original object. So they pass pointers when they want to save the argument, and references when they do not. This is a poor form of documentation, based on a misunderstanding.
If an object is passed to a constructor or initialization method, the user can expect the class to hang onto it. If a method saves an object from an argument, choose an appropriate name, like setColor(Color&) or addInterpolator(Interpolator&).
The worst excuse for using a pointer as an argument is that you want to give it a default value of null (0). You still have to document what a null object is supposed to mean. Worse, the user may overlook that the argument exists or is optional. Declare a separate method that lacks the extra argument. The effort is negligible.
§ Returning objects
One can always return objects from class methods by reference, either const or non-const. A user can take the address of the reference, if necessary, to save the object. But there are no drawbacks to returning objects always as pointers. Consistency is preferable, and most API's return pointers.
If you return an object allocated on the heap (with a new), then be clear who has ownership of the object--your class, the recipient, or a third party.
Think about whether you are breaking encapsulation of member data in a way that will prevent modification later.
Never return a reference to a class member allocated on the stack in the header file. If your class replaces the value, then the user may be left with an invalid reference, even though your object still exists. (Other reasons: Your class will never be able to remove the object as a member. A user may manipulate the logic of your class in unexpected ways.)
A method should modify an object constructed by the user by accepting it as a non-const reference. Returning the same object would be redundant and confusing.
§ Clean header files
A header file ideally includes only the header file of super-classes or of standard C++ libraries. All other classes can be forward declared, like class ClassName; or template class ClassName;. Forward declarations will greatly simplify your "make" dependencies and speed your builds. Repairs will be easier.
Member variables that are saved by value require your header to include another header file. Consider allocating such members on the heap, even if you must delete them in the destructor. Save member objects by value only when the default constructor creates a lightweight object with a useful state.
If you have reasons to put your entire implementation in the header file, then of course you cannot take advantage of forward declarations.
§ Write more Java
When you get a chance, write more Java to free your mind of such distractions. Your C++ will improve.
§ Examples
See an illustration of some of these patterns in [ ../code/cpp_prototype ] .
Bill Harlan
1998
Revision: 1.21 2004/09/14 18:01:26 harlan Exp $
Return to parent directory.
Managing C++ Objects
Here are some guidelines I have found useful for writing C++ classes. There are many good books on the subject, but they have not been sufficient to keep me out of trouble. The first time I returned to writing C++ after a year of writing Java, I was appalled at how much my design was constrained by managing the lifetime of objects. When C++ classes share objects, then they must negotiate who owns the object. Garbage collection is not available, and smart pointers often fall short.
§ Simple constructors
If your preferred constructor takes arguments, then define a default constructor (no arguments) and make it protected. Derived classes will require this method.
Define protected initialization methods void init(...) with arguments, and call them from your preferred constructors. Each initialization method should set all member variables to a valid state, without relying on constructor initialization blocks. Use these initialization methods from your public copy constructor and assignment operator, if required.
Remove everything from constructor initialization blocks except the simplest constructor of a superclass (preferably a default constructor). Call protected superclass initialization methods from the subclass initialization methods. Make initialization methods non-virtual to avoid hiding by derived classes (since the name will always be init(...).)
All init(...) methods should first call the init() equivalent of a default constructor, to initialize all member pointers, perhaps to nulls. If your constructor fails and throws an exception, then the destructor can be called safely.
Your constructors will now be much more flexible and robust. Derived class constructors can manipulate their arguments before initializing the superclass. (Superclass constructors can only be called in initialization blocks.) Within a single class, you can share more initialization between alternative constructors. You need not worry about the order of initialization blocks.
§ Implement "The Big Three"
Always define a copy constructor and an assignment operator. Don't let anyone use the default implementations. If your class contains pointers to objects which your class does not plan to delete, then just make these two methods private, without an implementation. Do not implement versions that make shallow copies. You do not want a user to accidentally make copies on the stack if required to call a non-copy constructor or clone method instead. Making copies of objects should be a very deliberate step Conversion operators (single-argument constructors) can be dangerous for the same reason.
Define a virtual destructor unless you never want anyone to derive from your class. Define a protected non-virtual void dispose() method that deletes the object's resources, then call this method from your destructor. (This is the destructor equivalent of an init() method.) You can use this method in assignment operators, initialization, and derived classes.
§ No references as members
A class member should never be a reference, whether const or non-const. A member's object reference can only be set in the initialization block of a constructor. You will not be able to set a reference member in an initialization method. A reference permanently prevents your class from replacing the object dynamically.
§ Optional ownership
If a constructor or initialization method takes a non-const object as an argument, then you must decide whether this wrapper class will assume ownership of this object. The destructor of a Bridge or Decorator class might need to delete the contained object. Or maybe not. If you have any doubt, then the constructor should allow the user to choose.
§ No pointers as arguments
Pass all objects to class methods and constructors as references. There is absolutely no advantage to passing objects as pointers. This rule is equally valid whether the objects are const or not.
I've already recommended that all class members be saved as pointers. You can easily take the address of an argument reference (with an ampersand) and assign it to your member pointer. Some C++ programmers do not seem to realize that the address of a reference is the same as the address of the original object. So they pass pointers when they want to save the argument, and references when they do not. This is a poor form of documentation, based on a misunderstanding.
If an object is passed to a constructor or initialization method, the user can expect the class to hang onto it. If a method saves an object from an argument, choose an appropriate name, like setColor(Color&) or addInterpolator(Interpolator&).
The worst excuse for using a pointer as an argument is that you want to give it a default value of null (0). You still have to document what a null object is supposed to mean. Worse, the user may overlook that the argument exists or is optional. Declare a separate method that lacks the extra argument. The effort is negligible.
§ Returning objects
One can always return objects from class methods by reference, either const or non-const. A user can take the address of the reference, if necessary, to save the object. But there are no drawbacks to returning objects always as pointers. Consistency is preferable, and most API's return pointers.
If you return an object allocated on the heap (with a new), then be clear who has ownership of the object--your class, the recipient, or a third party.
Think about whether you are breaking encapsulation of member data in a way that will prevent modification later.
Never return a reference to a class member allocated on the stack in the header file. If your class replaces the value, then the user may be left with an invalid reference, even though your object still exists. (Other reasons: Your class will never be able to remove the object as a member. A user may manipulate the logic of your class in unexpected ways.)
A method should modify an object constructed by the user by accepting it as a non-const reference. Returning the same object would be redundant and confusing.
§ Clean header files
A header file ideally includes only the header file of super-classes or of standard C++ libraries. All other classes can be forward declared, like class ClassName; or template class ClassName;. Forward declarations will greatly simplify your "make" dependencies and speed your builds. Repairs will be easier.
Member variables that are saved by value require your header to include another header file. Consider allocating such members on the heap, even if you must delete them in the destructor. Save member objects by value only when the default constructor creates a lightweight object with a useful state.
If you have reasons to put your entire implementation in the header file, then of course you cannot take advantage of forward declarations.
§ Write more Java
When you get a chance, write more Java to free your mind of such distractions. Your C++ will improve.
§ Examples
See an illustration of some of these patterns in [ ../code/cpp_prototype ] .
Bill Harlan
1998
Revision: 1.21 2004/09/14 18:01:26 harlan Exp $
Return to parent directory.
Thursday, January 11, 2007
Process start time in Unix
To find the start time of a process in unix use
ps -fu
zgrep "tosearch" *.gx | tr ',' '\12' | grep "tosearch"
ps -fu
zgrep "tosearch" *.gx | tr ',' '\12' | grep "tosearch"
Wednesday, January 10, 2007
Thread Safe and Thread Aware
From codeproject.com(http://www.codeproject.com/csharp/syncroot.asp)
Thread aware:
At any given time, at most one thread can be active on the object. The object is aware of the threads around it and protects itself from the threads by putting all the threads in a queue. Since there can be only a single thread active on the object at any given time, the object will always preserve its state. There will not be any synchronization problems.
Thread safe:
At a given time, multiple threads can be active on the object. The object knows how to deal with them. It has properly synchronized access to its shared resources. It can preserve its state data in this multi-threaded environment (i.e. it will not fall into intermediate and/or indeterminate states). It is safe to use this object in a multi-threaded environment.
Using an object that is neither thread-aware nor thread-safe may result in getting incorrect and random data and mysterious exceptions (due to trying to access the object when it is being used by a thread and is in an unstable, in-between state at the instant of access of the second thread).
Thread aware:
At any given time, at most one thread can be active on the object. The object is aware of the threads around it and protects itself from the threads by putting all the threads in a queue. Since there can be only a single thread active on the object at any given time, the object will always preserve its state. There will not be any synchronization problems.
Thread safe:
At a given time, multiple threads can be active on the object. The object knows how to deal with them. It has properly synchronized access to its shared resources. It can preserve its state data in this multi-threaded environment (i.e. it will not fall into intermediate and/or indeterminate states). It is safe to use this object in a multi-threaded environment.
Using an object that is neither thread-aware nor thread-safe may result in getting incorrect and random data and mysterious exceptions (due to trying to access the object when it is being used by a thread and is in an unstable, in-between state at the instant of access of the second thread).
Tuesday, January 09, 2007
Monday, December 04, 2006
Friday, December 01, 2006
Timers in C#
From msdn2.microsoft.com
private void CreateTimer()
{
System.Timers.Timer Timer1 = new System.Timers.Timer();
Timer1.Enabled = true;
Timer1.Interval = 5000;
Timer1.Elapsed +=
new System.Timers.ElapsedEventHandler(Timer1_Elapsed);
}
private void Timer1_Elapsed(object sender,
System.Timers.ElapsedEventArgs e)
{
System.Windows.Forms.MessageBox.Show("Elapsed!",
"Timer Event Raised!");
}
private void CreateTimer()
{
System.Timers.Timer Timer1 = new System.Timers.Timer();
Timer1.Enabled = true;
Timer1.Interval = 5000;
Timer1.Elapsed +=
new System.Timers.ElapsedEventHandler(Timer1_Elapsed);
}
private void Timer1_Elapsed(object sender,
System.Timers.ElapsedEventArgs e)
{
System.Windows.Forms.MessageBox.Show("Elapsed!",
"Timer Event Raised!");
}
Tuesday, November 28, 2006
Berkeley DB
From : http://pybsddb.sourceforge.net/ref/intro/terrain.html
1. Berkeley DB is an embedded database that supports fairly simple data access with a rich set of data management services
Data access in this context means
a) insert b)update c)search d)delete
Data management in this context means that
a)Concurrency b)Transactions c)Recovery
1. Berkeley DB is an embedded database that supports fairly simple data access with a rich set of data management services
Data access in this context means
a) insert b)update c)search d)delete
Data management in this context means that
a)Concurrency b)Transactions c)Recovery
Thursday, November 02, 2006
Unix Ports
From Google groups
netstat -lp
It will tell you which task is listening on the port.
fuser -v -n tcp 32768
Will tell you which task is listening on the specified port and under
which account it's running.
netstat -lp
It will tell you which task is listening on the port.
fuser -v -n tcp 32768
Will tell you which task is listening on the specified port and under
which account it's running.
Monday, October 30, 2006
IE6 duh?
urns out, IE doesn't like the script tags if they are using element minimization. I got the page rendering just as I intended by changing the tag to look like this:
Doing some research, I came across this post in theList by Eric Vitiello which clarifies this more. Apparently the DTD declaration for the script tag says , and the XHTML specs says (under Appendix C. 3):
Given an empty instance of an element whose content model is not EMPTY (for example, an empty title or paragraph) do not use the minimized form (e.g. use
So, I guess this isn't really a bug in IE. I'd think instead, that this is a bug in the DTD itself. The script tag doesn't have to contain #PCDATA (in fact, I consider it graceful if it doesn't), and forcing it is, well, stupid.
For now, I am explicitly closing the script tag with a seperate closing tag, and everything seems to be working well. Does anyone have any idea about handling this better, preferably with minimized element closures
stolen from piecesofrakesh.blogspot.com
Doing some research, I came across this post in theList by Eric Vitiello which clarifies this more. Apparently the DTD declaration for the script tag says , and the XHTML specs says (under Appendix C. 3):
Given an empty instance of an element whose content model is not EMPTY (for example, an empty title or paragraph) do not use the minimized form (e.g. use
and not ).
So, I guess this isn't really a bug in IE. I'd think instead, that this is a bug in the DTD itself. The script tag doesn't have to contain #PCDATA (in fact, I consider it graceful if it doesn't), and forcing it is, well, stupid.
For now, I am explicitly closing the script tag with a seperate closing tag, and everything seems to be working well. Does anyone have any idea about handling this better, preferably with minimized element closures
stolen from piecesofrakesh.blogspot.com
Monday, October 23, 2006
When do you need a pointer to a reference?
From C++ groups
> Why/when would someone need a pointer to a reference?
Never. A reference is another name for a real thing. A pointer can only
point to a real thing - it can't point to a name for a real thing.
References are often implemented as secret pointers, but it breaks the
language if you try to get a handle on this secret pointer - it is an
implementation detail.
If you meant a reference to a pointer, use this when you need something to
grab your pointer, point it to something else, and give the result back to
you. Consider a parser that reads statements written by the user:
WORD_TYPE getWord (char *&statement);
Each time you call this function it finds a word, returns its type, and
points the pointer off the end of the word.
> Why/when would someone need a pointer to a reference?
Never. A reference is another name for a real thing. A pointer can only
point to a real thing - it can't point to a name for a real thing.
References are often implemented as secret pointers, but it breaks the
language if you try to get a handle on this secret pointer - it is an
implementation detail.
If you meant a reference to a pointer, use this when you need something to
grab your pointer, point it to something else, and give the result back to
you. Consider a parser that reads statements written by the user:
WORD_TYPE getWord (char *&statement);
Each time you call this function it finds a word, returns its type, and
points the pointer off the end of the word.
Friday, October 20, 2006
VIM split
Vim viewport keybinding quick reference
:sp will split the Vim window horizontally. Can be written out entirely as :split .
:vsp will split the Vim window vertically. Can be written out as :vsplit .
Ctrl-w Ctrl-w moves between Vim viewports.
Ctrl-w j moves one viewport down.
Ctrl-w k moves one viewport up.
Ctrl-w h moves one viewport to the left.
Ctrl-w l moves one viewport to the right.
Ctrl-w = tells Vim to resize viewports to be of equal size.
Ctrl-w - reduce active viewport by one line.
Ctrl-w + increase active viewport by one line.
Ctrl-w q will close the active window.
Ctrl-w r will rotate windows to the right.
Ctrl-w R will rotate windows to the left.
From Linux.com
:sp will split the Vim window horizontally. Can be written out entirely as :split .
:vsp will split the Vim window vertically. Can be written out as :vsplit .
Ctrl-w Ctrl-w moves between Vim viewports.
Ctrl-w j moves one viewport down.
Ctrl-w k moves one viewport up.
Ctrl-w h moves one viewport to the left.
Ctrl-w l moves one viewport to the right.
Ctrl-w = tells Vim to resize viewports to be of equal size.
Ctrl-w - reduce active viewport by one line.
Ctrl-w + increase active viewport by one line.
Ctrl-w q will close the active window.
Ctrl-w r will rotate windows to the right.
Ctrl-w R will rotate windows to the left.
From Linux.com
Thursday, October 19, 2006
Monday, September 25, 2006
CRON
minute hour dom month dow user cmd
minute This controls what minute of the hour the command will run on,
and is between '0' and '59'
hour This controls what hour the command will run on, and is specified in
the 24 hour clock, values must be between 0 and 23 (0 is midnight)
dom This is the Day of Month, that you want the command run on, e.g. to
run a command on the 19th of each month, the dom would be 19.
month This is the month a specified command will run on, it may be specified
numerically (0-12), or as the name of the month (e.g. May)
dow This is the Day of Week that you want a command to be run on, it can
also be numeric (0-7) or as the name of the day (e.g. sun).
user This is the user who runs the command.
cmd This is the command that you want run. This field may contain
multiple words or spaces.
minute This controls what minute of the hour the command will run on,
and is between '0' and '59'
hour This controls what hour the command will run on, and is specified in
the 24 hour clock, values must be between 0 and 23 (0 is midnight)
dom This is the Day of Month, that you want the command run on, e.g. to
run a command on the 19th of each month, the dom would be 19.
month This is the month a specified command will run on, it may be specified
numerically (0-12), or as the name of the month (e.g. May)
dow This is the Day of Week that you want a command to be run on, it can
also be numeric (0-7) or as the name of the day (e.g. sun).
user This is the user who runs the command.
cmd This is the command that you want run. This field may contain
multiple words or spaces.
Thursday, September 21, 2006
Monday, August 21, 2006
STL:Map
from metashell.com
#pragma warning(disable: 4786)
#include
#include
#include
using namespace std;
int main() {
map ass_array;
// Assign keys and values
ass_array["fat"] = 0;
ass_array["sodium"] = 45;
ass_array["totalcarb"] = 46;
ass_array["protien"] = 0;
// Insert Value
ass_array.insert( map::value_type( "potassium", 25 ) );
// Print value of sodium
cout << ass_array["sodium"] << endl;
cout << "The map has " << ass_array.size() << " entries.\n";
// Iterator used to hold position in the map
map::iterator loc;
// Returns same value as ass_array.end() if not find.
loc = ass_array.find("sugar");
if(loc != ass_array.end())
cout << "Sugar found!\n";
else
cout << "No Sugar\n";
return 0;
}
#pragma warning(disable: 4786)
#include
#include
#include
using namespace std;
int main() {
map
// Assign keys and values
ass_array["fat"] = 0;
ass_array["sodium"] = 45;
ass_array["totalcarb"] = 46;
ass_array["protien"] = 0;
// Insert Value
ass_array.insert( map
// Print value of sodium
cout << ass_array["sodium"] << endl;
cout << "The map has " << ass_array.size() << " entries.\n";
// Iterator used to hold position in the map
map
// Returns same value as ass_array.end() if not find.
loc = ass_array.find("sugar");
if(loc != ass_array.end())
cout << "Sugar found!\n";
else
cout << "No Sugar\n";
return 0;
}
STL:Sort
From msoe.edu
#include
#include // Include algorithms
using namespace std;
vector vec;
vec.push_back (10);
vec.push_back (3);
vec.push_back (7);
sort(vec.begin(), vec.end()); // Sort the vector
// The vector now contains: 3, 7, 10
#include
#include
using namespace std;
vector
vec.push_back (10);
vec.push_back (3);
vec.push_back (7);
sort(vec.begin(), vec.end()); // Sort the vector
// The vector now contains: 3, 7, 10
STL: find
list nums;
list::iterator nums_iter;
nums.push_back (3);
nums.push_back (7);
nums.push_front (10);
nums_iter = find(nums.begin(), nums.end(), 3); // Search the list.
if (nums_iter != nums.end())
{
cout << "Number " << (*nums_iter) << " found." << endl; // 3
}
else
{
cout << "Number not found." << endl;
}
list
nums.push_back (3);
nums.push_back (7);
nums.push_front (10);
nums_iter = find(nums.begin(), nums.end(), 3); // Search the list.
if (nums_iter != nums.end())
{
cout << "Number " << (*nums_iter) << " found." << endl; // 3
}
else
{
cout << "Number not found." << endl;
}
Tuesday, August 15, 2006
Sharing mouse and keyboard between two computers with different operating system
from http://synergy2.sourceforge.net
Running Synergy
Synergy lets you use one keyboard and mouse across multiple computers. To do so it requires that all the computers are connected to each other via TCP/IP networking. Most systems come with this installed.
Step 1 - Choose a server
The first step is to pick which keyboard and mouse you want to share. The computer with that keyboard and mouse is called the "primary screen" and it runs the synergy server. All of the other computers are "secondary screens" and run the synergy client.
Step 2 - Install the software
Second, you install the software. Choose the appropriate package and install it. For example, on Windows you would run SynergyInstaller. You must install the software on all the computers that will share the mouse and keyboard (clients and server). On OS X you'll just have a folder with some documentation and two programs. You can put this folder anywhere.
Step 3 - Configure and start the server
Next you configure the server. You'll tell synergy the name of the primary and secondary screens, which screens are next to which, and choose desired options. On Windows there's a dialog box for setting the configuration. On other systems you'll create a simple text file.
Note that when you tell synergy that screen A is to the left of screen B this does not imply that B is to the right of A. You must explicitly indicate both relations. If you don't do both then when you're running synergy you'll find you're unable to leave one of the screens.
Windows
On Windows run synergy by double clicking on the synergy file. This brings up a dialog. Configure the server:
* Click the Share this computer's keyboard and mouse (server) radio button
* Click the Screens & Links Configure... button
* Click the + button to add the server to the Screens list
o Enter the name of server (the computer's name is the recommended name)
o Optionally enter other names the server is known by
o Click OK
* Use the + button to add your other computers
o Using a computer's name as its screen name is recommended
o Choose desired screen options on the Add Screen dialog
* Use the controls under Links to link screens together
o Click (once) on the server's name in the Screens list
o Choose the screen to the left of the server; use --- if there is no screen to the left of the server
o Choose the screens to the right, above and below the server
o Repeat the above steps for all the other screens
* Click OK to close the Screens & Links dialog
* Use Options... to set desired options
* If the server's screen name is not the server's computer name:
o Click Advanced...
o Enter the server's screen name next to Screen Name
o Click OK
Now click Test. The server will start and you'll see a console window with log messages telling you about synergy's progress. If an error occurs you'll get one or more dialog boxes telling you what the errors are; read the errors to determine the problem then correct them and try Test again. See Step 5 for typical errors.
Unix or Mac OS X
Create a text file named synergy.conf with the following:
section: screens
screen1:
screen2:
end
section: links
screen1:
right = screen2
screen2:
left = screen1
end
Replace each occurrence of screen1 with the host name of the primary screen computer (as reported by the hostname program) and screen2 with the host name of a secondary screen computer. In the above example, screen2 is to the right of screen1 and screen1 is to the left of screen2. If necessary you should replace right and left with left, right, up, or down. If you have more than two computers you can add those too: add each computer's host name in the screens section and add the appropriate links. See the configuration guide for more configuration possibilities.
Now start the server. Normally synergy wants to run "in the background." It detaches from the terminal and doesn't have a visible window, effectively disappearing from view. Until you're sure your configuration works, you should start synergy "in the foreground" using the -f command line option.
On unix type the command below in a shell. If synergys is not in your PATH then use the full pathname.
synergys -f --config synergy.conf
On OS X open Terminal in the Utilities folder in the Applications folder. Drag the synergys program from the synergy folder onto the Terminal window. The path to the synergys program will appear. Add the following to the same line, type a space at the end of the line but don't press enter:
-f --config
Now drag the synergy.conf file onto the Terminal window and press enter. Check the reported messages for errors. Use ctrl+c to stop synergy if it didn't stop automatically, correct any problems, and start it again.
Step 4 - Start the clients
Next you start the client on each computer that will share the server's keyboard and mouse.
Windows
On Windows run synergy by double clicking on the synergy file. This brings up a dialog. Configure the client:
* Click the Use another computer's shared keyboard and mouse (client) radio button
* Enter the server's computer name next to Other Computer's Host Name
o This is not the server's screen name, unless you made that the server's host name as recommended
* If the client's screen name is not the client's computer name:
o Click Advanced...
o Enter the client's screen name next to Screen Name
o Click OK
Now click Test.
Unix or Mac OS X
To start a client on unix, enter the following:
synergyc -f server-host-name
where server-host-name is replaced by the host name of the computer running the synergy server. If synergyc is not in your PATH then use the full pathname.
On OS X open Terminal in the Utilities folder in the Applications folder. Drag the synergyc program from the synergy folder onto the Terminal window. The path to the synergys program will appear. Add the following to the same line and press enter:
-f server-host-name
When you added the client to the server's configuration you chose a name for the client. If that name was not client's host name then you must tell the client the name you used. Instead of the above command use this instead:
synergyc -f --name name server-host-name
where name is the name for the client in the server's configuration. (On OS X drag the synergyc program to the Terminal window rather than typing synergyc.)
Step 5 - Test
Clients should immediately report a successful connection or one or more error messages. Some typical problems and possible solutions are below. See the troubleshooting and the FAQ pages for more help.
* failed to open screen (X11 only)
Check permission to open the X display;
check that the DISPLAY environment variable is set
use the --display command line option.
* address already in use
Another program (maybe another copy of synergy) is using the synergy port; stop the other program or choose a different port in the Advanced... dialog. If you change the port you must make the same change on all of the clients, too.
* connection forcefully rejected
The synergy client successfully contacted the server but synergy wasn't running or it's running on a different port. You may also see this if there's a firewall blocking the host or port. Make sure synergy is running on the server and check for a firewall.
* already connected
Check that the synergy client isn't already running.
* refused client
Add the client to the server's configuration file.
* connection timed out
Check that server-host-name is correct.
Check that you don't have a firewall blocking the server or synergy port.
* connection failed
Check that server-host-name is correct.
If you get the error "Xlib: No protocol specified" you're probably running synergy as root while logged in as another user. X11 may prevent this for security reasons. Either run synergy as the same user that's logged in or (not recommended) use "xhost +" to allow anyone to connect to the display.
When successful you should be able to move the mouse off the appropriate edges of your server's screen and have it appear on a client screen. Try to move the mouse to each screen and check all the configured links. Check the mouse buttons and wheel and try the keyboard on each client. You can also cut-and-paste text, HTML, and images across computers (HTML and images are not supported on OS X yet).
Step 6 - Run
Once everything works correctly, stop all the clients then the server. Then start the server with the Start button on Windows and without the -f option on Unix and Mac OS X. Finally start the clients similarly. On Windows before clicking Start you may want to set the Logging Level to Warning so the logging window doesn't pop up (because you currently can't close it, just minimize it).
You can also configure synergy to start automatically when your computer starts or when you log in. See the autostart guide for more information.
Command Line Options Guide
Common Command Line Options
The following options are supported by synergys and synergyc.
-d, --debug level use debugging level level
--daemon run as a daemon (Unix) or background (Windows)
-f, --no-daemon run in the foreground
--display display connect to X server at display (X11 only)
-n, --name name use name instead of the hostname
--restart automatically restart on failures
-1, --no-restart do not restart on failure
-h, --help print help and exit
--version print version information and exit
Debug levels are from highest to lowest: FATAL, ERROR, WARNING, NOTE, INFO, DEBUG, DEBUG1, and DEBUG2. Only messages at or above the given level are logged. Messages are logged to a terminal window when running in the foreground. Unix logs messages to syslog when running as a daemon. The Windows NT family logs messages to the event log when running as a service. The Windows 95 family shows FATAL log messages in a message box and others in a terminal window when running as a service.
The --name option lets the client or server use a name other than its hostname for its screen. This name is used when checking the configuration.
Neither the client nor server will automatically restart if an error occurs that is sure to happen every time. For example, the server will exit immediately if it can't find itself in the configuration. On X11 both the client and server will also terminate if the connection to the X server is lost (usually because it died).
Server Command Line Options
synergys [options]
The server accepts the common options and:
-a, --address address listen for connections on address address
-c, --config pathname read configuration from pathname
address has one of the following forms:
hostname
:port
hostname:port
hostname is a hostname or IP address of a network interface on the server system (e.g. somehost or 192.168.1.100). port is a port number from 1 to 65535. hostname defaults to the system's hostname and port defaults to 24800.
Client Command Line Options
synergyc [options] address[:port]
address is the hostname or IP address of the server and port is the optional netw
Running Synergy
Synergy lets you use one keyboard and mouse across multiple computers. To do so it requires that all the computers are connected to each other via TCP/IP networking. Most systems come with this installed.
Step 1 - Choose a server
The first step is to pick which keyboard and mouse you want to share. The computer with that keyboard and mouse is called the "primary screen" and it runs the synergy server. All of the other computers are "secondary screens" and run the synergy client.
Step 2 - Install the software
Second, you install the software. Choose the appropriate package and install it. For example, on Windows you would run SynergyInstaller. You must install the software on all the computers that will share the mouse and keyboard (clients and server). On OS X you'll just have a folder with some documentation and two programs. You can put this folder anywhere.
Step 3 - Configure and start the server
Next you configure the server. You'll tell synergy the name of the primary and secondary screens, which screens are next to which, and choose desired options. On Windows there's a dialog box for setting the configuration. On other systems you'll create a simple text file.
Note that when you tell synergy that screen A is to the left of screen B this does not imply that B is to the right of A. You must explicitly indicate both relations. If you don't do both then when you're running synergy you'll find you're unable to leave one of the screens.
Windows
On Windows run synergy by double clicking on the synergy file. This brings up a dialog. Configure the server:
* Click the Share this computer's keyboard and mouse (server) radio button
* Click the Screens & Links Configure... button
* Click the + button to add the server to the Screens list
o Enter the name of server (the computer's name is the recommended name)
o Optionally enter other names the server is known by
o Click OK
* Use the + button to add your other computers
o Using a computer's name as its screen name is recommended
o Choose desired screen options on the Add Screen dialog
* Use the controls under Links to link screens together
o Click (once) on the server's name in the Screens list
o Choose the screen to the left of the server; use --- if there is no screen to the left of the server
o Choose the screens to the right, above and below the server
o Repeat the above steps for all the other screens
* Click OK to close the Screens & Links dialog
* Use Options... to set desired options
* If the server's screen name is not the server's computer name:
o Click Advanced...
o Enter the server's screen name next to Screen Name
o Click OK
Now click Test. The server will start and you'll see a console window with log messages telling you about synergy's progress. If an error occurs you'll get one or more dialog boxes telling you what the errors are; read the errors to determine the problem then correct them and try Test again. See Step 5 for typical errors.
Unix or Mac OS X
Create a text file named synergy.conf with the following:
section: screens
screen1:
screen2:
end
section: links
screen1:
right = screen2
screen2:
left = screen1
end
Replace each occurrence of screen1 with the host name of the primary screen computer (as reported by the hostname program) and screen2 with the host name of a secondary screen computer. In the above example, screen2 is to the right of screen1 and screen1 is to the left of screen2. If necessary you should replace right and left with left, right, up, or down. If you have more than two computers you can add those too: add each computer's host name in the screens section and add the appropriate links. See the configuration guide for more configuration possibilities.
Now start the server. Normally synergy wants to run "in the background." It detaches from the terminal and doesn't have a visible window, effectively disappearing from view. Until you're sure your configuration works, you should start synergy "in the foreground" using the -f command line option.
On unix type the command below in a shell. If synergys is not in your PATH then use the full pathname.
synergys -f --config synergy.conf
On OS X open Terminal in the Utilities folder in the Applications folder. Drag the synergys program from the synergy folder onto the Terminal window. The path to the synergys program will appear. Add the following to the same line, type a space at the end of the line but don't press enter:
-f --config
Now drag the synergy.conf file onto the Terminal window and press enter. Check the reported messages for errors. Use ctrl+c to stop synergy if it didn't stop automatically, correct any problems, and start it again.
Step 4 - Start the clients
Next you start the client on each computer that will share the server's keyboard and mouse.
Windows
On Windows run synergy by double clicking on the synergy file. This brings up a dialog. Configure the client:
* Click the Use another computer's shared keyboard and mouse (client) radio button
* Enter the server's computer name next to Other Computer's Host Name
o This is not the server's screen name, unless you made that the server's host name as recommended
* If the client's screen name is not the client's computer name:
o Click Advanced...
o Enter the client's screen name next to Screen Name
o Click OK
Now click Test.
Unix or Mac OS X
To start a client on unix, enter the following:
synergyc -f server-host-name
where server-host-name is replaced by the host name of the computer running the synergy server. If synergyc is not in your PATH then use the full pathname.
On OS X open Terminal in the Utilities folder in the Applications folder. Drag the synergyc program from the synergy folder onto the Terminal window. The path to the synergys program will appear. Add the following to the same line and press enter:
-f server-host-name
When you added the client to the server's configuration you chose a name for the client. If that name was not client's host name then you must tell the client the name you used. Instead of the above command use this instead:
synergyc -f --name name server-host-name
where name is the name for the client in the server's configuration. (On OS X drag the synergyc program to the Terminal window rather than typing synergyc.)
Step 5 - Test
Clients should immediately report a successful connection or one or more error messages. Some typical problems and possible solutions are below. See the troubleshooting and the FAQ pages for more help.
* failed to open screen (X11 only)
Check permission to open the X display;
check that the DISPLAY environment variable is set
use the --display command line option.
* address already in use
Another program (maybe another copy of synergy) is using the synergy port; stop the other program or choose a different port in the Advanced... dialog. If you change the port you must make the same change on all of the clients, too.
* connection forcefully rejected
The synergy client successfully contacted the server but synergy wasn't running or it's running on a different port. You may also see this if there's a firewall blocking the host or port. Make sure synergy is running on the server and check for a firewall.
* already connected
Check that the synergy client isn't already running.
* refused client
Add the client to the server's configuration file.
* connection timed out
Check that server-host-name is correct.
Check that you don't have a firewall blocking the server or synergy port.
* connection failed
Check that server-host-name is correct.
If you get the error "Xlib: No protocol specified" you're probably running synergy as root while logged in as another user. X11 may prevent this for security reasons. Either run synergy as the same user that's logged in or (not recommended) use "xhost +" to allow anyone to connect to the display.
When successful you should be able to move the mouse off the appropriate edges of your server's screen and have it appear on a client screen. Try to move the mouse to each screen and check all the configured links. Check the mouse buttons and wheel and try the keyboard on each client. You can also cut-and-paste text, HTML, and images across computers (HTML and images are not supported on OS X yet).
Step 6 - Run
Once everything works correctly, stop all the clients then the server. Then start the server with the Start button on Windows and without the -f option on Unix and Mac OS X. Finally start the clients similarly. On Windows before clicking Start you may want to set the Logging Level to Warning so the logging window doesn't pop up (because you currently can't close it, just minimize it).
You can also configure synergy to start automatically when your computer starts or when you log in. See the autostart guide for more information.
Command Line Options Guide
Common Command Line Options
The following options are supported by synergys and synergyc.
-d, --debug level use debugging level level
--daemon run as a daemon (Unix) or background (Windows)
-f, --no-daemon run in the foreground
--display display connect to X server at display (X11 only)
-n, --name name use name instead of the hostname
--restart automatically restart on failures
-1, --no-restart do not restart on failure
-h, --help print help and exit
--version print version information and exit
Debug levels are from highest to lowest: FATAL, ERROR, WARNING, NOTE, INFO, DEBUG, DEBUG1, and DEBUG2. Only messages at or above the given level are logged. Messages are logged to a terminal window when running in the foreground. Unix logs messages to syslog when running as a daemon. The Windows NT family logs messages to the event log when running as a service. The Windows 95 family shows FATAL log messages in a message box and others in a terminal window when running as a service.
The --name option lets the client or server use a name other than its hostname for its screen. This name is used when checking the configuration.
Neither the client nor server will automatically restart if an error occurs that is sure to happen every time. For example, the server will exit immediately if it can't find itself in the configuration. On X11 both the client and server will also terminate if the connection to the X server is lost (usually because it died).
Server Command Line Options
synergys [options]
The server accepts the common options and:
-a, --address address listen for connections on address address
-c, --config pathname read configuration from pathname
address has one of the following forms:
hostname
:port
hostname:port
hostname is a hostname or IP address of a network interface on the server system (e.g. somehost or 192.168.1.100). port is a port number from 1 to 65535. hostname defaults to the system's hostname and port defaults to 24800.
Client Command Line Options
synergyc [options] address[:port]
address is the hostname or IP address of the server and port is the optional netw
Monday, August 14, 2006
Explicit in C++
Using Explicit in C++
In C++ it is possible to declare constructors for a class, taking a single parameter, and use those constructors for doing type conversion. For example:
class A {
public:
A(int);
};
void f(A) {}
void g()
{
A a1 = 37;
A a2 = A(47);
A a3(57);
a1 = 67;
f(77);
}
A declaration like:
A a1 = 37;
says to call the A(int) constructor to create an A object from the integer value. Such a constructor is called a "converting constructor".
However, this type of implicit conversion can be confusing, and there is a way of disabling it, using a new keyword "explicit" in the constructor declaration:
class A {
public:
explicit A(int);
};
void f(A) {}
void g()
{
A a1 = 37; // illegal
A a2 = A(47); // OK
A a3(57); // OK
a1 = 67; // illegal
f(77); // illegal
}
Using the explicit keyword, a constructor is declared to be
"nonconverting", and explicit constructor syntax is required:
class A {
public:
explicit A(int);
};
void f(A) {}
void g()
{
A a1 = A(37);
A a2 = A(47);
A a3(57);
a1 = A(67);
f(A(77));
}
Note that an expression such as:
A(47)
is closely related to function-style casts supported by C++. For example:
double d = 12.34;
int i = int(d);
Our Services
Back to Home Page
In C++ it is possible to declare constructors for a class, taking a single parameter, and use those constructors for doing type conversion. For example:
class A {
public:
A(int);
};
void f(A) {}
void g()
{
A a1 = 37;
A a2 = A(47);
A a3(57);
a1 = 67;
f(77);
}
A declaration like:
A a1 = 37;
says to call the A(int) constructor to create an A object from the integer value. Such a constructor is called a "converting constructor".
However, this type of implicit conversion can be confusing, and there is a way of disabling it, using a new keyword "explicit" in the constructor declaration:
class A {
public:
explicit A(int);
};
void f(A) {}
void g()
{
A a1 = 37; // illegal
A a2 = A(47); // OK
A a3(57); // OK
a1 = 67; // illegal
f(77); // illegal
}
Using the explicit keyword, a constructor is declared to be
"nonconverting", and explicit constructor syntax is required:
class A {
public:
explicit A(int);
};
void f(A) {}
void g()
{
A a1 = A(37);
A a2 = A(47);
A a3(57);
a1 = A(67);
f(A(77));
}
Note that an expression such as:
A(47)
is closely related to function-style casts supported by C++. For example:
double d = 12.34;
int i = int(d);
Our Services
Back to Home Page
Subscribe to:
Posts (Atom)