Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a `char* p`, which points to a `\0`-terminated string. How do I create a C++ `string` from it in an exception-safe way? Here is an unsafe version: ``` string foo() { char *p = get_string(); string str( p ); free( p ); return str; } ``` An obvious solution would be to try-catch - any easier ways?
You can use `shared_ptr` from [C++11](http://en.cppreference.com/w/cpp/memory/shared_ptr) or [Boost](http://www.boost.org/libs/smart_ptr/): ``` string foo() { shared_ptr<char> p(get_string(), &free); string str(p.get()); return str; } ``` This uses a very specific feature of `shared_ptr` not available in `auto_ptr` or anything else, namely the ability to specify a custom deleter; in this case, I'm using `free` as the deleter.
Can I ask you what exception you are expecting in your example? On many platforms (Linux, AIX) new or malloc will never fail and your app will get killed by the os if you run out of memory. See this link: [What happens when Linux runs out of memory.](http://www.linuxdevcenter.com/pub/a/linux/2006/11/30/linux-out-of-memory.html)
create std::string from char* in a safe way
[ "", "c++", "exception", "" ]
I want to search a table to find all rows where one particular field is one of two values. I know exactly what the values would be, but I'm wondering which is the most efficient way to search for them: for the sake of example, the two values are "xpoints" and "ypoints". I know for certain that there will be no other values in that field which has "points" at the end, so the two queries I'm considering are: ``` WHERE `myField` IN ('xpoints', 'ypoints') --- or... WHERE `myField` LIKE '_points' ``` which would give the best results in this case?
As always with SQL queries, run it through the profiler to find out. However, my gut instinct would have to say that the IN search would be quicker. Espcially in the example you gave, if the field was indexed, it would only have to do 2 lookups. If you did a like search, it may have to do a scan, because you are looking for records that end with a certain value. It would also be more accurate as LIKE '\_points' could also return 'gpoints', or any other similar string.
Unless all of the data items in the column in question start with 'x' or 'y', I believe IN will always give you a better query. If it is indexed, as @Kibbee points out, you will only have to perform 2 lookups to get both. Alternatively, if it is not indexed, a table scan using IN will only have to check the first letter most of the time whereas with LIKE it will have to check two characters every time (assuming all items are at least 2 characters) -- since the first character is allowed to be anything.
Using IN or a text search
[ "", "sql", "mysql", "optimization", "" ]
I am attempting to rewrite my [ForestPad](http://ForestPad.com) application utilizing WPF for the presentation layer. In WinForms, I am populating each node programmatically but I would like to take advantage of the databinding capabilities of WPF, if possible. In general, what is the best way to two-way databind the WPF TreeView to an Xml document? A generic solution is fine but for reference, the structure of the Xml document that I am trying to bind to looks like this: ``` <?xml version="1.0" encoding="utf-8"?> <forestPad guid="6c9325de-dfbe-4878-9d91-1a9f1a7696b0" created="5/14/2004 1:05:10 AM" updated="5/14/2004 1:07:41 AM"> <forest name="A forest node" guid="b441a196-7468-47c8-a010-7ff83429a37b" created="01/01/2003 1:00:00 AM" updated="5/14/2004 1:06:15 AM"> <data> <![CDATA[A forest node This is the text of the forest node.]]> </data> <tree name="A tree node" guid="768eae66-e9df-4999-b950-01fa9be1a5cf" created="5/14/2004 1:05:38 AM" updated="5/14/2004 1:06:11 AM"> <data> <![CDATA[A tree node This is the text of the tree node.]]> </data> <branch name="A branch node" guid="be4b0993-d4e4-4249-8aa5-fa9c940ae2be" created="5/14/2004 1:06:00 AM" updated="5/14/2004 1:06:24 AM"> <data> <![CDATA[A branch node This is the text of the branch node.]]></data> <leaf name="A leaf node" guid="9c76ff4e-3ae2-450e-b1d2-232b687214aa" created="5/14/2004 1:06:26 AM" updated="5/14/2004 1:06:38 AM"> <data> <![CDATA[A leaf node This is the text of the leaf node.]]> </data> </leaf> </branch> </tree> </forest> </forestPad> ```
Well, it would be easier if your element hierarchy was more like... ``` <node type="forest"> <node type="tree"> ... ``` ...rather than your current schema. As-is, you'll need 4 `HierarchicalDataTemplate`s, one for each hierarchical element including the root, and one `DataTemplate` for `leaf` elements: ``` <Window.Resources> <HierarchicalDataTemplate DataType="forestPad" ItemsSource="{Binding XPath=forest}"> <TextBlock Text="a forestpad" /> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="forest" ItemsSource="{Binding XPath=tree}"> <TextBox Text="{Binding XPath=data}" /> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="tree" ItemsSource="{Binding XPath=branch}"> <TextBox Text="{Binding XPath=data}" /> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="branch" ItemsSource="{Binding XPath=leaf}"> <TextBox Text="{Binding XPath=data}" /> </HierarchicalDataTemplate> <DataTemplate DataType="leaf"> <TextBox Text="{Binding XPath=data}" /> </DataTemplate> <XmlDataProvider x:Key="dataxml" XPath="forestPad" Source="D:\fp.xml"> </XmlDataProvider> </Window.Resources> ``` You can instead set the `Source` of the `XmlDataProvider` programmatically: ``` dp = this.FindResource( "dataxml" ) as XmlDataProvider; dp.Source = new Uri( @"D:\fp.xml" ); ``` Also, re-saving your edits is as easy as this: ``` dp.Document.Save( dp.Source.LocalPath ); ``` The `TreeView` itself needs a `Name` and an `ItemsSource` bonded to the `XmlDataProvider`: ``` <TreeView Name="treeview" ItemsSource="{Binding Source={StaticResource dataxml}, XPath=.}"> ``` I this example, I did `TwoWay` binding with `TextBox`es on each node, but when it comes to editing just one node at a time in a separate, single `TextBox` or other control, you would be binding it to the currently selected item of the `TreeView`. You would also change the above `TextBox`es to `TextBlock`s, as clicking in the `TextBox` does not actually select the corresponding `TreeViewItem`. ``` <TextBox DataContext="{Binding ElementName=treeview, Path=SelectedItem}" Text="{Binding XPath=data, UpdateSourceTrigger=PropertyChanged}"/> ``` The reason you must use two `Binding`s is that you cannot use `Path` and `XPath` together. **Edit:** Timothy Lee Russell asked about saving CDATA to the data elements. First, a little on `InnerXml` and `InnerText`. Behind the scenes, `XmlDataProvider` is using an `XmlDocument`, with it's tree of `XmlNodes`. When a string such as "stuff" is assigned to the `InnerXml` property of an `XmlNode`, then those tags are really tags. No escaping is done when getting or setting `InnerXml`, and it is parsed as XML. However, if it is instead assigned to the `InnerText` property, the angle brackets will be escaped with entities &lt; and &gt;. The reverse happens when the value is retreived. Entities (like &lt;) are resolved back into characters (like <). Therefore, if the strings we store in the data elements contain XML, entities have been escaped, and we need to undo that simply by retrieving `InnerText` before adding a CDATA section as the node's child... ``` XmlDocument doc = dp.Document; XmlNodeList nodes = doc.SelectNodes( "//data" ); foreach ( XmlNode node in nodes ) { string data = node.InnerText; node.InnerText = ""; XmlCDataSection cdata = doc.CreateCDataSection( data ); node.AppendChild( cdata ); } doc.Save( dp.Source.LocalPath ); ``` If the node already has a CDATA section and the value has not been changed in any way, then it still has a CDATA section and we essentially replace it with the same. However, through our binding, if we change the value of the data elements contents, it replaces the CDATA in favor of an escaped string. Then we have to fix them.
We had a similar issue. You may find reading [this article](http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx) helpful. We used the ViewModel pattern described and it simplified everything.
Two-way binding of Xml data to the WPF TreeView
[ "", "c#", "wpf", "xml", "data-binding", "treeview", "" ]
In a [coding style question about infinite loops](https://stackoverflow.com/questions/224138/infinite-loops-top-or-bottom), some people mentioned they prefer the for(;;) style because the while(true) style gives warning messages on MSVC about a conditional expression being constant. This surprised me greatly, since the use of constant values in conditional expressions is a useful way of avoiding #ifdef hell. For instance, you can have in your header: ``` #ifdef CONFIG_FOO extern int foo_enabled; #else #define foo_enabled 0 #endif ``` And the code can simply use a conditional and trust the compiler to elide the dead code when CONFIG\_FOO isn't defined: ``` if (foo_enabled) { ... } ``` Instead of having to test for CONFIG\_FOO every time foo\_enabled is used: ``` #ifdef CONFIG_FOO if (foo_enabled) { ... } #endif ``` This design pattern is used all the time in the Linux kernel (for instance, include/linux/cpumask.h defines several macros to 1 or 0 when SMP is disabled and to a function call when SMP is enabled). What is the reason for that MSVC warning? Additionally, is there a better way to avoid #ifdef hell without having to disable that warning? Or is it an overly broad warning which should not be enabled in general?
A warning doesn't automatically mean that code is *bad*, just suspicious-looking. Personally I start from a position of enabling all the warnings I can, then turn off any that prove more annoying than useful. That one that fires anytime you cast anything to a bool is usually the first to go.
I think the reason for the warning is that you might inadvertently have a more complex expression that evaluates to a constant without realizing it. Suppose you have a declaration like this in a header: ``` const int x = 0; ``` then later on, far from the declaration of x, you have a condition like: ``` if (x != 0) ... ``` You might not notice that it's a constant expression.
Constant value in conditional expression
[ "", "c++", "c", "warnings", "visual-c++", "" ]
I'm using my code-behind page to create a save button programmatically: ``` Button btnSave = new Button(); btnSave.ID = "btnSave"; btnSave.Text = "Save"; ``` However I think this must create an html button or perhaps needs something else as I cannot seem to set the OnClick attribute in the following line, I can specify OnClientClick but this isn't the one I want to set.
``` Button btnSave = new Button(); btnSave.ID = "btnSave"; btnSave.Text = "Save"; btnSave.Click += new System.EventHandler(btnSave_Click); protected void btnSave_Click(object sender, EventArgs e) { //do something when button clicked. } ```
Also remember that when the user clicks the button it will force a postback, which creates a *new instance* of your page class. The old instance where you created the button is already gone. You need to make sure that this new instance of the class also adds your button -- and it's event handler -- *prior to the load phase*, or the event handler won't run (the page's load event still will, however).
Creating an asp:Button programmatically?
[ "", "c#", "asp.net", ".net", "servercontrols", "" ]
In C#, I want to initialize a string value with an empty string. How should I do this? What is the right way, and why? ``` string willi = string.Empty; ``` or ``` string willi = String.Empty; ``` or ``` string willi = ""; ``` or what?
**Use whatever you and your team find the most readable.** Other answers have suggested that a new string is created every time you use `""`. This is not true - due to string interning, it will be created either once per assembly or once per AppDomain (or possibly once for the whole process - not sure on that front). This difference is negligible - massively, *massively* insignificant. Which you find more readable is a different matter, however. It's subjective and will vary from person to person - so I suggest you find out what most people on your team like, and all go with that for consistency. Personally I find `""` easier to read. The argument that `""` and `" "` are easily mistaken for each other doesn't really wash with me. Unless you're using a proportional font (and I haven't worked with *any* developers who do) it's pretty easy to tell the difference.
There really is no difference from a performance and code generated standpoint. In performance testing, they went back and forth between which one was faster vs the other, and only by milliseconds. In looking at the behind the scenes code, you really don't see any difference either. The only difference is in the IL, which `string.Empty` use the opcode `ldsfld` and `""` uses the opcode `ldstr`, but that is only because `string.Empty` is static, and both instructions do the same thing. If you look at the assembly that is produced, it is exactly the same. ## C# Code ``` private void Test1() { string test1 = string.Empty; string test11 = test1; } private void Test2() { string test2 = ""; string test22 = test2; } ``` ## IL Code ``` .method private hidebysig instance void Test1() cil managed { // Code size 10 (0xa) .maxstack 1 .locals init ([0] string test1, [1] string test11) IL_0000: nop IL_0001: ldsfld string [mscorlib]System.String::Empty IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ret } // end of method Form1::Test1 ``` ``` .method private hidebysig instance void Test2() cil managed { // Code size 10 (0xa) .maxstack 1 .locals init ([0] string test2, [1] string test22) IL_0000: nop IL_0001: ldstr "" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ret } // end of method Form1::Test2 ``` ## Assembly code ``` string test1 = string.Empty; 0000003a mov eax,dword ptr ds:[022A102Ch] 0000003f mov dword ptr [ebp-40h],eax string test11 = test1; 00000042 mov eax,dword ptr [ebp-40h] 00000045 mov dword ptr [ebp-44h],eax ``` ``` string test2 = ""; 0000003a mov eax,dword ptr ds:[022A202Ch] 00000040 mov dword ptr [ebp-40h],eax string test22 = test2; 00000043 mov eax,dword ptr [ebp-40h] 00000046 mov dword ptr [ebp-44h],eax ```
In C#, should I use string.Empty or String.Empty or "" to intitialize a string?
[ "", "c#", ".net", "string", "initialization", "" ]
I have two C++ processes (A and B), executing under Windows, where one launches the other. I would like to effectively single-thread their execution. For example: 1. Start process A 2. A creates B 3. A suspends 4. B executes some fixed set of operations 5. B suspends and A is resumed 6. A executes some fixed set of operations 7. A suspends and B is resumed 8. (Repeat 4 - 7) Which Windows synchronization and IPC services would be best to implement this type of behavior?
Events would work in this case: * A creates an event an starts Process B * A waits for the event to be signaled * B also creates an event, does it's first item, then signals A's event (which either has a well-known name or the handle can be passed to B when it starts or using some other mechanism * B waits on its event * when A resumes from waiting on its event, it does its work, signals B's event and waits on its own * so on... Just be sure you have error handling so each process can resume and do whatever is necessary if the other one hangs or terminates unexpectedly. Timeouts can handle the hang situation, and waiting on the other process's handle (using WaitForMultipleObjects() along with both the process and event handle) can determine if/when the other process terminates.
Pass two event handles (CreateEvent) to process B. signal one handle when process a is done working, signal the other when process b is done working. Each process calls WaitForSingleObject() to wait for the other process to finish a set of work.
Single-threading two processes
[ "", "c++", "multithreading", "synchronization", "process", "" ]
In the Render method of an ASP.NET web-control, I need to alter the output of the Html based on whether JavaScript is enabled or disabled on the clients browser, Does anyone know the right incantation to figure that out?
The problem with using script to check whether javascript is enabled is that you only find that out after the script hasn't run. Some solutions try the opposite - they use javascript to set a value and then supply Javascript enabled controls if that value is later detected. However, this fails with javascript-sometimes-enabled tools like the Firefox NoScript plugin. A more robust solution is to always send the plain-HTML compatible control, and then have javascript run on page load to add the correct event handlers/extra DOM elements/etc. However I don't know how this fits in with the ASP.NET approach takes to controls.
The [noscript](http://www.w3schools.com/TAGS/tag_noscript.asp) tag is used to define an alternate content (text) if a script is NOT executed. EDIT: Hi Kieron, take a look at this link: [Creating a Server Control for JavaScript Testing](http://www.15seconds.com/issue/030303.htm), and [Detect if JavaScript is enabled in ASPX](http://www.codeproject.com/KB/aspnet/Detect_JavaScript_in_ASPX.aspx)
Detect when JavaScript is disabled in ASP.NET
[ "", "asp.net", "javascript", "controls", "progressive-enhancement", "" ]
I am currently investigating how to make a connection to a SQL Server database from my Java EE web application using Windows Authentication instead of SQL Server authentication. I am running this app off of Tomcat 6.0, and am utilizing the Microsoft JDBC driver. My connection properties file looks as follows: ``` dbDriver = com.microsoft.sqlserver.jdbc.SQLServerDriver dbUser = user dbPass = password dbServer = localhost:1433;databaseName=testDb dbUrl = jdbc:sqlserver://localhost:1433 ``` I have zero problems with connecting to a SQL Server database in this fashion when using SQL Server authentication. Is there any way I can retrieve the credentials of the user's Windows Authentication and use **that** authentication for SQL Server? **UPDATE**: I know in ASP.net there is a way to set up Windows Authentication for access to the webapp, which is exactly what I am looking for, except I want to pass that token off to SQL Server for access to the database.
I do not think one can push the user credentials from the browser to the database (and does it makes sense ? I think not) But if you want to use the credentials of the user running Tomcat to connect to SQL Server then you can use Microsoft's JDBC Driver. Just build your JDBC URL like this: ``` jdbc:sqlserver://localhost;integratedSecurity=true; ``` And copy the appropriate DLL to Tomcat's bin directory (sqljdbc\_auth.dll provided with the driver) [MSDN > Connecting to SQL Server with the JDBC Driver > Building the Connection URL](http://msdn.microsoft.com/en-us/library/ms378428.aspx)
look at <http://jtds.sourceforge.net/faq.html#driverImplementation> What is the URL format used by jTDS? The URL format for jTDS is: ``` jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]] ``` ... domain Specifies the Windows domain to authenticate in. If present and the user name and password are provided, jTDS uses Windows (NTLM) authentication instead of the usual SQL Server authentication (i.e. the user and password provided are the domain user and password). This allows non-Windows clients to log in to servers which are only configured to accept Windows authentication. If the domain parameter is present but no user name and password are provided, jTDS uses its native Single-Sign-On library and logs in with the logged Windows user's credentials (for this to work one would obviously need to be on Windows, logged into a domain, and also have the SSO library installed -- consult README.SSO in the distribution on how to do this).
Can I connect to SQL Server using Windows Authentication from Java EE webapp?
[ "", "java", "sql-server", "tomcat", "jdbc", "jakarta-ee", "" ]
I would like to implement a producer/consumer scenario that obeys interfaces that are roughly: ``` class Consumer { private: vector<char> read(size_t n) { // If the internal buffer has `n` elements, then dequeue them // Otherwise wait for more data and try again } public: void run() { read(10); read(4839); // etc } void feed(const vector<char> &more) { // Safely queue the data // Notify `read` that there is now more data } }; ``` In this case, `feed` and `run` will run on separate threads and `read` should be a blocking read (like `recv` and `fread`). Obviously, I will need some kind of mutual exclusion on my deque, and I will need some kind of notification system to inform `read` to try again. I hear **condition variables** are the way to go, but all my multithreading experience lies with Windows and am having a hard time wrapping my head around them. Thanks for any help! (Yes, I know it's inefficient to return vectors. Let's not get into that.)
This code is not production ready. No error checking is done on the results of any library calls. I have wrapped the lock/unlock of the mutex in LockThread so it is exception safe. But that's about it. In addition if I was doing this seriously I would wrap the mutex and condition variables inside objects so they can cot be abused inside other methods of Consumer. But as long as you take note that the lock must be acquired before you use the condition variable (in any way) then this simple situation can stand as is. Out of interest have you checked the boost threading library? ``` #include <iostream> #include <vector> #include <pthread.h> class LockThread { public: LockThread(pthread_mutex_t& m) :mutex(m) { pthread_mutex_lock(&mutex); } ~LockThread() { pthread_mutex_unlock(&mutex); } private: pthread_mutex_t& mutex; }; class Consumer { pthread_mutex_t lock; pthread_cond_t cond; std::vector<char> unreadData; public: Consumer() { pthread_mutex_init(&lock,NULL); pthread_cond_init(&cond,NULL); } ~Consumer() { pthread_cond_destroy(&cond); pthread_mutex_destroy(&lock); } private: std::vector<char> read(size_t n) { LockThread locker(lock); while (unreadData.size() < n) { // Must wait until we have n char. // This is a while loop because feed may not put enough in. // pthread_cond() releases the lock. // Thread will not be allowed to continue until // signal is called and this thread reacquires the lock. pthread_cond_wait(&cond,&lock); // Once released from the condition you will have re-aquired the lock. // Thus feed() must have exited and released the lock first. } /* * Not sure if this is exactly what you wanted. * But the data is copied out of the thread safe buffer * into something that can be returned. */ std::vector<char> result(n); // init result with size n std::copy(&unreadData[0], &unreadData[n], &result[0]); unreadData.erase(unreadData.begin(), unreadData.begin() + n); return (result); } public: void run() { read(10); read(4839); // etc } void feed(const std::vector<char> &more) { LockThread locker(lock); // Once we acquire the lock we can safely modify the buffer. std::copy(more.begin(),more.end(),std::back_inserter(unreadData)); // Only signal the thread if you have the lock // Otherwise race conditions happen. pthread_cond_signal(&cond); // destructor releases the lock and thus allows read thread to continue. } }; int main() { Consumer c; } ```
I tend to use what I call a "Syncronized Queue". I wrap the normal queue and use a Semaphore class for both locking and making read block just as you desire: ``` #ifndef SYNCQUEUE_20061005_H_ #define SYNCQUEUE_20061005_H_ #include <queue> #include "Semaphore.h" // similar, but slightly simpler interface to std::queue // this queue implementation will serialize pushes and pops // and block on a pop while empty (as apposed to throwing an exception) // it also locks as neccessary on insertion and removal to avoid race // conditions template <class T, class C = std::deque<T> > class SyncQueue { protected: std::queue<T, C> m_Queue; Semaphore m_Semaphore; Mutex m_Mutex; public: typedef typename std::queue<T, C>::value_type value_type; typedef typename std::queue<T, C>::size_type size_type; explicit SyncQueue(const C& a = C()) : m_Queue(a), m_Semaphore(0) {} bool empty() const { return m_Queue.empty(); } size_type size() const { return m_Queue.size(); } void push(const value_type& x); value_type pop(); }; template <class T, class C> void SyncQueue<T, C>::push(const SyncQueue<T, C>::value_type &x) { // atomically push item m_Mutex.lock(); m_Queue.push(x); m_Mutex.unlock(); // let blocking semaphore know another item has arrived m_Semaphore.v(); } template <class T, class C> typename SyncQueue<T, C>::value_type SyncQueue<T, C>::pop() { // block until we have at least one item m_Semaphore.p(); // atomically read and pop front item m_Mutex.lock(); value_type ret = m_Queue.front(); m_Queue.pop(); m_Mutex.unlock(); return ret; } #endif ``` You can implement semaphores and mutexes with the appropriate primitives in your threading implementation. NOTE: this implementation is an example for single elements in a queue, but you could easily wrap this with a function which buffers results until N have been provided. something like this if it is a queue of chars: ``` std::vector<char> func(int size) { std::vector<char> result; while(result.size() != size) { result.push_back(my_sync_queue.pop()); } return result; } ```
How to implement blocking read using POSIX threads
[ "", "c++", "multithreading", "pthreads", "producer-consumer", "" ]
I have a web page that uses a scrolling div to display table information. When the window is resized (and also on page load), the display is centered and the div's scrollbar positioned to the right of the page by setting its width. For some reason, the behaviour is different under firefox than IE. IE positions/sizes the div as expected, but firefox seems to make it too wide, such that the scrollbar begins to disappear when the window client width reaches about 800px. I'm using the following methods to set the position and size: ``` function getWindowWidth() { var windowWidth = 0; if (typeof(window.innerWidth) == 'number') { windowWidth=window.innerWidth; } else { if (document.documentElement && document.documentElement.clientWidth) { windowWidth=document.documentElement.clientWidth ; } else { if (document.body && document.body.clientWidth) { windowWidth=document.body.clientWidth; } } } return windowWidth; } function findLPos(obj) { var curleft = 0; if (obj.offsetParent) { curleft = obj.offsetLeft while (obj = obj.offsetParent) { curleft += obj.offsetLeft } } return curleft; } var bdydiv; var coldiv; document.body.style.overflow="hidden"; window.onload=resizeDivs; window.onresize=resizeDivs; function resizeDivs(){ bdydiv=document.getElementById('bdydiv'); coldiv=document.getElementById('coldiv'); var winWdth=getWindowWidth(); var rghtMarg = 0; var colHdrTbl=document.getElementById('colHdrTbl'); rghtMarg = parseInt((winWdth - 766) / 2) - 8; rghtMarg = (rghtMarg > 0 ? rghtMarg : 0); coldiv.style.paddingLeft = rghtMarg + "px"; bdydiv.style.paddingLeft = rghtMarg + "px"; var bdydivLft=findLPos(bdydiv); if ((winWdth - bdydivLft) >= 1){ bdydiv.style.width = winWdth - bdydivLft; coldiv.style.width = bdydiv.style.width; } syncScroll(); } function syncScroll(){ if(coldiv.scrollLeft>=0){ coldiv.scrollLeft=bdydiv.scrollLeft; } } ``` Note that I've cut out other code which sets height, and other non-relevant parts. The full page can be seen [here](http://site1.funddata.com/mozilladivresize.html). If you go to the link in both IE and firefox, resize width until "800" is displayed in the green box top-right, and resize height until the scrollbar at the right is enabled, you can see the problem. If you then resize the IE width, the scrollbar stays, but if you resize the firefox width wider, the scrollbar begins to disappear. I'm at a loss as to why this is happening.... Note that AFAIK, getWindowWidth() should be cross-browser-compatible, but I'm not so sure about findLPos().... perhaps there's an extra object in Firefox's DOM or something, which is changing the result??
You are dealing with "[one of the best-known software bugs in a popular implementation of Cascading Style Sheets (CSS)](http://en.wikipedia.org/wiki/Internet_Explorer_box_model_bug)" according to Wikipedia. I recommend the [Element dimensions](http://www.quirksmode.org/viewport/elementdimensions.html) and [CSS Object Model View](http://www.quirksmode.org/dom/w3c_cssom.html) pages on [Quirksmode.org](http://www.quirksmode.org/). Also: I think you'll find that Safari and Opera behave like Firefox in most circumstances. A more compatible approach to working around these problems is testing for, and making exceptions for, MSIE instead of the other way around.
Ok, I found the problem. Seems to be that firefox does not include the style.paddingLeft value in its style.width setting, whereas IE does, thus the div was ending up exactly style.paddingLeft too wide. That is, if for example style.paddingLeft is 8, IE's style.width value would be 8 more than FireFox's - and thus the inverse when setting the value, for FireFox I needed to subtract the style.paddingLeft value Modified code with: ``` if (__isFireFox){ bdydiv.style.width = winWdth - bdydivLft - rghtMarg; } else { bdydiv.style.width = winWdth - bdydivLft; } ```
What is different with window and div widths between firefox and IE
[ "", "javascript", "html", "internet-explorer", "firefox", "" ]
I'm wanting to add a class to the body tag without waiting for the DOM to load, but I'm wanting to know if the following approach would be valid. I'm more concerned with validity than whether the browsers support it for now. ``` <body> $("body").addClass("active"); ... </body> ``` Thanks, Steve
The [.elementReady() plugin](http://plugins.jquery.com/project/elementReady) seems to be pretty close to what you're looking for. It operates by using a `setInterval` loop, that exits as soon as `document.getElementById()` returns an element for a given `id`. You could probably do a slight modification of that plugin (or commit an update/patch) to allow for generic selectors (at least for "tagNames") instead of just `id`s. I don't believe there is any truly reliable cross-browser compatible way to address an element before it's loaded - other than this sort of `setInterval` hacking Unless you are able to place your javascript command *inside* the target element like @JasonBunting suggests.
If the element doesn't exist in the DOM, the search will fail to find it and the action won't be applied. If you can't do it in the $(document).ready() function, you might want to try putting the code after the element being referenced. I believe this will work. ``` <body> <div id='topStories'></div> <script type='text/javascript'> $('div#topStories').addClass('active'); </script> </body> ``` If you need to add the class to the body, I would definitely use $(document).ready().
Can I target an element before it's closed?
[ "", "javascript", "jquery", "html", "css", "dom", "" ]
I'm trying to create a unit test to test the case for when the timezone changes on a machine because it has been incorrectly set and then corrected. In the test I need to be able to create DateTime objects in a none local time zone to ensure that people running the test can do so successfully irrespective of where they are located. From what I can see from the DateTime constructor I can set the TimeZone to be either the local timezone, the UTC timezone or not specified. How do I create a DateTime with a specific timezone like PST?
[Jon's answer](https://stackoverflow.com/questions/246498/creating-a-datetime-in-a-specific-time-zone-in-c-fx-35#246512) talks about [TimeZone](http://msdn.microsoft.com/en-us/library/system.timezone.aspx), but I'd suggest using [TimeZoneInfo](http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx) instead. Personally I like keeping things in UTC where possible (at least for the past; [storing UTC for the *future* has potential issues](https://codeblog.jonskeet.uk/2019/03/27/storing-utc-is-not-a-silver-bullet/)), so I'd suggest a structure like this: ``` public struct DateTimeWithZone { private readonly DateTime utcDateTime; private readonly TimeZoneInfo timeZone; public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone) { var dateTimeUnspec = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified); utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTimeUnspec, timeZone); this.timeZone = timeZone; } public DateTime UniversalTime { get { return utcDateTime; } } public TimeZoneInfo TimeZone { get { return timeZone; } } public DateTime LocalTime { get { return TimeZoneInfo.ConvertTime(utcDateTime, timeZone); } } } ``` You may wish to change the "TimeZone" names to "TimeZoneInfo" to make things clearer - I prefer the briefer names myself.
The DateTimeOffset structure was created for exactly this type of use. See: <http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx> Here's an example of creating a DateTimeOffset object with a specific time zone: `DateTimeOffset do1 = new DateTimeOffset(2008, 8, 22, 1, 0, 0, new TimeSpan(-5, 0, 0));`
Creating a DateTime in a specific Time Zone in c#
[ "", "c#", ".net", "datetime", "timezone", ".net-3.5", "" ]
Should I always wrap external resource calls in a try-catch? (ie. calls to a database or file system) Is there a best practice for error handling when calling external resources?
Catch **only exceptions** that you **can handle**. So for example when using external resources, the best practice is to catch **specific** exceptions that you know you can handle. In case of files this can be (IOException, SecurityException, etc), in case of Database the exception can be SqlException or others. In any case, **don't catch** exceptions that you **don't handle**, let them flow to a upper layer that can. Or if for some reason you do catch exceptions but don't handle them, rethrow them using just *throw;* (which will create an rethrow IL op, as opposed to trow). In case of using resources that you don't know what type of exceptions might throw, you are kind of forced to catch the general exception type. And in this case the safes thing would be to use the said resources from a different app domain (if possible), or let the exception bubble up to top level (ex UI) where they can be displayed or logged.
I think there are three reasons to have a catch block: * You can handle the exception and recover (from "low level" code) * You want to rewrap the exception (again, from "low level" code) * You're at the top of the stack, and while you can't recover the operation itself, you don't want the whole app to go down If you stick to these, you should have very few catch blocks compared with `try/finally` blocks - and those `try/finally` blocks are almost always just calling `Dispose`, and therefore best written as `using` statements. Bottom line: It's very important to have a `finally` block to free resources, but `catch` blocks should usually be rarer.
always try-catch external resource calls?
[ "", "c#", "exception", "external", "" ]
I'm creating a custom Java Struts tag that is for building and formatting an html select box in a standardised way (part of our usability guidelines). Each select box has an additional/initial value which describes the requirement of the value returned by the select element, i.e.: * *Mandatory* - with the label "Please Select"* *Optional* - "None Selected"* *Select All* - "Select All" The custom tag will have a property that controls which of these are to be used. So the problem is, I need to think of a variable name that can adequately explain that is is holding one of these three values! I will be commenting the code in any case, but I'd prefer that co-workers didn't have to look up the source code to remember what the tag variable's purpose is. **Edit:** To put some context around this problem, the usability strategy that I'm implementing here is that if there are more than 5 items that can be selected, the options should appear as a select box. 5 or less items will appear as radio buttons. When radio buttons are being used, the mandatory label won't be displayed (form validation will complain if there's no value selected anyway).
**NOTE: See EDIT below for a different approach than the one given here** How about `requirementConstraint`? ``` <my:customSelect requirementConstraint="Mandatory"> <option value="1">A</option> <option value="2">B</option> <option value="3">C</option> </my:customSelect> ``` Another possiblity is not to tri-state the value in the first place. For example, you can instead provide two separate properties: `required` (`"yes" | "no"`), and `selectAll` (`"yes" | "no"`) to make the intent clearer. --- **EDIT**: Actually, I can see how a tri-state might still be useful, if I understand your requirements correctly. Another possibility would be to call the property `mustSelect` and make the allowed values `one` (mandatory), `any` (optional), and `all` (select all). Also, since "Select All" is a possibility, I'm assuming your `customSelect` tag renders each option as a checkbox. An example of how `mustSelect` might be used: **Mandatory (at least one)** ``` <my:customSelect mustSelect="one"> <option value="1">A</option> <option value="2">B</option> <option value="3">C</option> </my:customSelect> ``` **Optional (zero or more)** ``` <my:customSelect mustSelect="any"> <option value="1">A</option> <option value="2">B</option> <option value="3">C</option> </my:customSelect> ``` **Select all** ``` <my:customSelect mustSelect="all"> <option value="1">A</option> <option value="2">B</option> <option value="3">C</option> </my:customSelect> ```
'multiplicity' would seem the right name. Looks like you're describing the following values: Mandatory: 1 Optional: 0+ Select All: n
What descriptive variable name can I use here?
[ "", "java", "variables", "struts", "html-select", "" ]
I was wondering if there is some way to name or rename a property on an Anonymous type to include a space in the property name. For example: ``` var resultSet = from customer in customerList select new { FirstName = customer.firstName; }; ``` In this example I would like FirstName to be "First Name". The reason for this question, is I have a user control that exposes a public DataSource property that I bind to different anonymous type. It is working perfectly right now, except for the one little shortcoming of the column names being a little less than user friendly (FirstName instead of First Name).
What about doing something like this: ``` var resultSet = from customer in customerList select new { Value = customer.firstName, Title = "First Name" }; ``` Then in your user control use Value as the contents and Title as the column name.
No, its not possible, spaces are not allowed in the names of members, you can use perhaps underscore or programmatically change the captions of your columns after the data is bound...
C# 3.0 Anonymous Types: Naming
[ "", "c#", "naming", "anonymous-types", ".net-3.0", "" ]
I've done some research and I can't really find a preferred way to do updating of form controls from a worker thread in C#. I know about the BackgroundWorker component, but what is the best way to do it without using the BackgroundWorker component?
There's a general rule of thumb that says don't update the UI from any thread other than the UI thread itself. Using the features of the BackgroundWorker is a good idea, but you don't want to and something is happening on a different thread, you should do an "Invoke" or BeginInvoke to force the delegate to execute the method on the UI thread. Edit: Jon B made this good point in the comments: > Keep in mind that Invoke() is > synchronous and BeginInvoke() is > asynchronous. If you use Invoke(), you > have to be careful not to cause a > deadlock. I would recommend > BeginInvoke() unless you really need > the call to be synchronous. Some simple example code: ``` // Updates the textbox text. private void UpdateText(string text) { // Set the textbox text. m_TextBox.Text = text; } public delegate void UpdateTextCallback(string text); // Then from your thread you can call this... m_TextBox.Invoke(new UpdateTextCallback(this.UpdateText), new object[]{"Text generated on non-UI thread."}); ``` The code above is from a FAQ about it [here](http://blogs.msdn.com/csharpfaq/archive/2004/03/17/91685.aspx) and a longer more involved one [here](http://weblogs.asp.net/justin_rogers/articles/126345.aspx).
Why dont you want to do it using the BackgroundWorker? It has a fantastic callback event called ProgressChanged which lets the UI thread know about updates, perfect for progess bar-type updates and the like. [link to details](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.progresschanged.aspx)
What is the best way to update form controls from a worker thread?
[ "", "c#", "multithreading", "forms", "" ]
What happen when SQL Server 2005 happen to reach the maximum for an IDENTITY column? Does it start from the beginning and start refilling the gap? What is the behavior of SQL Server 2005 when it happen?
**You will get an overflow error when the maximum value is reached**. If you use the bigint datatype with a maximum value of `9,223,372,036,854,775,807` this will most likely never be the case. The error message you will get, will look like this: ``` Msg 220, Level 16, State 2, Line 10 Arithmetic overflow error for data type tinyint, value = 256. ``` [(Source)](http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=4038424&SiteID=1&pageid=0) As far as I know MS SQL provides no functionality to fill the identity gaps, so you will either have to do this by yourself or change the datatype of the identity column. In addition to this you can set the start value to the smallest negative number, to get an even bigger range of values to use. [Here is a good blog post about this topic](http://mssqlserver.wordpress.com/2006/12/01/what-happens-when-my-integer-identity-runs-out-of-scope/).
It will not fill in the gaps. Instead inserts will fail until you change the definition of the column to either drop the identity and find some other way of filling in the gaps or increase the size (go from int to bigint) or change the type of the data (from int to decimal) so that more identity values are available.
What happen in SQL 2005 when it run out of number for an autonumber column?
[ "", "sql", "sql-server-2005", "identity", "limits", "" ]
I'd like to implement a big int class in C++ as a programming exercise—a class that can handle numbers bigger than a long int. I know that there are several open source implementations out there already, but I'd like to write my own. I'm trying to get a feel for what the right approach is. I understand that the general strategy is get the number as a string, and then break it up into smaller numbers (single digits for example), and place them in an array. At this point it should be relatively simple to implement the various comparison operators. My main concern is how I would implement things like addition and multiplication. I'm looking for a general approach and advice as opposed to actual working code.
Things to consider for a big int class: 1. Mathematical operators: +, -, /, \*, % Don't forget that your class may be on either side of the operator, that the operators can be chained, that one of the operands could be an int, float, double, etc. 2. I/O operators: >>, << This is where you figure out how to properly create your class from user input, and how to format it for output as well. 3. Conversions/Casts: Figure out what types/classes your big int class should be convertible to, and how to properly handle the conversion. A quick list would include double and float, and may include int (with proper bounds checking) and complex (assuming it can handle the range).
A fun challenge. :) I assume that you want integers of arbitrary length. I suggest the following approach: Consider the binary nature of the datatype "int". Think about using simple binary operations to emulate what the circuits in your CPU do when they add things. In case you are interested more in-depth, consider reading [this wikipedia article on half-adders and full-adders](http://en.wikipedia.org/wiki/Half_adder). You'll be doing something similar to that, but you can go down as low level as that - but being lazy, I thought I'd just forego and find a even simpler solution. But before going into any algorithmic details about adding, subtracting, multiplying, let's find some data structure. A simple way, is of course, to store things in a std::vector. ``` template< class BaseType > class BigInt { typedef typename BaseType BT; protected: std::vector< BaseType > value_; }; ``` You might want to consider if you want to make the vector of a fixed size and if to preallocate it. Reason being that for diverse operations, you will have to go through each element of the vector - O(n). You might want to know offhand how complex an operation is going to be and a fixed n does just that. But now to some algorithms on operating on the numbers. You could do it on a logic-level, but we'll use that magic CPU power to calculate results. But what we'll take over from the logic-illustration of Half- and FullAdders is the way it deals with carries. As an example, consider how you'd implement the **+= operator**. For each number in BigInt<>::value\_, you'd add those and see if the result produces some form of carry. We won't be doing it bit-wise, but rely on the nature of our BaseType (be it long or int or short or whatever): it overflows. Surely, if you add two numbers, the result must be greater than the greater one of those numbers, right? If it's not, then the result overflowed. ``` template< class BaseType > BigInt< BaseType >& BigInt< BaseType >::operator += (BigInt< BaseType > const& operand) { BT count, carry = 0; for (count = 0; count < std::max(value_.size(), operand.value_.size(); count++) { BT op0 = count < value_.size() ? value_.at(count) : 0, op1 = count < operand.value_.size() ? operand.value_.at(count) : 0; BT digits_result = op0 + op1 + carry; if (digits_result-carry < std::max(op0, op1) { BT carry_old = carry; carry = digits_result; digits_result = (op0 + op1 + carry) >> sizeof(BT)*8; // NOTE [1] } else carry = 0; } return *this; } // NOTE 1: I did not test this code. And I am not sure if this will work; if it does // not, then you must restrict BaseType to be the second biggest type // available, i.e. a 32-bit int when you have a 64-bit long. Then use // a temporary or a cast to the mightier type and retrieve the upper bits. // Or you do it bitwise. ;-) ``` The other arithmetic operation go analogous. Heck, you could even use the stl-functors std::plus and std::minus, std::times and std::divides, ..., but mind the carry. :) You can also implement multiplication and division by using your plus and minus operators, but that's very slow, because that would recalculate results you already calculated in prior calls to plus and minus in each iteration. There are a lot of good algorithms out there for this simple task, [use](http://en.wikipedia.org/wiki/Multiplication_algorithm) [wikipedia](http://en.wikipedia.org/wiki/Division_algorithm) or the web. And of course, you should implement standard operators such as `operator<<` (just shift each value in value\_ to the left for n bits, starting at the `value_.size()-1`... oh and remember the carry :), `operator<` - you can even optimize a little here, checking the rough number of digits with `size()` first. And so on. Then make your class useful, by befriendig std::ostream `operator<<`. Hope this approach is helpful!
How to implement big int in C++
[ "", "c++", "biginteger", "bignum", "largenumber", "" ]
I am using partial classes to split some functionality between 2 files, but I am getting an error. What am I doing wrong? A1.cs: ``` private partial class A { private string SomeProperty { get { return "SomeGeneratedString"; } } } ``` A2.cs: ``` private partial class A { void SomeFunction() { //trying to access this.SomeProperty produces the following compiler error, at least with C# 2.0 //error CS0117: 'A' does not contain a definition for 'SomeProperty' } } ```
Are the two partial classes in the same namespace? That could be an explanation.
Same answer as @Andrey K but in simple terms **Set the build action of all your partial classes to 'Compile' using the 'Properties' windows of each of those files** [![Properties window -> Build action property](https://i.stack.imgur.com/eLv99.png)](https://i.stack.imgur.com/eLv99.png)
Error with C# Partial classes
[ "", "c#", "partial-classes", "" ]
I'm stuck in .NET 2.0 Windows Forms. It doesn't look like the ability to select multiple nodes exists in the standard `TreeView` control. I'm trying to do this for a context menu selection. So check boxes aren't an acceptable UI paradigm here. What's the best way to provide that very necessary functionality?
We did this in a WTL project once, but the basic work needed is the same for .NET. To achieve a multiple selection tree control, you will need to draw the tree items yourself and override the keyboard and mouse handling. You will also need to maintain your own list of items that are selected. Don't forget to consider selection rules (are parents and children allowed, for example), and don't forget to implement the keyboard shortcuts including selection using Ctrl, Shift, and Ctrl+Shift, as well as the Spacebar for selecting/deselecting.
[TreeView.CheckBoxes](http://msdn.microsoft.com/en-us/library/system.windows.forms.treeview.checkboxes.aspx)
Allow multi-select in a .NET TreeView
[ "", "c#", ".net", "winforms", ".net-2.0", "treeview", "" ]
*[This question is related to but not the same as [this one](https://stackoverflow.com/questions/206564/what-is-the-performance-implication-of-converting-to-bool-in-c).]* If I try to use values of certain types as boolean expressions, I get a warning. Rather than suppress the warning, I sometimes use the ternary operator (`?:`) to convert to a bool. Using two not operators (`!!`) seems to do the same thing. Here's what I mean: ``` typedef long T; // similar warning with void * or double T t = 0; bool b = t; // performance warning: forcing 'long' value to 'bool' b = t ? true : false; // ok b = !!t; // any different? ``` So, does the double-not technique really do the same thing? Is it any more or less safe than the ternary technique? Is this technique equally safe with non-integral types (e.g., with `void *` or `double` for `T`)? I'm not asking if `!!t` is good style. I am asking if it is semantically different than `t ? true : false`.
The argument of the ! operator and the first argument of the ternary operator are both implicitly converted to bool, so !! and ?: are IMO silly redundant decorations of the cast. I vote for ``` b = (t != 0); ``` No implicit conversions.
Alternatively, you can do this: `bool b = (t != 0)`
Is !! a safe way to convert to bool in C++?
[ "", "c++", "visual-c++", "boolean", "" ]
In general, is it a best practice to have simple POJO Java classes implement java.io.Serializable?
Generally not. Joshua Bloch says to [implement Serializable judiciously](http://my.safaribooksonline.com/0201310058/ch10lev1sec1 "Implement Serializable judiciously"). A summary of drawbacks that he describes: * decreases flexibility of changing class implementation later - the serialized form is part of the class's API * makes some bugs and security holes more likely - an attacker can access class internals within the serialized byte stream * increases test burden - now you have to test serialization! * burdens authors of subclasses - they have to make their subclasses Serializable too Of course, sometimes you need a POJO to implement Serializable, say for RMI, but if the need isn't there, your code will be simpler and more secure without it.
Only if you need to be able to serialise them. It's [not worth the effort](http://en.wikipedia.org/wiki/YAGNI) otherwise.
Is implementing java.io.Serializable even in simple POJO Java classes a best practice?
[ "", "java", "serialization", "" ]
Does anyone know how to stop jQuery fromparsing html you insert through before() and after()? Say I have an element: ``` <div id='contentdiv'>bla content bla</div> ``` and I want to wrap it in the following way: ``` <div id='wrapperDiv'> <div id='beforeDiv'></div> <div id='contentDiv'>bla content bla</div> <div id='afterDiv'></div> </div> ``` I use the following jQuery/Javascript ``` $('#contentDiv').each( function() { var beforeHTML = "<div id='wrapperDiv'><div id='beforeDiv'></div>"; var afterHTML = "<div id='afterDiv'></div></div>"; $(this).before(beforeHTML); $(this).after(afterHTML); } ``` This however will not result in the correct wrapping, it will create: ``` <div id='wrapperDiv'> <div id='beforeDiv'></div> </div> <div id='contentDiv'>bla content bla</div> <div id='afterDiv'></div> ``` Using wrap() won't work either since that gets jQuery even more mixed up when using: ``` $(this).wrap("<div id='wrapperDiv'><div id='beforeDiv'></div><div id='afterDiv'></div></div>"); ``` How should I solve this? Thanks in advance!
``` $('#contentDiv').each(function() { $(this).wrap('<div id="wrapperDiv">'); $(this).before('<div id="beforeDiv">'); $(this).after('<div id="afterDiv">'); }); ``` produces: ``` <div id='wrapperDiv'> <div id='beforeDiv'></div> <div id='contentDiv'>bla content bla</div> <div id='afterDiv'></div> </div> ```
your markup isn't complete...before and after are to take complete nodes only... what you are trying to do is **wrap** your content, which is different. you want this: .wrap(html); <http://docs.jquery.com/Manipulation/wrap#html>
How to keep jQuery from parsing inserted HTML?
[ "", "javascript", "jquery", "html", "dom", "" ]
After using them a while I can't help but feel that the hoops you're forced to jump through when using anonymous classes are not worth it. You end up with `final` all over the place and no matter what the code is more difficult to read than if you'd used a well named inner class. So what are the advantages of using them? I must be missing something.
The advantage is that it's an implementation of closures. It's clunky, but it's the best we've got in Java at the moment. In other words, you don't have to create a new class just for the sake of preserving some state which you've already got as a local variable somewhere. I have [an article comparing C# and Java closures](http://csharpindepth.com/Articles/Chapter5/Closures.aspx), and why they're useful in the first place, which might help.
Well I usually only use it when needing an implementation of an interface for a single purpose (and an interface with few functions or the code because really fast ugly)... like in the following example : ``` this.addListener(new IListener(){ public void listen() {...} }); ```
Are Anonymous Classes a bad idea?
[ "", "java", "" ]
I'm reading through the [Zend Framework coding standards](http://framework.zend.com/manual/en/coding-standard.coding-style.html), where they state that curly brace after a Class definitions should be on the next line, the "one true brace form". ``` class MyClass { function.... } ``` I usually have the braces on the same line: ``` class OtherClass { function ... } ``` What's the reason for putting the brace on the next line? Or using any other style, for that matter?
Personal preference is really the only real "reason".
Having the braces on lines by themselves helps to visually separate the inner part from the outer part. That makes it easier to quickly scan through source code and distinguish blocks from their surroundings. Plus, having the braces at the same indentation level makes it easier for the eye to find a match.
Whats the reasoning behind the different brace forms?
[ "", "php", "coding-style", "" ]
I am just beginning to write an application. Part of what it needs to do is to run queries on a database of nutritional information. What I have is the USDA's [SR21 Datasets](http://www.ars.usda.gov/Services/docs.htm?docid=17478) in the form of flat delimited ASCII files. What I need is advice. I am looking for the best way to import this data into the app and have it easily and quickly queryable at run time. I'll be using it for all the standard things. Populating controls dynamically, Datagrids, calculations, etc. I will also need to do user specific persistent data storage as well. This will not be a commercial app, so hopefully that opens up the possibilities. I am fine with .Net Framework 3.5 so Linq is a possibility when accessing the data (just don't know if it would be the best solution or not). So, what are some suggestions for persistent storage in this scenario? What sort of gotchas should I be watching for? Links to examples are always appreciated of course.
It looks pretty small, so I'd work out an appropriate object model, load the whole lot into memory, and then use LINQ to Objects. I'm not quite sure what you're asking about in terms of "persistent storage" - aren't you just reading the data? Don't you already have that in the text files? I'm not sure why you'd want to introduce anything else.
I would import the flat files into SQL Server and access via standard ADO.NET functionality. Not only is DB access always better (more robust and powerful) than file I/O as far as data querying and manipulation goes, but you can also take advantage of SQL Server's caching capabilities, especially since this nutritional data won't be changing too often. If you need to download updated flat files periodically, then look into developing a service that polls for these files and imports into SQL Server automatically. EDIT: I refer to SQL Server, but feel free to use any DBMS.
.Net Data Handling Suggestions
[ "", "c#", ".net", "database", "persistence", "text-files", "" ]
I have an application in which most requests are submitted via AJAX, though some are submitted via "regular" HTTP requests. If a request is submitted and the user's session has timed out, the following JSON is returned: ``` {"authentication":"required"} ``` The JavaScript function which submits all AJAX requests handles this response by showing a popup message and redirecting the user back to the login page. However, when a non-AJAX request receives this response the JSON is simply shown in the browser because the response is processed directly by the browser (i.e. the aforementioned JavaScript function is bypassed). Obviously this is not ideal and I would like the non-AJAX requests that receive this response to behave the same as the AJAX requests. In order to achieve this, I can think of 2 options: 1. Go through the application and convert all the requests to AJAX requests. This would work, but could also take a long time! 2. The JSON shown above is generated by a very simple JSP. I'm wondering if it might be possible to add a JavaScript event handler to this JSP which is run just before the content is displayed in the browser - I'm assuming this would never be called for AJAX requests? This handler could call the other JavaScript code that displays the popup and performs the redirection. If anyone knows how exactly I can implement the handler I've outlined in (2), or has any other potential solutions, I'd be very grateful if they'd pass them on. Cheers, Don
You cannot add a handler to the JSP that way. Anything you add to it will make it a non-JSON producing page. There are two options that I can see: Add a parameter to the page by appending a URL parameter to the screen that modifies the output. URL: <http://domain/page.jsp?ajaxRequest=true> would output json only URL: <http://domain/page.jsp> would display a jsp page that could forward to another page. OR change the response to have the forwarding code in the JSP that will get executed by the web browser if it is hit directly. Then have your calling AJAX to strip the forwarding code out, and then process what is left.
3) Change your AJAX code to add a variable to the GET or POST: `outputJson=1`
detecting JSON loaded by browser
[ "", "javascript", "json", "jsp", "" ]
I am creating an application which displays some messages and its directions in the DataGridView. I would like to replace some columns content with pictures. For example I would like to replace number 0 which represents the incoming call with a green arrow (some .jpg image). Does anyone know how this could be achieved? Thanks!
We stored the images in the resource file as BMP files. Then, we handle the CellFormatting event in the DataGridView like this: ``` private void messageInfoDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { // Is this the correct column? (It's actually a DataGridViewImageColumn) if (messageInfoDataGridView.Columns[e.ColumnIndex] == messageSeverityDataGridViewTextBoxColumn) { // Get the row we're formatting DataGridViewRow row = messageInfoDataGridView.Rows[e.RowIndex]; // Get the enum from the row. MessageSeverity severity = ((MessageInfo)row.DataBoundItem).MessageSeverity; Bitmap cellValueImage; // Map the enumerated type to an image... // SeverityImageMap is a Dictionary<MessageSeverity,Bitmap>. if (ReferenceTables.SeverityImageMap.ContainsKey(severity)) cellValueImage = ReferenceTables.SeverityImageMap[severity]; else cellValueImage = Resources.NoAction; // Set the event args. e.Value = cellValueImage; e.FormattingApplied = true; } } ```
GridViews have the ability to use an image field as opposed to a data bound field. This sounds like it would do the trick.
Replacing DataGridView words and numbers with images
[ "", "c#", "datagridview", "" ]
How can I display a sort arrow in the header of the sorted column in a list view which follows the native look of the operating system?
You can use the following extension method to set the sort arrow to a particular column: ``` [EditorBrowsable(EditorBrowsableState.Never)] public static class ListViewExtensions { [StructLayout(LayoutKind.Sequential)] public struct HDITEM { public Mask mask; public int cxy; [MarshalAs(UnmanagedType.LPTStr)] public string pszText; public IntPtr hbm; public int cchTextMax; public Format fmt; public IntPtr lParam; // _WIN32_IE >= 0x0300 public int iImage; public int iOrder; // _WIN32_IE >= 0x0500 public uint type; public IntPtr pvFilter; // _WIN32_WINNT >= 0x0600 public uint state; [Flags] public enum Mask { Format = 0x4, // HDI_FORMAT }; [Flags] public enum Format { SortDown = 0x200, // HDF_SORTDOWN SortUp = 0x400, // HDF_SORTUP }; }; public const int LVM_FIRST = 0x1000; public const int LVM_GETHEADER = LVM_FIRST + 31; public const int HDM_FIRST = 0x1200; public const int HDM_GETITEM = HDM_FIRST + 11; public const int HDM_SETITEM = HDM_FIRST + 12; [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, ref HDITEM lParam); public static void SetSortIcon(this ListView listViewControl, int columnIndex, SortOrder order) { IntPtr columnHeader = SendMessage(listViewControl.Handle, LVM_GETHEADER, IntPtr.Zero, IntPtr.Zero); for (int columnNumber = 0; columnNumber <= listViewControl.Columns.Count - 1; columnNumber++) { var columnPtr = new IntPtr(columnNumber); var item = new HDITEM { mask = HDITEM.Mask.Format }; if (SendMessage(columnHeader, HDM_GETITEM, columnPtr, ref item) == IntPtr.Zero) { throw new Win32Exception(); } if (order != SortOrder.None && columnNumber == columnIndex) { switch (order) { case SortOrder.Ascending: item.fmt &= ~HDITEM.Format.SortDown; item.fmt |= HDITEM.Format.SortUp; break; case SortOrder.Descending: item.fmt &= ~HDITEM.Format.SortUp; item.fmt |= HDITEM.Format.SortDown; break; } } else { item.fmt &= ~HDITEM.Format.SortDown & ~HDITEM.Format.SortUp; } if (SendMessage(columnHeader, HDM_SETITEM, columnPtr, ref item) == IntPtr.Zero) { throw new Win32Exception(); } } } } ``` Then, you can call the extension method like such: ``` myListView.SetSortIcon(0, SortOrder.Ascending); ``` It works by using P/Invoke to: * Get the handle to the header control for a list view using the [LVM\_GETHEADER](http://msdn.microsoft.com/en-us/library/windows/desktop/bb774937%28v=vs.85%29.aspx) message. * Get the information about a header column using the [HDM\_GETITEM](http://msdn.microsoft.com/en-us/library/windows/desktop/bb775335%28v=vs.85%29.aspx) message. * It then modifies the `fmt` to set / clear the `HDF_SORTDOWN` and `HDF_SORTUP` flags on the returned [HDITEM](http://msdn.microsoft.com/en-us/library/windows/desktop/bb775247%28v=vs.85%29.aspx) structure. * Finally it re-sets the information usintg the [HDM\_SETITEM](http://msdn.microsoft.com/en-us/library/windows/desktop/bb775367%28v=vs.85%29.aspx) message. This is what it looks like: ![Arrows on a list view column](https://i.stack.imgur.com/4deP5.png)
Great answer by Andrew. If Anyone is looking for the VB.net equivalent here it is: ``` Public Module ListViewExtensions Public Enum SortOrder None Ascending Descending End Enum <StructLayout(LayoutKind.Sequential)> Public Structure HDITEM Public theMask As Mask Public cxy As Integer <MarshalAs(UnmanagedType.LPTStr)> Public pszText As String Public hbm As IntPtr Public cchTextMax As Integer Public fmt As Format Public lParam As IntPtr ' _WIN32_IE >= 0x0300 Public iImage As Integer Public iOrder As Integer ' _WIN32_IE >= 0x0500 Public type As UInteger Public pvFilter As IntPtr ' _WIN32_WINNT >= 0x0600 Public state As UInteger <Flags()> Public Enum Mask Format = &H4 ' HDI_FORMAT End Enum <Flags()> Public Enum Format SortDown = &H200 ' HDF_SORTDOWN SortUp = &H400 ' HDF_SORTUP End Enum End Structure Public Const LVM_FIRST As Integer = &H1000 Public Const LVM_GETHEADER As Integer = LVM_FIRST + 31 Public Const HDM_FIRST As Integer = &H1200 Public Const HDM_GETITEM As Integer = HDM_FIRST + 11 Public Const HDM_SETITEM As Integer = HDM_FIRST + 12 <DllImport("user32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> Public Function SendMessage(hWnd As IntPtr, msg As UInt32, wParam As IntPtr, lParam As IntPtr) As IntPtr End Function <DllImport("user32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> Public Function SendMessage(hWnd As IntPtr, msg As UInt32, wParam As IntPtr, ByRef lParam As HDITEM) As IntPtr End Function <Extension()> Public Sub SetSortIcon(listViewControl As ListView, columnIndex As Integer, order As SortOrder) Dim columnHeader As IntPtr = SendMessage(listViewControl.Handle, LVM_GETHEADER, IntPtr.Zero, IntPtr.Zero) For columnNumber As Integer = 0 To listViewControl.Columns.Count - 1 Dim columnPtr As New IntPtr(columnNumber) Dim item As New HDITEM item.theMask = HDITEM.Mask.Format If SendMessage(columnHeader, HDM_GETITEM, columnPtr, item) = IntPtr.Zero Then Throw New Win32Exception If order <> SortOrder.None AndAlso columnNumber = columnIndex Then Select Case order Case SortOrder.Ascending item.fmt = item.fmt And Not HDITEM.Format.SortDown item.fmt = item.fmt Or HDITEM.Format.SortUp Case SortOrder.Descending item.fmt = item.fmt And Not HDITEM.Format.SortUp item.fmt = item.fmt Or HDITEM.Format.SortDown End Select Else item.fmt = item.fmt And Not HDITEM.Format.SortDown And Not HDITEM.Format.SortUp End If If SendMessage(columnHeader, HDM_SETITEM, columnPtr, item) = IntPtr.Zero Then Throw New Win32Exception Next End Sub End Module ```
How to I display a sort arrow in the header of a list view column using C#?
[ "", "c#", "listview", "" ]
I'm still getting used to the sizers in wxWidgets, and as such can't seem to make them do what I want. I want a large panel that will contain a list of other panels/boxes, which each then contain a set of text fields ``` ---------------------- | label text box | | label2 text box2 | ---------------------- ---------------------- | label text box | | label2 text box2 | ---------------------- ---------------------- | label text box | | label2 text box2 | ---------------------- ``` I also need to be able to add (at the end), and remove(anywhere) these boxes. If there's too many to fit in the containing panel a vertical scroll bar is also required. This is what I've tried so far, it works for the first box that's created with the containing panel, but additional added items are just a small box in the top left of the main panel, even though the sizer code is the same for all boxes. ``` //itemsList is a container containg a list of *Item pointers to each box/panel/whatever the right name is Items::Items(wxWindow *parent) :wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxBORDER_SUNKEN) { //one sstarting item OnAdd(wxCommandEvent()); } void Items::OnAdd(wxCommandEvent &event) { unsigned id = itemsList .size(); Item *item = new Item(this,id); itemsList .push_back(item); RebuildSizer(); } void Items::RebuildSizer() { this->SetSizer(0,true); wxBoxSizer *sizerV = new wxBoxSizer(wxVERTICAL); for(std::vector<Item*>::iterator it = itemsList .begin(); it != itemsList .end(); ++it) sizerV->Add(*it, 1, wxEXPAND | wxLEFT | wxRIGHT, 5); SetSizer(sizerV); } void Items::OnRemove (wxCommandEvent &event, unsigned itemId) { delete itemsList [itemId]; itemsList .erase(items.begin()+itemId); for(std::vector<Item*>::iterator it = itemsList .begin()+itemId; it != itemsList .end(); ++it) (*it)->ChangeId(itemId++); RebuildSizer(); } ``` Also what's the best way to lay out the contents of each box? I was thinking of using a 2 by 2 grid sizer but I'm not sure how to make the text boxes to expand to be as wide as possible while making the labels stay as small as possible (but also maintaining the alignment between the 2 text boxes)?
"If theres too many to fit in the containing panel a vertical scroll bar is also required." You could have a look at wxScrolledWindow. "additional added items are just a small box in the top left of the main panel" I am not sure, but, maybe a call to wxSizer::Layout() will help. "Also whats the best way to lay out the contents of each box?" Have a look at [this sizerdemo](http://neume.sourceforge.net/sizerdemo/). If it is not mandatory, that the labels stay as small as possible, you could give the labels a fixed width and only let the text boxes grow. If you want to adapt the size when adding or removing new boxes, you could implement the OnSize() event handler.
May I suggest to you to post this question to one of the [wxWidgets mailing list](http://www.wxwidgets.org/support/maillst2.htm)? They will be able to help you very quickly.
Understanding wxWidgets sizers
[ "", "c++", "wxwidgets", "" ]
I'm writing a web application which uses windows authentication and I can happily get the user's login name using something like: ``` string login = User.Identity.Name.ToString(); ``` But I don't need their login name I want their DisplayName. I've been banging my head for a couple hours now... Can I access my organisation's AD via a web application?
How about this: ``` private static string GetFullName() { try { DirectoryEntry de = new DirectoryEntry("WinNT://" + Environment.UserDomainName + "/" + Environment.UserName); return de.Properties["displayName"].Value.ToString(); } catch { return null; } } ```
See related question: [Active Directory: Retrieve User information](https://stackoverflow.com/questions/132277/active-directory-retrieve-user-information) See also: [Howto: (Almost) Everything In Active Directory via C#](http://www.codeproject.com/KB/system/everythingInAD.aspx) and more specifically section "[Enumerate an object's properties](http://www.codeproject.com/KB/system/everythingInAD.aspx#26)". If you have a path to connect to a group in a domain, the following snippet may be helpful: ``` GetUserProperty("<myaccount>", "DisplayName"); public static string GetUserProperty(string accountName, string propertyName) { DirectoryEntry entry = new DirectoryEntry(); // "LDAP://CN=<group name>, CN =<Users>, DC=<domain component>, DC=<domain component>,..." entry.Path = "LDAP://..."; entry.AuthenticationType = AuthenticationTypes.Secure; DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(SAMAccountName=" + accountName + ")"; search.PropertiesToLoad.Add(propertyName); SearchResultCollection results = search.FindAll(); if (results != null && results.Count > 0) { return results[0].Properties[propertyName][0].ToString(); } else { return "Unknown User"; } } ```
How do I find a user's Active Directory display name in a C# web application?
[ "", "c#", "active-directory", "" ]
I've been asked to add Google e-commerce tracking into my site. This tracking involves inserting some javascript on your receipt page and then calling it's functions. From my asp.net receipt page, I need to call one function (\_addTrans) for the transaction info and then another (\_addItem) for each item on the order. An example of what they want is [here](http://www.google.com/support/analytics/bin/answer.py?answer=55528) This is for a 1.1 site. Can anybody give me a jumpstart on calling these two functions from my c# code-behind? I can't imagine that I'm alone out there in needing to call Google e-commerce tracking, so I'm hopeful.
Probably the easiest way is to build up the required Javascript as a string with something like ``` StringBuilder sb = new StringBuilder() sb.AppendLine( "<script>" ); sb.AppendLine( "var pageTracker = _gat._getTracker('UA-XXXXX-1');" ); sb.AppendLine( "pageTracker._trackPageview();" ); sb.AppendFormat( "pageTracker._addTrans('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}' );\n", orderId, affiliation, total, tax, shipping, city, state, country ); sb.AppendFormat( "pageTracker._addItem('{0}','{1}','{2}','{3}','{4}','{5}');\n", itemNumber, sku, productName, category, price, quantity ); sb.AppendLine("pageTracker._trackTrans();"); sb.AppendLine( "</script>" ); ``` Then register it to appear in the page with ``` Page.RegisterStartupScript("someKey", sb.ToString()); ```
Here i just wrote an Google Analytics E-Commerce class to dynamically add analytics transactions. <http://www.sarin.mobi/2008/11/generate-google-analytics-e-commerce-code-from-c/> Hope this hope.
Tracking e-commerce with Google
[ "", "c#", "asp.net", "e-commerce", "" ]
We are rolling out a site for a client using IIS tomorrow. I am to take the site down to the general public (Sorry, we are updating message) and allow the client to test over the weekend after we perform the upgrade. If it is successful, I open it to everbody - if not, I rollback. What is the easiest way to put a "We're not open" sign for the general public, but leave the rest open to testers?
Redirect via IIS. Create a new website in IIS and put your "Sorry updating" message in the Default.aspx. Then switch ports between the real site (will go from 80, to something else (6666)) and the 'maintenance' site (set on 80). Then tell your testers to go to yoursite.com:6666. Then switch the real site back to 80 after taking down the 'maintenance' site.
I thought it would be worthwhile to mention ASP.NET 2.0+'s "app offline" feature. (Yes, I realize the questioner wants to leave the app up for testing, but I'm writing this for later readers who might come here with different needs). If you really want to take the application offline for *everyone* (for instance to do server maintenance) there is a very simple option. All you have to do in ASP.NET 2.0 and higher is put a file with this name: ``` app_offline.htm ``` ...in the root directory of your ASP.NET application. Put an appropriate "sorry come back later" message in there. That's it. The ASP.NET runtime does the rest. Details on [Scott Guthrie's blog](http://weblogs.asp.net/scottgu/archive/2006/04/09/442332.aspx).
Take down website to public, but leave for testing... "We're Not Open"
[ "", "c#", "asp.net", "iis", "web", "rollout", "" ]
I receive this message (see image below) when I try to edit in debugging. This occur only in my Vista64bits OS, not in my XP computer. Why and what should I do? **Update** I found that I need to compile in x86 to be able to change value when debugging. So my question is WHY that I can't do it in x64? [alt text http://img183.imageshack.us/img183/8523/changetohe5.png](http://img183.imageshack.us/img183/8523/changetohe5.png)
There is no technical reason, it is just simply not implemented. According to some sources, Microsoft wants to implement it by the next release of the CLR. See: <http://blogs.msdn.com/stevejs/archive/2005/11/15/493018.aspx#499593>
Mike Stall [says](http://blogs.msdn.com/jmstall/archive/2006/02/13/cant-do-enc.aspx): > EnC does some very low-level things > that are pretty OS-specific and so > limiting to a single platform was > primarily a resource-constraint. > Future CLRs will no doubt expand this. > Our porting effort also started from > scratch in V2, and so all the rest of > the debugging services had to be > ported too, so we already had a very > large item here. Also, we believe the > biggest scenarios for EnC would > revolve around pure-IL apps that allow > people to at least develop in x86. > There's a workaround in such cases: on > a 64-bit machine, you can launch a > pure-IL app as 32-bit app in the WOW, > and then do EnC on it. > > These are all limitations of the CLR, > not Visual Studio, which means if a > 3rd-party debugger adds EnC, they'll > have the same restrictions. In all > cases, we were felt happy that the the > cost of enabling each case was better > spent making the core-scenarios > stronger.
Change to 64 bits not allowed when trying to edit in debug, why?
[ "", "c#", ".net", ".net-2.0", "editing", "compilation", "" ]
I'm using Python's Imaging Library and I would like to draw some bezier curves. I guess I could calculate pixel by pixel but I'm hoping there is something simpler.
A bezier curve isn't that hard to draw yourself. Given three points `A`, `B`, `C` you require three linear interpolations in order to draw the curve. We use the scalar `t` as the parameter for the linear interpolation: ``` P0 = A * t + (1 - t) * B P1 = B * t + (1 - t) * C ``` This interpolates between two edges we've created, edge AB and edge BC. The only thing we now have to do to calculate the point we have to draw is interpolate between P0 and P1 using the same t like so: ``` Pfinal = P0 * t + (1 - t) * P1 ``` There are a couple of things that need to be done before we actually draw the curve. First off we have will walk some `dt` (delta t) and we need to be aware that `0 <= t <= 1`. As you might be able to imagine, this will not give us a smooth curve, instead it yields only a discrete set of positions at which to plot. The easiest way to solve this is to simply draw a line between the current point and the previous point.
``` def make_bezier(xys): # xys should be a sequence of 2-tuples (Bezier control points) n = len(xys) combinations = pascal_row(n-1) def bezier(ts): # This uses the generalized formula for bezier curves # http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Generalization result = [] for t in ts: tpowers = (t**i for i in range(n)) upowers = reversed([(1-t)**i for i in range(n)]) coefs = [c*a*b for c, a, b in zip(combinations, tpowers, upowers)] result.append( tuple(sum([coef*p for coef, p in zip(coefs, ps)]) for ps in zip(*xys))) return result return bezier def pascal_row(n, memo={}): # This returns the nth row of Pascal's Triangle if n in memo: return memo[n] result = [1] x, numerator = 1, n for denominator in range(1, n//2+1): # print(numerator,denominator,x) x *= numerator x /= denominator result.append(x) numerator -= 1 if n&1 == 0: # n is even result.extend(reversed(result[:-1])) else: result.extend(reversed(result)) memo[n] = result return result ``` This, for example, draws a heart: ``` from PIL import Image from PIL import ImageDraw if __name__ == '__main__': im = Image.new('RGBA', (100, 100), (0, 0, 0, 0)) draw = ImageDraw.Draw(im) ts = [t/100.0 for t in range(101)] xys = [(50, 100), (80, 80), (100, 50)] bezier = make_bezier(xys) points = bezier(ts) xys = [(100, 50), (100, 0), (50, 0), (50, 35)] bezier = make_bezier(xys) points.extend(bezier(ts)) xys = [(50, 35), (50, 0), (0, 0), (0, 50)] bezier = make_bezier(xys) points.extend(bezier(ts)) xys = [(0, 50), (20, 80), (50, 100)] bezier = make_bezier(xys) points.extend(bezier(ts)) draw.polygon(points, fill = 'red') im.save('out.png') ```
How can I draw a bezier curve using Python's PIL?
[ "", "python", "python-imaging-library", "bezier", "imaging", "" ]
Several times, while perusing the Boost library's documentation, I've run across return values that are marked "[convertible to `bool`](http://www.boost.org/doc/libs/1_36_0/libs/utility/Collection.html)" (search that page for the phrase "convertible to bool", it's about a third of the way down). I once stumbled across an oblique reference to a paper explaining the reason for that, but have never been able to find said paper (and I can no longer find the page I saw the reference on either). Can anyone explain why (and when) you should return something that's "convertible to `bool`" rather than simply returning a `bool`?
“convertible to bool” simply means anything which can meaningfully be used in a boolean context (e.g. in an `if` condition). This makes sense in implicit conversions. Imagine an object which you want to use in a boolean context, e.g. `std::fstream`: ``` ifstream ifs("filename"); while (ifs >> token) cout "token " << token << " read." << endl; ``` Here, `ifs` is convertible to boolean. Well, actually, it isn't. Rather, it is convertible to something that, in turn, is convertible to `bool`. This is to prevent such statements: ``` int b = ifs; ``` The reasoning is that such a statement is most probably not intended and the compiler should therefore prevent it. By returning a “convertible to bool” rather than a `bool`, this is achieved because two user-defined implicit conversions can't be chained in one expression. In this context, you might want to look up the [safe bool idiom](http://www.artima.com/cppsource/safebool.html). Chris has already alluded to one possible implementation, using `void*` as a return type. Usually, the `this` pointer is then used to represent `true`. This is what gets used by the STL. However, this is unfortunately still flawed. Several alternatives have been proposed (neatly wrapped up in the article I've linked above) and as far as I know, have also been included into C++0x for consideration. I'm not aware of the current status of these proposals, though.
`bool`s are promotable to `int`s and can participate in arithmetic operations. This is often not the desired outcome, when a value should just be used for truth testing. A convertible-to-`bool` is usually something like a `void*`, where the null pointer is false, and anything else is true, and yet can't be used for arithmetic operations.
Why do Boost libraries return things "convertible to `bool`" rather than just returning `bool`s?
[ "", "c++", "boost", "" ]
Is there a cross database platform way to get the primary key of the record you have just inserted? I noted that [this answer](https://stackoverflow.com/questions/165156/easy-mysql-question-regarding-primary-keys-and-an-insert) says that you can get it by Calling `SELECT LAST_INSERT_ID()` and I think that you can call `SELECT @@IDENTITY AS 'Identity';` is there a common way to do this accross databases in jdbc? If not how would you suggest I implement this for a piece of code that could access any of SQL Server, MySQL and Oracle?
Copied from my code: ``` pInsertOid = connection.prepareStatement(INSERT_OID_SQL, Statement.RETURN_GENERATED_KEYS); ``` where pInsertOid is a prepared statement. you can then obtain the key: ``` // fill in the prepared statement and pInsertOid.executeUpdate(); ResultSet rs = pInsertOid.getGeneratedKeys(); if (rs.next()) { int newId = rs.getInt(1); oid.setId(newId); } ``` Hope this gives you a good starting point.
extraneon's answer, although correct, **doesn't work for Oracle**. The way you do this for Oracle is: ``` String key[] = {"ID"}; //put the name of the primary key column ps = con.prepareStatement(insertQuery, key); ps.executeUpdate(); rs = ps.getGeneratedKeys(); if (rs.next()) { generatedKey = rs.getLong(1); } ```
Primary key from inserted row jdbc?
[ "", "java", "jdbc", "identity", "" ]
I'm working with jQuery and looking to see if there is an easy way to determine if the element has a specific CSS class associated with it. I have the id of the element, and the CSS class that I'm looking for. I just need to be able to, in an if statement, do a comparison based on the existence of that class on the element.
Use the `hasClass` method: ``` jQueryCollection.hasClass(className); ``` or ``` $(selector).hasClass(className); ``` The argument is (obviously) a string representing the class you are checking, and it returns a boolean (so it doesn't support chaining like most jQuery methods). **Note:** If you pass a `className` argument that contains whitespace, it will be matched literally against the collection's elements' `className` string. So if, for instance, you have an element, ``` <span class="foo bar" /> ``` then this will return `true`: ``` $('span').hasClass('foo bar') ``` and these will return `false`: ``` $('span').hasClass('bar foo') $('span').hasClass('foo bar') ```
from the [FAQ](http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_test_whether_an_element_has_a_particular_class.3F) ``` elem = $("#elemid"); if (elem.is (".class")) { // whatever } ``` or: ``` elem = $("#elemid"); if (elem.hasClass ("class")) { // whatever } ```
Determine if an element has a CSS class with jQuery
[ "", "javascript", "jquery", "css", "" ]
I have a WinForms application (I'm using VB) that can be minimized to the system tray. I used the "hackish" methods described in multiple posts utilizing a NotifyIcon and playing with the Form\_Resize event. This all works fine aesthetically, but the resources and memory used are unaffected. I want to be able to minimize resources when minimizing to system tray, just like Visual Studio does. If you are coding in Visual Studio, the memory usage can creep up (depending on project size) to above 500 MB, but when minimizing Visual Studio to the taskbar, the memory drastically decreases to (what I'm assuming) is the minimal amount. Does anyone have any clue as to how to accomplish this? Here's a short description of the application, if anyone finds it relevant: I have a windows form with a ListView that contains Work Orders for my IT department. The application has a "listener" that notifies when a new Work order is submitted. So, when the application is running in the system tray, all I really do is compare the count of items in the ListView to a count of rows in a SQL table every couple of minutes. EDIT: To be more specific, a windows form intrinsically has threads and resources being used by means of the controls, when the form is invisible (in the system tray) these resources are still being used. What can I do to minimize these resources, short of killing all the controls and redrawing them when the form is restored.
Calling MiniMizeMemory() will do a garbage collection, trim the process working size, then compact the process' heap. ``` public static void MinimizeMemory() { GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); SetProcessWorkingSetSize( Process.GetCurrentProcess().Handle, (UIntPtr)0xFFFFFFFF, (UIntPtr)0xFFFFFFFF); IntPtr heap = GetProcessHeap(); if (HeapLock(heap)) { try { if (HeapCompact(heap, 0) == 0) { // error condition ignored } } finally { HeapUnlock(heap); } } } [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetProcessWorkingSetSize( IntPtr process, UIntPtr minimumWorkingSetSize, UIntPtr maximumWorkingSetSize); [DllImport("kernel32.dll", SetLastError = true)] internal static extern IntPtr GetProcessHeap(); [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool HeapLock(IntPtr heap); [DllImport("kernel32.dll")] internal static extern uint HeapCompact(IntPtr heap, uint flags); [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool HeapUnlock(IntPtr heap); ```
You're probably looking for this function call: [SetProcessWorkingSetSize](http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx) If you execute the API call SetProcessWorkingSetSize with -1 as an argument, then Windows will trim the working set immediately. However, if most of the memory is still being held by resources you haven't released minimizing the working set will do nothing. This combined with the suggestion of forcing Garbage Collection might be your best bet. From your application description, you might want to also verify how much memory the ListView is consuming as well as the database access objects. I'm also not clear on how you're making those monitoring database calls. You might want to isolate that into a separate object and avoid touching any of the forms while minimized, otherwise the program will be forced to keep the controls loaded and accessible. You could start a separate thread for monitoring, and pass the ListView.Count as a parameter. Some sources: [.NET Applications and the Working Set](http://www.ddj.com/windows/184416804) [How much memory does my .Net Application use?](http://www.itwriting.com/dotnetmem.php)
.NET Minimize to Tray AND Minimize required resources
[ "", "c#", ".net", "vb.net", "visual-studio", "winforms", "" ]
I'm trying to change default firstDayOfWeek for java.util.Calendar from SUNDAY to MONDAY. Is it possible to achieve this through JVM configuration instead of adding this piece of code? ``` cal.setFirstDayOfWeek(Calendar.MONDAY); ```
The first day of the week is derived from the current locale. If you don't set the locale of the calendar ([Calendar.getInstance(Locale)](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html#getInstance(java.util.Locale)), or [new GregorianCalendar(Locale)](http://java.sun.com/j2se/1.5.0/docs/api/java/util/GregorianCalendar.html#GregorianCalendar(java.util.Locale))), it will use the system's default. The system's default can be overridden by a JVM parameter: ``` public static void main(String[] args) { Calendar c = new GregorianCalendar(); System.out.println(Locale.getDefault() + ": " + c.getFirstDayOfWeek()); } ``` This should show a different output with different JVM parameters for language/country: * *`-Duser.language=en -Duser.country=US`* -> **`en_US: 1`** *(Sunday)* * *`-Duser.language=en -Duser.country=GB`* -> **`en_GB: 2`** *(Monday)* Don't forget that this could change other behavio(u)r too.
According to the API: > Calendar defines a locale-specific seven day week using two parameters: the first day of the week and the minimal days in first week (from 1 to 7). These numbers are taken from the locale resource data when a Calendar is constructed. They may also be specified explicitly through the methods for setting their values. So if you ensure that your locale is appropriately configured, this will be implicitly set. Personally, I would prefer explicitly setting this... See [#64038](https://stackoverflow.com/questions/64038/setting-java-locale-settings) for ways to set a locale from the command line.
How to specify firstDayOfWeek for java.util.Calendar using a JVM argument
[ "", "java", "calendar", "jvm-arguments", "" ]
If I have a method such as: ``` public void MyMethod(int arg1, string arg2) ``` How would I go about getting the actual names of the arguments? I can't seem to find anything in the MethodInfo which will actually give me the name of the parameter. I would like to write a method which looks like this: ``` public static string GetParamName(MethodInfo method, int index) ``` So if I called this method with: ``` string name = GetParamName(MyMethod, 0) ``` it would return "arg1". Is this possible?
``` public static string GetParamName(System.Reflection.MethodInfo method, int index) { string retVal = string.Empty; if (method != null && method.GetParameters().Length > index) retVal = method.GetParameters()[index].Name; return retVal; } ``` The above sample should do what you need.
Try something like this: ``` foreach(ParameterInfo pParameter in pMethod.GetParameters()) { //Position of parameter in method pParameter.Position; //Name of parameter type pParameter.ParameterType.Name; //Name of parameter pParameter.Name; } ```
How can you get the names of method parameters?
[ "", "c#", ".net", "reflection", "" ]
The following two queries each give the same result: ``` SELECT column FROM table GROUP BY column SELECT DISTINCT column FROM table ``` Is there anything different in the way these commands are processed, or are they the same thing? (This is not a question about aggregates. The use of `GROUP BY` with aggregate functions is understood.)
[MusiGenesis](https://stackoverflow.com/questions/164319/is-there-any-difference-between-group-by-and-distinct#164485)' response is functionally the correct one with regard to your question as stated; the SQL Server is smart enough to realize that if you are using "Group By" and not using any aggregate functions, then what you actually mean is "Distinct" - and therefore it generates an execution plan as if you'd simply used "Distinct." However, I think it's important to note [Hank](https://stackoverflow.com/questions/164319/is-there-any-difference-between-group-by-and-distinct#164323)'s response as well - cavalier treatment of "Group By" and "Distinct" could lead to some pernicious gotchas down the line if you're not careful. It's not entirely correct to say that this is "not a question about aggregates" because you're asking about the functional difference between two SQL query keywords, one of which is **meant to be used with aggregates** and one of which is not. A hammer can work to drive in a screw sometimes, but if you've got a screwdriver handy, why bother? (for the purposes of this analogy, `Hammer : Screwdriver :: GroupBy : Distinct` and `screw => get list of unique values in a table column`)
`GROUP BY` lets you use aggregate functions, like `AVG`, `MAX`, `MIN`, `SUM`, and `COUNT`. On the other hand `DISTINCT` just removes duplicates. For example, if you have a bunch of purchase records, and you want to know how much was spent by each department, you might do something like: ``` SELECT department, SUM(amount) FROM purchases GROUP BY department ``` This will give you one row per department, containing the department name and the sum of all of the `amount` values in all rows for that department.
Is there any difference between GROUP BY and DISTINCT?
[ "", "sql", "group-by", "distinct", "" ]
If a variable is declared as `static` in a function's scope it is only initialized once and retains its value between function calls. What exactly is its lifetime? When do its constructor and destructor get called? ``` void foo() { static string plonk = "When will I die?"; } ```
The lifetime of function `static` variables begins the first time[0] the program flow encounters the declaration and it ends at program termination. This means that the run-time must perform some book keeping in order to destruct it only if it was actually constructed. Additionally, since the standard says that the destructors of static objects must run in the reverse order of the completion of their construction[1], and the order of construction may depend on the specific program run, the order of construction must be taken into account. **Example** ``` struct emitter { string str; emitter(const string& s) : str(s) { cout << "Created " << str << endl; } ~emitter() { cout << "Destroyed " << str << endl; } }; void foo(bool skip_first) { if (!skip_first) static emitter a("in if"); static emitter b("in foo"); } int main(int argc, char*[]) { foo(argc != 2); if (argc == 3) foo(false); } ``` **Output:** > C:>sample.exe > Created in foo > Destroyed in foo > > C:>sample.exe 1 > Created in if > Created in foo > Destroyed in foo > Destroyed in if > > C:>sample.exe 1 2 > Created in foo > Created in if > Destroyed in if > Destroyed in foo `[0]` Since **C++98**[2] has no reference to multiple threads how this will be behave in a multi-threaded environment is unspecified, and can be problematic as [Roddy](https://stackoverflow.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-a-c-function#246594) mentions. `[1]` **C++98** section `3.6.3.1` *[basic.start.term]* `[2]` In C++11 statics are initialized in a thread safe way, this is also known as [*Magic Statics*](http://herbsutter.com/2013/09/09/visual-studio-2013-rc-is-now-available/).
Motti is right about the order, but there are some other things to consider: Compilers typically use a hidden flag variable to indicate if the local statics have already been initialized, and this flag is checked on every entry to the function. Obviously this is a small performance hit, but what's more of a concern is that this flag is not guaranteed to be thread-safe. If you have a local static as above, and `foo` is called from multiple threads, you may have race conditions causing `plonk` to be initialized incorrectly or even multiple times. Also, in this case `plonk` may get destructed by a different thread than the one which constructed it. Despite what the standard says, I'd be very wary of the actual order of local static destruction, because it's possible that you may unwittingly rely on a static being still valid after it's been destructed, and this is really difficult to track down.
What is the lifetime of a static variable in a C++ function?
[ "", "c++", "static", "lifetime", "" ]
I am launching a child process with ProcessBuilder, and need the child process to exit if the parent process does. Under normal circumstances, my code is stopping the child properly. However, if I cause the OS to kill the parent, the child will continue running. Is there any way to "tie" the child process to the parent, such that it'll exit when the parent is killed? --- Similar questions: * [How to make child process die after parent exits?](https://stackoverflow.com/questions/284325/how-to-make-child-process-die-after-parent-exits) * [Are child processes created with fork() automatically killed when the parent is killed?](https://stackoverflow.com/questions/395877/are-child-processes-created-with-fork-automatically-killed-when-the-parent-is-k)
There is no tie between a child process and its parent. They may know each others process ID, but there's no hard connection between them. What you're talking about a [orphan process](http://en.wikipedia.org/wiki/Orphan_process). And it's an OS level concern. Meaning any solution is probably platform dependent. About the only thing I can think of is to have the child check its parents status periodically, exiting if the parent's shutdown. I don't think this would be all that reliable though.
While you cannot protect against a hard abort (e.g. SIGKILL on Unix), you can protect against other signals that cause your parent process to shut down (e.g. SIGINT) and clean up your child process. You can accomplish this through use of shutdown hooks: see [Runtime#addShutdownHook](http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html), as well as a related SO question [here](https://stackoverflow.com/questions/40376/handle-signals-in-the-java-virtual-machine). Your code might look something like this: ``` String[] command; final Process childProcess = new ProcessBuilder(command).start(); Thread closeChildThread = new Thread() { public void run() { childProcess.destroy(); } }; Runtime.getRuntime().addShutdownHook(closeChildThread); ```
How can I cause a child process to exit when the parent does?
[ "", "java", "process", "" ]
I know how to program Console application with parameters, example : myProgram.exe param1 param2. My question is, how can I make my program works with |, example : echo "word" | myProgram.exe?
You need to use `Console.Read()` and `Console.ReadLine()` as if you were reading user input. Pipes replace user input transparently. You can't use both easily (although I'm sure it's quite possible...). **Edit:** A simple `cat` style program: ``` class Program { static void Main(string[] args) { string s; while ((s = Console.ReadLine()) != null) { Console.WriteLine(s); } } } ``` And when run, as expected, the output: ``` C:\...\ConsoleApplication1\bin\Debug>echo "Foo bar baz" | ConsoleApplication1.exe "Foo bar baz" C:\...\ConsoleApplication1\bin\Debug> ```
The following will not suspend the application for input and works when data is *or* is not piped. A bit of a hack; and due to the error catching, performance could lack when numerous piped calls are made but... easy. ``` public static void Main(String[] args) { String pipedText = ""; bool isKeyAvailable; try { isKeyAvailable = System.Console.KeyAvailable; } catch (InvalidOperationException expected) { pipedText = System.Console.In.ReadToEnd(); } //do something with pipedText or the args } ```
C# Console receive input with pipe
[ "", "c#", "pipe", "" ]
I have two tables: Table 1: ID, PersonCode, Name, Table 2: ID, Table1ID, Location, ServiceDate I've got a query joining table 1 to table 2 on table1.ID = table2.Table1ID where PersonCode = 'XYZ' What I want to do is return Table1.PersonCode,Table1.Name, Table2.Location, Table2.ServiceDate, I don't want all rows, In table 2 I'm only interested in the row with the most recent ServiceDate for each location. How would I go about doing this?
Something like this: ``` SELECT Table1.PersonCode, Table1.Name, Table2.Location, MAX(Table2.ServiceDate) FROM Table1 INNER JOIN Table2 on Table1.ID = Table2.Table1ID WHERE TABLE1.PersonCode = 'XYZ' GROUP BY Table1.PersonCode,Table1.Name, Table2.Location ```
Use MAX(ServiceDate)
Help with sql join
[ "", "sql", "sql-server", "" ]
My group has a source analysis tool that enforces certain styles that we have to comply with. I can't change it, and some of the rules are just a pain. One example is that all properties have to come before methods, and all constructors must come before properties. It seems silly to me that I have to take time to do something to the program when to the compiler it is the same. I would like some thing that is a plugin to VS that will let me do things like this automatically. Also, it would be nice to have it automatically put using's inside the namespace block.
You have different possibilities, depending on what exactly you want to do: Resharper: There is a auto-format function which formats the source code of a single file or all files in the project / solution depending on your selected rules. So you set the settings for braces, naming, whitespaces, operators, lamdas, ... For more information see [here](http://www.jetbrains.com/resharper/). Resharper also supports settings a source- code file for all solutions or a shared settings file which is the same for all persons in the team. FxCop: I havn't ever used this at work, but it's also a great tool an you can also select the rules which you want to enforce.
Unless they bake it into VS2010, Resharper has the auto formatting capabilities you're probably looking for. CodeSmith probably has it too, I just haven't used it...
Is there a C# auto formatter that I can use to define custom rules for formatting?
[ "", "c#", "formatting", "text-formatting", "" ]
I have a .NET class library containing a class with a method that performs some lengthy operation. When a client calls this method it should perform the lengthy operation on a new thread in order to avoid blocking the caller. But once the method finishes it should execute some code on the main thread. In a WinForms application I could have used the System.Windows.Forms.Control.Invoke method but this is not my case. So how can I achieve this in C#?
I found a simple solution to the problem : My COM object is declared like this: ``` public class Runner { public void Run(string executable, object processExitHandler) { ThreadPool.QueueUserWorkItem(state => { var p = new Process() { StartInfo = new ProcessStartInfo() { FileName = executable } }; p.Start(); while (!p.HasExited) { Thread.Sleep(100); } state .GetType() .InvokeMember( "call", BindingFlags.InvokeMethod, null, state, new object[] { null, p.ExitCode } ); }, processExitHandler); } } ``` And in my HTML page I use it like this: ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head><title>ActiveXRunner</title> <script type="text/javascript"> function runNotepad() { var ax = new ActiveXObject('ActiveXRunner.Runner'); ax.Run('c:\\windows\\notepad.exe', h); } function h(exitCode) { alert('exitCode = ' + exitCode); } </script> </head> <body> <a href="#" onclick="runNotepad();">Run notepad and show exit code when finished</a> </body> </html> ```
You can invoke a function on a specific thread by using a `System.Windows.Threading.Dispatcher` object (from the WindowsBase assembly). For example: ``` public class ClassCreatedBySomeThread { Dispatcher dispatcher = Dispatcher.CurrentDispatcher; public void SafelyCallMeFromAnyThread(Action a) { dispatcher.Invoke(a); } } ```
How to invoke a function on parent thread in .NET?
[ "", "c#", "multithreading", "" ]
In spring you can initialize a bean by having the applicationContext.xml invoke a constructor, or you can set properties on the bean. What are the trade offs between the two approaches? Is it better to have a constructor (which enforces the contract of having everything it needs in one method) or is it better to have all properties (which gives you flexibility to only inject selectively for example when unit testing.) What are the trade offs (between writing a bean that uses a constructor to establish it's initial state, or using properties and perhaps an afterProperties() method) ?
I'm not sure there is a "best" way to initialize a bean. I think there are pros and cons to each, and depending on the situation, one or the other might be appropriate. This certainly isn't an exhaustive list, but here are some things to consider. Using a constructor allows you to have an immutable bean. Immutable objects are good if you can fit them in your design. They don't require copying, serialized access or other special handling between threads. If you have setters, your object isn't immutable. Using a constructor also ensures the object is properly initialized. After the constructor finishes, the object is valid. If your object *requires* the use of setters to initialize it, it's possible to have an invalid object. On the other hand, using constructors often leads to a telescoping problem. Often times you'll need many different constructors, most of which will be a superset of another constructor. Often times these are for convenience. For instance: ``` public class Person { public Person(String name) { ... } public Person(String name, String phone) { ... } public Person(String name, String phone, String email) { ... } } ``` One alternative to this that I very much like is the so called "enhanced" builder pattern presented by Josh Bloch at JavaOne. You can see this in his book "Effective Java, Second Edition". If you look at the way the pattern is used, it will also solve your "afterProperties" method issue. The builder pattern will guarantee the object is correctly initialized. Here is an additional blog post discussing the pattern: <http://www.screaming-penguin.com/node/7598> I'm not sure this fits into your spring requirement, but in general, I'm a big fan of builder.
IMO the major advantage of constructor injection is that it is compatible with immutability. However, if a class has more than about 3 dependencies, this requires providing a constructor which takes a large number of parameters, which is unwieldy. When using setter-injection, I prefer to use the `@PostConstruct` annotation to identify the initialization method. This involves looser coupling to the Spring framework than the `afterProperties()` method you mention (actually, I think it's `afterPropertiesSet()`). Another option is the init method attribute of the `<bean>` element.
What is the best way to initialize a bean?
[ "", "java", "spring", "" ]
Newish to Oracle programming (from Sybase and MS SQL Server). What is the "Oracle way" to avoid filling the trans log with large updates? In my specific case, I'm doing an update of potentially a very large number of rows. Here's my approach: ``` UPDATE my_table SET a_col = null WHERE my_table_id IN (SELECT my_table_id FROM my_table WHERE some_col < some_val and rownum < 1000) ``` ...where I execute this inside a loop until the updated row count is zero, Is this the best approach? Thanks,
The amount of updates to the redo and undo logs will not at all be reduced if you break up the UPDATE in multiple runs of, say 1000 records. On top of it, the total query time will be most likely be higher compared to running a single large SQL. There's no real way to address the UNDO/REDO log issue in UPDATEs. With INSERTs and CREATE TABLEs you can use a DIRECT aka APPEND option, but I guess this doesn't easily work for you.
Depends on the percent of rows almost as much as the number. And it also depends on if the update makes the row longer than before. i.e. going from null to 200bytes in every row. This could have an effect on your performance - chained rows. Either way, you might want to try this. Build a new table with the column corrected as part of the select instead of an update. You can build that new table via CTAS (Create Table as Select) which can avoid logging. Drop the original table. Rename the new table. Reindex, repoint contrainst, rebuild triggers, recompile packages, etc. you can avoid a lot of logging this way.
Oracle SQL technique to avoid filling trans log
[ "", "sql", "oracle", "optimization", "" ]
I want something that can check if a string is `"SELECT"`, `"INSERT"`, etc. I'm just curious if this exists.
Easy enough to add : ``` HashSet<String> sqlKeywords = new HashSet<String>(Arrays.asList( new String[] { ... cut and paste a list of sql keywords here .. })); ```
If you're trying to prevent SQL injection, it would be better to leverage the built in features of JDBC, such as prepared statements. In general, using string concatenation to form the SQL statement is dangerous. From [Preventing SQL Injection in Java](http://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java): **Prepared Statements**: ``` String selectStatement = "SELECT * FROM User WHERE userId = ? "; PreparedStatement prepStmt = con.prepareStatement(selectStatement); prepStmt.setString(1, userId); ResultSet rs = prepStmt.executeQuery(); ```
Is there a class or method in Java that will check if a string is a SQL Server keyword?
[ "", "java", "sql-server", "" ]
A friend of mine asked me to implement a blue and a red pointer to represent the inputs of two separate mice to expedite a mixing desk scenario for real time audio mixing. I'd love to, but as much as I think it is a great idea, I don't have a clue as to where to start looking for a possible solution. Where should I start researching a viable method of implementing dual mouse inputs?
Look at [jinput](http://java.net/projects/jinput). I have had multiple keyboards working with it, I am nearly certain it supports multiple mice too.
dont know about java.. but for C#/c++ you can try the [Microsoft Windows MultiPoint Software Development Kit](http://www.microsoft.com/downloads/details.aspx?FamilyID=A137998B-E8D6-4FFF-B805-2798D2C6E41D&displaylang=en) i've tried it on windows.. it works with 2 USB mice.
How can I handle multiple mouse inputs in Java?
[ "", "java", "mouse", "human-computer-interface", "" ]
Currently I'm using ``` var x = dict.ContainsKey(key) ? dict[key] : defaultValue ``` I'd like some way to have dictionary[key] return null for nonexistant keys, so I could write something like ``` var x = dict[key] ?? defaultValue; ``` this also winds up being part of linq queries etc. so I'd prefer one-line solutions.
With an extension method: ``` public static class MyHelper { public static V GetValueOrDefault<K, V>(this IDictionary<K, V> dic, K key, V defaultVal = default(V)) { V ret; bool found = dic.TryGetValue(key, out ret); if (found) { return ret; } return defaultVal; } void Example() { var dict = new Dictionary<int, string>(); dict.GetValueOrDefault(42, "default"); } } ```
You can use a helper method: ``` public abstract class MyHelper { public static V GetValueOrDefault<K,V>( Dictionary<K,V> dic, K key ) { V ret; bool found = dic.TryGetValue( key, out ret ); if ( found ) { return ret; } return default(V); } } var x = MyHelper.GetValueOrDefault( dic, key ); ```
C# dictionaries ValueOrNull / ValueorDefault
[ "", "c#", ".net", "dictionary", "" ]
I have two html pages, when you click on something on the first html, it will go to the second one. What I want to do is to show text according to what you clicked on the first html. different texts are wrapped with different ids. Here's how I wrote: ``` <a href="secondpage.html#one"></a> <a href="secondpage.html#two"></a> <a href="secondpage.html#three"></a> ``` I'm expecting to see two.html load the text with id "one", but it doesn't work, does anyone know what I did wrong? Here's the code on second page: ``` <ul id="menu" class="aaa"> <li><a id="one" href="#">one</a></li> <li><a id="two" href="#">two</a></li> <li><a id="three" href="#">three</a></li> </ul> ``` And I have a JS file to modify each id: ``` $("one").observe('click', function() { $('Pic').writeAttribute('src',"picone.jpg"); $('Bio').update("texthere!"); }); ``` Same for two and three. Right now if I click on a button on the first page, it will always show the text and pic for "one", no matter which button I click. But I want to see the pic and text for "two" if i click on it.
What you want to do is simulate a click on your anchor when the page loads. Since you're using jQuery, the simplest approach (but far form best) would be the following: ``` $(window).observe('domready', function () { $(location.hash).click(); }); ``` attach ondomready-event to window. Fetch element with id=one (with jQuery this would be '#one', same as your location.hash would be, very handy in this case), trigger a click on it. You might need to replace $(location.hash).click(); with $(location.hash).get(0).click() since jQuery tend to return arrays of jQuery-objects. But a better solution in your case would be to have an event-handler that you can trigger manually, thus circumvent the need of firing events, aswell as drop the anchors and put onclick directly on your li's. And furthermore, why do you load a second page when all you seem to want to do is to show/hide content dynamically? Do it on the same page...
tags do not have id's but names to handle the anchors in Urls, you will still need the ID to manage them in JS though. So your list should be: ``` <ul id="menu" class="aaa"> <li><a id="one" name="one" href="#">one</a></li> <li><a id="two" name="two" href="#">two</a></li> <li><a id="three" name="three" href="#">three</a></li></ul> ``` Your javascript seemed correct though.
JavaScript anchor- access to id on another HTML page
[ "", "javascript", "html", "anchor", "" ]
I want to get the method `System.Linq.Queryable.OrderyBy<T, TKey>(the IQueryable<T> source, Expression<Func<T,TKey>> keySelector)` method, but I keep coming up with nulls. ``` var type = typeof(T); var propertyInfo = type.GetProperty(group.PropertyName); var propertyType = propertyInfo.PropertyType; var sorterType = typeof(Func<,>).MakeGenericType(type, propertyType); var expressionType = typeof(Expression<>).MakeGenericType(sorterType); var queryType = typeof(IQueryable<T>); var orderBy = typeof(System.Linq.Queryable).GetMethod("OrderBy", new[] { queryType, expressionType }); /// is always null. ``` Does anyone have any insight? I would prefer to not loop through the `GetMethods` result.
Solved (by hacking LINQ)! I saw your question while researching the same problem. After finding no good solution, I had the idea to look at the LINQ expression tree. Here's what I came up with: ``` public static MethodInfo GetOrderByMethod<TElement, TSortKey>() { Func<TElement, TSortKey> fakeKeySelector = element => default(TSortKey); Expression<Func<IEnumerable<TElement>, IOrderedEnumerable<TElement>>> lamda = list => list.OrderBy(fakeKeySelector); return (lamda.Body as MethodCallExpression).Method; } static void Main(string[] args) { List<int> ints = new List<int>() { 9, 10, 3 }; MethodInfo mi = GetOrderByMethod<int, string>(); Func<int,string> keySelector = i => i.ToString(); IEnumerable<int> sortedList = mi.Invoke(null, new object[] { ints, keySelector } ) as IEnumerable<int>; foreach (int i in sortedList) { Console.WriteLine(i); } } ``` output: 10 3 9 EDIT: Here is how to get the method if you don't know the type at compile-time: ``` public static MethodInfo GetOrderByMethod(Type elementType, Type sortKeyType) { MethodInfo mi = typeof(Program).GetMethod("GetOrderByMethod", Type.EmptyTypes); var getOrderByMethod = mi.MakeGenericMethod(new Type[] { elementType, sortKeyType }); return getOrderByMethod.Invoke(null, new object[] { }) as MethodInfo; } ``` Be sure to replace typeof(Program) with typeof(WhateverClassYouDeclareTheseMethodsIn).
A variant of your solution, as an extension method: ``` public static class TypeExtensions { private static readonly Func<MethodInfo, IEnumerable<Type>> ParameterTypeProjection = method => method.GetParameters() .Select(p => p.ParameterType.GetGenericTypeDefinition()); public static MethodInfo GetGenericMethod(this Type type, string name, params Type[] parameterTypes) { return (from method in type.GetMethods() where method.Name == name where parameterTypes.SequenceEqual(ParameterTypeProjection(method)) select method).SingleOrDefault(); } } ```
Get a generic method without using GetMethods
[ "", "c#", ".net", "generics", "reflection", "" ]
I am talking about Google Text Translation User Interface, in [Google Language Tools](http://www.google.com/language_tools). I like the fact that you can get translations of text for a lot of languages. However, I think is not so good always to show all options of translation. I believe is preferably to show, in first instance, only the most frequent options for text translation. Really, it has become very annoying trying to translate from English to spanish, for example. Using the keyboard (E, Tab, then S Key repeatedly), the first three options presented are Serbian, Slovak, Slovenian, and finally Spanish... Another example: from English to French. Using the keyboard again (F key repeatedly) shows Filipino and Finish before French!!! What sort of ideas do you think can it be applied to this GUI to make it more effective for real people usage?
I've been frustrated with this interface as well. I think it would be a good idea to (a) use cookies to give preference to the languages this user has selected in the past; and (b) to display a limited list (4-8 languages) of the most common languages, with a "more..." option that expands the list. I really appreciate the fact that a lot of websites and software applications have started using this approach when asking you to specify your time zone. Why display "Mid-Atlantic", "Azores", etc. if you expect 95% of your users to be in (for example) the 5 U.S. time zones.
I think it's probably fine. There are only a little over 30 languages in the list, and close to half of them are pretty common languages, so I don't think it really makes sense to put the common ones first. It's not like a country list where you have to search through 180+ countries to find yours. The only thing I would probably do is use a cookie to store your last language selection(s).
What ideas do you think can it be applied to this GUI to make it more effective for real people usage?
[ "", "javascript", "user-interface", "" ]
I just spent half an one our to find out what caused the Error-Message "Ci is not defined" in my JavaScript code. I finally found the reason: It should be (jQuery): ``` $("asd").bla(); ``` It was: ``` ("asd").bla(); ``` (Dollar sign gone missing) Now after having fixed the problem I'd like to understand the message itself: What does Firefox mean when it tells me that "Ci" is not defined. What's "Ci"? --- Update: I'm using the current version of Firefox (3.0.3). To reproduce, just use this HTML code: ``` <html><head><title>test</title> <script> ("asd").bla(); </script> </head><body></body></html> ``` To make it clear: I know what caused the error message. I'd just like to know what Firefox tries to tell me with "Ci"...
I don't know which version of FF you are using, but regardless, the message is probably referring to the fact that `bla()` is not a function available on the String object. Since you were missing the `$`, which means you were missing a function, `("asd")` would evaluate to a string, and then the JavaScript interpreter would try to call `bla()` on that object. So, if you had the following code in your project: ``` String.prototype.bla = function() {}; // now this next line will execute without any problems: ("asd").bla(); ``` So, it is possible that `Ci` is some internal Firefox symbol that simply refers to the idea of a function. That is my guess, I imagine you are going to need someone that knows something about Firefox's internals to get a better answer to this question... --- UPDATE: I am running your example code in the *exact* same version of FF as you are, but it reports the error as: > Error: "asd".bla is not a function > Source File: file:///C:/test.html > Line: 3 Perhaps you have an extension/plug-in running that does something with this? Maybe some Greasemonkey script or something?
Jason seems to be right. Many plugins (e.g. Firebug, Geode) use Ci as a shortcut: ``` const Ci = Components.interfaces; ``` So the plugins seem to cause that strange error message.
JavaScript: Ci is not defined
[ "", "javascript", "firefox", "continuous-integration", "" ]
I have a website built using Asp.net and LinqToSql for Data Access. In a certain section of the site, LinqToSql produces a query that looks like this (from my dev machine): ``` select ... from table1 left outer join table2 on table1 where ... left outer join table3 on table2 where ... ``` Since the connection between table2 and table1 is not always there, the left outer join is appropriate in this situation. And since the link between table3 and table1 goes through table2, it also needs a left outer join. This sql returns the correct recordset. I just put the code up to a server. Running the identical code in the same scenario, LinqToSql produces the following query: ``` select ... from table1 left outer join table2 on table1 where ... join table3 on table2 where ... ``` For some reason, it renders the join between table2 and table3 as an inner join, instead of an outer join. This results in zero records being returned from the query. Both dev machine and server are using .Net 3.5 SP1. Dev machine is Vista64, Server is Windows Server 2003 SP2. A colleague of mine using Windows XP PRO also confirmed the same correct behavior on their dev machine. Can anyone think of a reason why the server would create different sql? How can I fix this? It seems to be something tied into the way that Linq and .Net is running on the server. However, I can't think of any way to confirm and fix this. --- Linq Code (I am only including the parts that are relevant to the section where the sql changed): ``` from Import_Table t in db.Import_Tables select new { CheckedOutUser = (!t.IsCheckedOut) ? "--" : t.Import_CheckoutHistory.System_User.FirstName + " " + t.Import_CheckoutHistory.System_User.LastName, CheckedOutUserID = (!t.IsCheckedOut) ? 0 : t.Import_CheckoutHistory.System_UserID}; ``` In the context of the description above, table1 = Import\_Table, table2 = Import\_CheckoutHistory, table3 = System\_User. If I comment out the line here that begins with "CheckedOutUser = ..." then it works on the server - so this is definitely the culprit. Actual sql returned: ``` SELECT (CASE WHEN NOT ([t0].[IsCheckedOut] = 1) THEN CONVERT(NVarChar(401),'--') ELSE ([t2].[FirstName] + ' ') + [t2].[LastName] END) AS [CheckedOutUser], (CASE WHEN NOT ([t0].[IsCheckedOut] = 1) THEN 0 ELSE [t1].[system_UserID] END) AS [CheckedOutUserID] FROM [dbo].[import_Table] AS [t0] LEFT OUTER JOIN [dbo].[import_CheckoutHistory] AS [t1] ON [t1].[import_CheckoutHistoryID] = [t0].[import_CheckoutHistoryID] LEFT OUTER/INNER JOIN [dbo].[system_User] AS [t2] ON [t2].[system_UserID] = [t1].[system_UserID] ``` On the dev machines, the last line begins with "Left outer". On the server, the last line begins with "Inner" **Update:** My solution is [below](https://stackoverflow.com/questions/269594/linqtosql-producing-different-sql-queries-on-different-machines-for-identical-c#275751)
I have checked the following: 1. Both use the same database 2. Both have the identical code 3. Both have the identical dbml file I know that something has to be out of synch somewhere, but I can't find it. So I have implemented the following workaround: I added a view to my database that includes both left outer joins. This view is now in my dbml file, and in the query above, I reference the view instead of the table. This is working fine.
Is your production database different to your development one, e.g. SQL Server 2008 instead of 2005? I believe LINQ to SQL will vary the SQL it generates based on the actual execution-time database it's talking to. Also, are the schemas exactly the same on both databases?
LinqToSql Producing Different Sql Queries on Different Machines for Identical Code
[ "", ".net", "asp.net", "sql", "linq-to-sql", "" ]
I'm not sure if the title is very clear, but basically what I have to do is read a line of text from a file and split it up into 8 different string variables. Each line will have the same 8 chunks in the same order (title, author, price, etc). So for each line of text, I want to end up with 8 strings. The first problem is that the last two fields in the line may or may not be present, so I need to do something with stringTokenizer.hasMoreTokens, otherwise it will die messily when fields 7 and 8 are not present. I would ideally like to do it in one while of for loop, but I'm not sure how to tell that loop what the order of the fields is going to be so it can fill all 8 (or 6) strings correctly. Please tell me there's a better way that using 8 nested if statements! EDIT: The String.split solution seems definitely part of it, so I will use that instead of stringTokenizer. However, I'm still not sure what the best way of feeding the individual strings into the constructor. Would the best way be to have the class expecting an array, and then just do something like this in the constructor: ``` line[1] = isbn; line[2] = title; ```
The best way is to not use a StringTokenizer at all, but use String's [split](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#split(java.lang.String)) method. It returns an array of Strings, and you can get the length from that. For each line in your file you can do the following: ``` String[] tokens = line.split("#"); ``` `tokens` will now have 6 - 8 Strings. Use `tokens.length()` to find out how many, then create your object from the array.
Regular expression is the way. You can convert your incoming String into an array of String using the split method <http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#split(java.lang.String)>
What's the best way to have stringTokenizer split up a line of text into predefined variables
[ "", "java", "string", "tokenize", "" ]
I have a file I need to rename to that of an existing file. This is a copy, modify, replace original operation on an existing JAR file. I've got the first two steps done, I just need help with the replace original bit. What's the best way to rename the new version of the JAR to that of the old. The old JAR doesn't need preserving and I don't want to have a copy of the new with its initial name sticking around. I have commons lang and io already, so if there's a method I've missed, that would be great.
You're going to need to create two `java.io.File` objects: one for the new file, one for the old file. Lets call these `oldFile` and `newFile`. ``` oldFile.delete() newFile.renameTo(oldFile); ``` Edit: mmyers beat me to it.
`Java.io.File.renameTo(java.io.File)` You might need to call `File.delete()` first on the original file first - some systems won't rename a file onto an existing file.
Rename file onto another in java
[ "", "java", "file", "" ]
I've got an MS access database and I would need to create an SQL query that allows me to select all the not distinct entries in one column while still keeping all the values. In this case more than ever an example is worth thousands of words: Table: ``` A B C 1 x q 2 y w 3 y e 4 z r 5 z t 6 z y ``` *SQL magic* Result: ``` B C y w y e z r z t z y ``` Basically it removes all unique values of column B but keeps the multiple rows of the data kept. I can "group by b" and then "count>1" to get the not distinct but the result will only list one row of B not the 2 or more that I need. Any help? Thanks.
``` Select B, C From Table Where B In (Select B From Table Group By B Having Count(*) > 1) ```
Another way of returning the results you want would be this: ``` select * from my_table where B in (select B from my_table group by B having count(*) > 1) ```
Multiple NOT distinct
[ "", "sql", "ms-access", "distinct", "" ]
I have a image button. I wanted to add a text "Search" on it. I am not able to add it because the "imagebutton" property in VS 2008 does not have text control in it. Can anyone tell me how to add text to a image button?? ``` <asp:ImageButton ID="Searchbutton" runat="server" AlternateText="Search" CssClass="bluebutton" ImageUrl="../Graphics/bluebutton.gif" Width="110px" onclick="Searchbutton_Click"/> ```
``` <button runat="server" style="background-image:url('/Content/Img/stackoverflow-logo-250.png')" > your text here<br/>and some more<br/><br/> and some more .... </button> ```
This tip from [dotnetslave.com](http://forums.asp.net/t/1024015.aspx) worked for me: ``` <asp:LinkButton CssClass="lnkSubmit" ID="lnkButton" runat="server">SUBMIT</asp:LinkButton> a.lnkSubmit:active { margin:0px 0px 0px 0px; background:url(../../images/li_bg1.jpg) left center no-repeat; padding: 0em 1.2em; font: 8pt "tahoma"; color: #336699; text-decoration: none; font-weight: normal; letter-spacing: 0px; ``` }
Text on an Image button in c# asp.net 3.5
[ "", "c#", "asp.net", "" ]
I have a page where my combo box has hundreds of elements which makes it very hard to pick the one item I want. Is there a good Javascript replacement that would do better than ``` <select id="field-component" name="field_component"> <option selected="selected">1</option><option>2</option>... </select> ``` Is there something with "Intellisense"-like auto-complete?
![http://www.dhtmlx.com/images/logo_combo.gif](https://i.stack.imgur.com/TouKN.gif) You have [dhtmlCombo](http://www.dhtmlx.com/docs/products/dhtmlxCombo/index.shtml), using ajax to retrieve data when you are filling the input field. dhtmlxCombo is a cross-browser JavaScript combobox with autocomplete feature. It extends basic selectbox functionality to meet the requirements of the most up-to-date web applications. dhtmlxCombo can be converted from existing HTML SELECT or populated with JavaScript. Supporting AJAX, it can also **get list values from the server datasource dynamically**.
In HTML 5 there's standard combo box. Currently only Opera supports it, but if you happen to be time traveller or writing Opera-only application, it's a nice solution :) ``` <input type=text list=listid> <datalist id=listid> <select><option>1<option>2</select> </datalist> ```
Good Javascript Combo Box replacement for combo boxes with tons of elements?
[ "", "javascript", "html", "combobox", "dhtml", "" ]
What is the best way to manage a database connection in a Java servlet? Currently, I simply open a connection in the `init()` function, and then close it in `destroy()`. However, I am concerned that "permanently" holding onto a database connection could be a bad thing. Is this the correct way to handle this? If not, what are some better options? edit: to give a bit more clarification: I have tried simply opening/closing a new connection for each request, but with testing I've seen performance issues due to creating too many connections. Is there any value in sharing a connection over multiple requests? The requests for this application are almost all "read-only" and come fairly rapidly (although the data requested is fairly small).
I actually disagree with using Commons DBCP. You should really defer to the container to manage connection pooling for you. Since you're using Java Servlets, that implies running in a Servlet container, and all major Servlet containers that I'm familiar with provide connection pool management (the Java EE spec may even require it). If your container happens to use DBCP (as Tomcat does), great, otherwise, just use whatever your container provides.
As everybody says, you need to use a connection pool. Why? What up? Etc. **What's Wrong With Your Solution** I know this since I also thought it was a good idea once upon a time. The problem is two-fold: 1. All threads (servlet requests get served with one thread per each) will be sharing the same connection. The requests will therefore get processed one at a time. This is very slow, even if you just sit in a single browser and lean on the F5 key. Try it: this stuff sounds high-level and abstract, but it's empirical and testable. 2. If the connection breaks for any reason, the init method will not be called again (because the servlet will not be taken out of service). Do not try to handle this problem by putting a try-catch in the doGet or doPost, because then you will be in hell (sort of writing an app server without being asked). 3. Contrary to what one might think, you will not have problems with transactions, since the transaction start gets associated with the thread and not just the connection. I might be wrong, but since this is a bad solution anyway, don't sweat it. **Why Connection Pool** Connection pools give you a whole bunch of advantages, but most of all they solve the problems of 1. Making a real database connection is costly. The connection pool always has a few extra connections around and gives you one of those. 2. If the connections fail, the connection pool knows how to open a new one 3. Very important: every thread gets its own connection. This means that threading is handled where it should be: at the DB level. DBs are super efficient and can handle concurrent request with ease. 4. Other stuff (like centralizing location of JDBC connect strings, etc.), but there are millions of articles, books, etc. on this **When to Get a Connection** Somewhere in the call stack initiated in your service delegate (doPost, doGet, doDisco, whatever) you should get a connection and then you should do the right thing and return it in a finally block. I should mention that the C# main architect dude said once up a time that you should use `finally` blocks 100x more than `catch` blocks. Truer words never spoken... **Which Connection Pool** You're in a servlet, so you should use the connection pool the container provides. Your JNDI code will be completely normal except for how you obtain the connection. As far as I know, all servlet containers have connection pools. Some of the comments on the answers above suggest using a particular connection pool API instead. Your WAR should be portable and "just deploy." I think this is basically wrong. If you use the connection pool provided by your container, your app will be deployable on containers that span multiple machines and all that fancy stuff that the Java EE spec provides. Yes, the container-specific deployment descriptors will have to be written, but that's the EE way, mon. One commenter mentions that certain container-provided connection pools do not work with JDBC drivers (he/she mentions Websphere). That sounds totally far-fetched and ridiculous, so it's probably true. When stuff like that happens, throw everything you're "supposed to do" in the garbage and do whatever you can. That's what we get paid for, sometimes :)
Best way to manage database connection for a Java servlet
[ "", "java", "database", "servlets", "connection", "" ]
Either for comparisons or initialization of a new variable, does it make a difference which one of these you use? I know that BigDecimal.ZERO is a 1.5 feature, so that's a concern, but assuming I'm using 1.5 does it matter? Thanks.
`BigDecimal.ZERO` is a predefined constant and therefore doesn't have to be evaluated from a string at runtime as `BigDecimal("0")` would be. It will be faster and won't require creation of a new object. If your code needs to run on pre-1.5, then you can use the (much maligned) Singleton pattern to create an object equivalent to `BigDecimal.ZERO`. The first time it is used, it would call `BigDecimal("0")` to create a zero object, and return that object on subsequent calls. Otherwise, if your code is running on a 1.5 system, your singleton object can just return `BigDecimal.ZERO` with no runtime penalty.
Using ZERO doesn't create a new object or require any parsing. Definitely the way to go.
Is there a difference between BigDecimal("0") and BigDecimal.ZERO?
[ "", "java", "bigdecimal", "zero", "" ]
An application that has been working well for months has stopped picking up the JPA `@Entity` annotations that have been a part of it for months. As my integration tests run I see dozens of "`org.hibernate.MappingException: Unknown entity: com.whatever.OrderSystem`" type errors. It isn't clear to me what's gone wrong here. I have no `hibernate.cfg.xml` file because I'm using the Hibernate Entity Manager. Since I'm exclusively using annotations, there are no .hbm.xml files for my entities. My `persistence.xml` file is minimal, and lives in `META-INF` as it is supposed to. I'm obviously missing something but can't put my finger on it. I'm using hibernate-annotations 3.2.1, hibernate-entitymanager 3.2.1, persistence-api 1.0 and hibernate 3.2.1. hibernate-commons-annotations is also a part of the project's POM but I don't know if that's relevant. Is there a web.xml entry that has vanished, or a Spring configuration entry that has accidentally been deleted?
I seem to recall I had a similar issue at one time. Its a long shot, but if you're not already doing this, have you explicitly specified the provider you are using? ``` <persistence ...> <persistence-unit ...> <provider>org.hibernate.ejb.HibernatePersistence</provider> <---- explicit setting .... </persistence-unit> </persistence> ``` Otherwise, I'm not sure?
verify in your entity classe that you import javax.persistent.Entity and not org.hibernate.annotations.Entity
Hibernate/JPA Annotations -- Unknown Entity
[ "", "java", "hibernate", "jpa", "annotations", "" ]
Is keeping JMS connections / sessions / consumer always open a bad practice? Code draft example: ``` // app startup code ConnectionFactory cf = (ConnectionFactory)jndiContext.lookup(CF_JNDI_NAME); Connection connection = cf.createConnection(user,pass); Session session = connection.createSession(true,Session.TRANSACTIONAL); MessageConsumer consumer = session.createConsumer(new Queue(queueName)); consumer.setMessageListener(new MyListener()); connection.start(); connection.setExceptionListener(new MyExceptionHandler()); // handle connection error // ... Message are processed on MyListener asynchronously ... // app shutdown code consumer.close(); session.close(); connection.close(); ``` Any suggestions to improve this pattern of JMS usage?
That is a very common and acceptable practice when dealing with long lived connections. For many JMS servers it is in fact preferable to creating a new connection each time it is needed.
Agreed. Here are some [good tips on how to use JMS efficiently](http://activemq.apache.org/how-do-i-use-jms-efficiently.html) which includes keeping around connections/sessions/producers/consumers. You might also want to check the [recommendation on using transactions](http://activemq.apache.org/should-i-use-transactions.html) too if you are interested in maximising performance.
Long lived JMS sessions. Is Keeping JMS connections / JMS sessions always opened a bad practice?
[ "", "java", "jms", "" ]
I cannot understand how this is possible. Please help!! I have an app with a trayicon. I want a form to be show when the user double clicks the trayicon. I have a problem where it is possible to get 2 or more forms showing by quickly triple or quadruple clicking the trayicon. The reason I don't want a singleton is that I want the form to be released each time it is closed to save memory, maybe this is not a good idea? I have a field called m\_form1. I have a method called ShowForm1; I call the method ShowForm1 on the double-click of the TrayIcon. ``` private Form1 m_form1; private void ShowForm1() { if (m_form1 == null) { Trace.WriteLine("*CREATE*" + Thread.CurrentThread.ManagedThreadId.ToString()); m_form1 = new Form1(); m_form1.FormClosed += new FormClosedEventHandler(m_form1_FormClosed); m_form1.Show(); } m_form1.BringToFront(); m_form1.Activate(); } ``` So when Form1 takes a while to construct, then it is possible to create 2 because m\_form1 is still null when the second call arrives. Locking does not seem to work as it is the same thread both calls (I'm guessing the UI thread) ie the trace writes out \*CREATE\*1 twice (below). ``` [3560] *CREATE*1 [3560] *CREATE*1 ``` Changing the code to include a lock statement does not help me. ``` private Form1 m_form1; private object m_Locker = new object(); private void ShowForm1() { lock (m_Locker) { if (m_form1 == null) { Trace.WriteLine("****CREATE****" + Thread.CurrentThread.ManagedThreadId.ToString()); m_form1 = new Form1(); m_form1.FormClosed += new FormClosedEventHandler(m_form1_FormClosed); m_form1.Show(); } } m_form1.BringToFront(); m_form1.Activate(); } ``` How should I handle this situation? Thanks guys Tim.
Have an additional boolean variable, "m\_formUnderConstruction" which you test for before constructing the form, and which you set as soon as you've decided to construct it. The re-entrancy makes all of this a little icky, unfortunately. I've removed the lock, as if this ever gets called from a different thread then you've got the nasty situation of trying to show a form from a different thread to the one it was constructed on. ``` private Form1 m_form1; private bool m_underConstruction = false; private void ShowForm1() { if (m_underConstruction) { // We're about to show it anyway return; } m_underConstruction = true; try { if (m_form1 == null) { m_form1 = new Form1(); m_form1.FormClosed += new FormClosedEventHandler(m_form1_FormClosed); m_form1.Show(); } } finally { m_underConstruction = false; } m_form1.BringToFront(); m_form1.Activate(); } ```
Use Interlocked.Increment to change the nr of the tries. If it is 1, open the form, otherwise, don't. And use Interlocked.Decrement after the test or on form's close. ``` private int openedForms = 0; private Form1 m_form1; private void ShowForm1() { if (Interlocked.Increment(ref openedForms) = 1) { m_form1 = new Form1(); m_form1.FormClosed += new FormClosedEventHandler(m_form1_FormClosed); m_form1.Show(); } else { Interlocked.Decrement(ref openedForms); } if (m_form1 != null) { m_form1.BringToFront(); m_form1.Activate(); } } private void m_form1_FormClosed(object Sender, EventArgs args) { Interlocked.Decrement(ref openedForms); } ```
Single instance form but not singleton
[ "", "c#", "winforms", "multithreading", "" ]
I am working on a project to enhance our production debugging capabilities. Our goal is to reliably produce a minidump on any unhandled exception, whether the exception is managed or unmanaged, and whether it occurs on a managed or unmanaged thread. We use the excellent [ClrDump](http://www.debuginfo.com/tools/clrdump.html) library for this currently, but it does not quite provide the exact features we need, and I'd like to understand the mechanisms behind exception filtering, so I set out to try this for myself. I started out by following this blog article to install an SEH handler myself: <http://blogs.microsoft.co.il/blogs/sasha/archive/2007/12.aspx>. This technique works for console applications, but when I try the same thing from a WinForms application, my filter is not called for any variety of unmanaged exceptions. What can ClrDump be doing that I'm not doing? ClrDump produces dumps in all cases, so its exception filter must still be called... Note: I'm aware of ADPlus's capabilities, and we've also considered using the AeDebug registry keys... These are also possibilities, but also have their tradeoffs. Thanks, Dave ``` // Code adapted from <http://blogs.microsoft.co.il/blogs/sasha/archive/2007/12.aspx> LONG WINAPI MyExceptionFilter(__in struct _EXCEPTION_POINTERS *ExceptionInfo) { printf("Native exception filter: %X\n",ExceptionInfo->ExceptionRecord->ExceptionCode); Beep(1000,1000); Sleep(500); Beep(1000,1000); if(oldFilter_ == NULL) { return EXCEPTION_CONTINUE_SEARCH; } LONG ret = oldFilter_(ExceptionInfo); printf("Other handler returned %d\n",ret); return ret; } #pragma managed namespace SEHInstaller { public ref class SEHInstall { public: static void InstallHandler() { oldFilter_ = SetUnhandledExceptionFilter(MyExceptionFilter); printf("Installed handler old=%x\n",oldFilter_); } }; } ```
Windows Forms has a built-in exception handler that does the following by default: * Catches an unhandled managed exception when: + no debugger attached, and + exception occurs during window message processing, and + jitDebugging = false in App.Config. * Shows dialog to user and prevents app termination. You can disable the first behaviour by setting **jitDebugging = true** in App.Config. This means that your last chance to stop the app terminating is to catch the unhandled exception by registering for the event Application.ThreadException, e.g. in C#: ``` Application.ThreadException += new Threading.ThreadExceptionHandler(CatchFormsExceptions); ``` If you decide not to catch the unhandled exception here, then you will need to check and/or change the registry setting **DbgJitDebugLaunchSetting** under HKLM\Software.NetFramework. This has one of three values of which I'm aware: * 0: shows user dialog asking "debug or terminate". * 1: lets exception through for CLR to deal with. * 2: launches debugger specified in DbgManagedDebugger registry key. In Visual Studio, go to Tools>Options>Debugging>JIT to set this key to 0 or 2. But a value of 1 is usually what you want on an end-user's machine. Note that this registry key is acted on before the CLR unhandled exception event that you discuss. Then you can set the native exception filter that you discussed.
If you want your GUI thread exceptions to work just like your-non GUI ones, so that they get handled the same way, you can do this: ``` Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException); ``` Here's the background: In a manged GUI app, by default, exceptions that originate in the GUI thread are handled by whatever is assigned to the Application.ThreadException, which you can customize like this: ``` Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); ``` Exceptions that originate in the other threads are handled by AppDomain.CurrentDomain.UnhandledException, which you can customize like this: ``` AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(Program.CurrentDomain_UnhandledException); ``` Assigning to UnHandledException works exactly like calling Win32 SetUnhandledExceptionFilter. If you goal is to create minidumps and then use them, you'll need to use Debugging Tools for Windows, sos.dll. You'll need to produce minidumps MiniDumpWithFullMemory. And then, even then, you probably won't have everything you might want. System.Diagnostics.StackTrace to get the call managed call stack.
How does SetUnhandledExceptionFilter work in .NET WinForms applications?
[ "", "c#", ".net", "debugging", "clrdump", "" ]
I've just started experimenting with SDL in C++, and I thought checking for memory leaks regularly may be a good habit to form early on. With this in mind, I've been running my 'Hello world' programs through Valgrind to catch any leaks, and although I've removed everything except the most basic `SDL_Init()` and `SDL_Quit()` statements, Valgrind still reports 120 bytes lost and 77k still reachable. My question is: Is there an acceptable limit for memory leaks, or should I strive to make all my code completely leak-free?
Be careful that Valgrind isn't picking up false positives in its measurements. Many naive implementations of memory analyzers flag lost memory as a leak when it isn't really. Maybe have a read of some of the papers in the external links section of the [Wikipedia article on Purify](http://en.wikipedia.org/wiki/IBM_Rational_Purify). I know that the documentation that comes with Purify describes several scenarios where you get false positives when trying to detect memory leaks and then goes on to describe the techniques Purify uses to get around the issues. BTW I'm not affiliated with IBM in any way. I've just used Purify extensively and will vouch for its effectiveness. Edit: Here's an [excellent introductory article](http://www.ibm.com/developerworks/rational/library/06/0822_satish-giridhar/) covering memory monitoring. It's Purify specific but the discussion on types of memory errors is very interesting. HTH. cheers, Rob
You have to be careful with the definition of "memory leak". Something which is allocated once on first use, and freed on program exit, will sometimes be shown up by a leak-detector, because it started counting before that first use. But it's not a leak (although it may be bad design, since it may be some kind of global). To see whether a given chunk of code leaks, you might reasonably run it once, then clear the leak-detector, then run it again (this of course requires programmatic control of the leak detector). Things which "leak" once per run of the program usually don't matter. Things which "leak" every time they're executed usually do matter eventually. I've rarely found it too difficult to hit zero on this metric, which is equivalent to observing creeping memory usage as opposed to lost blocks. I had one library where it got so fiddly, with caches and UI furniture and whatnot, that I just ran my test suite three times over, and ignored any "leaks" which didn't occur in multiples of three blocks. I still caught all or almost all the real leaks, and analysed the tricky reports once I'd got the low-hanging fruit out of the way. Of course the weaknesses of using the test suite for this purpose are (1) you can only use the parts of it that don't require a new process, and (2) most of the leaks you find are the fault of the test code, not the library code...
Is there an acceptable limit for memory leaks?
[ "", "c++", "memory-leaks", "sdl", "" ]
I'm looking for a good way to run a Apache Derby server in network mode. I'm using the NetworkServerControl to start the server and it's working great. I start the server like this: ``` /** * starts the network server * @return true if sucessfull */ public boolean start() { try { // just to be sure that we don't start two servers this.stop(); server = new NetworkServerControl(); server.start( null ); return true; } catch ( Exception ex ) { this.logLogger.debug( ex ); return false; } } ``` And stop it like this: ``` /** * stops the server * * @return true if there were no problems stopping the server */ public boolean stop() { try { if ( server == null ) { server = new NetworkServerControl(); } server.shutdown(); return true; } catch ( Exception ex ) { this.logLogger.debug( ex ); return false; } } ``` On the main() I have this so the process doesn't die while the server is running ``` (...) clsDB.start(); while( clsDB.testForConnection() ) { Thread.sleep( 60000 ); } ``` testForConnection() looks like this: ``` /** * Try to test for a connection * * @return true if the server is alive */ public boolean testForConnection() { try { server.ping(); return true; } catch ( Exception ex ) { this.logLogger.debug( ex ); return false; } } ``` My problem is that when a new instace of my JAR is called the old one will still be running (unless I'm really really lucky and the test is made before the new server is started). I know I could just test if the server is already running and then I wouldn't start again, but I would like for start to work like a restart if the server is already there.
We ended up with using a file that is created when the server is to be killed, then on the server process we periodically check if the file exists, if it's there we kill the server.
I did a project awhile ago with derby (including running in network mode), and I seem to remember that there is some SQL you can execute on the server which shuts derby down. So, assuming that's the case (no time to google for it atm sorry) you could, on start up, look for your network instance. If it exists, run this SQL on it. Once you have determined that it's finally shut down (polling that it exists I suppose) you can then start it up again. **Edit:** Oh, it wasn't SQL, it's connecting to the DB with 'shutdown=true' as a parameter. See [here](http://db.apache.org/derby/docs/dev/devguide/tdevdvlp40464.html): ``` DriverManager.getConnection( "jdbc:derby:sample;shutdown=true"); ```
Kill Derby DB Network Server on background
[ "", "java", "derby", "javadb", "" ]
According to [Wikipedia](http://en.wikipedia.org/wiki/Rounding) when rounding a negative number, you round the absolute number. So by that reasoning, -3.5 would be rounded to -4. But when I use java.lang.Math.round(-3.5) returns -3. Can someone please explain this?
According to the [javadoc](http://java.sun.com/javase/6/docs/api/java/lang/Math.html#round(double)) > Returns the closest long to the > argument. The result is rounded to an > integer by adding 1/2, taking the > floor of the result, and casting the > result to type long. In other words, > the result is equal to the value of > the expression: > > `(long)Math.floor(a + 0.5d)` Conceptually, you round **up**. In other words, to the next integer **greater** than the value and -3 is greater than -3.5, while -4 is less.
There are a variety of methods of rounding; the one you are looking at is called Symmetrical Arithmetic Rounding (as it states). The section you are referring to states: "This method occurs commonly used in mathematical applications, for example in accounting. It is the one generally taught in elementary mathematics classes." This seems to acknowledge that it is not a rule that is globally agreed upon, just the one that is most common. Personally, I don't recall ever being taught that rule in school. My understanding of rounding has always been that .5 is rounded up, regardless of the sign of the number. Apparently the authors of Java have the same understanding. This is Asymmetrical Arithmetic Rounding. Different tools and languages potentially use different rounding schemes. Excel apparently uses the symmetric method. (Overall, I would advise that if you find a conflict between Wikipedia and experience, you look for information elsewhere. Wikipedia is not perfect.)
Rounding negative numbers in Java
[ "", "java", "rounding", "" ]
As well-known, C++ has steeper learning curve than most of the mainstream languages, which results in better performance . But, does using C++ over other languages[like Java,Ruby,Python] for Qt development have still (major) advantages,let's say about Qtopia? If any, what are they?
Qt is natively a C++ API, so any other languages have to have wrapper code around it which needs to be maintained, etc. The primary documentation will also be for the C++ API. I'm not sure if there are any "official" bindings to other languages which are maintained and released together with Qt.
If you are looking at Qtopia, you are probably looking into embedded systems. In that case, C++ will likely be the one you want to choose, specifically for those performance reasons. Otherwise, Trolltech maintains a Java binding, and I imagine that some of the other language bindings aren't too bad either, since those languages can interact directly with c/c++ code. However, those bindings are likely to always be a little out of date.
What advantages does C++ have over other languages for Qt development?
[ "", "c++", "qt", "" ]
I have recently been exposed to naked objects. It looks like a pretty decent framework. However I do not see it in widespread use like say, Spring. So why is this framework not getting any mainstream application credit. What are its shortcomings as you see?
From my experience using NOF 3.0.3... The good: * Automagically generates an DnD UI for your domain objects, like what db4o does for persistence. * This is what MVC was always meant to be, according to the MVC pattern creator. * The framework only asks your domain objects (POJOs) to be subclassed from AbstractDomainObject thats all the minimum wiring. * The framework favors convention OVER configuration: lots of annotations no freaking XML config giles. * Works great for prototyping along with db4o for persistence. * Out of the box functionality for Hibernate. * In my case, I required like 30 mins from Download to Hello world app. (IntelliJ IDEA IDE) * Deployment as JNLP, standalone, Web (NOX embedded Jetty or Scimpi flavor) and Eclipse RCP. * The NOF team is ALWAYS there for you when you ask for help in the forums. * The Naked Object Pattern is an awesome idea, do yourself a favor and take your time to grok it. * Theres a lot of usability flaming going on around the Drag and Drop GUI, but if your prospective end users simply ***can't*** work with the DnD UI then you are in deep trouble anyway. The bad: * None that I can think of. The kinda ugly: * No Swing components allowed, so say goodbye to JGoodies and all your favorite Swing component sets. The UI components are custom made; to get you an idea they look like early 90's VB controls. But there's a SWT port in the works. * The multiline line field for long strings has some issues. (NOF 3.0.3) * DnD UI for images is kinda buggy. * The validation code for getters n setters only fires if the domain object is modified from the UI. (This is probably wrong due to my n00bness, lets hope a NOF committer corrects me) * If an object is modified from a non-ui thread, lets say a b.g. worker, such object will not update its view on screen. This invalidates a use case such as representing a mail queue in real time on the DnD autogenerated UI. (Again) * Veikko
I've been working on the naked objects approach for over a year now and I haven't even begun to scratch the surface of the possibilities it provides for your system's architecture. To properly utilize it though, it requires that you create a paradigm shift and seek out full OO solutions and revert from resorting to functional duck tapes, because the paradigm seems to work only when you create a design that would allow for high-level development. Having said that, I absolutely love how Django has implemented naked objects within it's Django Models. Most of the things I love about the framework have been, what I come to believe, a direct result of it's models and there are some wows off the top I'd like to share about the architecture: Model fields, that map to table columns, are behaviorally complete objects--they know how they're represented in both the application and database domain, how they're converted between the two and how the information they hold is validated and displayed to the user visually for inputs. All of this utilized with a single line of code in your model. **Wow**! Managers are attached to models and provide CRUD and any generic operations on collections, such as reusable queries (give me the last five blog posts, most occuring tags, etc.), mass delete\update operations, and business logic performed on instances. **Wow**! Now consider you have a model that represents a user. Sometimes, you'd only like to have a partial view of all the information a user model holds (when resetting a user's password you may only need need the user's email and his secret question). They've provided a Forms API that exactly displays and manages inputs for only parts of the model data. Allows for any customization of the what/how in handling user input. **Wow**! The end result is that your models are only used to describe what information you use to describe a particular domain; managers perform all the operations on models; forms are used for creating views and for handling user inputs; controllers (views) are only there for handling HTTP verbs and if they work with models it's solely through managers and forms; views (templates) are there for the presentation (the part that can't be automatically generated). This, imho, is a very clean architecture. Different managers can be used and reused across different models, different forms can be created for models, different views can use different managers. These degrees of separation allow you to quickly design your application. You create a ecosystem of intelligent objects and get a whole application from the way they're interconnected. With the premise that they're loosely coupled (lot's of possibilities for letting them communicate in different ways) and can be easily modified and extended (a few lines for that particular requirement), following the paradigm you really do get an architecture where you a component write once and then reuse it throughout your other projects. It's what MVC should have always been, yet I've often had to write something from scratch even though I did the same thing a few projects ago.
Naked Objects. Good or Bad
[ "", "java", "frameworks", "naked-objects", "" ]
Could someone please tell me which objects types can be tested using Regular Expressions in C#?
If I understand you correctly and you are asking which object types can be tested against regular expressions then the answer is: strings and only strings. Thus your test would be: ``` if(obj is string){...} ```
Regular expressions only apply to strings. What does it even mean to apply a regular expression to (say) a SqlConnection? If you need some other sort of pattern matching (e.g. being able to match the values of particular properties) you should think about and then explain those requirements in detail.
What objects can be tested with Regular Expressions in C#
[ "", "c#", "regex", "" ]
Is one more preferred, or performs better over the other?
[`is_int()`](http://php.net/is_int) returns true if the argument is an integer type, [`ctype_digit()`](http://www.php.net/ctype_digit) takes a string argument and returns true if all the characters in the string are digits. **Example:** ``` ┌──────────┬───────────┬────────────────┐ │ │ is_int: │ ctype_digit: │ ├──────────┼───────────┼────────────────┤ │ 123 │ true │ false │ ├──────────┼───────────┼────────────────┤ │ 12.3 │ false │ false │ ├──────────┼───────────┼────────────────┤ │ "123" │ false │ true │ ├──────────┼───────────┼────────────────┤ │ "12.3" │ false │ false │ ├──────────┼───────────┼────────────────┤ │ "-1" │ false │ false │ ├──────────┼───────────┼────────────────┤ │ -1 │ true │ false │ └──────────┴───────────┴────────────────┘ ```
There is also [`is_numeric`](http://php.net/manual/en/function.is-numeric.php) which returns true if passed in value can be parsed as number. [![enter image description here](https://i.stack.imgur.com/iwREU.png)](https://i.stack.imgur.com/iwREU.png) If I try to compare performance of functions on **PHP 5.5.30** here are the results: [![enter image description here](https://i.stack.imgur.com/apq2O.png)](https://i.stack.imgur.com/apq2O.png) This is the code I used for benchmark ``` // print table cell and highlight if lowest value is used function wr($time1, $time2, $time3, $i) { if($i == 1) $time = $time1; if($i == 2) $time = $time2; if($i == 3) $time = $time3; echo('<td>'); if(min($time1, $time2, $time3) === $time) printf('<b>%.4f</b>', $time); else printf('%.4f', $time); echo('</td>'); } $test_cases = array( 123, 12.3, '123', true); $tests = 1000000; $result = true; // Used just to make sure cycles won't get optimized out echo('<table>'.PHP_EOL); echo('<tr><td>&nbsp;</td><th>is_int</th><th>ctype_digit</th><th>is_numeric</th></tr>'); foreach($test_cases as $case) { echo('<tr><th>'.gettype($case).'</th>'); $time = microtime(true); for($i = 0; $i < $tests; $i++) { $result |= is_int((int)rand()); } $time1 = microtime(true)-$time; $time = microtime(true); for($i = 0; $i < $tests; $i++) { $result |= ctype_digit((int)rand()); } $time2 = microtime(true)-$time; $time = microtime(true); for($i = 0; $i < $tests; $i++) { $result |= is_numeric((int)rand()); } $time3 = microtime(true)-$time; wr($time1, $time2, $time3, 1); wr($time1, $time2, $time3, 2); wr($time1, $time2, $time3, 3); echo('</tr>'.PHP_EOL); } echo('</table>'); exit(); ```
Is there a difference between is_int() and ctype_digit()?
[ "", "php", "function", "numbers", "" ]
I would be interested to learn about large scale development in Python and especially in how do you maintain a large code base? * When you make incompatibility changes to the signature of a method, how do you find all the places where that method is being called. In C++/Java the compiler will find it for you, how do you do it in Python? * When you make changes deep inside the code, how do you find out what operations an instance provides, since you don't have a static type to lookup? * How do you handle/prevent typing errors (typos)? * Are UnitTest's used as a substitute for static type checking? As you can guess I almost only worked with statically typed languages (C++/Java), but I would like to try my hands on Python for larger programs. But I had a very bad experience, a long time ago, with the clipper (dBase) language, which was also dynamically typed.
Since nobody pointed out pychecker, pylint and similar tools, I will: pychecker and pylint are tools that can help you find incorrect assumptions (about function signatures, object attributes, etc.) They won't find everything that a compiler might find in a statically typed language -- but they can find problems that such compilers for such languages can't find, too. Python (and any dynamically typed language) is fundamentally different in terms of the errors you're likely to cause and how you would detect and fix them. It has definite downsides as well as upsides, but many (including me) would argue that in Python's case, the ease of writing code (and the ease of making it structurally sound) and of modifying code *without* breaking API compatibility (adding new optional arguments, providing different objects that have the same set of methods and attributes) make it suitable just fine for large codebases.
## Don't use a screw driver as a hammer Python is not a statically typed language, so don't try to use it that way. When you use a specific tool, you use it for what it has been built. For Python, it means: * **Duck typing** : no type checking. Only behavior matters. Therefore your code must be designed to use this feature. A good design means generic signatures, no dependences between components, high abstraction levels.. So if you change anything, you won't have to change the rest of the code. Python will not complain either, that what it has been built for. Types are not an issue. * **Huge standard library**. You do not need to change all your calls in the program if you use standard features you haven't coded yourself. And Python come with batteries included. I keep discovering them everyday. I had no idea of the number of modules I could use when I started and tried to rewrite existing stuff like everybody. It's OK, you can't get it all right from the beginning. You don't write Java, C++, Python, PHP, Erlang, whatever, the same way. They are good reasons why there is room for each of so many different languages, they do not do the same things. ## Unit tests are not a substitute Unit tests must be performed with any language. The most famous unit test library ([JUnit](http://en.wikipedia.org/wiki/JUnit)) is from the Java world! This has nothing to do with types. You check behaviors, again. You avoid trouble with regression. You ensure your customer you are on tracks. ## Python for large scale projects > Languages, libraries and frameworks > don't scale. Architectures do. If you design a solid architecture, if you are able to make it evolves quickly, then it will scale. Unit tests help, automatic code check as well. But they are just safety nets. And small ones. Python is especially suitable for large projects because it enforces some good practices and has a lot of usual design patterns built-in. But again, do not use it for what it is not designed. E.g : Python is not a technology for CPU intensive tasks. In a huge project, you will most likely use several different technologies anyway. As a [SGBD](https://stackoverflow.com/questions/980813/what-is-sgbd) (French for [DBMS](https://en.wikipedia.org/wiki/Database)) and a templating language, or else. Python is no exception. You will probably want to use C/C++ for the part of your code you need to be fast. Or Java to fit in a [Tomcat](http://en.wikipedia.org/wiki/Apache_Tomcat) environment. Don't know, don't care. Python can play well with these. ## As a conclusion My answer may feel a bit rude, but don't get me wrong: this is a very good question. A lot of people come to Python with old habits. I screwed myself trying to code Java like Python. You can, but will never get the best of it. If you have played / want to play with Python, it's great! It's a wonderful tool. But just a tool, really.
How can I use Python for large scale development?
[ "", "python", "development-environment", "" ]
I'm familiar with the issue behind ORA-01775: looping chain of synonyms, but is there any trick to debugging it, or do I just have to "create or replace" my way out of it? Is there a way to query the schema or whatever to find out what the current definition of a public synonym is? Even more awesome would be a graphical tool, but at this point, anything would be helpful.
As it turns out, the problem wasn't actually a looping chain of synonyms, but the fact that the synonym was pointing to a view that did not exist. Oracle apparently errors out as a looping chain in this condition.
If you are using TOAD, go to View>Toad Options>Oracle>General and remove TOAD\_PLAN\_TABLE from EXPLAIN PLAN section and put PLAN\_TABLE
How to debug ORA-01775: looping chain of synonyms?
[ "", "sql", "oracle", "synonym", "" ]
I want to change the registry values on the pocketPC. I ran the following code: ``` if(enabled) { dwData = 120; } if(RegSetValueEx(HKEY_LOCAL_MACHINE, _T("System\\CurrentControlSet\\Control\\Power\\Timeouts\\BattSuspendTimeout"), 0, REG_DWORD, (LPBYTE)&dwData, sizeof(DWORD))) { return FALSE; } ``` but it doesn't shange the registry entry. Does anyone know how to set registry key values with c++? Thanks!
There are a two problems with what you are doing: 1: RegSetValueEx does not take a path, only a valuename. So you need to open the key path first. e.g. ``` HKEY key; if(ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Control\\Power\\Timeouts", 0, 0, &key)) { if(RegSetValueEx(key, _T("BattSuspendTimeout"), 0, REG_DWORD, (LPBYTE)&dwData, sizeof(DWORD))) { RegCloseKey(key); return FALSE; } RegCloseKey(key); } ``` 2: That area of the registry requires Privileged code signing to work on all Windows Mobile devices. You can get away with it on most current touch-screen windows mobile devices if the user says "yes" to the unknown publisher question when the application is first run or installed. If you get a "Access Denied" error on the set, then you really need to be Privileged code signed for the set to work.
RegSetValueEx returns a descriptive error code. You can get a human-readable message out of this error code using FormatMessage and possibly via the Error Lookup tool, or the @ERR facility in VS. The code you have looks correct so see what the error message tells you.
Edit Registry Values
[ "", "c++", "windows-mobile", "registry", "pocketpc", "" ]
I'm using a decimal column to store money values on a database, and today I was wondering what precision and scale to use. Since supposedly char columns of a fixed width are more efficient, I was thinking the same could be true for decimal columns. Is it? And what precision and scale should I use? I was thinking precision 24/8. Is that overkill, not enough or ok? --- This is what I've decided to do: * Store the conversion rates (when applicable) in the transaction table itself, as a float * Store the currency in the account table * The transaction amount will be a `DECIMAL(19,4)` * All calculations using a conversion rate will be handled by my application so I keep control of rounding issues I don't think a float for the conversion rate is an issue, since it's mostly for reference, and I'll be casting it to a decimal anyway. Thank you all for your valuable input.
If you are looking for a one-size-fits-all, I'd suggest `DECIMAL(19, 4)` is a popular choice (a quick Google bears this out). I think this originates from the old VBA/Access/Jet Currency data type, being the first fixed point decimal type in the language; `Decimal` only came in 'version 1.0' style (i.e. not fully implemented) in VB6/VBA6/Jet 4.0. The rule of thumb for *storage* of fixed point decimal values is to store at least one more decimal place than you actually require to allow for rounding. One of the reasons for mapping the old `Currency` type in the front end to `DECIMAL(19, 4)` type in the back end was that `Currency` exhibited bankers' rounding by nature, whereas `DECIMAL(p, s)` rounded by truncation. An extra decimal place in storage for `DECIMAL` allows a custom rounding algorithm to be implemented rather than taking the vendor's default (and bankers' rounding is alarming, to say the least, for a designer expecting all values ending in .5 to round away from zero). Yes, `DECIMAL(24, 8)` sounds like overkill to me. Most currencies are quoted to four or five decimal places. I know of situations where a decimal scale of 8 (or more) *is* required but this is where a 'normal' monetary amount (say four decimal places) has been pro rata'd, implying the decimal precision should be reduced accordingly (also consider a floating point type in such circumstances). And no one has that much money nowadays to require a decimal precision of 24 :) However, rather than a one-size-fits-all approach, some research may be in order. Ask your designer or domain expert about accounting rules which may be applicable: GAAP, EU, etc. I vaguely recall some EU intra-state transfers with explicit rules for rounding to five decimal places, therefore using `DECIMAL(p, 6)` for storage. Accountants generally seem to favour four decimal places. --- PS Avoid SQL Server's `MONEY` data type because it has serious issues with accuracy when rounding, among other considerations such as portability etc. See [Aaron Bertrand's blog](https://sqlblog.org/2008/04/27/performance-storage-comparisons-money-vs-decimal). --- Microsoft and language designers chose banker's rounding because hardware designers chose it [citation?]. It is enshrined in the Institute of Electrical and Electronics Engineers (IEEE) standards, for example. And hardware designers chose it because mathematicians prefer it. See [Wikipedia](http://en.wikipedia.org/wiki/Rounding#History); to paraphrase: The 1906 edition of Probability and Theory of Errors called this 'the computer's rule' ("computers" meaning humans who perform computations).
We recently implemented a system that needs to handle values in multiple currencies and convert between them, and figured out a few things the hard way. **NEVER USE FLOATING POINT NUMBERS FOR MONEY** Floating point arithmetic introduces inaccuracies that may not be noticed until they've screwed something up. All values should be stored as either integers or fixed-decimal types, and if you choose to use a fixed-decimal type then make sure you understand exactly what that type does under the hood (ie, does it internally use an integer or floating point type). When you do need to do calculations or conversions: 1. Convert values to floating point 2. Calculate new value 3. Round the number and convert it back to an integer When converting a floating point number back to an integer in step 3, don't just cast it - use a math function to round it first. This will usually be `round`, though in special cases it could be `floor` or `ceil`. Know the difference and choose carefully. **Store the type of a number alongside the value** This may not be as important for you if you're only handling one currency, but it was important for us in handling multiple currencies. We used the 3-character code for a currency, such as USD, GBP, JPY, EUR, etc. Depending on the situation, it may also be helpful to store: * Whether the number is before or after tax (and what the tax rate was) * Whether the number is the result of a conversion (and what it was converted from) **Know the accuracy bounds of the numbers you're dealing with** For real values, you want to be as precise as the smallest unit of the currency. This means you have no values smaller than a cent, a penny, a yen, a fen, etc. Don't store values with higher accuracy than that for no reason. Internally, you may choose to deal with smaller values, in which case that's a *different type of currency value*. Make sure your code knows which is which and doesn't get them mixed up. Avoid using floating point values even here. --- Adding all those rules together, we decided on the following rules. In running code, currencies are stored using an integer for the smallest unit. ``` class Currency { String code; // eg "USD" int value; // eg 2500 boolean converted; } class Price { Currency grossValue; Currency netValue; Tax taxRate; } ``` In the database, the values are stored as a string in the following format: ``` USD:2500 ``` That stores the value of $25.00. We were able to do that only because the code that deals with currencies doesn't need to be within the database layer itself, so all values can be converted into memory first. Other situations will no doubt lend themselves to other solutions. --- And in case I didn't make it clear earlier, **don't use float!**
Storing money in a decimal column - what precision and scale?
[ "", "sql", "database", "database-design", "currency", "" ]
I have a large existing c++ codebase. Typically the users of the codebase edit the source with gvim, but we'd like to start using the nifty IDE features in Eclipse. The codebase has an extensive directory hierarchy, but the source files use include directives without paths due to some voodoo we use in our build process. When I link the source to my project in Eclipse, the indexer complains that it can't find any header files (because we don't specify paths in our includes.) If I manually add the directories from the workspace to the include path then everything works wonderfully, but obviously adding hundreds of directories manually isn't feasible. Would there be a simple method to tell Eclipse to look anywhere in the project for the include files without having to add them one by one? If not, then can anyone suggest a good starting place, like what classes to extend, for writing a plugin to just scan the project at creation/modification and programatically add all directories to the include path?
This feature has already been implemented in the current CDT development stream and will be available in CDT 6.0, which will be released along with Eclipse 3.5 in June 2009. Basically if you have an #include and the header file exists somewhere in your project then CDT will be able to find it without the need to manually set up include paths. If you need the feature now you can download and install the latest CDT development build. Eclipse Bugzilla: <https://bugs.eclipse.org/bugs/show_bug.cgi?id=213562> Latest CDT 6.0 Builds: <http://download.eclipse.org/tools/cdt/builds/6.0.0/index.html>
The way that CDT manages build paths is by looking at the .cdtbuild xml file in the base of your projects directory (it might be a different name on windows... not sure) In this you should see something like ``` <option id="gnu.c.compiler.option.include.paths....> <listoptionValue builtIn="false" value="&quot;${workspace_loc:/some/path}$quot;" /> <listOptionValue ... /> ... </option> ``` this is where all the build paths that you configure in the gui are placed. It should be pretty easy to add all the directories to this using a simple perl script to walk the project and generate all the listOptionValue entries. This is obviously not the ideal method. But im curious, what build system are you migrating from, if it is make based you should be able to get eclipse to use your make files.
Search entire project for includes in Eclipse CDT
[ "", "c++", "eclipse", "eclipse-cdt", "" ]
I've always wondered why the C++ Standard library has instantiated basic\_[io]stream and all its variants using the `char` type instead of the `unsigned char` type. `char` means (depending on whether it is signed or not) you can have overflow and underflow for operations like get(), which will lead to implementation-defined value of the variables involved. Another example is when you want to output a byte, unformatted, to an ostream using its `put` function. Any ideas? --- **Note**: I'm still not really convinced. So if you know the definitive answer, you can still post it indeed.
Possibly I've misunderstood the question, but conversion from unsigned char to char isn't unspecified, it's implementation-dependent (4.7-3 in the C++ standard). The type of a 1-byte character in C++ is "char", not "unsigned char". This gives implementations a bit more freedom to do the best thing on the platform (for example, the standards body may have believed that there exist CPUs where signed byte arithmetic is faster than unsigned byte arithmetic, although that's speculation on my part). Also for compatibility with C. The result of removing this kind of existential uncertainty from C++ is C# ;-) Given that the "char" type exists, I think it makes sense for the usual streams to use it even though its signedness isn't defined. So maybe your question is answered by the answer to, "why didn't C++ just define char to be unsigned?"
I have always understood it this way: the purpose of the `iostream` class is to read and/or write a stream of characters, which, if you think about it, are abstract entities that are only represented by the computer using a character encoding. The C++ standard makes great pains to avoid pinning down the character encoding, saying only that "Objects declared as characters (`char`) shall be large enough to store any member of the implementation's basic character set," because it doesn't need to force the "implementation basic character set" to define the C++ language; the standard can leave the decision of *which* character encoding is used to the implementation (compiler together with an STL implementation), and just note that `char` objects represent single characters in some encoding. An implementation writer could choose a single-octet encoding such as [ISO-8859-1](http://en.wikipedia.org/wiki/ISO/IEC_8859-1) or even a double-octet encoding such as [UCS-2](http://en.wikipedia.org/wiki/UCS-2). It doesn't matter. As long as a `char` object is "large enough to store any member of the implementation's basic character set" (note that this explicitly forbids [variable-length encodings](http://en.wikipedia.org/wiki/Variable-width_encoding)), then the implementation may even choose an encoding that represents basic Latin in a way that is incompatible with any common encoding! It is confusing that the `char`, `signed char`, and `unsigned char` types share "char" in their names, but it is important to keep in mind that `char` does not belong to the same family of fundamental types as `signed char` and `unsigned char`. `signed char` is in the family of signed integer types: > There are four *signed integer types*: "signed char", "short int", "int", and "long int." and `unsigned char` is in the family of unsigned integer types: > For each of the signed integer types, there exists a corresponding (but different) *unsigned integer type*: "unsigned char", "unsigned short int", "unsigned int", and "unsigned long int," ... The one similarity between the `char`, `signed char`, and `unsigned char` types is that "[they] occupy the same amount of storage and have the same alignment requirements". Thus, you can `reinterpret_cast` from `char *` to `unsigned char *` in order to determine the numeric value of a character in the execution character set. To answer your question, the reason why the STL uses `char` as the default type is because the standard streams are meant for reading and/or writing streams of characters, represented by `char` objects, not integers (`signed char` and `unsigned char`). The use of `char` versus the numeric value is a way of separating concerns.
Why do C++ streams use char instead of unsigned char?
[ "", "c++", "types", "stream", "overflow", "iostream", "" ]
I am currently defining regular expressions in order to capture parameters in a URL, as described in the tutorial. How do I access parameters from the URL as part the `HttpRequest` object? My `HttpRequest.GET` currently returns an empty `QueryDict` object. I'd like to learn how to do this without a library, so I can get to know Django better.
When a URL is like `domain/search/?q=haha`, you would use `request.GET.get('q', '')`. `q` is the parameter you want, and `''` is the default value if `q` isn't found. However, if you are instead just configuring your `URLconf`\*\*, then your captures from the `regex` are passed to the function as arguments (or named arguments). Such as: ``` (r'^user/(?P<username>\w{0,50})/$', views.profile_page,), ``` Then in your `views.py` you would have ``` def profile_page(request, username): # Rest of the method ```
To clarify [camflan](https://stackoverflow.com/users/22445/camflan)'s [explanation](https://stackoverflow.com/a/150518/11573842), let's suppose you have * the rule `url(regex=r'^user/(?P<username>\w{1,50})/$', view='views.profile_page')` * an incoming request for `http://domain/user/thaiyoshi/?message=Hi` The URL dispatcher rule will catch parts of the URL *path* (here `"user/thaiyoshi/"`) and pass them to the view function along with the request object. The query string (here `message=Hi`) is parsed and parameters are stored as a `QueryDict` in `request.GET`. No further matching or processing for HTTP GET parameters is done. This view function would use both parts extracted from the URL path and a query parameter: ``` def profile_page(request, username=None): user = User.objects.get(username=username) message = request.GET.get('message') ``` As a side note, you'll find the request method (in this case `"GET"`, and for submitted forms usually `"POST"`) in `request.method`. In some cases, it's useful to check that it matches what you're expecting. **Update:** When deciding whether to use the URL path or the query parameters for passing information, the following may help: * use the URL path for uniquely identifying resources, e.g. `/blog/post/15/` (not `/blog/posts/?id=15`) * use query parameters for changing the way the resource is displayed, e.g. `/blog/post/15/?show_comments=1` or `/blog/posts/2008/?sort_by=date&direction=desc` * to make human-friendly URLs, avoid using ID numbers and use e.g. dates, categories, and/or slugs: `/blog/post/2008/09/30/django-urls/`
How to get GET request values in Django?
[ "", "python", "django", "url", "get", "url-parameters", "" ]
At the risk of being downmodded, I want to ask what the best mechanism (best is obviously subjective for the practice violation inherent here) for viewing data from a table, using C#, with a *lot* of columns. By a lot, I mean something like 1000. Now before you get all click happy, or throw out responses like "why the hell would you ever have a table with that many columns" let me say that it's actually part of a design requirement. We are collecting data as fast as we can from 1000 data points. We need to store these as fast as possible, hence the flat table. The data needs to be directly accessible from SQL Server, hence the database (we're using SQL Compact with table-direct). So let's forget, for now, all that we've learned about proper database design, the rules of normalization, etc. and just focus on the fact that I have a table with 1000 columns and I want to be able to display the data on screen to verify that the data is actually going in there. I've tried a data grid. It pukes because (not surprisingly) it's not designed to handle that many columns. I've tried using the viewer in Studio. It pukes after 256, plus the end user won't have Studio installed anyway. For now the result need not be pretty, it need not be updateable, nor does it need to be sensitive to data changes - just a static snapshot of data in the table at a given point in time. Relevant (or semi-relevant) info: * Table has 1000 columns (read above before getting click happy) * Using SQL Compact version 3.5 * Running on the desktop * Looking for a managed-code answer
Ok, what turned out to be the right answer for me was to use the [ReportViewer control](http://msdn.microsoft.com/en-us/library/ms251671(VS.80).aspx), but not in any manner documented in MSDN. The problem is that I have dynamic data, so I need a dynamic report, and all of the tutorials, etc. seem to assume you have the luxury of knowing everything at design time so you can point and click your way through a Wizard. The solution ended up requiring a couple pieces. First, I had to create code to dynamically generate the RDLC that the ReportViewer uses to describe the report layout and what data fields map to what. This is what I came up with: ``` public static Stream BuildRDLCStream( DataSet data, string name, string reportXslPath) { using (MemoryStream schemaStream = new MemoryStream()) { // save the schema to a stream data.WriteXmlSchema(schemaStream); schemaStream.Seek(0, SeekOrigin.Begin); // load it into a Document and set the Name variable XmlDocument xmlDomSchema = new XmlDocument(); xmlDomSchema.Load(schemaStream); xmlDomSchema.DocumentElement.SetAttribute("Name", data.DataSetName); // load the report's XSL file (that's the magic) XslCompiledTransform xform = new XslCompiledTransform(); xform.Load(reportXslPath); // do the transform MemoryStream rdlcStream = new MemoryStream(); XmlWriter writer = XmlWriter.Create(rdlcStream); xform.Transform(xmlDomSchema, writer); writer.Close(); rdlcStream.Seek(0, SeekOrigin.Begin); // send back the RDLC return rdlcStream; } } ``` The second piece is an XSL file that I took right off of [Dan Shipe's blog](http://csharpshooter.blogspot.com/2007/08/revised-dynamic-rdlc-generation.html). The RDLC code there was pretty worthless as it was all intended for Web use, but the XSL is pure gold. I've put it at the bottom of this post for completeness in case that blog ever goes offline. Once I has those two pieces, it was simply a matter of creating a Form with a ReportViewer control on it, then using this bit of code to set it up: ``` ds.DataSetName = name; Stream rdlc = RdlcEngine.BuildRDLCStream( ds, name, "c:\\temp\\rdlc\\report.xsl"); reportView.LocalReport.LoadReportDefinition(rdlc); reportView.LocalReport.DataSources.Clear(); reportView.LocalReport.DataSources.Add( new ReportDataSource(ds.DataSetName, ds.Tables[0])); reportView.RefreshReport(); ``` The key here is that 'ds' is a DataSet object with a single DataTable in it with the data to be displayed. Again, for completeness, here's the XSL - sorry about the size: ``` <?xml version="1.0"?> <!-- Stylesheet for creating ReportViewer RDLC documents --> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner" xmlns="http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition" > <xsl:variable name="mvarName" select="/xs:schema/@Name"/> <xsl:variable name="mvarFontSize">8pt</xsl:variable> <xsl:variable name="mvarFontWeight">500</xsl:variable> <xsl:variable name="mvarFontWeightBold">700</xsl:variable> <xsl:template match="/"> <xsl:apply-templates select="/xs:schema/xs:element/xs:complexType/xs:choice/xs:element/xs:complexType/xs:sequence"> </xsl:apply-templates> </xsl:template> <xsl:template match="xs:sequence"> <Report xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner" xmlns="http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition"> <BottomMargin>1in</BottomMargin> <RightMargin>1in</RightMargin> <LeftMargin>1in</LeftMargin> <TopMargin>1in</TopMargin> <InteractiveHeight>11in</InteractiveHeight> <InteractiveWidth>8.5in</InteractiveWidth> <Width>6.5in</Width> <Language>en-US</Language> <rd:DrawGrid>true</rd:DrawGrid> <rd:SnapToGrid>true</rd:SnapToGrid> <rd:ReportID>7358b654-3ca3-44a0-8677-efe0a55c7c45</rd:ReportID> <xsl:call-template name="BuildDataSource"> </xsl:call-template> <xsl:call-template name="BuildDataSet"> </xsl:call-template> <Body> <Height>0.50in</Height> <ReportItems> <Table Name="table1"> <DataSetName><xsl:value-of select="$mvarName" /></DataSetName> <Top>0.5in</Top> <Height>0.50in</Height> <Header> <TableRows> <TableRow> <Height>0.25in</Height> <TableCells> <xsl:apply-templates select="xs:element" mode="HeaderTableCell"> </xsl:apply-templates> </TableCells> </TableRow> </TableRows> </Header> <Details> <TableRows> <TableRow> <Height>0.25in</Height> <TableCells> <xsl:apply-templates select="xs:element" mode="DetailTableCell"> </xsl:apply-templates> </TableCells> </TableRow> </TableRows> </Details> <TableColumns> <xsl:apply-templates select="xs:element" mode="TableColumn"> </xsl:apply-templates> </TableColumns> </Table> </ReportItems> </Body> </Report> </xsl:template> <xsl:template name="BuildDataSource"> <DataSources> <DataSource Name="DummyDataSource"> <ConnectionProperties> <ConnectString/> <DataProvider>SQL</DataProvider> </ConnectionProperties> <rd:DataSourceID>84635ff8-d177-4a25-9aa5-5a921652c79c</rd:DataSourceID> </DataSource> </DataSources> </xsl:template> <xsl:template name="BuildDataSet"> <DataSets> <DataSet Name="{$mvarName}"> <Query> <rd:UseGenericDesigner>true</rd:UseGenericDesigner> <CommandText/> <DataSourceName>DummyDataSource</DataSourceName> </Query> <Fields> <xsl:apply-templates select="xs:element" mode="Field"> </xsl:apply-templates> </Fields> </DataSet> </DataSets> </xsl:template> <xsl:template match="xs:element" mode="Field"> <xsl:variable name="varFieldName"> <xsl:value-of select="@name" /> </xsl:variable> <xsl:variable name="varDataType"> <xsl:choose> <xsl:when test="@type='xs:int'">System.Int32</xsl:when> <xsl:when test="@type='xs:string'">System.String</xsl:when> <xsl:when test="@type='xs:dateTime'">System.DateTime</xsl:when> <xsl:when test="@type='xs:boolean'">System.Boolean</xsl:when> </xsl:choose> </xsl:variable> <Field Name="{$varFieldName}"> <rd:TypeName><xsl:value-of select="$varDataType"/></rd:TypeName> <DataField><xsl:value-of select="$varFieldName"/></DataField> </Field> </xsl:template> <xsl:template match="xs:element" mode="HeaderTableCell"> <xsl:variable name="varFieldName"> <xsl:value-of select="@name" /> </xsl:variable> <TableCell> <ReportItems> <Textbox Name="textbox{position()}"> <rd:DefaultName>textbox<xsl:value-of select="position()"/> </rd:DefaultName> <Value><xsl:value-of select="$varFieldName"/></Value> <CanGrow>true</CanGrow> <ZIndex>7</ZIndex> <Style> <TextAlign>Center</TextAlign> <PaddingLeft>2pt</PaddingLeft> <PaddingBottom>2pt</PaddingBottom> <PaddingRight>2pt</PaddingRight> <PaddingTop>2pt</PaddingTop> <FontSize><xsl:value-of select="$mvarFontSize"/></FontSize> <FontWeight><xsl:value-of select="$mvarFontWeightBold"/></FontWeight> <BackgroundColor>#000000</BackgroundColor> <Color>#ffffff</Color> <BorderColor> <Default>#ffffff</Default> </BorderColor> <BorderStyle> <Default>Solid</Default> </BorderStyle> </Style> </Textbox> </ReportItems> </TableCell> </xsl:template> <xsl:template match="xs:element" mode="DetailTableCell"> <xsl:variable name="varFieldName"> <xsl:value-of select="@name" /> </xsl:variable> <TableCell> <ReportItems> <Textbox Name="{$varFieldName}"> <rd:DefaultName><xsl:value-of select="$varFieldName"/></rd:DefaultName> <Value>=Fields!<xsl:value-of select="$varFieldName"/>.Value</Value> <CanGrow>true</CanGrow> <ZIndex>7</ZIndex> <Style> <TextAlign>Left</TextAlign> <PaddingLeft>2pt</PaddingLeft> <PaddingBottom>2pt</PaddingBottom> <PaddingRight>2pt</PaddingRight> <PaddingTop>2pt</PaddingTop> <FontSize><xsl:value-of select="$mvarFontSize"/></FontSize> <FontWeight><xsl:value-of select="$mvarFontWeight"/></FontWeight> <BackgroundColor>#e0e0e0</BackgroundColor> <Color>#000000</Color> <BorderColor> <Default>#ffffff</Default> </BorderColor> <BorderStyle> <Default>Solid</Default> </BorderStyle> </Style> </Textbox> </ReportItems> </TableCell> </xsl:template> <xsl:template match="xs:element" mode="TableColumn"> <TableColumn> <Width>0.75in</Width> </TableColumn> </xsl:template> <xsl:template name="replace-string"> <xsl:param name="text"/> <xsl:param name="from"/> <xsl:param name="to"/> <xsl:choose> <xsl:when test="contains($text, $from)"> <xsl:variable name="before" select="substring-before($text, $from)"/> <xsl:variable name="after" select="substring-after($text, $from)"/> <xsl:variable name="prefix" select="concat($before, $to)"/> <xsl:value-of select="$before"/> <xsl:value-of select="$to"/> <xsl:call-template name="replace-string"> <xsl:with-param name="text" select="$after"/> <xsl:with-param name="from" select="$from"/> <xsl:with-param name="to" select="$to"/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select="$text"/> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet> ```
If you're going to implement your own custom user control, you could do a Fisheye Grid like this: > [Dead image link](http://img145.imageshack.us/img145/6793/nothingbettertodocd5.jpg) This example shows a full-size 3x4 panel moving around within a 9x10 table. Since (I assume) you don't need to edit this data, the UI could just be something where the user grabs the panel and drags it around. If you're really masochistic and/or have lots of free time, you can even have multiple fisheye panels on the same grid, allowing you to compare one or more regions of the grid simultaneously. Update: Silverlight [has one of these](http://objectpeddler.com/feg/FlickrFEGTestTestPage.aspx), apparently. Sort of.
Best way to view a table with *lots* of columns?
[ "", "c#", "database", "reporting", "" ]
What I am looking for is the equivalent of `System.Windows.SystemParameters.WorkArea` for the monitor that the window is currently on. **Clarification:** The window in question is `WPF`, not `WinForm`.
`Screen.FromControl`, `Screen.FromPoint` and `Screen.FromRectangle` should help you with this. For example in WinForms it would be: ``` class MyForm : Form { public Rectangle GetScreen() { return Screen.FromControl(this).Bounds; } } ``` I don't know of an equivalent call for WPF. Therefore, you need to do something like this extension method. ``` static class ExtensionsForWPF { public static System.Windows.Forms.Screen GetScreen(this Window window) { return System.Windows.Forms.Screen.FromHandle(new WindowInteropHelper(window).Handle); } } ```
You can use this to get desktop workspace bounds of the primary screen: [`System.Windows.SystemParameters.WorkArea`](http://msdn.microsoft.com/en-us/library/system.windows.systemparameters.workarea.aspx) This is also useful for getting just the size of the primary screen: [`System.Windows.SystemParameters.PrimaryScreenWidth`](http://msdn.microsoft.com/en-us/library/system.windows.systemparameters.primaryscreenwidth.aspx) [`System.Windows.SystemParameters.PrimaryScreenHeight`](http://msdn.microsoft.com/en-us/library/system.windows.systemparameters.primaryscreenheight.aspx)
How can I get the active screen dimensions?
[ "", "c#", "wpf", "" ]
Unsure if I've phrased this correctly, but in the callback how do I reference the controls property of the base class? This has been bugging me for some time and I usually work around it, but I'd be grateful if anybody can enlighten me on how I should do this properly. ``` var base = function() { var controls = {}; return { init: function(c) { this.controls = c }, foo: function(args) { this.init(args.controls); $(this.controls.DropDown).change(function() { $(this.controls.PlaceHolder).toggle(); }); } } }; ``` Much Obliged, Paul
Use the power of closures: ``` var base = function() { var controls = {}; return { init: function(c) { this.controls = c }, foo: function(args) { var self = this; this.init(args.controls); $(this.controls.DropDown).change(function() { $(self.controls.PlaceHolder).toggle(); }); } } }; ```
Although [closures](https://stackoverflow.com/questions/254200/access-parent-property-in-jquery-callback#254233) are [preferred](https://stackoverflow.com/questions/254200/access-parent-property-in-jquery-callback#254237), you could also use jquery `bind` to pass an object along: ``` var base = function() { var controls = {}; return { init: function(c) { this.controls = c }, foo: function(args) { this.init(args.controls); $(this.controls.DropDown).bind('change', {controls: this.controls}, function(event) { $(event.data.controls.PlaceHolder).toggle(); }); } } }; ```
Access parent property in jQuery callback
[ "", "javascript", "jquery", "" ]
Uhm I'm not sure if anyone has encountered this problem a brief description is on IE6 any `<select>` objects get displayed over any other item, even div's... meaning if you have a fancy javascript effect that displays a div that's supposed to be on top of everything (e.g: lightbox, multibox etc..) onclick of a certain element and that div overlaps a `<select>` your div get's to be displayed as if it's under the `<select>` [on this case a max and minimum z-index doesn't work ] I've tried googling and found the iframe shim solution but I wanted some pretty clean alternatives or better yet has anyone found a better solution? since the method using iframes uses around 130mb of ram might slow down poor people's machines
You don't have to hide every `select` using a loop. All you need is a CSS rule like: ``` * html .hideSelects select { visibility: hidden; } ``` And the following JavaScript: ``` //hide: document.body.className +=' hideSelects' //show: document.body.className = document.body.className.replace(' hideSelects', ''); ``` (Or, you can use your favourite `addClass` / `removeClass` implementation).
There is a plugin for jquery called [bgiframe](http://plugins.jquery.com/project/bgiframe) that makes the iframe method quite easy to implement. Personally, as a web developer, I'm to the point where I no longer care about the user experience in IE6. I'll make it render as close to "correct" as possible, and make sure it's functional, but as far as speed goes, too bad. They can upgrade. IE7 (though still quite slow, compared to every other browser) has been out for 2 years (almost to the day!). IE8 is going to be out shortly. Firefox is available for every platform. Safari is also an option (and super fast). Opera is available for most/every platform. IE6 was released in over 7 years ago. IMHO, there is no reason to still be using it, other than lazy users and incompetent IT departments (or if you're a web developer).
iframe shimming or ie6 (and below) select z-index bug
[ "", "javascript", "internet-explorer-6", "shim", "" ]
FORTRAN provides several functions to convert a double precision number to an integral value. The method used for truncation/rounding differs. I am converting complex scientific algorithms which use these. According to FORTRAN documentation: **aint(x)** returns the integral value between x and 0, nearest x. **anint(x)** returns the nearest integral value to x, except halfway cases are rounded to the integral value larger in magnitude. **nint(x)** converts x into int format rounding to the nearest int value, except halfway cases are rounded to the int value larger in magnitude. **Does anyone have an implementation of these in C#?** It might be tricky getting it right. (int)x appears to match aint() Convert.ToInt32(x) does not match any of the above. Trunc(x) does not match any of the above. Round(x) might match anint or nint. The difference between anint and nint seems to be the return type, where anint returns a double precision value but nint returns an integer. Both are used (acutal sample): DOUBLE PRECISION A, B, C, D, E, F, G ... values set here ... F = ANINT(A-B) + ANINT(C-D) + ANINT(B+D-E) G = NINT(F) + 1D0; Perhaps a FORTRAN expert could help clarify why the author chose to use both (I am assuming it was intentional).
From your definitions of the calls, **`nint`** and **`anint`** are provided by `Math.Round` using `MidpointRounding.AwayFromZero`. For **`aint`**, an explicit cast from `double` to `int` will achieve that result.
From what I can see, `aint()` is just `Math.Floor()`. For the other two, I think you are right that the only difference is the return type: `nint()` returns an actual integer, while `anint()` returns a double (fortran: real) that happens to have an integral value.
Matching FORTRAN rounding in C#
[ "", "c#", "fortran", "rounding", "truncation", "" ]
I'm passing small (2-10 KB)XML documents as input to a WCF service. now I've two option to read data values from incoming XML 1. Deserialize to a strongly typed object and use object properties to access values 2. use XPath to access values which approach is faster? some statistics to support your answer would be great.
I would deserialize it. If you use xpath, you will deserialize (or "load") it to XmlDocument or something anyway. So both solutions use time deserializing. After this is done, xpath will be slower because of the time spent parsing that string, resolving names, executing functions and so on. Also, if you go with xpath, you get no type safety. Your compiler can't check the xpath syntax for you. If you use XmlSerializer and classes, you get static typing. Really fast access to you data, and if you want to query them with xpath, there are still ways to do that. Also, I would like to say that your code would probably be easier to understand with classes. The only drawback is that the xml has to conform to the same schema all the time, but that might not be a real problem in your case. I hope that you forgive the absence of statistics, I think the arguments are strong enough without examples. If you want an ultimate answer, try both and keep a stopwatch ready.
There's a third option of sticking with XML, but query with whatever XML API you're using - e.g. LINQ to XML makes queries relatively straightforward in code. Have you already parsed the text into an XML document? Are you convinced that this is actually a significant performance bottleneck in your code? (e.g. if you're then talking to a database, then don't worry about this to start with - just get it to work in the simplest way first) Are the queries always the same, or are they dynamic in some way? Do you have a test rig with realistic messages and queries? If not, you need one in order to evaluate any answers given here with *your* data. If you do, I would expect it to be reasonably easy to try it yourself :)
XPath vs DeSerialization: which one is better in performance for read operations
[ "", "c#", "wcf", "performance", "serialization", "xpath", "" ]
I have an app that is failing on the install. The vendor says I probably have ini\_set() disabled. How can I check this?
I did some research on this, and it turns out that sometimes ini\_set will not return FALSE, but an empty string. This is mentioned in the URL pointed out by gabriel1836. The best way to check if it works is to first check the disable\_functions flag in php.ini to see if it is disabled, and then (if it is not disabled), change a value with it, and echo phpinfo() immediately after. If the value is changed under the local column, then you know ini\_set works.
You might want to take a look at the CHANGEABLE directives in php.ini: <https://www.php.net/manual/en/ini.php#ini.list> In regard to verify whether an ini\_set function worked, you can check the return value to make certain that it worked: <https://www.php.net/manual/en/function.ini-set.php> The code would look something like this: ``` <?php if(ini_set('error_reporting', 'ALL') === false) { // Perform failure handling logic } ?> ```
How do I check if ini_set() is enabled either in the global PHP.INI or in my PHP script?
[ "", "php", "ini-set", "" ]
How can I transform a `String` value into an `InputStreamReader`?
[ByteArrayInputStream](http://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayInputStream.html) also does the trick: ``` InputStream is = new ByteArrayInputStream( myString.getBytes( charset ) ); ``` Then convert to reader: ``` InputStreamReader reader = new InputStreamReader(is); ```
I also found the apache commons `IOUtils` class , so : ``` InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(myString)); ```
How do I turn a String into a InputStreamReader in java?
[ "", "java", "string", "stream", "" ]
This was an job placement interview I faced. They asked whether we can realloc Array, I told yes. Then They asked - then why we need pointers as most of the people give reason that it wastes memory space. I could not able to give satisfactory answer. If any body can give any satisfactory answer, I'll be obliged. Please mention any situation where the above statement can contradict. Thank you.
You can only reallocate an array that was allocated dynamically. If it was allocated statically, it cannot be reallocated [safely].\* Pointers hold addresses of data in memory. They can be allocated, deallocated, and reallocated dynamically using the new/delete operators in C++ and malloc/free in C. I would strongly suggest that you read [*The C Programming Language*](https://rads.stackoverflow.com/amzn/click/com/0131103628) by Kernighan and Ritchie and a solid C++ text like [*C++ From the Ground Up*](https://rads.stackoverflow.com/amzn/click/com/0072228970) by Herbert Schildt. Using dynamic memory, pointers, offsets, etc are all fundamental to using these two languages. Not knowing how they work, and why they exist will be a likely reason for potential employers to turn you down. \*the compiler **shouldn't** let you reallocate anything that's been allocated statically, but if it does, the behavior is undefined
The phrasing is a bit strange, but to me it seems like the interview question was an open ended question designed to get you to explain what you know about arrays, pointers, dynamic memory allocation, etc. If I was the interviewer I'd want the candidate to articulate the differences between `int *a = malloc(10 * sizeof(int));` and `int a[10];`. The followup question is not worded very well, but it was probably an attempt at nudging the candidate in the direction of the difference between a pointer and an array and setting off the train of thought.
can realloc Array, then Why use pointers?
[ "", "c++", "c", "pointers", "data-structures", "" ]
I have a query that is currently using a correlated subquery to return the results, but I am thinking the problem could be solved more eloquently perhaps using ROW\_NUMBER(). The problem is around the profile of a value v, through a number of years for an Item. Each item has a number of versions, each with its own profile whick starts when the version is introduced and the data currently looks like this: ``` ItemId ItemVersionId Year Value =========================================== 1 1 01 0.1 1 1 02 0.1 1 1 03 0.2 1 1 04 0.2 1 1 05 0.2 1 1 06 0.3 1 1 07 0.3 1 1 08 0.4 1 2 04 0.3 1 2 05 0.3 1 2 06 0.3 1 2 07 0.4 1 2 08 0.5 1 3 07 0.6 1 3 08 0.7 2 1 01 0.1 2 1 01 0.1 2 1 01 0.2 etc ``` I want to return the full profile for an Item using the most recent version where applicable. For the above example for item 1: ``` ItemId ItemVersionId Year Value =========================================== 1 1 01 0.1 1 1 02 0.1 1 1 03 0.2 1 2 04 0.3 1 2 05 0.3 1 2 06 0.3 1 3 07 0.6 1 3 08 0.7 ``` I am currently using ``` SELECT ItemId, ItemVersionId, Year, Value FROM table t WHERE ItemId = 1 AND ItemVersionId = (SELECT MAX(ItemVersionId) FROM table WHERE ItemId = t.ItemId AND Year = t.Year) ``` Whilst this returns the correct I suspect there is a more efficient way to do it, especially when the table gets large. I am using SQL Server 2005. Thanks in advance
I would do it with a CTE: ``` WITH Result AS ( SELECT Row_Number() OVER (PARTITION BY ItemId, Year ORDER BY ItemversionId DESC) AS RowNumber ,ItemId ,ItemversionId ,Year ,Value FROM table ) SELECT ItemId ,ItemversionId ,Year ,Value FROM Result WHERE RowNumber = 1 ORDER BY ItemId, Year ```
I think it's okay how you do it. You could check if there is a **composite index on ItemId and Year**. You could inspect the query plan to see the impact of that query. If there is an "Item" table in your database you could try another approach. **Insert a column ItemVersionId** in that table and make sure you update that value when new versions are saved. Then in your query **join the Item table using ItemId and ItemVersionId** instead of using that subquery.
T SQL - Eloquent replacement of Correlated Subquery
[ "", "sql", "sql-server-2005", "" ]
I am pretty new to php, but I am learning! I have a simple form on a client website. I am testing the form and when I click submit, I get the following error: Form Mail Script ``` Wrong referrer (referring site). For security reasons the form can only be used, if the referring page is part of this website. Note for the Admin: Please add the name of your server to the referrer variable in the index.php configuration file: mywebsite.com ``` Powered by Form Mail Script I am looking through the forms configuration and support files but I do not understand exactly what it is I need to change. Can someone please explain to me what the Admin note above means and how to fix it?
The referrer is a value that's usually sent to a server by a client (your browser) along with a request. It indicates the URL from which the requested resource was linked or submitted. This error is part of a security mechanism in FormMail that is intended to prevent the script from handling input that doesn't originate from your website. For example, say your form is at *<http://www.foo.com/form.html>* and your script is at *<http://www.foo.com/script.php>*. If the script does not check the referrer value, I can create a form on my site at *<http://www.bar.com/myform.html>* and submit it to your script. Scripts that send mail are often abused in this manner to send spam. To fix your problem, find the parameter in your script's configuration file that indicates the referrers that your script should handle input from and change it to include your domain or the specific URL of your page. Note that referrer is generally misspelled as REFERER with only one 'R' within the context of the HTTP protocol.
You are obviously using the Form Mail script on your page. It has a security feature that prevents other domains from submitting to the form. This is done to prevent bots from using the script to send out spam. In the configuration for the form mail script or in the script itself, you will find an array or variable with the referrers listed. This is the sites that you want to allow calling of this form mail. You should add your own domain to this list or assign it to this variable. Sorry, I haven't used this script, so I can't be more specific.
PHP "Wrong referrer" error when submitting a mail form
[ "", "php", "formmail", "" ]
I'm writing a program in C# that runs in the background and allows users to use a hotkey to switch keyboard layouts in the active window. (Windows only supports `CTRL`+`SHIFT` and `ALT`+`SHIFT`) I'm using RegisterHotKey to catch the hotkey, and it's working fine. The problem is that I can't find any API to change the keyboard layout for the focused window. ActivateKeyboardLayout and LoadKeyboardLayout can only change the keyboard layout for the calling thread. Does anyone know how to change the keyboard layout for a different thread (the way the Language Bar does)?
Another way that may be acceptable if you are writing something just for yourself: define a separate key combination for every layout (such as Alt+Shift+1, etc), and use [SendInput](http://msdn.microsoft.com/en-us/library/ms646310.aspx "SendInput") to switch between them. The circumstances in which this is usable are limited of course.
``` PostMessage(handle, WM_INPUTLANGCHANGEREQUEST, 0, LoadKeyboardLayout( StrCopy(Layout,'00000419'), KLF_ACTIVATE) ); ```
Change Keyboard Layout for Other Process
[ "", "c#", ".net", "winapi", "keyboard-layout", "registerhotkey", "" ]
I'm playing around with BCEL. I'm not using it to generate bytecode, but instead I'm trying to inspect the structure of existing compiled classes. I need to be able to point to an arbitrary .class file anywhere on my hard drive and load a [JavaClass](http://jakarta.apache.org/bcel/apidocs/org/apache/bcel/classfile/JavaClass.html) object based on that. Ideally I'd like to avoid having to add the given class to my classpath.
The straightforward way is to create a ClassParser with the file name and call parse(). Alternatively you can use SyntheticRepository and supply a classpath (that is not your classpath, IYSWIM).
The existing .class can be class loaded to java lang class object. Then it can be converted into BCEL intermediate javaclass structure. The following code may help:- ``` Class<?> javaClass1 = null; javaClass1 = ucl.loadClass("com.sample.Customer"); org.apache.bcel.classfile.JavaClass javaClazz1=org.apache.bcel.Repository.lookupClass(javaClass1); ```
Create a BCEL JavaClass object from arbitrary .class file
[ "", "java", "bytecode", "bcel", "" ]
OK, I have a somewhat complicated system in C++. In a nutshell, I need to add a method to a third party abstract base class. The third party also provides a ton of derived classes that also need the new functionality. I'm using a library that provides a standard Shape interface, as well as some common shapes. ``` class Shape { public: Shape(position); virtual ~Shape(); virtual position GetPosition() const; virtual void SetPosition(position); virtual double GetPerimeter() const = 0; private: ... }; class Square : public Shape { public: Square(position, side_length); ... }; class Circle, Rectangle, Hexagon, etc ``` Now, here's my problem. I want the Shape class to also include a GetArea() function. So it seems like I should just do a: ``` class ImprovedShape : public virtual Shape { virtual double GetArea() const = 0; }; class ImprovedSquare : public Square, public ImprovedShape { ... } ``` And then I go and make an ImprovedSquare that inherits from ImprovedShape and Square. Well, as you can see, I have now created the dreaded [diamond inheritance problem](http://en.wikipedia.org/wiki/Diamond_problem). This would easily be fixed if the third party library used [virtual inheritance](http://en.wikipedia.org/wiki/Virtual_inheritance) for their Square, Circle, etc. However, getting them to do that isn't a reasonable option. So, what do you do when you need to add a little functionality to an interface defined in a library? Is there a good answer? Thanks!
We had a very similar problem in a project and we solved it by just NOT deriving ImprovedShape from Shape. If you need Shape functionality in ImprovedShape you can dynamic\_cast, knowing that your cast will always work. And the rest is just like in your example.
Why does this class need to derive from shape? ``` class ImprovedShape : public virtual Shape { virtual double GetArea() const = 0; }; ``` Why not just have ``` class ThingWithArea { virtual double GetArea() const = 0; }; ``` ImprovedSquare is a Shape and is a ThingWithArea
Looking for a better way than virtual inheritance in C++
[ "", "c++", "inheritance", "multiple-inheritance", "" ]
I have been thinking about starting a side project at home to exercise my brain a bit. [Reversi](http://en.wikipedia.org/wiki/Reversi) looks like a simply game, where mobility has a profound effect on game play. It is at least a step up from tic tac toe. This would be a single player against an AI of some sort. I am thinking to try this in C++ on a PC. What issues am I likely to run into? What graphics library would you recommend? What questions am I not smart enough to ask myself?
In overall, issues you will end up running onto will depend on you and your approaches. Friend tends to say that complex is simple from different perspective. Choice of graphics library depends about what kind of game you are going to write? OpenGL is common choice in this kind of projects, but you could also use some GUI-library or directly just use windows' or xorg's own libraries. If you are going to do fancy, just use OpenGL. Questions you ought ask: Is C++ sensible choice for this project? Consider C and/or python as well. My answer to this would be that if you just want to write reversi, go python. But if you want to learn a low level language, do C first. C++ is an **extension** to C, therefore there's more to learn in there than there's in C. And to my judge, the more you have to learn onto C++ is not worth the effort. How do you use the graphics library? If you are going to do fancy effects, go to the scene graph. Instead you can just render the reversi grid with buttons on it. How ought you implement the UI, should you use the common UI concepts? Usual UI concepts (windowing, frames, buttons, menubars, dialogs) aren't so good as people think they are, there's lot of work in implementing them properly. Apply the scene graph for interpreting input and try different clever ways onto controlling the game. Avoid intro menus(they are dumb and useless work), use command line arguments for most configuration. I yet give you some ideas to get you started: Othello board is 8x8, 64 cells in overall. You can assign a byte per each cell, that makes it 64 bytes per each board state. It's 8 long ints, not very much at all! You can store the whole progress of the game and the player can't even notice it. Therefore it's advised to implement the othello board as an immutable structure which you copy always when you change a state. It will also help you later with your AI and implementing an 'undo' -feature. Because one byte can store more information than just three states (EMPTY, BLACK, WHITE), I advice you will also provide two additional states (BLACK\_ALLOWED, WHITE\_ALLOWED, BOTH\_ALLOWED). You can calculate these values while you copy the new state. Algorithm for checking out where you can put a block, could go the board through one by one, then trace from empty cells to every direction for regex-patterns: B+W => W^, W+B => B^ This way you can encapsulate the game rules inside a simple interface that takes care of it all.
Issues... Well, just be sure when writing the strategy part of the game, not to simply do the move that gives you the most pieces. You must also give weight to board position. For example, given the opportunity to place a piece in a board corner should take priority over any other move (besides winning the game) as that piece can never be turned back over. And, placing a piece adjacent to a corner spot is just about the worst move you can ever make (if the corner space is open). Hope this helps!
How would you go about implementing the game reversi? (othello)
[ "", "c++", "graphics", "" ]
I’m trying to implement a dictionary for use with WCF. My requirements are: * actual (private variable or base class) type equivalent to Dictionary * Comparer = `System.StringComparer.InvariantCultureIgnoreCase` * Custom (override/new) Add(key, value) method (to include validations). * Override ToString() * Use of the same type on both the client and host I’ve attempted using this class in a common project shared by the WCF host and client projects: ``` [Serializable] public class MyDictionary : Dictionary<string, object> { public MyDictionary() : base(System.StringComparer.InvariantCultureIgnoreCase) { } public new void Add(string key, object value) { /* blah */ } public override string ToString() { /* blah */ } } [DataContract] [KnownType(typeof(MyDictionary))] [KnownType(typeof(object[]))] [KnownType(typeof(double[]))] [KnownType(typeof(string[]))] [KnownType(typeof(DateTime[]))] public class ResultClass { public object Value{ get; set; } /* More properties */ } public class ParmData { public object Value{ get; set; } /* More properties */ } [DataContract] [KnownType(typeof(MyDictionary))] [KnownType(typeof(object[]))] [KnownType(typeof(double[]))] [KnownType(typeof(string[]))] [KnownType(typeof(DateTime[]))] public class ParameterClass { public List<ParmData> Data{ get; set; } /* More properties */ } [OperationContract] ResultClass DoSomething(ParameterClass args); ``` Results: * When I pass MyDictionary as one of the ParameterClass.Data.Value elements, I get a missing KnownType exception. * I can safely return MyDictionary in the ResultClass, but it is no longer my type. It is just a Dictionary, and is not castable to `MyDictionary`. Also comparer = `System.Collections.Generic.GenericEqualityComparer<string>`, not the case insensitive comparer I’m looking for. The help I’m asking for is to either fix my failed attempt, or a completely different way to achieve my stated requirements. Any solution should not involve copying one dictionary to another. Thanks
* Use the `CollectionDataContract` attribute as jezell suggested * Manually generate the reference (proxy) code with SvcUtil, using the /collectionType parameter. This parameter is not supported by the vs2008 service reference GUI. Source: [WCF Collection Type Sharing](http://www.codeproject.com/KB/WCF/WCFCollectionTypeSharing.aspx)
Add CollectionDataContract to the Dictionary class: For more information on using collection data contracts to implement dictionaries, check this link: <http://msdn.microsoft.com/en-us/library/aa347850.aspx>
How to implement an inherited Dictionary over WCF
[ "", "c#", "wcf", "c#-3.0", "" ]