Friday, April 8, 2011

Masked TextBox, how to include the promptchar to value?

How to include the prompt char on masked textbox's Text? I also want to save the prompt char

Example i specify mask: &&&&/&&

And prompt char of _

Then I enter 12 4/5. the program should save it as 12_4/5. Anything left blank should be converted to prompt char when getting the masked Textbox's Text

[EDIT]

Found it, set TaskMaskFormat to IncludePromptAndLiterals

From stackoverflow
  • You could create a derived class from the MaskedTextBox and then override the Text property. On setting you would find/replace the prompt char with a space and when getting replace the space with the prompt char.

Using Boost with Cygwin on Windows

This shoud be a simple problem for users more advanced than I am. :-) How do I use the boost library with cygwin on windows?

I am programing with g++ using cygwin on a winxp machine. I need modified Bessel functions of the second order, so I downloaded the latest version of the boost library and installed it in 'c:\cygwin\lib\boost_ 1_ 38_0\' folder.

I am trying to run the "example.cpp" program from the "getting started" section of their website: http://www.boost.org/doc/libs/1_35_0/more/getting_started/unix-variants.html

I am compiling from the directory where I created the example file using a simple Bash shell command line: 'g++ -Wall example.cpp'

I keep getting the message: "boost/lambda/lambda.hpp: no such file or directory"

I tried every possible combination of -L, -l, -I options in the command line to include the directory, to no avail. Also tried to add the folder in the PATH line of my windows system.

How do I link to the /boost directory and ALSO to all subdirectories? The header file 'lambda.hpp' is calling other header files in subdirectories.

From stackoverflow
  • You're probably not that familiar with C++ yet? It seems you are confusing terms.

    C++ programs are built in two steps: compiling and linking. In the first step, each source file (typically called .cpp) is handled individually. Each .cpp file usually uses multiple headers, so the compiler first inserts those - literally. That's why it's called #include.

    In the second step, the linker takes all the compiled .cpp files together and builds your final program. Some of those compiled .cpp's might have been bundled together before, in which the bundle is called a library.

    Boost is a collection of headers and .cpp files. So, both compiler and linker might need to find the Boost directories. From your error message, it's clear that the compiler step is the problem. The linker does not need headers anymore.

    The compiler will see the #include <boost/lambda/lambda.hpp> instuction. That means it needs to know where that first-level boost directory is found. I would guess at this point that the path would be /lib/boost_ 1_ 38_0/include (there's always the find / -name lambda.hpp shotgun appraoch)

  • If you are not utterly wedded to cygwin, you should take a look at http://nuwen.net/mingw.html which gives you a complete MinGW C++ installation with all the libraries (such as Boost) set up for you.

    Edit: I should make it clear you can use this MinGW installation in addition to Cygwin, not as a replacement. Just make sure the MinGW bin directory appears in your PATH before the Cygwin one.

  • I think you need -I /lib/boost_1_38_0 - although that's a pretty unusual place to put it. You'll have to let us know how you installed it, did you just unzip it in the location you said, or did you run the makefiles? I assume that since you gave a windows path you didn't install it within cygwin - which you probably should do. The instructions in the getting started guide for unix should help - although don't download a prebuilt bjam - it needs to be built with cygwin.

    But if you're not very familiar with cygwin (or unix in general) I think you might find it easier to use a native windows tool - as in Neil Butterworth's answer.

  • Thank you all for the information, it's a nice introduction to the use of libraries with cygwin. Daniel was right. While any variation gives an error, the following line (using caps i) does the trick:

    g++ -Wall -I /cygdrive/c/cygwin/lib/boost_1_38_0/ example.cpp -o example

    I will also check MinGW in the next few days.

    p.s. I simply downloaded and unzipped boost in that folder, but since I am only using header files I probably won't need to compile with cygwin. [The boost version included with cygwin was 1.33, which does not seem to have Bessel functions.]

multiple fork() question

I have a parent with 5 child processes. I'm wanting to send a random variable to each child process. Each child will square the variable and send it back to the parent and the parent will sum them all together.

Is this even possible? I can't figure it out...

edit: this process would use shared memory.

From stackoverflow
  • There are a great number of ways to do this, all involving some form of inter-process communication. Which one you choose will depend on many factors, but some are:

    • shared memory.
    • pipes (popen and such).
    • sockets.

    In general, I would probably popen a number of communications sessions in the parent before spawning the children; the parent will know about all five but each child can be configured to use only one.

    Shared memory is also a possibility, although you'd probably have to have a couple of values in it per child to ensure communications went smoothly:

    • a value to store the variable and return value.
    • a value to store the state (0 = start, 1 = variable ready for child, 2 = variable ready for parent again).

    In all cases, you need a way for the children to only pick up their values, not those destined for other children. That may be as simple as adding a value to the shared memory block to store the PID of the child. All children would scan every element in the block but would only process those where the state is 1 and the PID is their PID.

    For example:

    • Main creates shared memory for five children. Each element has state, PID and value.
    • Main sets all states to "start".
    • Main starts five children who all attach to the shared memory.
    • Main stores all their PIDs.
    • All children start scanning the shared memory for state = "ready for child" and their PID.
    • Main puts in first element (state = "ready for child", PID = pid1, value = 7).
    • Main puts in second element (state = "ready for child", PID = pid5, value = 9).
    • Child pid1 picks up first element, changes value to 49, sets state to "ready for parent"), goes back to monitoring.
    • Child pid5 picks up second element, changes value to 81, sets state to "ready for parent"), goes back to monitoring.
    • Main picks up pid5's response, sets that state back to "start.
    • Main picks up pid1's response, sets that state back to "start.

    This gives a measure of parallelism with each child continuously monitoring the shared memory for work it's meant to do, Main places the work there and periodically receives the results.

    kylex : i'd be using shared memory
    Jonathan Leffler : You probably don't need to do the scanning; the children get a copy of the parent process data, so (unlike the vfork() example) the children could look at a counter that tells them which entry is theirs. You could preload the memory with the random values,; then the children know the data is ready.
    paxdiablo : That'll work if you just fork (with parent and child code in the same executable) but not if you exec to bring in the child: the process space is overwritten (including a counter). Not execing generally leaves a lot of dangerous things about that are shared between both forks. Still, it's an option.
  • The nastiest method uses vfork() and lets the different children trample on different parts of memory before exiting; the parent then just adds up the modified bits of memory.

    Highly unrecommended - but about the only case I've come across where vfork() might actually have a use.

    Just for amusement (mine) I coded this up:

    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <time.h>
    #include <sys/wait.h>
    
    int main(void)
    {
        int i;
        int array[5];
        int square[5];
        long sum = 0;
    
        srand(time(0));
        for (i = 0; i < 5; i++)
        {
            array[i] = rand();
            if (vfork() == 0)
            {
                square[i] = array[i] * array[i];
                execl("/bin/true", "/bin/true", (char *)0);
            }
            else
                wait(0);
        }
    
        for (i = 0; i < 5; i++)
        {
            printf("in: %d; square: %d\n", array[i], square[i]);
            sum += square[i];
        }
        printf("Sum: %d\n", sum);
        return(0);
    }
    

    This works. The previous trial version using 'exit(0)' in place of 'execl()' did not work; the square array was all zeroes. Example output (32-bit compilation on Solaris 10, SPARC):

    in: 22209; square: 493239681
    in: 27082; square: 733434724
    in: 2558; square: 6543364
    in: 17465; square: 305026225
    in: 6610; square: 43692100
    Sum: 1581936094
    

    Sometimes, the sum overflows - there is much room for improvement in the handling of that.

    The Solaris manual page for 'vfork()' says:

    Unlike with the fork() function, the child process borrows the parent's memory and thread of control until a call to execve() or an exit (either abnormally or by a call to _exit() (see exit(2)). Any modification made during this time to any part of memory in the child process is reflected in the parent process on return from vfork(). The parent process is suspended while the child is using its resources.

    That probably means the 'wait()' is unnecessary in my code. (However, trying to simplify the code seemed to make it behave indeterminately. It is rather crucial that i does not change prematurely; the wait() does ensure that synchronicity. Using _exit() instead of execl() also seemed to break things. Don't use vfork() if you value your sanity - or if you want any marks for your homework.)

    Craig S : Interesting. You also don't need `pid_t pid`, by the way. On Mac OS X, I get incorrect results, too. It printed 2 blocks of output, and some of the squares were obviously wrong. After the 2nd block of output, the process is hung (but taking no cycles). Haven't tried to debug it though.
    Jonathan Leffler : @Craig S: yup - you're right about pid. It is a hangover from an experiment while debugging. I'll remove it. Fundamentally, vfork() is evil; I'm amused to have found a potential (but not good!) use for it.
    Craig S : Yes, and vfork() is not very portable either. It is amusing to see it in action. Maybe tomorrow I'll come up with my own solution that works on Mac OS X. I also wonder what would happen if you called _exit(), not exit(), instead of exec'ing /bin/true.
    Jonathan Leffler : I tried _exit() as noted; it didn't seem to work properly. That is, I got odd results: in: 25671; square: 3 in: 27310; square: -2147485992 in: 14472; square: 4 in: 1771; square: -2147485976 in: 26575; square: 5 Sum: -4294971956 (Sorry, that's all smushed up, of course. _exit() and wait().
    codelogic : On OS X, "true" is in "/usr/bin", hence the error. _exit(0) works as well though.
    Craig S : Ah, it was the end of my day and I never thought to check the location of `true` on OS X.
  • Things like the anti thread might make this a little easier for you, see the examples (in particular the ns lookup program).

SQL To search the entire MS SQL 2000 database for a value.

I would like to search an entire MS SQL 2000 database for one value. This would be to aid development only. Keep that in mind when considering this question.

This will get all the table names and the column of the data type I'm looking for:

SELECT Columns.COLUMN_NAME, tables.TABLE_NAME
FROM INFORMATION_SCHEMA.Columns as Columns 
JOIN INFORMATION_SCHEMA.TABLES as tables 
On Columns.TABLE_NAME = tables.TABLE_NAME
WHERE Columns.DATA_TYPE = 'INT'

I was thinking something like this:

-- Vars
DECLARE @COUNTER INT
DECLARE @TOTAL INT
DECLARE @TABLE CHAR(128)
DECLARE @COLUMN CHAR(128)
DECLARE @COLUMNTYPE CHAR(128)
DECLARE @COLUMNVALUE INT

-- What we are looking for
SET @COLUMNTYPE = 'INT'
SET @COLUMNVALUE = 3
SET @COUNTER = 0

-- Find out how many possible columns exist
SELECT @TOTAL = COUNT(*)  
FROM INFORMATION_SCHEMA.Columns as Columns 
JOIN INFORMATION_SCHEMA.TABLES as tables 
On Columns.TABLE_NAME = tables.TABLE_NAME
WHERE Columns.DATA_TYPE = @COLUMNTYPE
PRINT CAST(@TOTAL AS CHAR) + 'possible columns'
WHILE @COUNTER < @TOTAL
BEGIN
    SET @COUNTER = @COUNTER +1
    -- ADD MAGIC HERE
END

Any ideas?

UPDATE I recently found this tool that works quite well.

From stackoverflow
  • Since it is dev only (and probably doesn't have to be very elegant), how about using TSQL to generate a pile of TSQL that you then copy back into the query window and execute?

    SELECT 'SELECT * FROM [' + tables.TABLE_NAME + '] WHERE ['
           + Columns.Column_Name + '] = ' + CONVERT(varchar(50),@COLUMNVALUE)
    FROM INFORMATION_SCHEMA.Columns as Columns
    INNER JOIN INFORMATION_SCHEMA.TABLES as tables 
        On Columns.TABLE_NAME = tables.TABLE_NAME
    WHERE Columns.DATA_TYPE = @COLUMNTYPE
    

    It won't be pretty, but it should work... an alternative might be to insert something like the above into a table-variable, then loop over the table-variable using EXEC (@Sql). But for dev purposes it probably isn't worth it...

What screen size is better for end user

I have a SW that the minimal screen size requirement is 1024x768, 800x600 may be too small, 1024x768 would be too big? Maybe something in between? What screen size is better or the best? Thanks.

From stackoverflow
  • Are you asking what size you should design your application for?? If so, the best "size" would be a flowing layout that allows the user to set whatever size suits them and their monitor.

  • Check out the browser display statistics at w3schools, it might be a good start. But beware, as they say:

    W3Schools is a website for people with an interest for web technologies. This fact indicates that the figures below might not be 100% realistic. The average user might have display screens with a lower resolution.

    It's all up to how well you can determine your user segment.

  • Nowdays, 1024x768 is the standard and preferred screen size. Most of the web based applications, web-sites design their sites as per 1024x768 standard. But, you could go for a lesser intial size if yours is a desktop allipcation. But then you have to make sure that UI doesn't go bad when you maximize the application to a higher resolution.

  • You can set your minimum size to whatever you want, as long as your software looks nice on all sizes greater than that.

    I'd be surprised if many people still ran 800x600 but they may, and you will be limiting your market by not handling it. Personally, I don't think that would be much of a limit.

    In addition, there's not a lot between 800x600 and 1024x768, they're the two "standard" resolutions right next to each other. So if you think 1024x768 is too big (it's not), 800x600 is the next option down.

  • [I assume you are referring to a desktop application]

    Though 1024x768 is a reasonable screen resolution which is supported by all recent monitors (purchased in last 4 years I guess), yet I most software still work with 800x600.

    What makes your software require that resolution? I hope you dont have a dialog which is that big. If there are some, consider splitting them into tab sheets or wizards.

  • Only dialog boxes should be fixed size, and not all of them. All other UI windows should use flow-based layout so as to adapt to the available window. There is extensive support for the management of dynamic layout in WinForms and even better support in XAML.

    You may well have seen websites designed for fixed width but this is IMHO a sign of either incompetence or laziness. Or possibly a triumph of form over function.

    None of these is a good excuse. They all look ridiculous on my 3840x1200 display (two linked 1920x1200 monitors) and come the revolution, designers of fixed-layout UI will be the first up against the wallscreen.

    bobince : ‘Only dialogs’... and of course if you've got a dialog box that needs more than 800x600, it's very unlikely to be at all usable and you should probably consider refactoring the interface.
  • it doesn't matter if you can't find a 1024x768 or lower monitor these days. even if everybody has 1920x1200, why should your app be the only one on screen? the idea of windowing GUIs is to use several windows at the same time.

    i, for one, never use the 'maximize' button. even really immersive apps (think CADs) should leave some space for other tools.

    paxdiablo : That's interesting - I actually maximize *everything* since I generally want to concentrate on one thing at a time without distraction (my wife doesn't do that but she explains that it's because I'm a man and can't do more than one thing concurrently :-)
    Javier : this is a very common vice. i think the responsibles are 1: bad UI designers that leave very little usable area on each window and 2:MDI, which obscures everything not inside it's 'window' (how can you call 'window' something that's effectively the whole screen? it makes no sense at all)
  • I am surprised that nobody has mentioned netbooks. If your application could conceivably run on a netbook, you may want to consider resolutions lower than 1024x768. For instance, the 7" Asus EeePC has a resolution of 800x480 and the 9" to 10" models typically have a resolution of 1024x600.

    EDIT: Agreed that a flowing layout should be used regardless, but I was talking about the minimum size that should work.

  • ~960px wide is a pretty common standard these days.

  • For a Windows app, design it for 800x600. That way users with 1024x768 screens don't need to maximize the Window to see everything (and the few users with 800x600 screens can still view it).

    Javier : where's the +10 button?
  • The ultimate thing you need to do is to find out what your target audience is running, or is likely to run. That said, your applications should be able to cope with nearly any reasonable screen resolution. It doesn't have to look pretty at excessively low resolutions, but it does have to be functional at excessively low resolutions. I know several applications that lack the functional-at-low-resolutions part, and they are rather annoying.

    If your application is something that is more crucial than usual, you'll want to make even more sure that it will work in resolution-constrained environments. For both Windows and Linux systems, the default fail-safe resolution (depending on the system) is either 640x480 or 800x600. If you expect your application to be considered critical, it should be able to work in even such restrictive conditions.

Using objects as a data source for a remote SQL Server Reporting Services report

Is it possible to use objects as a datasource for a remote SSRS report? I know it is possible to use objects locally from within an application. I would like to like to use business objects as a data source for reports that are run on the SSRS server. In the past I have created stored procedures that returned the same information as my business objects. This is redundant and therefore would like to find a better way.

Would it work if I expose my business objects as web services?

From stackoverflow
  • Based on my experience this cannot be done with SSRS reports, at least not easily and sensibily. You can add custom assemblies to enhance what you can do with code expressions but I doubt you'll get much ROI on trying to bind the SSRS controls to the objects through the expressions.

  • I did something like this in a less than ideal way when integrating reporting services into a larger application. Because I needed reports run against different databases with identical schemas depending on the client database they were coming from I used a custom authentication provider to have my reporting services code deploy a new report for a client user the first time it is requested for that client. (The rdl files are stored in my client databases and on login they are deployed and I programmatically change datasources when it is being deployed the first time for that client).

    This solution worked well for my situation but it's fairly involved and probably not exactly what you're looking for. If you can, http://www.gotreportviewer.com/ might suit your needs.

CastException attempting to call Action<KeyValuePair<>> delegate asynchronously

I can't seem to figure out why I am getting an InvalidCastException running the following code:

var item = new KeyValuePair<string, string>("key", "value");

Action<KeyValuePair<string, string>> kvrAction = 
    kvr =>Console.WriteLine(kvr.Value);

var result = kvrAction.BeginInvoke(item, null, null);
kvrAction.EndInvoke(result);

Exception Info:

Test method Utilities.Tests.IEnumerableExtensionTests.ProveDelegateAsyncInvokeFailsForKeyValuePair threw exception:  System.Runtime.Remoting.RemotingException: The argument type '[key, value]' cannot be converted into parameter type 'System.Collections.Generic.KeyValuePair`2[System.String,System.String]'.
--->  System.InvalidCastException: Object must implement IConvertible..

Any assistance would be appreciated =) This code seems to work with anything I throw at it except a KeyValuePair<>.

Update: It appears this condition exists for any struct. I hadn't noticed KeyValuePair<> was a struct and so was only testing with classes. I still don't understand why this is the case though.

Update 2: Simon's answer helped confirm this behavior is unexpected, however implementing a custom type won't work for what I'm trying to do. I am trying to implement an extension method on IEnumerable<> to execute a delegate Asynchronously for each item. I noticed the error running tests against a generic Dictionary object.

    public static IEnumerable<T> ForEachAsync<T>(this IEnumerable<T> input, Action<T> act)
    {
        foreach (var item in input)
        {
            act.BeginInvoke(item, new AsyncCallback(EndAsyncCall<T>), null);
        }

        return input;
    }

    private static void EndAsyncCall<T>(IAsyncResult result)
    {
        AsyncResult r = (AsyncResult)result;
        if (!r.EndInvokeCalled)
        {
            var d = (Action<T>)((r).AsyncDelegate);
            d.EndInvoke(result);
        }
    }

I would rather not limit the method with a constraint on T to ensure only classes are used so I have refactored the method as follows to get around the problem with BeginInvoke but I have not worked with the TreadPool directly before and would like to make sure I am not missing anything important.

    public static IEnumerable<T> ForEachAsync<T>(this IEnumerable<T> input, Action<T> act)
    {
        foreach (var item in input)
            ThreadPool.QueueUserWorkItem(obj => act((T)obj), item);

        return input;
    }
From stackoverflow
  • Odd, seems to be some sort of bug in .NET (C#?) with marshalling the argument to the worker thread.

    If you implement IConvertable on the passed struct:

    struct MyPair<TKey, TValue> : IConvertable
    {
     public readonly TKey Key;
     public readonly TValue Value;
    
     public MyPair(TKey key, TValue value)
     {
      Key = key;
      Value = value;
     }
    
     // I just used the smart-tag on IConvertable to get all these...
     // public X ToX(IFormatProvider provider) { throw new InvalidCastException(); }
    
     ...
    
     public object ToType(Type conversionType, IFormatProvider provider)
     {
      if (typeof(MyPair<TKey, TValue>).GUID == conversionType.GUID)
       return this;
      throw new InvalidCastException();
     }
    }
    

    It runs fine. The passed conversionType doesnt pass .Equal(), IsAssignableFrom(), or anything else I tried except GUID comparison, which is probably related to why it asks for an IConvertable in the first place.

    EDIT: A simple workaround is to use closures to pass the parameter:

    var data = new Dictionary<string, string> {
     { "Hello", "World" },
     { "How are", "You?" },
     { "Goodbye", "World!" }
    };
    foreach (var pair in data)
    {
     var copy = pair; // define a different variable for each worker
     Action worker = () => Console.WriteLine("Item {0}, {1}", copy.Key, copy.Value);
     worker.BeginInvoke(null, null);
    }
    

    Of course, if you need the results, you will need to store the IAsyncResults, which will probably have the same issue as parameters, in the other direction. As an alternative, you could add them to a collection when they are complete, but the locking gets a bit weird:

    var data = new Dictionary<string, string> {
     { "Hello", "World" },
     { "How are", "You?" },
     { "Goodbye", "World!" }
    };
    
    var results = new List<KeyValuePair<string, string>>();
    var pending = 0;
    var done = new ManualResetEvent(false);
    
    var workers = new List<Action>();
    foreach (var pair in data)
    {
     ++pending;
     var copy = pair; // define a different variable for each worker
     workers.Add(delegate()
     {
      Console.WriteLine("Item {0}, {1}", copy.Key, copy.Value);
      lock (results)
       results.Add(new KeyValuePair<string, string>("New " + copy.Key, "New " + copy.Value));
      if (0 == Interlocked.Decrement(ref pending))
       done.Set();
     });
    }
    
    foreach (var worker in workers)
     worker.BeginInvoke(null, null);
    
    done.WaitOne();
    
    foreach (var pair in results)
     Console.WriteLine("Result {0}, {1}", pair.Key, pair.Value);
    
    Venr : Thanks Simon, I'm glad I wasn't just overlooking something silly. I assume its a bug in the framework causing the type checks to fails resulting in check for the IConvertable interface. Unfortunately implementing a custom type is not an option for what I am trying to do. I more detail to come.

Regarding Mysql Master-slave configuration

Hi to all,

I am developing one social-networking. For DB Load Balancing, i want to use Master-slave Replication in Mysql.

Before start working on Replication, i want to know something like

1) How can we setup that replication

2) what is the advantage & Dis-advantages of Master-slave Replication

3) when we are using "select" queries, Is that , we need to send request to Master or Slave (manually)

or Master automatically sent to slave...i want to know about this.

4) can we install Master & Slaves in one system(i.e. CPU)? is it suggestable?

Thanks in advance

From stackoverflow
  • Firstly, read the MySQL Replication documentation. It's very useful and will answer a lot of questions you haven't even realized you will need to ask.

    Handling replication in your application means you can distribute the SELECT statements. They don't need to replicate and will return the same results no matter which server they hit. However, UPDATE, INSERT and DELETE statements must occur on the master.

    Remember that replication spreads the read load, but every server still has the same write load. Depending on your query read/write ratio, this might not be appropriate. (Check out LiveJournal's presentation about how they scaled. It's easy to find.)

    Edit: Meant to reference LiveJournal, not Facebook. D'oh!

    : thanks for your answer

Is it possible to install SSRS Report Manager by itself?

I've been asked to look into writing an installer that will just set up Reporting Service's Report Manager by itself on a machine.

Is this possible? My web searching has not given me a good answer.

From stackoverflow

Remove end of line characters from Java string

I have string like this

"hello
java
book"

I want remove \r and \n from string(hello\r\njava\r\nbook). I want string as "hellojavabook". How can i do this?

From stackoverflow
  • Given a String str:

    str = str.replaceAll("\\\\r","")
    str = str.replaceAll("\\\\n","")
    
    Rob Lachlan : Zounds. Beat me to it!
    Software Monkey : This is an unnecessarily inefficient way to do it.
  • Have you tried using the replaceAll method to replace any occurence of \n or \r with the empty String?

  • str = "hello java book" str.replaceAll("\r", "") str.replaceAll("\n", "")

    Not that I know java or anything, but I got the info from Google in less than 2 seconds.

    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)

    wds : Which is why you got the escaping of the \r wrong. :)
  • Regex with replaceAll.

    public class Main
    {
        public static void main(final String[] argv) 
        {
            String str;
    
            str = "hello\r\njava\r\nbook";
            str = str.replaceAll("(\\r|\\n)", "");
            System.out.println(str);
        }
    }
    

    If you only want to remove \r\n when they are pairs (the above code removes either \r or \n) do this instead:

    str = str.replaceAll("\\r\\n", "");
    
  • If you want to avoid the regex, or must target an earlier JVM, String.replace() will do:

    str=str.replace("\r","").replace("\n","");
    

    And to remove a CRLF pair:

    str=str.replace("\r\n","");
    

    The latter is more efficient than building a regex to do the same thing. But I think the former will be faster as a regex since the string is only parsed once.

  • static byte[] discardWhitespace(byte[] data) {
        byte groomedData[] = new byte[data.length];
        int bytesCopied = 0;
    
        for (int i = 0; i < data.length; i++) {
            switch (data[i]) {
                case (byte) '\n' :
                case (byte) '\r' :
                    break;
                default:
                    groomedData[bytesCopied++] = data[i];
            }
        }
    
        byte packedData[] = new byte[bytesCopied];
    
        System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
    
        return packedData;
    }
    

    Code found on commons-codec project.

How to pass parameter values to a T-SQL query

I am using the following T-SQL query in SQL server 2005 (Management Studio IDE):

DECLARE @id int;
DECLARE @countVal int;
DECLARE @sql nvarchar(max);
SET @id = 1000;
SET @sql = 'SELECT COUNT(*) FROM owner.myTable WHERE id = @id';
EXEC (@sql) AT oracleServer -- oracleServer is a lined server to Oracle

I am not sure how to pass the input parameter @id to the EXEC query, and pass the count result out to @countVal. I saw some examples for Microsoft SQL server like:

EXEC (@sql, @id = @id)

I tried this for Oracle but I got a statement error:

OLE DB provider "OraOLEDB.Oracle" for linked server "oracleServer" 
returned message "ORA-00936: missing expression"
From stackoverflow
  • I don't know why you are pass id separately.

    You could do the following
    SET @sql = 'SELECT COUNT(*) FROM owner.myTable WHERE id = ' + @id

    David.Chu.ca : Input parameter is fine in this way, but how about the result?
  • Try this:

    EXEC sp_executesql @sql, N'@id int', @id
    

    More info at this great article: http://www.sommarskog.se/dynamic_sql.html


    As for the output, your SELECT needs to look something like this:

    SELECT @countVal = COUNT(id) FROM owner.myTable WHERE id = @id
    

    I'm selecting 'id' instead of '*' to avoid pulling unnecessary data...

    Then your dynamic sql should be something like this:

    EXEC sp_executesql @sql, 
                       N'@id int, @countVal int OUTPUT', 
                       @id, 
                       @countVal OUTPUT
    

    This example is adapted from the same article linked above, in the section sp_executesql.


    As for your Oracle error, you will need to find out the exact SQL that sp_executesql is sending to Oracle. If there is a profiler or query log in Oracle, that may help. I have limited experience with Oracle, but that would be the next logical step for troubleshooting your problem.

    David.Chu.ca : The EXEC() example does not work with Oracle, very sad. If not parameters in @sql, it runs fine. I have no clue to use pass-through query for Oracle db with output parameter back to SQL.
    David.Chu.ca : SET @sql = 'select ? = count(*) from owner.mytable'; exec (@sql, @countVal output) at oracleServer -- failure for Oracle case
  • The quick and dirty way is to just build the string before using the EXEC statement, however this is not the recommended practice as you may open yourself up to SQL Injection.

    DECLARE @id int;
    DECLARE @countVal int;
    DECLARE @sql nvarchar(max);
    SET @id = 1000;
    SET @sql = 'SELECT COUNT(*) FROM owner.myTable WHERE id = ' + @id 
    EXEC (@sql) AT oracleServer -- oracleServer is a lined server to Oracle
    

    The correct way to do this is to use the system stored procedure sp_executesql as detailed by magnifico, and recommended by Microsoft in Books Online is:

    EXEC sp_executesql @sql, N'@id int', @id
    

Sort algorithm to use for this specific scenario

I have two lists - let's call them details and totals.

The items in details have multiple elements for each key that the list is sorted on, as such:

KEY1
KEY1
KEY2
KEY2
KEY3
KEY3
KEY3
etc

The items in totals will only have each key once, as such:

KEY1
KEY2
KEY3
etc

Both lists are sorted by key already. The lists need to be combined so that the new list has the details elements followed by it's corresponding element from totals, as such:

KEY1 (this is from details)
KEY1 (this is from details)
KEY1 (this is from totals) etc

Which sorting algorithm will result in the best performance in this scenario?

(in all honesty, I'm just going to change the code so that the row from totals is created-and-inserted as the details list is being built, this is more of an academic question)

From stackoverflow
  • If you're looking at combining the two lists into one, and they're sorted already, you shouldn't be resorting.

    A simple merge will do, as follows. This is assuming your assumptions are correct and there are no "naked" detail or total lines (details without totals or totals without details). If there are, you'll need extra code to handle that but the principle is the same.

    Get first detail-list
    Get first total-list
    
    While total-list not finished:
        If detail-list.key > total-list.key:
            Output total-list
            Get next total-list
            Next while
        Output detail-list
        Get next detail-list
    
    rjohnston : I guess when I said "sorting" I meant "putting elements in order". The existing code does a sort because the lists aren't in order, I've just updated the DB to return them sorted correctly.

What is a namespace and how is it implemented in PHP?

I've heard the latest PHP has support for namespaces. I know variables defined in the global scope have no namespace, so how does one make a variable in a different namespace?

Is it just a way of categorising variables/functions?

From stackoverflow
  • Namespaces are often used with libraries, the ability to reference the library code with 1 single namespace helps to not clobber up others that are already being used.

  • A namespace allows you to organize code and gives you a way to encapsulate your items.

    You can visualize namespaces as a file system uses directories to group related files.

    Basically namespaces provide you a way in which to group related classes, functions and constants.

    They also help to avoid name collisions between your PHP classes/functions/constants, and improve the code readability, avoiding extra-long class names.

    Example namespace declaration:

    <?php
    namespace MyProject;
    
    const CONNECT_OK = 1;
    class Connection { /* ... */ }
    function connect() { /* ... */  }
    
    ?>
    
    alex : So for a bunch of string helper functions, I should get them out of static functions in a class and do namespace String; function match() { } etc?
  • Namespaces solve the problem of naming collisions when importing classes and functions from libraries.

    Without namespaces, if you include two libraries which happen to define a function/class with the same name (ie, two libraries that both include a class called 'user'), it will fail.

    With no namespace support in PHP, most libraries have taken to prefixing their function/class names with something that is likely to be unique, in an attempt to avoid name collisions. The trouble is, this creates longer function or class names.

    The example given here is of the exception class:

    PEAR_Form_Loader_Validate_Table_Element_Validator_Exception.
    

    You can import from a long namespace into your own local scope as an alias using the 'AS' keyword - a name you choose. Thus, you can still have a short class name of your choice in your local scope.

    The following applies an 'alias' called DbConnection to Zend::DB::Connection.

    use Zend::DB::Connection as DbConnection
    
  • Namespaces are a programming language mechanism for organizing variables, functions and classes. PHP 5.3 adds support for namespaces, which I'll demonstrate in the following example:

    Say you would like to combine two projects which use the same class name User, but have different implementations of each:

    // Code for Project One (proj1.php)
    <?php
      class User {
        protected $userId;
        public function getUserId() {
          return $this->userId;
        }
      }
      $user = new User;
      echo $user->getUserId();
    ?>
    
    // Code for Project Two (proj2.php)
    <?php
      class User {
        public $user_id;
      }
      $user = new User;
      echo $user->user_id;
    ?>
    
    <?php
      // Combine the two projects
      require 'proj1.php';
      require 'proj2.php'; // Naming collision!
      $myUser = new User; // Which class to use?
    ?>
    

    For versions of PHP less than 5.3, you would have to go through the trouble of changing the class name for all instances of the class User used by one of the projects to prevent a naming collision:

    <?php
      class ProjectOne_User {
        // ...
      }
      $user = new ProjectOne_User; // Code in Project One has to be changed too
    ?>
    

    For versions of PHP greater than or equal to 5.3, you can use namespaces when creating a project, by adding a namespace declaration:

    <?php
      // Code for Project One (proj1.php)
      namespace ProjectOne;
      class User {
        // ...
      }
      $user = new User;
    ?>
    
    <?php
      // Combine the two projects
      require 'proj1.php';
    
      use ProjectOne as One; // Declare namespace to use
    
      require 'proj2.php' // No collision!
    
      $user = new \One\User; // State which version of User class to use (using fully qualified namespace)
    
      echo $user->user_id; // Use ProjectOne implementation
    ?>
    

    For more information:

    Mohit Nanda : very well illustrated, with comments and code. +1
    invenetix : Agreed. Very well done. I just wish they went with a different delimiter between namespace and class. :(
    jakemcgraw : With the whole delimiter griping: it will work perfectly fine if you only use single quoted strings which I do for every string in php except for newlines
    jasondavis : great example and explanation, I was completely lost on what namespaces do and php.net did not help at all but your answer does, thanks +1
    Vili : Update: namespace delimiter happened to be \ instead of ::
    jakemcgraw : @Vili updated thanks

drawRect question

When I call setNeedsDisplayInRect on a UIView, and the drawRect method fires...am I responsible for making sure I'm not rendering stuff that's outside the CGRect I called, or will the framework handle that for me? Example:

-(void)drawRect:(CGRect)rect
{
  //assume this is called through someMethod below
  CGContextRef ctx = UIGraphicsGetCurrentContext();      
  [[UIColor redColor] setFill];
  CGContextFillRect(ctx, rect);
  [[UIColor blueColor] setFill];
  // is this following line a no-op? or should I check to make sure the rect
  // I am making is contained within the rect that is passed in?
  CGContextFillRect(ctx, CGRectMake(100.0f, 100.0f, 25.0f, 25.0f));

}

-(void)someMethod
{
  [self setNeedsDisplayInRect:CGRectMake(50.0f, 50.0f, 25.0f, 25.0f)];
}

Thanks!

From stackoverflow
  • The framework will clip your drawing. On OS X (AppKit), drawing is clipped to the dirty areas of the NSView (as of 10.3). I'm not sure what the exact clipping algorithm is in UIKit. Of course, you can speed drawing by checking what needs to be drawn and only drawing in the dirty areas of the view, rather than relying on the framework to clip unnecessary drawing.

  • To simplify what Barry said: Yes, the framework will handle it for you.

    You can safely ignore the rect, anything you draw outside of it will be ignored.

    On the other hand, if you draw outside of the rect you are wasting CPU time, so if you can limit your drawing based on the rect, you should.

Is there a basic Java Set implementation that does not permit nulls?

The API for the Java Set interface states:

For example, some implementations prohibit null elements, and some have restrictions on the types of their elements

I am looking for a basic Set implementation that does not require ordering (as ArrayList provides for the List interface) and that does not permit null. TreeSet, HashSet, and LinkedHashSet all allow null elements. Additionally, TreeSet has the requirement that elements implement Comparable.

It seems that no such basic Set exists currently. Does anyone know why? Or if one does exist where I can find it?

[Edit]: I do not want to allow nulls, because later in the code my class will iterate over all elements in the collection and call a specific method. (I'm actually using HashSet<MyRandomObject>). I would rather fail fast than fail later or accidentally incur some bizarre behavior due to a null being in the set.

From stackoverflow
  • You could easily write your own, by subclassing an appropriate existing class, and overriding all relevant methods so that you can't add null elements.

    Paul Tomblin : Don't you hate it when somebody puts in the answer while you're typing the same answer?
    Paul Tomblin : Don't forget allAll and the constructors!
    Eric Petroelje : Actually, addAll and the constructors don't need to be overridden since they are defined in AbstractSet and AbstractCollection to simply call the add method. So only add really needs to be overridden.
    cdmckay : You might be better off using composition instead of subclassing, since you're not in control of the class you are subclassing (what if Sun adds a new method to sets that would allow users to add null?)
    Steve Kuo : You are better off wrapping a Set implementation.
  • I am not sure of a type which this is true. But could you not inherit from a collection or HashTable of your choice and override the Add method, throwing an exception if the element is null?

  • Why do you not want to allow null?

    Do you want to throw an exception if null is added to your set? If so, just do something like this:

    private Set<Object> mySet = new HashSet<Object>() {
        @Override
        public boolean add(Object e) {
            if (e == null)
                throw new IllegalArgumentException("null"); // or NPE
            // or, of course, you could just return false
            return super.add(e);
        }
    };
    

    HashSet's addAll() calls add() repeatedly, so this is the only method you'd have to override.

    cdmckay : You should not count on addAll() calling add() as that is an implementation detail and may not always be true.
    Michael Myers : @cdmckay: If you haven't already upvoted Tom Hawtin's answer, do it now! :)
    Michael Myers : Oh, I see you've added your own answer instead.
    matt b : @cdmckay - if you extend HashSet, that is always true...
    Darron : @matt b: is this true of the HashSet in IBM's JVM? JRocket? GNU Classpath? The new optimized one in Sun's Java 8? Unless this is in the JLS you can't count on it.
  • Better than extending a particular implementation, you can easily write a proxy implementation of Set that checks for nulls. This analogous to Collections.checkedSet. Other than being applicable to any implementation, you can also be sure that you have overridden all applicable methods. Many flaws have been found by extending concrete collections which then have additional methods added in later versions.

    Michael Myers : A little more work, but that's a good idea. +1
    Michael Myers : Actually, it might not even be more work.
    Aaron K : Any idea why Sun didn't do this already?
    duffymo : +1 - terrific thought.
    Steve Kuo : A much better idea than inheritance
    Tom Hawtin - tackline : Sun? Updates to the collection framework are likely to be driven by Google. Btw, there should hopefully be a collections BOF a JavaOne.
  • I would say use composition instead of inheritance... it might be more work but it'll be more stable in the face of any changes that Sun might make to the Collections Framework.

    public class NoNullSet<E> implements Set<E>
    {
       /** The set that is wrapped. */
       final private Set<E> wrappedSet = new HashSet<E>();
    
       public boolean add(E e)
       {
         if (e == null) 
           throw new IllegalArgumentException("You cannot add null to a NoNullSet");
         return wrappedSet.add(e);
       }
    
       public boolean addAll(Collection<? extends E> c)
       {
         for (E e : c) add(e);
       }
    
       public void clear()
       { wrappedSet.clear(); }
    
       public boolean contains(Object o)
       { return wrappedSet.contains(o); }
    
       ... wrap the rest of them ...
    }
    

    Edit: Also note that this implementation does not depend on addAll calling add (which is an implementation detail and should not be used because it cannot be guaranteed to remain true in all Java releases).

    Edit: Added more descriptive error message.

    Edit: Made it so clear() doesn't return anything.

    Edit: Made it so it's add(E e).

    Edit: Throws IllegalArgumentException instead of NullPointerException.

    Thorbjørn Ravn Andersen : instead of throwing NullPointerException, consider throwing RuntimeException("e == null") (or an IllegalArgumentException) as this tells the developer reading the stacktrace that this is a deliberately thrown exception and not a logic error.
    matt b : Or an add a descriptive message to the NullPointerException. Also, +1 for compisition over inheritance.
    Steve Kuo : throw IllegalArgumentException as that is what it's for, an illegal argument (null)
    Andrew Coleson : Should fix your void clear() to not return anything, but otherwise +1 for sample code and composition.
    Nikhil Chelliah : Should be add(E e), not add(E o).
    Shervin : Also there is an error in your add method. It should `return wrappedSet.add(e)`.
    cdmckay : @Shervin: Fixed, thanks.
    Jason S : I'd suggest not explicitly allocating a HashSet, but instead take a Set argument in the constructor. This then makes NoNullSet a decorator class that can work w/ HashSet or TreeSet or EnumSet or whatever.
  • You may also wish to check out Google Collections. They are more null phobic, I believe.

  • You could use apache collections and its PredicatedCollection class, and set the predicate to not allow nulls. You will get exceptions if someone sends nulls in.

  • This is a failry general purpose way of doing it - you provide a Filter implementation that can restrict what gets added in whatevber way you want. Take a look at the source for java.util.Collections for ideas on the wrapping (I think my implementaiton of the FilteredCollection class is correct... but it is not extensivly tested). There is a sample program at the end that shows the usage.

    public interface Filter<T>
    {
        boolean accept(T item);
    }
    
    import java.io.Serializable;
    import java.util.Collection;
    import java.util.Iterator;
    
    
    public class FilteredCollections
    {
        private FilteredCollections()
        {
        }
    
        public static <T> Collection<T> filteredCollection(final Collection<T> c,
                                                           final Filter<T>     filter)
        {
            return (new FilteredCollection<T>(c, filter));
        }
    
        private static class FilteredCollection<E>
            implements Collection<E>,
                       Serializable
        {
            private final Collection<E> wrapped;
            private final Filter<E> filter;
    
            FilteredCollection(final Collection<E> collection, final Filter<E> f)
            {
                if(collection == null)
                {
                    throw new IllegalArgumentException("collection cannot be null");
                }
    
                if(f == null)
                {
                    throw new IllegalArgumentException("f cannot be null");
                }
    
                wrapped = collection;
                filter  = f;
            }
    
            public int size()
            {
                return (wrapped.size());
            }
    
            public boolean isEmpty()
            {
                return (wrapped.isEmpty());
            }
    
            public boolean contains(final Object o)
            {
                return (wrapped.contains(o));
            }
    
            public Iterator<E> iterator()
            {
                return new Iterator<E>()
                {
                    final Iterator<? extends E> i = wrapped.iterator();
    
                    public boolean hasNext()
                    {
                        return (i.hasNext());
                    }
    
                    public E next()
                    {
                        return (i.next());
                    }
    
                    public void remove()
                    {
                        i.remove();
                    }
                };
            }
    
            public Object[] toArray() 
            {
                return (wrapped.toArray());
            }
    
            public <T> T[] toArray(final T[] a)
            {
                return (wrapped.toArray(a));
            }
    
            public boolean add(final E e)
            {
                final boolean ret;
    
                if(filter.accept(e))
                {
                    ret = wrapped.add(e);
                }
                else
                {
                    // you could throw an exception instead if you want - 
                   // IllegalArgumentException is what I would suggest
                    ret = false;
                }
    
                return (ret);
            }
    
            public boolean remove(final Object o)
            {
                return (wrapped.remove(o));
            }
    
            public boolean containsAll(final Collection<?> c)
            {
                return (wrapped.containsAll(c));
            }
    
            public boolean addAll(final Collection<? extends E> c)
            {
                final E[] a;
                boolean   result;
    
                a = (E[])wrapped.toArray();
    
                result = false;
    
                for(final E e : a)
                {
                    result |= wrapped.add(e);
                }
    
                return result;
            }
    
            public boolean removeAll(final Collection<?> c)
            {
                return (wrapped.removeAll(c));
            }
    
            public boolean retainAll(final Collection<?> c)
            {
                return (wrapped.retainAll(c));
            }
    
            public void clear() 
            {
                wrapped.clear();
            }
    
            public String toString()
            {
                return (wrapped.toString());
            }
        }
    }
    
    
    import java.util.ArrayList;
    import java.util.Collection;
    
    
    public class Main
    {
        private static class NullFilter<T>
            implements Filter<T>
        {
            public boolean accept(final T item)
            {
                return (item != null);
            }
        }
    
        public static void main(final String[] argv) 
        {
            final Collection<String> strings;
    
            strings = FilteredCollections.filteredCollection(new ArrayList<String>(), 
                                                             new NullFilter<String>());
            strings.add("hello");
            strings.add(null);
            strings.add("world");
    
            if(strings.size() != 2)
            {
                System.err.println("ERROR: strings.size() == " + strings.size());
            }
    
            System.out.println(strings);
        }
    }
    
  • BTW, if you'd asked for a Map implementation that does not allow nulls, the old java.uitl.Hashtable does not.

What Languages are Windows, Mac OS X and Linux written in?

I was just wondering who knows what programming languages Windows, Mac OS X and Linux are made up from and what languages are used for each part of the OS (ie: Kernel, plug-in architecture, GUI components, etc).

I assume that there are multiple languages for each and obviously I know the Linux kernel is written in C.

I'm totally guessing here that Mac OS X contains a lot of Objective-C code as it is Apple's language derived from NeXT.

Windows, I have heard contains C, C++ and Intel Assembly. Do Linux or Mac OS contain any Assembly code?

Also, are there scripting languages like Ruby, Python, etc used by the OS developers for scripting parts of the OS? What parts of the OS would be written in each language?

From stackoverflow
  • Windows: Mostly C and C++, some C#

    Aaron : c#!!! NO WAY, REALLY??????!
    Jonathan Parker : .NET is shipped with Windows. A lot of .NET is in C#.
    Jonathan Parker : There's rumors that future versions (Windows 8 maybe) of windows will have some C++ code replaced with C#/.NET.
    Randolpho : They've already managed a working OS (almost) completely in C#. It's called Singularity. http://research.microsoft.com/en-us/projects/singularity/
    Sharique : C/C++ is managed(.net version of) C/C++
    Larry Osterman : Luc M: Yes, there's C# code in Windows. Poke around and you'll find it. .Net is shipped with the OS but it doesn't mean the OS is written using .Net. And Windows isn't Singularity. There's a huge difference between a research prototype and a real operating system.
    Joachim Sauer : I'm pretty sure at least Windows XP can work entirely without any .NET runtime installed (I'm not sure about Vista), so there can't be any C# in there.
    Brock Woolf : C# consists of bytecode and a virtual machine....if they used that in Windows it would make it rather slow... Oh... now i see.
    1800 INFORMATION : Obviously XP was released a long time before .Net so it would have no dependancy on .Net
    1800 INFORMATION : @Brock - you have some seriously wrong information there - C# compiles to IL or native machine code, from there the JIT compiles the IL to machine code when it is run. There is no bytecode and no virtual machine. Perhaps you are thinking of Java?
    Brock Woolf : @1800Information - C# compiles to machine code from there JIT compiles to machine code when run? I think you are the confused one. There IS bytecode and there IS a virtual machine: http://en.wikipedia.org/wiki/Common_Intermediate_Language
  • You're right MacOSX has Objective-C in the core.

    Windows C++

    Linux C

    About the scripting languages, no, they pretty much high level.

    abatishchev : Windows in C: kernel, drivers, API. Only system applications and tools in C++, I guess. So it's more clear to say just C
    • Windows: C++, kernel is in C
    • Mac: Objective C, kernel is in C (IO PnP subsystem is Embedded C++)
    • Linux: Most things are in C, many userland apps are in Python, KDE is all C++
  • The Linux kernel is mostly written in C (and a bit of assembly language, I'd imagine), but some of the important userspace utilities (programs) are shell scripts written in the Bash scripting language. Beyond that, it's sort of hard to define "Linux" since you basically build a Linux system by picking bits and pieces you want and putting them together, and depending on what an individual Linux user wants, you can get pretty much any language involved. (As Paul said, Python and C++ play important roles)

  • I have read or heard that Mac OS X is written mostly in Objective-C with some of the lower level parts, such as the kernel, and hardware device drivers written in C. I believe that Apple "eat(s) its own dog food", meaning that they write Mac OS X using their own Xcode Developer Tools. The GCC(GNU Compiler Collection) compiler-linker is the unix command line tool that xCode used for most of its compiling and/or linking of executables. Among other possible languages, I know GCC compiles source code from the C, Objective-C, C++ and Objective-C++ languages.

  • http://www.lextrait.com/vincent/implementations.html

    this should helped

  • Windows is obviously not written in C# (!)

    Simply see the source code of Windows and you'll see...

    Joachim Sauer : "Simply see the source code of Windows" if you're one of the few that is allowed/able to do that ...
    abatishchev : There are a lot of Windows source code parts in Torrents, also a few reviews of it
    unwind : Parts of the Windows code have leaked out, years ago. See for instance this old thread: . :)
  • Mac OS X uses large amounts of C++ inside some libraries, but it isn't exposed as they're afraid of the ABI breaking.