## Wednesday, February 9, 2011

### C++: Multithreading and refcounted object

I'm currently trying to pass a mono threaded program to multithread. This software do heavy usage of "refCounted" objects, which lead to some issues in multithread. I'm looking for some design pattern or something that might solve my problem.

The main problem is object deletion between thread, normally deletion only decrement the reference counting, and when refcount is equal to zero, then the object is deleted. This work well in monothread program, and allow some great performance improvement with copy of big object.

However, in multithread, two threads might want to delete the same object concurrently, as the object is protected by a mutex, only one thread delete the object and block the other one. But when it releases the mutex, then the other thread continue its execution with invalid (freed object), which lead to memory corruption.

Here is an example with this class RefCountedObject

class RefCountedObject
{
public:
RefCountedObject()
: _refCount( new U32(1) )
{}

RefCountedObject( const RefCountedObject& obj )
: _refCount( obj._refCount )
{
ACE_Guard< ACE_Mutex > guard( _refCountMutex );
++(*_refCount);
}

~RefCountedObject()
{
Destroy();
}

RefCountedObject& operator=( const RefCountedObject& obj )
{
if( this != &obj )
{
Destroy();
ACE_Guard< ACE_Mutex > guard( _refCountMutex );
_refCount = obj._refCount;
++(*_refCount);
}

return *this;
}

private:
void Destroy()
{
ACE_Guard< ACE_Mutex > guard( _refCountMutex );  // thread2 are waiting here
--(*_refCount);         // This cause a free memory write by the thread2
if( 0 == *_refCount )
delete _refCount;
}

private:
mutable U32* _refCount;
mutable ACE_Mutex _refCountMutex; // BAD: this mutex only protect the refCount pointer, not the refCount itself
};


Suppose that two threads want to delete the same RefCountedObject, both are in ~RefCountedObject and call Destroy(), the first thread has locked the mutex and the other one is waiting. After the deletion of the object by the first thread, the second will continue its execution and cause a free memory write.

Anyone has experience with a similar problem and found a solution ?

Thanks all for your help, I realize my mistake: The mutex is only protecting refCount pointer, not the refCount itself! I've created a RefCount class which is mutex protected. The mutex is now shared between all refCounted object.

Now all works fine.

• Surely each thread simply needs to manage the reference counts correctly... That is, if ThreadA and ThreadB are both working with Obj1 then BOTH ThreadA and ThreadB should own a reference to the object and BOTH should call release when they're done with the object.

In a single threaded application it's likely that you have a point where a reference counted object is created, you then do work on the object and eventually call release. In a multi-threaded program you would create the object and then pass it to your threads (however you do that). Before passing the object to the thread you should call AddRef() on your object to give the thread its own reference count. The thread that allocated the object can then call release as it's done with the object. The threads that are working with the object will then call release when they're done and when the last reference is released the object will be cleaned up.

Note that you dont want the code that's running on the threads themselves to call AddRef() on the object as you then have a race condition between the creating thread calling release on the object before the threads that you've dispatched to get a chance to run and call AddRef().

• Any object that you are sharing between threads should be protected with a mutex, and the same applies to refcount handles ! That means you will never be deleting the last one handle to an object from two threads. You might be concurrently deleting two distinct handles that happen to point to one object.

In Windows, you could use InterlockedDecrement. This ensures that precisely one of the two decrements will return 0. Only that thread will delete the refcounted object.

Any other thread cannot have been copying one of the two handles either. By common MT rules one thread may not delete an object still used by another thread, and this extends to refcount handles too.

From MSalters
• One solution is to make the reference counter an atomic value, so that each concurrent call to destroy can safely proceed with only 1 deletion actually occurring, the other merely decrementing the atomic reference count.

The Intel Thread Building Blocks library (TBB) provides atomic values.

Also, so does the ACE library in the ACE_Atomic_Op template.

The Boost library provides a reference counting smart pointer library that already implements this.

From grrussel
• I believe something along this line would solve your problem:

private:
void Destroy()
{
ACE_Guard< ACE_Mutex > guard( _refCountMutex );  // thread2 are waiting here
if (_refCount != 0) {
--(*_refCount);         // This cause a free memory write by the thread2
if( 0 == *_refCount ) {
delete _refCount;
_refcount = 0;
}
}
}
private:
mutable U32* _refCount;
mutable ACE_Mutex _refCountMutex;

From tloach
• If the count is part of the object then you have an inherent problem if one thread can be trying to increase the reference count whilst another is trying to remove the last reference. There needs to be an extra value on the ref count for each globally accessible pointer to the object, so you can always safely increase the ref count if you've got a pointer.

One option would be to use boost::shared_ptr (see the docs). You can use the free functions atomic_load, atomic_store, atomic_exchange and atomic_compare_exchange (which are conspicuously absent from the docs) to ensure suitable protection when accessing global pointers to shared objects. Once your thread has got a shared_ptr referring to a particular object you can use the normal non-atomic functions to access it.

Another option is to use Joe Seigh's atomic ref-counted pointer from his atomic_ptr_plus project

• thinking about your issue a little... what you're saying is that you have 1 object (if the refcount is 1) and yet 2 threads both call delete() on it. I think this is where your problem truly lies.

The other way round this issue, if you want a threaded object you can safely reuse between threads, is to check that the refcount is greater than 1 before freeing internal memory. Currently you free it and then check whether the refcount is 0.

From gbjbaanb
• This isn't an answer, but just a bit of advice. In a situation like this, before you start fixing anything, please make sure you can reliably duplicate these problems. Sometimes this is a simple as running your unit tests in a loop for a while. Sometimes putting some clever Sleeps into your program to force race conditions is helpful.

Ref counting problems tend to linger, so an investment in your test harness will pay off in the long run.

Ian Hickman : +1 the only real way of solving multi-threaded issues is to make them repeatable.
From twk

### How can I just get the "Year" portion from the output of timespan() in CodeIgniter?

I have a Date of Birth field and trying to use the timespan function to get the age, but returns "28 Years, 2 Months, 2 Weeks, 3 Days, 15 Hours, 16 Minutes".

Any idea how I can just get the "28 Years" part?

Thanks!

• ## There are many ways to do this, with the string in $date, like so: $date = '28 Years, 2 Months, 2 Weeks, 3 Days, 15 Hours, 16 Minutes';

This will give you "28 Years"
$yearsPart = substr($date, 0, strpos($date, 'Years') + 5);  So will this: $parts = split(', ', $date);$yearsPart = $parts[0];  From Kevin Chan • I suggest you use PHP's strftime() function. Instead of using the CI's timespan(). echo strftime('%Y', 1226239392); ### C# code from desktop to the web If I develop a desktop app using C#, and later want to turn it into a webapp but don't want to use ASP.NET, what are my options? I did a bit of searching and it looks like there doesn't appear to be a good solution to integrate C# code with any scripting language other than running it as a web service and making SOAP calls. Any other ideas? • Why would you make things so difficult for yourself? The best thing would be to put almost all of your code into an assembly, and just use the winforms app for display purposes. Then, later, you can just reimplement the display logic in asp.net. So, I guess the answer is no. • AJAX + WebService + plain HTML From Mote • You could embed a webserver in the application. It's quite easy, even with threading so that you can handle simultaneous requests. There's a bunch of examples on the web, here's one at the codeplex: http://www.codeplex.com/webserver • The reason I don't want to use ASP.NET is that I can't seem to find any decent (ie recommended) VPS hosting and I don't want to go with dedicated hosting right off the gate. Linux hosting is much more plentiful. I guess the other thing I could do is use Mono and forget about PHP etc Joel Coehoorn : mono is probably your best bet if you already have C# objects you'll want to use. Ilya Kochetov : http://maximumasp.com/ are pretty good for .NET hosting • It would be easy enough to have your application offering a SOAP service, which you could then integrate with a front-end in pretty much any language. If you really want to avoid that then just go for some less recommended but cheap ASP.Net hosting and use that - if the application is a success you can always shift to dedicated hosting later. It's worth spending a bit of money to make your life a whole lot easier and from what you have said there really isn't a lot of point in avoiding ASP.Net if it means you have to do four times as much work. From glenatron • How about ASP.NET on Mono? How painful is that realistically? • I can't leave a comment for your reply about hosting but I've had .net hosting with Lunarpages for ages now and found it to be just about as affordable as linux hosting and with the same perks like php support, unlimited mysql and ms sql dbs etc. To answer the mono question, it's fine but I think Mono only supports up to 3.0 ATM. From Echostorm • I vote monorail. Keep a nice MVC model. ### How to detect file ends in newline? Over at Can you modify text files when committing to subversion? Grant suggested that I block commits instead. However I don't know how to check a file ends with a newline. How can you detect that the file ends with a newline? • You should be able to do it via a SVN pre-commit hook. See this example. • You could use something like this as your pre-commit script: #! /usr/bin/perl while (<>) {$last = $_; } if (! ($last =~ m/\n$/)) { print STDERR "File doesn't end with \\n!\n"; exit 1; }  From bstark • Using only bash: x=tail -n 1 your_textfile if [ "$x" == "" ]; then echo "empty line"; fi


(Take care to copy the whitespaces correctly!)

@grom:

tail does not return an empty line

Damn. My test file didn't end on \n but on \n\n. Apparently vim can't create files that don't end on \n (?). Anyway, as long as the “get last byte” option works, all's well.

• @Konrad: tail does not return an empty line. I made a file that has some text that doesn't end in newline and a file that does. Here is the output from tail:

$cat test_no_newline.txt this file doesn't end in newline$

$cat test_with_newline.txt this file ends in newline$


Though I found that tail has get last byte option. So I modified your script to:

#!/bin/sh
c=tail -c 1 $1 if [ "$c" != "" ]; then echo "no newline"; fi

From grom
• This answer worked well for me.

From nwahmaet
• Or even simpler:

#!/bin/sh
test tail -c 1 $1 && echo "no newline at eof:$1"

From felipec

### Does anyone know some cool PL/SQL plugin for IntelliJ Idea?

I've evaluated some plugins from official IntelliJ repository, but none of them seems to provide more then basic syntax highlighting. Even highlighting is limited. For example, Database Navigator doesn't highlight IF. It would be great to have proper highlighting. And if it would have auto-complete feature and provide file structure view I would be completely happy. I use SQL Query Plugin when I need to post some little stuff to database or to query something from it. I use PL/SQL Developer when I need to make more complex things, or when I need to modify PL/SQL. But most of the time I need to navigate through mix of Java, JavaScript and PL/SQL code. Unfortunately, SQL Query Plugin doesn't help with that as well as PL/SQL Developer.

• Have you tried SQL Query Plugin? It comes with a great host of features, including multiple query windows, direct editing of tables, and of course, proper highlighting for PL/SQL syntax and a browser of the internal database structure.

It also integrates well with the main editor: you can right-click on any selected Java string containing SQL and "Send to SQLPlugin" to strip out all of the quotes and non-SQL syntax.

From David

### OPTION(MAXDOP 1) in SQL Server

I have never clearly understood the usage of MAXDOP. I know it makes the query faster and thats the last that I can use in Query Optimization. But when and where it is best suited..

Thanks Guys!!!

• This is a general rambling on Parallelism in SQL Server, it might not answer your question directly.

From Books Online, on MAXDOP:

Sets the maximum number of processors the query processor can use to execute a single index statement. Fewer processors may be used depending on the current system workload.

See Rickie Lee's blog on parallelism and CXPACKET wait type. It's quite interesting.

Generally, in an OLTP database, my opinion is that if a query is so costly it needs to be executed on several processors, the query needs to be re-written into something more efficient.

Why you get better results adding MAXDOP(1)? Hard to tell without the actual execution plans, but it might be so simple as that the execution plan is totally different that without the OPTION, for instance using a different index (or more likely) JOINing differently, using MERGE or HASH joins.

• As Kaboing mentioned, MAXDOP(n) actually controls the number of CPU cores that are being used in the query processor.

On a completely idle system, SQL Server will attempt to pull the tables into memory as quickly as possible and join between them in memory. It could be that, in your case, it's best to do this with a single CPU. This might have the same effect as using OPTION (FORCE ORDER) which forces the query optimizer to use the order of joins that you have specified. IN some cases, I have seen OPTION (FORCE PLAN) reduce a query from 26 seconds to 1 second of execution time.

Books Online goes on to say that possible values for MAXDOP are:

0 - Uses the actual number of available CPUs depending on the current system workload. This is the default value and recommended setting. 1 - Suppresses parallel plan generation. The operation will be executed serially. 2-64 - Limits the number of processors to the specified value. Fewer processors may be used depending on the current workload. If a value larger than the number of available CPUs is specified, the actual number of available CPUs is used.

I'm not sure what the best usage of MAXDOP is, however I would take a guess and say that if you have a table with 8 partitions on it, you would want to specify MAXDOP(8) due to I/O limitations, but I could be wrong.

Here are a few quick links I found about MAXDOP:

Books Online: Degree of Parallelism

General guidelines to use to configure the MAXDOP option

• There are a couple of parallization bugs in SQL server with abnormal input. OPTION(MAXDOP 1) will sidestep them.

Ed Sykes : Could you elaborate on those bugs please?
Joshua : I was unable to fully qualify the bugs, but one in particular: when a left join was expected to match very few % of rows would try to spool both tables and loop join rather than bookmark lookup only with parallelization on.
From Joshua
• As something of an aside, MAXDOP can apparently be used as a workaround to a potentially nasty bug:

Returned identity values not always correct

From Paul

### Eclipse for IntelliJ Idea Users

I have a coworker who is looking to switch from InteilliJ Idea to Eclipse, and is concerned about not knowing the Eclipse set of commands.

I was wondering - would anyone have a link to keyboard mappings that can set Eclipse commands to at least sort of match Idea?

Have you made this switch? Any "gotchas", tips, or info we should be aware of?

Thanks!

• Sorry for offtopic and excuse me for that, but what are the reasons for such switch?

awied : Mostly because the version that we have available is not too current and is reportedly quite slow.
Bartosz Blimke : Eclipse is much slower.
From Vugluskr
• Why would he change from IntelliJ to Eclipse? Unless he is a masochist and wants to change his life into a nightmare. There is a reason why it is easy to find Eclipse mappings for IntelliJ and difficult to find IntelliJ mappings for Eclipse.

• If he definitely want to do this:

http://www.jroller.com/ervines/entry/intellij_style_mappings_for_eclipse

• Get the plugin from here. It seems easier to install than the one in Bartosz' answer, plus no 404s...

For the lazy: direct link to plugin

Drop the plugin jar in eclipse/plugins folder and restart eclipse. Now in preferences dialog under General > Keys you can find "Intellij Idea" key scheme.

From itsadok

### How to open a form in a thread and force it to stay open

I am still having problems with figuring out how to create winforms in a separate UI thread that I discussed here.

In trying to figure this out I wrote the following simple test program. I simply want it to open a form on a separate thread named "UI thread" and keep the thread running as long as the form is open while allowing the user to interact with the form (spinning is cheating). I understand why the below fails and the thread closes immediately but am not sure of what I should do to fix it.

using System;
using System.Windows.Forms;
using System.Threading;

namespace UIThreadMarshalling {
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var tt = new ThreadTest();
ThreadStart ts = new ThreadStart(tt.StartUiThread);
Thread t = new Thread(ts);
t.Name = "UI Thread";
t.Start();
Thread.Sleep(new TimeSpan(0, 0, 10));
}

}

public class ThreadTest {
Form _form;
public ThreadTest() {
}

public void StartUiThread() {
_form = new Form1();
_form.Show();
}
}
}

• George Mauer : If I put that on the main thread it will join immediately, if I put that on the UI Thread it will block disallowing user interaction.
plinth : Ah yes - I missed that you were doing form.Show() not Application.Run in your thread.
From plinth
• On a new thread, call Application.Run passing the form object, this will make the thread run its own message loop while the window is open.

Then you can call .Join on that thread to make your main thread wait until the UI thread has terminated, or use a similar trick to wait for that thread to complete.

Example:

public void StartUiThread()
{
using (Form1 _form = new Form1())
{
Application.Run(_form);
}
}

George Mauer : ahh...I think Application.Run might be my missing jigsaw piece
• You cannot open a GUI form in any thread, because it will be missing a message pump. You have to explicitly start a message pump in that thread by invoking Application.Run() in a thread method. Another option is to call a DoEvents() in a loop, if you need to do something else, because after Application.Run() that thread will wait a user to close a form in that point of execution.

From Nenad
• private void button1_Click(object sender, EventArgs e) { var t = new Thread(RunNewForm); t.Start(); } public static void RunNewForm() { Application.Run(new Form2()); }

From CheeZe5
• I think your problem is with this thought: "open a form on a separate thread named 'UI thread'"

The way windows works is like this (plz note Vista may change some of these realities):

There is one important thread called the "Main Thread" or the "UI Thread". This thread is the one that processes windows messages, like "hey the mouse clicked on this pixel."

These messages go into a queue, and the main thread processes them when it isn't busy doing something else.

So if you make a function call foo() on the main thread, if it takes a long time, no windows messages are processed during that time, and so no user interaction can occur.

The main thread also paints the UI on the screen, so long-running foo() will also stop your app from painting.

All other threads besides this holy and special main thread are grunt worker threads. These worker threads can do things, but they can never interact directly with the user interface.

This reality causes two problems:

1. GETTING OFF THE MAIN THREAD: Since you don't want long-running foo() to halt all user interaction, you need to ship that work off to a worker thread.

2. GETTING BACK TO THE MAIN THREAD: When long-running foo() completes, you probably want to notify the user by doing something in the UI, but you cannot do that in a worker thread, so you need to "get back" to the main thread.

So I believe your problem in the above program is very general: Your very goal is incorrect, because it is not supposed to be possible to call _form.Show() in any thread but the holy main thread.

From rice
• I think just calling ShowDialog instead of Show will help. The problem seems to be that the thread finishes just after calling Show, after that the Form get's garbage collected. ShowDialog will halt the thread but still run form-events on it so the thread will keep running until the form is closed.

Normally i would do it the other way around. Run the form on the starting thread and start background threads when you want to start long-running background tasks.

I also read your other question but couldn't figure out what you're trying to do. MVP-architecture doesn't require you to run your business logic on different threads. Multi threading is hard to do right so I'd only use multiple threads if I really needed them.

From Mendelt
• Thank you for the answer from Lasse V. Karlsen, I used the code and runs OK, really thanks very much!!!

### Any clever way to launch a makefile in Visual Studio only if build succeeded?

We have a makefile that is built last in our build process using Visual Studio to launch our unit tests. Unfortunately if the build fails the makefile is still processed and we have extra (annoying) errors. Any way to prevent that?

Example Project A : build dummy.exe Project B (makefile) : build command is : run dummy.exe /unittest

We want Project B to skip its build command when Project A has build errors. Thanks!

• Go to Project Properties. I assume you already have something in the "Post-Build event command line" box? There is a "Run the post-build event" combobox, set it to "On successful build".

Is that what you're looking for?

Enigme : Unfortunately it's not a post-build, it's a makefile project
xero : Is there a way to get your makefile to do nothing if the other project's output hasn't been updated in the last 20 seconds? It's a hack but might work.
From xero
• Set Project B (your makefile project) to be dependant on Project A. This way Project B will always try to build Project A before it builds.

Enigme : I had great hope for this simple solution but even with compiling 1 project at a time it still fails (makefile is launched)

### Using .Net Framework Source debugging

I'm getting a null-object exception deep within XsltCompiledTransform, and I'd like to use the .Net Framework Source debugging feature to see what isn't being initialized, but even after following the directions for enabling it, I can't figure out how to step into the .Transform() method and start spelunking.

The tutorials I've found online say you can load the symbols for the framework library by using the Call Stack window while debugging, but this isn't useful when the callstack has yet to contain the library you want to debug. I've also tried loading symbols from the Modules window, but Step-Into still doesn't work.

Is the System.Xml.Xslt namespace source even available to step into when debugging?

• If you have trouble fetching the sources on the fly, you might want to try out .NET Mass Downloader

As it looks, the sources for XsltCompiledTransform are included.

### How can I export the data in a DataGridView data to an Excel spreadsheet?

In my Winforms application, I want to export the data from my DataGridView to a Excel spreadsheet.

Is it simply a job of looping and outputting the results comma seperated?

• Is it simply a job of looping and outputing the results comma seperated? Yes. It is a simpler way without any dependencies.

If you need more control, you can always automate excel from vb.net or from C#..

From Gulzar
• Outputting results comma separated will give you a .csv not an excel spreadsheet; although excel can read a csv, and once open in excel you could save it document as excel file. To actually write a file in the excel format I believe you have to use an Ole Provider or something like that, but I've never bothered, since the workaround of creating a csv and outside of code making it an excel file is simple enough.

• Slightly hacky, but Excel will also open a html file saved with a .xls extension. This has the advantage of being able to include formatting.

### Question about accessing data

If two users are accessing same database table, How do we prevent users from overwriting each other’s data? Thank you, -Nimesh

• There is no straightforward way to do that. You could use transactions to make sure that updates are resolved correctly (i.e. that you do not get partial updates) but you would probably lose the first set of changes as it will be overwritten by the second.

Two options you probably have are:

• implement some locking mechanism on the application level (i.e. when someone start editing a record put some flag somewhere which would prevent another user from doing the same)
• implement version control so each time someone writes to the database a new record is created. This way both sets of data will be in the database and you could have a logic in your application to merge them or select the one you like
• Look at This discussion for a review of different strategies or techniques for database locking in an application.

• Well, that depends. When you're editing a table, it's not like opening a file up in MSWord or something.

You are issuing commands that specifically add or alter one row or a group of rows at a time, so unless two people are editing the same row, then changes by both users will be preserved.

Tables can also be locked, either implicitly while you are performing an operation (or within a transaction), or explicitly if you know exactly what it is you want to prevent edits to. Most databases provide "row-level locking", which means the entire table does not need to be locked for every operation.

It gets a lot more complicated when you start thinking about transactions and MVCC. If you let us know a bit more information about what exactly the situation is you're interested in, we can provide you with some more specific assistance.

From Dan
• The slickest approach that I've ran across is to use an additional field called last_actv_dtm that is updated every time someone modifies the record. Assuming that your application queries the record first you should have the last_actv_dtm for the record that is being modified.

Use this SQL to perform the update.

UPDATE tab1
SET
col1 = ?
, col2 = ?
, last_actv_dtm = GETDATE()
WHERE
pkcol = rec.pkcol
AND last_actv_dtm = rec.last_actv_dtm;


This will only update the row if it has not been modified since the application selected the record.

From DL Redden
• This is a big question with no easy answer. It call comes down to how willing are you to block one user while another user is working on it, and how do you prevent deadlocks and lousy performance while it's happening. Also, are you trying to prevent one user from updating the same row as the other, or just updating a different row in the same table? If user A updates the row, and then user B attempts to update the row, should it fail, update, or silently ignore it? Once you define the problem more, you can decide if need table level locks, row level locks, transactions, and whether you need various levels of transaction isolation.

• Thank you all for your help!

• Some database servers support a construct like the following:

SELECT column FROM table WHERE something = 'whatever' FOR UPDATE;


Which locks all the rows returned by the select until either a COMMIT or ROLLBACK are issued.

MySQL (InnoDB) and Oracle are two databases that support this.

S.Lott : Most DB's support this. It interacts with Update and Delete statements to correctly hold locks.
From R. Bemrose

### detect svn changes in a .bat

I have a .bat and inside the .bat i would like to execute a special code if there's some modification inside the svn repository (for example, compile).

• Are you wanting this to be reactive? Or, on-demand?

For reactive, see hooks. The script will have to be named according to it's purpose: pre-commit.bat, post-commit.bat. The scripts are called as: [script] [repos-path] [revision-number]

For, on-demand:

• Working Copy
• svn log
• svn st
• svn diff
• svn proplist
• Repository
• svnlook author
• svnlook changed
• svnlook date
• svnlook diff
• svnlook history

Example:

svn st "C:\path\to\working\directory\" >> C:\path\to\working\project.log


Every time you run the BAT, it'll add the st output to project.log. Adjust as needed.

acemtp : It on demand. I know the svn command (it s easy to find them eveyrwhere). The question is to know how to use that in a .bat script
acemtp : I don't want to put the status into a log file :) I want the code of the .bat that do something like: if(svn_changed()) do this else do that
• For Win 2000 and later, this would assign the last output row from the svn status commmand to the svnOut variable and then test if the variable contains anything:

@echo off
set svnOut=
set svnDir=C:Your\path\to\svn\dir\to\check
for /F "tokens=*" %%I in ('svn status %svnDir%') do set svnOut=%%I

if "%svnOut%"==""  (
echo No changes
) else (
echo Changed files!
)


Why there is a line like this

set svnOut=


you have to figure out yourself. ;-)

acemtp : Thank you very much. It's perfect, I'll test that ASAP.
acemtp : In fact, it doesn't work. For example, svn status returns some line with: ? files M files2 that are local modification or files that are not in the repository. I only want to have see "Changed files" when there s some repository changes.
acemtp : I posted the answer with a modified version
Tooony : Then I am not sure I understand what you want to do here... Do you want to perform a svn update, and if something has changed in the svn server repository, you want to perform a build with the new code? Or is it if something has been modified locally you want to rebuild? If 1: What about conflicts?
From Tooony
• Ok, the solution I found with the help of Tooony:

set vHEAD = 0
set vBASE = 0

set svnDir=<path to local svn directory>

for /F "tokens=1,2" %%I in ('svn info -r HEAD %svnDir%') do if "%%I"=="Revision:" set vHEAD=%%J
for /F "tokens=1,2" %%I in ('svn info -r BASE %svnDir%') do if "%%I"=="Revision:" set vBASE=%%J

if "%vBASE%"=="%vHEAD"  (
echo No changes
) else (
echo Changed files!
)

From acemtp
• Have your .bat execute svnversion (if you're using Subversion) or SvnWCRev.exe (if you're using TortoiseSVN) against the top-most level of your working copy.

Both output if your working copy has been modified.

svnversion appends a "M" to its output. SvnWCRev.exe will print a line of text that the WC has been modified.

From antik

### How do I get the last possible time of a particular day

Hi ,

I'm trying to achieve the last possible time of a particular day eg for Date of 2008-01-23 00:00:00.000 i would need 2008-01-23 23:59:59.999 perhaps by using the dateadd function on the Date field?

• Surely 23:59:59 is always the last possible time of the day?

Commodore Jaeger : Not if we take leap seconds [http://en.wikipedia.org/wiki/Leap_second] into account, but many systems simply count 23:59:59 twice instead of adding 23:59:60
From Valerion
• SELECT DATEADD(ms, -2, DATEADD(dd, 1, DATEDIFF(dd, 0, GetDate())))


I thought you had c# at first.. I will leave this here in case anyone else stumbles across this.

DateTime now = DateTime.Now;
DateTime endofDay = now.Date.AddDays(1).AddMilliseconds(-1);


You can replace the 'now' variable with whatever day you are trying to figure out

Danimal : check the tag -- he wants to do it in tsql
From Shaun Bowe
• The answer is SELECT DATEADD(ms, -3, '2008-01-24'), the explanation is below.

From Marc's blog:

But wait, Marc... you said you like to use BETWEEN, but that query doesn't have one... that's because BETWEEN is inclusive, meaning it includes the end-points. If I had an Order that was due at midnight of the first day of the next month it would be included. So how do you get the appropriate value for an end-of-period? It's most certainly NOT by using date-parts to assemble one (but is you must, please remember that it's 23:59:59.997 as a maximum time... don't forget the milliseconds). To do it right, we use the incestuous knowledge that Microsoft SQL Server DATETIME columns have at most a 3 millisecond resolution (something that is not going to change). So all we do is subtract 3 milliseconds from any of those end-of-period formulas given above. For example, the last possible instant of yesterday (local time) is:

    SELECT DATEADD(ms, -3, DATEADD(dd, DATEDIFF(dd, 0, GetDate()), 0))


So to do the orders due this month as a BETWEEN query, you can use this:

    SELECT [ID]
FROM [dbo].[Orders]
WHERE [ShipDue] BETWEEN DATEADD(mm, DATEDIFF(mm, 0, GetUTCDate()), 0)
AND DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, GetUTCDate()) + 1, 0))


Remember, always make sure that you do math against input parameters, NOT columns, or you will kill the SARG-ability of the query, which means indexes that might have been used aren't.

test : Sorry but this selected the latest time of day before the date I wanted..... rather than that particular day
Pandincus : This is great! A really, really easy way to get the end of the day.
From bdukes
• Add -1 milliseconds to the start of the next day (DateAdd even supports nanoseconds, if you want to get real fine).

But most likely you just want to use this value in a comparison, and in that case it's even simpler.

Rather than something like this:

AND @CompareDate <= [LastTimeforThatday]


or this:

@compareDate BETWEEN [StartDate] AND [LastTimeforThatday]


Do it like this:

AND @CompareDate < [BeginningOfNextDay]


or this:

AND (@CompareDate >= [StartDate] AND @CompareDate < [BeginningOfNextDay])

David B : As you say, excluding the endpoint is a very stable approach for these problems. It also allows for durations to be calculated without fudging.
• Could you please say how you intend to use this last possible time of a particular day? Perhaps we can find an elegant way around it.

From Nuno G

### How to become a programmer for hire?

Anyone know how to successfully start your own business as a programmer for hire. Consultant or contractor or whatever you want to call it.

• Best way to start is to get offers from people who (a) know your skillset, (b) have money, and (c) want to pay you.

Brian G : The whole getting offers part is the tricky bit i think
• You could always start out working on sites like Rent a coder and see if you enjoy it or are good at it. After that... good luck :)

Rob Allen : eLance(http://www.elance.com/) is also a good stop for this.
Kev : Don't waste your time with rent a coder, it's jammed packed with people who want their applications built for next to nothing. Tried it after I was made redundant, full of idiots who know the value of nothing.
bcwood : My experience with sites like rent a coder and eLance have been very poor. There are lots of developers on there from poor countries willing to do the work for next to nothing. It's next to impossible to get a decent gig on these sites.
Brian G : Agreed on Rent-a-coder
spoulson : Been there, done that. You will work you ass off for \$200 and get no real appreciation.
From FryHard
• This is really a duplicate.

Good pointers on Selling yourself.

You might also check here is you want to start your own company.

Consultants are people with a skill that a company doesn't have and doesn't want to have permanently, but is willing to pay reasonably well to have temporarily.

With that in mind, develop those kind of skills

Andre Bossard : No it isn't. the question is different. No all 'programmers for hire' are or want to be consultants.
Benoit : Start your own business...contractor? Sorry, but that's consulting. However you have a point. The answers were more geared towards working in a consultancy.
From Benoit
• This is very easy. Put your CV on a job board and wait for the agents to get in touch.

Most job boards have a profile setting setting that lets you specify if you are looking for Permanent or Contact work.

• I work as a contractor. A small company resells me to big companies. My employee gives me a fixed loan. I got the Job, because one of my former work collegues started working there (and he's really a crack).

So I think my way is to relay on my social network.

• I had a friend that decided to go into the business for himself doing custom VB and Access programming back in the late 90's. He went to the trouble to create some nice marketing materials showing the kinds of things he had done and was capable of doing. Then he started cold calling out of the phone book. Any place that he imagined might benefit from a little custom programming was open to him.

After working for below minimum wage on a few projects, he learned how to give better estimates and after a year or so, he was doing pretty well. He is now a sought after Java programmer in the Health Care field.

Moral of the story, if you want it badly enough and continuously work on upgrading your skills, you can make it.

Best of luck :o)

From wcm
• More info:

http://stackoverflow.com/questions/25177/sites-for-getting-freelancer-jobs

• I work as an IT Consultant / Developer and have for over 10 years. Before that I did the standard Blue Chip programming gig from Programmer to Project Manager, then spent a period as an Oracle DBA. I moved to working for myself because (a) I love coding and developing stuff and (b) I loath office politics.

I have never advertised for work, people have always come to me.

In my experience you need two things - good coding skills and good people skills. The vast majority of my clients are either small to medium businesses (between 5 and 50 employees) or departments within larger organizations. I'm not generally coding large systems - my typical project would be around one man month of development, although I have a fair few 'maintenance' contracts where I maintain a system for x nominal days a quarter.

In most cases I'm talking directly to the manager. Most such managers do not have IT development experience and are not comfortable with it - but know it's crucial to their business. What they are looking for is someone with whom they can discuss their requirements in plain business language and who they trust to offer them options and then deliver what they need. The ability to handle both the code and the human interface stuff is the key - many coders cannot. It's a great and rewarding role to perform and give you a lot of insight into different organizations.

The issue then is how do you get the contacts which feed you work - I have about half a dozen 'core' clients at any one point and another half dozen less so - and there's a certain low level churn and the occasional once-off. The hardest part is undoubtedly getting started - nowadays new clients tend to appear by word of mouth (employees of my clients leaving and then either starting there own businesses or telling their new employees about me is a major route).

In my case the initial contacts came by two routes - firstly writing some shareware, one user of which turned into a contact who needed an office system writing, which then expanded out from there (I think I have 4 or 5 different clients that can be traced back to that one) and secondly from talking to my local computer hardware supplier who was sufficiently impressed by the shareware that he passed my name on as a competent developer to a couple of local companies who he knew were looking for work done - I've many that can be traced back to that.

Obviously your circumstances will differ, but I would strongly advise going down some version of this route rather than simply body-shopping as a code monkey on a rent a code website. You will always be less competitive than the eastern Europeans on such sites, instead consider how you might find face-to-face contacts. Writing shareware or open source as an Apprentice Piece to show you capabilities is a good move, and talk to your local computer shop or some other such people to get local contacts. Most business operates on a personal network basis - just because you're a coder doesn't make that any less true.

Added - Another good source of contacts who will know people who are looking for coding work done are local IT Support companies - the type of organization who look after the hardware and systems administration for local small businesses who won't have in-house IT staff. Generally they themselves won't have a coder on the books, but will be aware if their clients are looking for work done and may pass your name along or contract you themselves.

Dave Sherohman : Very good stuff and very true to my experience. Most of my current clients have come by way of a friend/former coworker who is now with a local IT support company of the sort described in the addition.
From Cruachan