Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
This piece of code compiles file in VC6 but in VS 2008 it gives an error. Can anyone tell me why? I guess it is because you can no longer compare a pointer to NULL (which is a typedef for 0). If that is the case, how do I do this comparison in VC9? ``` for ( std::vector<aCattrBase*>::iterator iT = attrLst.begin(); iT < attrLst.end(); iT++) { if ( (iT != NULL) && (*iT != NULL) ) //Error: C2678 { //code } } ``` > error C2678: binary '!=' : no operator > found which takes a left-hand operand > of type > 'std::\_Vector\_iterator<\_Ty,\_Alloc>' > (or there is no acceptable conversion)
The type for 'std::vector::iterator' is not necessarily a pointer type so you can not compare it to NULL. In your old compiler it just happened to be a pointer and so your code compiled. But you just got lucky (as shown when you moved the code to a different compiler). The only test on iterator you have is to compare it to end() or begin() or any valid iterator within the range begin() -> end(). Since this is a vector you can do mathematical operations with the iterator. iT-begin() should give you an offset. But this is not valid for all containers (check each containers documentation). All you need to do is test what the iterator points at: ``` for ( std::vector<aCattrBase*>::iterator iT = attrLst.begin(); iT != attrLst.end(); // Changed this. Notice the != ++iT) // Changed this. Prefer pre increment for not integer types { if ( *iT != NULL) { //code } } ```
The iterator is not a pointer, it's a class instance and does not have the binary operator != to compare it with null.
Error C2678 after migrating C++ code from VC6 to VS2008 - no operator found which takes a left-hand operand of type 'type'
[ "", "c++", "visual-studio", "visual-studio-2008", "visual-c++-6", "" ]
Given the following code: ``` class A<T> { internal void Add(T obj) { } } class C { } class B<T> where T : C { public B() { A<T> a = new A<T>(); a.Add(new C()); } } ``` The call to `Add` does not compile. It does when I cast it to `T` first: ``` a.Add((T)new C()); ``` It might be the sleep deprivation, but what am I missing here? If `T` is of type `C` (note the constraint on `B`), then why isn't `A<T>` equivalent to `A<C>`?
Because if B were declared with a type of D, which would be a class which extends C, then adding a new C would violate the type.
because T could be a subclass of C. you can't add a Animal bob = new Fish() to a List<Giraffe>
Generics: why won't this compile?
[ "", "c#", "generics", "constraints", "" ]
I need to make asynchronous calls to .NET web services from java since synchronous calls are too slow. I know in .NET this is easily done since the stub (proxy) class created by wsdl.exe also generates methods for asynchronous calls(BeginMethod()/EndMethod()). I created the service stub using eclipse Ganymede but no asynchronous method call were generated. How do you do this in java? Thanks in advance
Since you are using Eclipse, you are probably using Axis2 to generate the Web Services client. Axis2 is capable of generating an asynchronous client. Have a look at the instructions [here](http://ws.apache.org/axis2/0_94/CodegenTools-EclipsePlugin.html). You need to select the "Generate async" or "Generate both sync and async" option. This is an [article](http://www.ibm.com/developerworks/webservices/library/ws-axis2/) for asynchronous web services with Axis2. It refers mainly to the service (not the client), but the client code isn't much different. All Java Web Services Framework support asynchronous operations. You just need to configure the generator properly.
Check this out. It should help. [Asynchronous JAX-WS Web Service Client End-to-End Scenario](http://www.netbeans.org/kb/55/websvc-jax-ws-asynch.html)
Calling .NET Web Services Asynchronically from Java
[ "", "java", ".net", "web-services", "asynchronous", "" ]
The problem: Consider the following floats[]: ``` d[i] = 1.7 -0.3 2.1 0.5 ``` What I want is an array of int[] that represents the order of the original array with indices. ``` s[i] = 1 3 0 2 d[s[i]] = -0.3 0.5 1.7 2.1 ``` Of course it could be done with a custom comparator, a sorted set of custom objects, or by simply sorting the array and then searching for the indices in the original array (shudder). What I am in fact looking for is the equivalent for the second return argument of [Matlab's sort function](http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/ref/sort.html). Is there an easy way to do that (<5 LOC)? May there be a solution that does not need to allocate a new object for each element? --- Update: Thanks for your responses. Unfortunately, none of what has been proposed so far resembles the simple and efficient solution I was hoping for. I therefore openened a thread in the JDK feedback forum, proposing the addition of a new class-library function to address the issue. Lets see what Sun/Oracle thinks about the issue. <http://forums.java.net/jive/thread.jspa?threadID=62657&tstart=0>
I would tailor the quicksort algorithm to perform the exchange operation on multiple arrays at the same time: the index array and the value array. For example (based on this [quicksort](http://www.cs.princeton.edu/introcs/42sort/QuickSort.java.html)): ``` public static void quicksort(float[] main, int[] index) { quicksort(main, index, 0, index.length - 1); } // quicksort a[left] to a[right] public static void quicksort(float[] a, int[] index, int left, int right) { if (right <= left) return; int i = partition(a, index, left, right); quicksort(a, index, left, i-1); quicksort(a, index, i+1, right); } // partition a[left] to a[right], assumes left < right private static int partition(float[] a, int[] index, int left, int right) { int i = left - 1; int j = right; while (true) { while (less(a[++i], a[right])) // find item on left to swap ; // a[right] acts as sentinel while (less(a[right], a[--j])) // find item on right to swap if (j == left) break; // don't go out-of-bounds if (i >= j) break; // check if pointers cross exch(a, index, i, j); // swap two elements into place } exch(a, index, i, right); // swap with partition element return i; } // is x < y ? private static boolean less(float x, float y) { return (x < y); } // exchange a[i] and a[j] private static void exch(float[] a, int[] index, int i, int j) { float swap = a[i]; a[i] = a[j]; a[j] = swap; int b = index[i]; index[i] = index[j]; index[j] = b; } ```
Simple solution to create an indexer array: sort the indexer comparing the data values: ``` final Integer[] idx = { 0, 1, 2, 3 }; final float[] data = { 1.7f, -0.3f, 2.1f, 0.5f }; Arrays.sort(idx, new Comparator<Integer>() { @Override public int compare(final Integer o1, final Integer o2) { return Float.compare(data[o1], data[o2]); } }); ```
Java Array sort: Quick way to get a sorted list of indices of an array
[ "", "java", "arrays", "sorting", "class-library", "" ]
The problem is that I need to know if it's version 3.5 SP 1. `Environment.Version()` only returns `2.0.50727.3053`. I found [this solution](http://blogs.msdn.com/astebner/archive/2006/08/02/687233.aspx), but I think it will take much more time than it's worth, so I'm looking for a simpler one. Is it possible?
Something like this should do it. Just grab the value from the registry **For .NET 1-4**: `Framework` is the highest installed version, `SP` is the service pack for that version. ``` RegistryKey installed_versions = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP"); string[] version_names = installed_versions.GetSubKeyNames(); //version names start with 'v', eg, 'v3.5' which needs to be trimmed off before conversion double Framework = Convert.ToDouble(version_names[version_names.Length - 1].Remove(0, 1), CultureInfo.InvariantCulture); int SP = Convert.ToInt32(installed_versions.OpenSubKey(version_names[version_names.Length - 1]).GetValue("SP", 0)); ``` **For .NET 4.5+** (from [official documentation](https://msdn.microsoft.com/en-us/library/hh925568)): ``` using System; using Microsoft.Win32; ... private static void Get45or451FromRegistry() { using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\")) { int releaseKey = Convert.ToInt32(ndpKey.GetValue("Release")); if (true) { Console.WriteLine("Version: " + CheckFor45DotVersion(releaseKey)); } } } ... // Checking the version using >= will enable forward compatibility, // however you should always compile your code on newer versions of // the framework to ensure your app works the same. private static string CheckFor45DotVersion(int releaseKey) { if (releaseKey >= 528040) { return "4.8 or later"; } if (releaseKey >= 461808) { return "4.7.2 or later"; } if (releaseKey >= 461308) { return "4.7.1 or later"; } if (releaseKey >= 460798) { return "4.7 or later"; } if (releaseKey >= 394802) { return "4.6.2 or later"; } if (releaseKey >= 394254) { return "4.6.1 or later"; } if (releaseKey >= 393295) { return "4.6 or later"; } if (releaseKey >= 393273) { return "4.6 RC or later"; } if ((releaseKey >= 379893)) { return "4.5.2 or later"; } if ((releaseKey >= 378675)) { return "4.5.1 or later"; } if ((releaseKey >= 378389)) { return "4.5 or later"; } // This line should never execute. A non-null release key should mean // that 4.5 or later is installed. return "No 4.5 or later version detected"; } ```
Not sure why nobody suggested following the **official advice from Microsoft** right [here](http://msdn.microsoft.com/en-us/library/hh925568(v=vs.110).aspx). This is the code they recommend. Sure it's ugly, but it works. ## For .NET 1-4 ``` private static void GetVersionFromRegistry() { // Opens the registry key for the .NET Framework entry. using (RegistryKey ndpKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, ""). OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\")) { // As an alternative, if you know the computers you will query are running .NET Framework 4.5 // or later, you can use: // using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, // RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\")) foreach (string versionKeyName in ndpKey.GetSubKeyNames()) { if (versionKeyName.StartsWith("v")) { RegistryKey versionKey = ndpKey.OpenSubKey(versionKeyName); string name = (string)versionKey.GetValue("Version", ""); string sp = versionKey.GetValue("SP", "").ToString(); string install = versionKey.GetValue("Install", "").ToString(); if (install == "") //no install info, must be later. Console.WriteLine(versionKeyName + " " + name); else { if (sp != "" && install == "1") { Console.WriteLine(versionKeyName + " " + name + " SP" + sp); } } if (name != "") { continue; } foreach (string subKeyName in versionKey.GetSubKeyNames()) { RegistryKey subKey = versionKey.OpenSubKey(subKeyName); name = (string)subKey.GetValue("Version", ""); if (name != "") sp = subKey.GetValue("SP", "").ToString(); install = subKey.GetValue("Install", "").ToString(); if (install == "") //no install info, must be later. Console.WriteLine(versionKeyName + " " + name); else { if (sp != "" && install == "1") { Console.WriteLine(" " + subKeyName + " " + name + " SP" + sp); } else if (install == "1") { Console.WriteLine(" " + subKeyName + " " + name); } } } } } } } ``` ## For .NET 4.5 and later ``` // Checking the version using >= will enable forward compatibility, // however you should always compile your code on newer versions of // the framework to ensure your app works the same. private static string CheckFor45DotVersion(int releaseKey) { if (releaseKey >= 393295) { return "4.6 or later"; } if ((releaseKey >= 379893)) { return "4.5.2 or later"; } if ((releaseKey >= 378675)) { return "4.5.1 or later"; } if ((releaseKey >= 378389)) { return "4.5 or later"; } // This line should never execute. A non-null release key should mean // that 4.5 or later is installed. return "No 4.5 or later version detected"; } private static void Get45or451FromRegistry() { using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\")) { if (ndpKey != null && ndpKey.GetValue("Release") != null) { Console.WriteLine("Version: " + CheckFor45DotVersion((int) ndpKey.GetValue("Release"))); } else { Console.WriteLine("Version 4.5 or later is not detected."); } } } ```
Is there an easy way to check the .NET Framework version?
[ "", "c#", ".net", ".net-core", "" ]
HI, Is there a way by which I can rotate an image inside a div clockwise or anticlockwise. I have a main fixed width div[overflow set to hidden] with images loaded from database. There is a scroll bar for showing the images inside the div. When image is clicked then I need to show the rotating animation either in clockwise or anticlockwise direction. I have done it using Matrix filter. I would like to know whether it is possible to be done in IE only without using any filters.
try this: <http://raphaeljs.com/image-rotation.html> uses canvas but also supports IE
If you're using jQuery, jQueryRotate is a small (less than 3Kb minified+gzipped) plugin that rotates images: <http://jqueryrotate.com/>
Rotate image clockwise or anticlockwise inside a div using javascript
[ "", "javascript", "image-manipulation", "rotation", "" ]
Eclipse WTP creates its own server.xml file which it places in some folder which configures the tomcat instance you are running for your web project. If you double click on the server in the servers list you get a nice screen which makes it simple to configure some aspects of the server.xml file. How do I configure a new connection to allow SSL connections on port 8443. Everytime I edit the server.xml file manually, eclipse overwrites my changes with the settings it has stored in the server properties page of the configuration and it seems there is no way to add a new connector from the interface that eclipse provides. Is this possible? Here is the connector I want to add: ``` <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true" maxThreads="150" scheme="https" secure="true" keystoreFile="D:\apache-tomcat-6.0.18\keystore\key.ssl" keystorePass="pass" clientAuth="false" sslProtocol="TLS" /> ```
If you've already created the server, you can edit the server.xml template it copies. If you use the project explorer, It is under Other Projects->Servers->*Tomcat Server Name*->server.xml
Here is how you get it to work: Create the keystore: ``` keytool -genkey -alias tomcat -keypass mypassword -keystore keystore.jks -storepass mypassword -keyalg RSA -validity 360 -keysize 2048 ``` (Follow through the prompts and fill in the information) It should then save a keystore.key file to your home directory. To get it to work in eclipse : ``` <Connector port="8443" SSLEnabled="true" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="true" disableUploadTimeout="true" acceptCount="100" debug="0" scheme="https" secure="true" clientAuth="false" sslProtocol="TLSv1" keystoreFile="/home/myUsername/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/conf/keystore.key" keystorePass="mypassword" /> ``` The above path for keystoreFile is something you absolutely need to get right for this to work. When eclipse uses a workspace metadata location to run tomcat, it copies over some files into a path that looks like the above. On OS X this would be: ``` /Users/<username>/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/conf/keystore.key ``` Hope that helps. For More Reference : [SSL/TLS Configuration HOW-TO in Apache Tomcat 7](https://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html)
Eclipse WTP: How do I enable SSL on Tomcat?
[ "", "java", "eclipse", "tomcat", "eclipse-wtp", "" ]
I know, I quite dislike the catch-all survey type questions, but I couldn't think of a better way to find out what I think I need to know. I'm very green in the world of database development, having only worked on a small number of projects that merely interacted with the database rather than having to actually create a new one from scratch. However, things change and now I am faced with creating my own database. So far, I have created the tables I need and added the columns that I think I need, including any link tables for many-many relationships and columns for one-to-many relationships. I have some specific questions on this, but I felt that rather than get just these answered, it would make more sense to ask about things I may not even know, which I should address now rather than 6 months from now when we have a populated database and client tools using it. First the questions on my database which have led me to realise I don't know enough: 1. How do I ensure my many-to-many link tables and my one-to-many columns are up-to-date when changes are made to the referenced tables? What problems may I encounter? * I am using nvarchar(n) and nvarchar(MAX) for various text fields. Should I use varchar equivalents instead (I had read there may be performance risks in using nvarchar)? Are there any other gotchas regarding the selection of datatypes besides being wary of using fixed length char arrays to hold variable length information? Any rules on how to select the appropriate datatype? * I use `int` for the `ID` column of each table, which is my primary key in all but the link tables (where I have two primary keys, the `ID`s of the referenced table rows). This ID is set as the identity. Are there pitfalls to this approach? * I have created metadata tables for things like unit types and statuses, but I don't know if this was the correct thing to do or not. Should you create new tables for things like enumerated lists or is there a better way? I understand that databases are complex and the subject of many many worthy tomes, but I suspect many of you have some tips and tricks to augment such reading material (though tips for essential reading would also be welcome). Community wiki'd due to the rather subjective nature of these kinds of posts. Apologies if this is a duplicate, I've conducted a number of searches for something like this but couldn't find any, though [this one is certainly related](https://stackoverflow.com/questions/346659/what-are-the-most-common-sql-anti-patterns). Thanks. ### Update I just found [this question](https://stackoverflow.com/questions/387339/database-design-best-practices), which is very similar in a roundabout way.
1. Not normalising 2. Not using normalisation 3. Trying to implement a denormalised schema from the start Seriously: 1. Foreign keys will disallow deletes or updates from the parent tables. Or they can be cascaded. 2. Small as possible: 2 recent SO questions [datatypes](https://stackoverflow.com/questions/927331/927543#927543) and [(n)varchar](https://stackoverflow.com/questions/35366/varchar-vs-nvarchar-performance/198753#198753) 3. May not be portable and your "natural key" (say "product name") still needs a unique constraint. Otherwise no, but remember that an IDENTITY column is a "[surrogate key](http://en.wikipedia.org/wiki/Surrogate_key)" Edit: Say you expect to store fruit with columns FruitID and FruitName. You have no way to restrict to one occurence of "Apple" or "Orange" because although this is your "natural key", you are using a surrogate key (FruitID). So, to maintain integrity, you need a unique constraint on FruitName 4. Not sure or your meaning, sorry. Edit: Don't do it. Ye olde "[One true lookup table](https://stackoverflow.com/questions/927331/927543#927543)" idea.
I'll reply to your subjective query with some vague generalities. :) The most common pitfall of designing a database is the same pitfall of any programming solution, not fully understanding the problem being solved. In the case of a database, it is understanding the nature of the data. How big it is, how it comes and goes, what business rules must it adhere to. Here are some questions to ponder. What is updated the most frequently? Is keeping that table write-locked going to lock up queries? Will it become a hot spot? Even a seemingly well normalized schema can be a poor performer if you don't understand your read versus write ratios. What are your external interface needs? I've been on projects where the dotted line to "that other system" nearly scuttled the whole project because implementing it was delayed until everything else was in place, that is to say, everything else was inflexible. Any other unspoken requirements? My favorite is date sensitivity. All the data is there, your reports are beautiful, the boss looks them over and asks, when did that datum change? Who did it and when? Is the database supposed to track itself and its users, or just the data? Will your front end do it for you? Just some things to think about.
What are common pitfalls when developing a new SQL database?
[ "", "sql", "sql-server-2005", "t-sql", "" ]
this is a simple question. With PHP and MySQL, I'm trying to build a bug reporting application. Currently, the user can post bugs and a list of bugs is portrayed to the technician/administrator. How do I make it so that many technician or administrators can reply to the report (thread?) As in both mysql table layout and PHP coding? The current MySQL table has layout of: ``` id (Bug ID) by (person reporting it) title (Report Title) content (Contents of Report) datetime (Date/Time of report) application (Application/page where problems happens) priority (Priority) assigned (Assigned To) status (Status of report/bug) ``` So no response column yet, but how do I achieve multiple post/responses with PHP and MySQLi? Thanks
What you usually do is you create a separate table for the responses. In that table you have one field that "points" to the first table. It could look like this: ``` TABLE responses id (Unique id) bug_id ("Pointer" to which bug this response "belongs to") body (Contents of response) ``` This way you can have many responses which all point back to one bug, and thus you have virtually created an "ownership" or "relation". It is customary to call a relation like the one above a "one to many" if we pretend we're in the bugs table, looking out. (And a "many to one" of we're in the responses table, looking back at the bugs table.) Then, in PHP, when you want to retrieve all the responses belonging to a bug, you do something like this: (pseudo code) ``` $bug = SELECT * FROM bugs WHERE id = $some_id $resps = SELECT * FROM responses WHERE bug_id = $bug['id'] ORDER BY created_at ``` Voilá! Now you have the bug and all of its responses, ordered by creation date. When you insert new responses you need to set `bug_id` to the appropriate value, of course. Cheers!
This would be a many-to-one relationship. You can either have: response table ``` id (response id) bugid (bug id) columns related to the response ``` or response table ``` id (response id) columns related to the response ``` with bugresponse table ``` responseid (response id) bugid (bug id) columns related to the bug-response relationship ``` where the second design can also handle many-to-many relationship (unlikely to be necessary in this case) and can also has some other benefits depending on your requirements.
How to have multiple replies in posting app?
[ "", "php", "database-design", "mysqli", "" ]
Why is it that the following code won't work: ``` endDate.AddDays(7-endDate.DayOfWeek); ``` While this will: ``` endDate.AddDays(0-endDate.DayOfWeek + 7); ``` ? (By "won't work" I mean results in the following compilation error: "cannot convert from 'System.DayOfWeek' to 'double'")
To expand upon what Lasse said (or rather, make it a little more explicit). Because 0 is convertable to an Enum type, ``` 0 - endDate.DayOfWeek becomes (DayOfWeek)0 - endDate.DayOfWeek ``` And since you can subtract one enum from another and get an integer difference: ``` (DayOfWeek)0 - endDate.DayOfWeek == (int)endDate.DayOfWeek ``` Thus, since the result of the subtraction is an int, you can then add 7 to it. ``` endDate.AddDays(0-endDate.DayOfWeek + 7); ``` So, if Monday's Enum value is 1 ``` 0 - endDate.DayOfWeek == -1 + 7 == 6 ``` However, you can't do the reverse. ``` endDate.DayOfWeek - 0 + 7, ``` because the result type of the calculation is dependant upon the leftmost side. Thus, while 0 - endDate.DayOfWeek results in an integer, endDate.DayOfWeek - 0 results in an enum DayOfWeek. Most interestingly, you could use this side-effect to get the value of an enum without casting, though I would consider this hackish and confusing... thus to be avoided. ``` int enumValue = -(0 - endDate.DayOfWeek); ```
This is very interesting. The right way to do this is: ``` endDate.AddDays(7 - (int)endDate.DayOfWeek); ``` But, your question isn't about a solution, but a reason for the behavior. It has something to do with the way the compiler treats a zero. Either line fails if no zero is present, while both lines work if a zero is present.
Math with Enums (e.g. DayOfWeek) in C#
[ "", "c#", "enums", "dayofweek", "" ]
I inherited a website and see that folder in the web root. I'm trying to clean out the old crap, and wondering if I can delete it. What is this folder used by? Is it auto generated? Is it a cache? What creates it?
It is generated by the ASPNET\_regiis /c command. Most websites I use have ended up including this in the distribution because the sys admins always forgot to install it. It contains the client side JavaScript libraries required by .NET1.x to handle the postback eventing model on the client side. You can delete it if you have upgraded to .NET 2 which uses a different handler for the scripts (or if you are prepared to recreate it.) But check first that there aren't additional files added there by the author as sometimes I have seen it used for extra stuff.
That folder is used to store auto-generated validation scripts when you add client side validation to your server controls.
What is the aspnet_client folder in my ASP.NET website?
[ "", "c#", "asp.net", "web", "directory", "" ]
I have a table with about 10 fields to store gps info for customers. Over time as we have added more customers that table has grown to about 14 million rows. As the gps data comes in a service constantly inserts a row into the table. 90% of the data is not revelent i.e. the customer does not care where the vehicle was 3 months ago, but the most recent data is used to generate tracking reports. My goal is to write a sql to perform a purge of the data that is older than a month. Here is my problem I can NOT use TRUNCATE TABLE as I would lose everything? Yesterday I wrote a delete table statement with a where clause. When I ran it on a test system it locked up my table and the simulation gps inserts were intermittently failing. Also my transaction log grew to over 6GB as it attempted to log each delete. My first thought was to delete the data a little at a time starting with the oldest first but I was wondering if there was a better way.
Try this WHILE EXISTS ( SELECT \* FROM table WHERE (condition for deleting)) BEGIN SET ROWCOUNT 1000 DELETE Table WHERE (condition for deleting) SET ROWCOUNT 0 ENd This will delete the rows in groups of 1000
My 2 cents: If you are using SQL 2005 and above, you can consider to partition your table based on the date field, so the table doesn't get locked when deleting old records. Maybe, if you are in position of making dba decisions, you can temporarily change your log model to Simple, so it won't grow up too fast, it will still be growing, but the log won't be too detailed.
Deleting data from a large table
[ "", "sql", "" ]
The project my team has been working on has reached a point where we need to deploy it to computers without the development environment (Visual Studio 2005) installed on them. We fixed the dependency issues we had at first, but we're still having issues. Now, once the installer is finished, our project gets stuck somewhere before entering WinMain. It only takes up 13MB of RAM, but takes up 50% of the cpu cycles. Are there any suggestions as to how debug this problem? Edit: Clarification - this is a C++ project.
Is it possible the hang occurs while some global variable is initialized? That happens before WinMain, and from a global variable's constructor any code could be run. Also, take a look at the busy thread's stack using [Process Explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) (make sure you deploy the PBD in order to get a meaningful stack trace). The stack trace should make it obvious where is that thread hanging.
If your running vista or windows 7 you can create a memory dump from task manager (right click and select create dump file) and then transfer that to your dev computer, load the symbols and it will show you where the program was at that time.
Program Deployment Failing
[ "", "c++", "debugging", "deployment", "visual-studio-2005", "" ]
I need to get data from a web site written in PHP. My boss wants me to provide an RSS feed to get updated content. The problem is that I need to provide several informations (at least a dozen different field). Is returning data as XML a better way than RSS?
It's really going to depend on what the data is and how it's going to be consumed. RSS *is* XML, but it's XML meant to syndicate data with a consistent format (there's a pretty good overview here: <http://cyber.law.harvard.edu/rss/rss.html>), and that allows feed readers and other consumers to know how to process and display them. So if your boss wants to look at this data in his or her feed reader of choice, then go for RSS. If the data is more varied or arbitrary, and is going to be consumed by some sort of application or other processor on the other end, then XML is probably a better solution.
[RSS](http://cyber.law.harvard.edu/rss/rss.html) is a form of XML. If you find yourself outputting the same sorts of data as what is in the RSS specification, it definately doesn't hurt to output in the RSS spec. That way, you can syndicate your content.
RSS or XML
[ "", "php", "xml", "rss", "" ]
I have some functions that I am calling and they take some time (milliseconds), but I don't want the page to display until these functions have completed. Right now, I can tell that the page loads and then the scripts eventually complete. Right now, I am calling the functions in the body onload. Also, another issue I may have is that I need to access div elements in the html content, can I do that in my body onload function (getElementById('somDiv')? Here is the workflow. 1. Make a call to getElementById('someDiv') to get an element from the page. 2. Invoke the function someFunc, this function is in the body onload=someFunc() 3. Wait until someFunc is finished 4. Display page to user once my function has completed.
What you could do is keep your page content in a `div` that is initially styled with `display:none`. Then when your javascript code finishes, update the style on the `div` to `display:block`, e.g.: ``` <html> <head> ... <style type="text/css"> html, body, #body { height: 100%; width: 100%; padding: 0; margin: 0; } #body { display: none; } </style> <script type="text/javascript"> function myFunc() { ... getElementById('body').style.display = 'block'; } </script> </head> <body onload="myFunc();"> <div id="body> ... </div> </body> </html> ``` Then Bob's your uncle: the page looks like it has delayed loading until after your script is finished.
Functions that are called in the `<body>` tag's `onLoad` event are only fired when the DOM is loaded (however it does not wait for external dependencies such as JavaScript files and CSS to load), so you can be sure that when your `someFunc()` function is called, (if attached to the `<body>` tag's `onLoad` event) the elements in the page have been loaded. If you want to access a DIV that is loaded in the page then you can be sure that it will have loaded when your `someFunc()` function is called. To solve your problem you could wrap then content of your page in a DIV, with the `display` of it set initially to `none`. Then when the page has loaded, your `someFunc()` function is called. When it has finished executing, you can set the `display` of your wrapper DIV to `block`, so that it is visible to the user. However, make sure that you make the user aware that the page is loading, and you do not simply show them a blank screen whilst your JavaScript is loading.
Javascript: Have body onload function wait until scripts have completed
[ "", "javascript", "html", "dhtml", "" ]
Partial Code: My below code pulls a query from my DB and then uses inner.HTML = to display the data inside a div. It works fine in it original use.... However the below version is called inside a iFrame as it is used to update the page. The page has no errors and the JavaScript fires however the last line does not work... I have just realized that perhaps since it is loading in the hidden iFrame it is trying to set the innerHTML of a div inside the iFrame and that of course will not work. Is this what is happening? It doesn't make sense because I have another script that calls JavaScript at the end of it in the same manner and it works fine. ``` <?php while ($row = mysql_fetch_array($result)) { $p = $p.'<div id="left"><img src="http://www.sharingizcaring.com/bleepV2/images/thumbs/'.$row[image].'" /></div>'; $p = $p.'<div id="right"><h2>'.$row[artist].' - '.$row['title'].'</h2><br>'.$row['message'].'<br>'; $p = $p.'<a href="http://www.sharingizcaring.com/bleepV2/'.$row[username].'">'.$row[username].'</a> '.$row[date].'</div>'; $p = $p.'<div style="clear: both;"></div>'; $p = $p.'<div id="dotted-line"></div>'; } $p = addslashes($p); ?> <script> alert('posts are firing? '); document.getElementById('posts').innerHTML = 'why doth this faileth?'; </script> ```
You can do it! [Read here for more info](http://www.oreillynet.com/pub/a/javascript/excerpt/jstdg_ch13/?page=7) You can affect the document with contains the iframe by setting and getting variables from the window element: ``` // normally you use... var whatever = "value"; // use the window object instead, which is shared // between the iframe and the parent window.whatever = "value"; ``` The other thing you should know is that you can access the main document via the parent object inside the iframe you can use... ``` parent.someattr; // or try this parent.getElementById('some_element'); ```
I think what you want is: ``` parent.getElementById('posts').innerHTML = 'why doth this faileth?'; ```
Can javascript running inside an iframe affect the main page?
[ "", "javascript", "iframe", "" ]
I have an application which is running on tomcat, one of the methods is, creating a simple thumbnail from an jpeg image. The functions works fine offline and a week ago also on tomcat. But now i get the following error: ``` java.lang.NoClassDefFoundError java.lang.Class.forName0(Native Method) java.lang.Class.forName(Class.java:164) java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvironment.java:68) java.awt.image.BufferedImage.createGraphics(BufferedImage.java:1141) eval.impl.ImageEval.getThumbnail(ImageEval.java:155) eval.impl.ImageServlet.doGet(ImageServlet.java:79) javax.servlet.http.HttpServlet.service(HttpServlet.java:690) javax.servlet.http.HttpServlet.service(HttpServlet.java:803) ``` I don't think that i have change anything what should influence this (actually i didn't change the function at all according to the svn repository), so it must be a library problem. But i can't figure out what is missing. Here are the actual lines from the getThumbnail function, where the error occures: ``` BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(simage, 0, 0, thumbWidth, thumbHeight, null); ``` [edit] I decided to update the problem description a little. Yes it seems that he can not find some class from java.awt or one related to that. But they do exist on the server in the jvm. Java headless mode doesn't solve the problem. In another project the exact same code, but inside an axis2 webservice on this server is working fine. [/edit]
It seems like you've change the configuration of Tomcat. Either you've changed to a l{0,1}[iu]n[iu]x box or installed on a virtual machine with different security control than the one where you test it. Apparently the ``` GraphicsEnvironment.getLocalGraphicsEnvironment() ``` Is trying to access the property: *java.awt.graphicsenv* Which may return null or some non existing class name which is then loaded and throws the ClassNotFoundException. [1](http://www.docjar.com/docs/api/java/awt/GraphicsEnvironment.html#getLocalGraphicsEnvironment) The solution seems to be specifying the "java.awt.headless" property. This is a similar question: [java.awt.Color error](https://stackoverflow.com/questions/427482/java-awt-color-error) Try this [search](http://www.google.com/search?hl=en&q=%22-Djava.awt.headless%3Dtrue%22+GraphicsConfiguration&btnG=Search&aq=f&oq=&aqi=) , it shows similar situations as your. I remember there was something in the sun bugs database too. Post the solution when you find it! 1.[GraphicsEnvironment.java](http://www.docjar.com/docs/api/java/awt/GraphicsEnvironment.html#getLocalGraphicsEnvironment) **EDIT** It is not eclipse!! In my original post there is a link to the source code of the class which is throwing the exception. Since I looks like you miss it, I'll post it here for you: ``` public static synchronized GraphicsEnvironment getLocalGraphicsEnvironment() { if (localEnv == null) { // Y O U R E R R O R O R I G I N A T E S H E R E !!! String nm = (String) java.security.AccessController.doPrivileged (new sun.security.action.GetPropertyAction ("java.awt.graphicsenv", null)); try { // long t0 = System.currentTimeMillis(); localEnv = (GraphicsEnvironment) Class.forName(nm).newInstance(); // long t1 = System.currentTimeMillis(); // System.out.println("GE creation took " + (t1-t0)+ "ms."); if (isHeadless()) { localEnv = new HeadlessGraphicsEnvironment(localEnv); } } catch (ClassNotFoundException e) { throw new Error("Could not find class: "+nm); } catch (InstantiationException e) { throw new Error("Could not instantiate Graphics Environment: " + nm); } catch (IllegalAccessException e) { throw new Error ("Could not access Graphics Environment: " + nm); } } return localEnv; } ``` That's what gets executed. And in the original post which you don't seem to have read, I said the code is accessing the property *"java.awt.graphicsenv"* If that other project using axis doesn't have the same problem it may be because it may be running in a different tomcat configuration or the axis library allowed the access to that property. But we cannot be sure. That's pure speculation. So why don't you test the following and see what gets printed: ``` String nm = (String) java.security.AccessController.doPrivileged (new sun.security.action.GetPropertyAction ("java.awt.graphicsenv", null)); System.out.println("java.awt.graphicsenv = " + nm ); ``` It it prints null then you now what the problem is. You don't have that property in your system, or the security forbids you do use it. It is very hard to tell you from here: *"Go and edit file xyz and add : fail = false*" So you have to do your work and try to figure out what's the real reason. Start by researching what's the code being executed is ( which I have just posted ) and follow by understand what it does and how does all that "AccessController.doPrivileged" works. (You may use Google + StackOverflow for that).
We had a similar issue and after much trouble shooting it was identified to be related to the `java.awt.headless` property. The issue was resolved by explicitly setting the JVM option to ``` -Djava.awt.headless=true ```
NoClassDefFoundError while accessing GraphicsEnvironment.getLocalGraphicsEnvironment on Tomcat
[ "", "java", "tomcat", "noclassdeffounderror", "" ]
I was trying to make a kind of background in which some clouds were moving, but after I got the clouds moving I found that I should either make them stop and return when reaching the browser's max-width, or make them disappear. I was trying to get their position but I can't manage to get all the positions dynamically. Right now (for the sake of simplicity) I'm only using 1 cloud to test and I do this: ``` $(function () { var p = $('.clouds').position(); var w = $("#sky").width(); while (p < w); $('.clouds', this).stop().animate({ left: "+=50000px" }, { queue: false, duration: 90000 }); }); ``` the thing is, that position isn't dynamically refreshed, it sticks with the first one it gets and I have tried to move it inside the while loop but it didn't work...so I'm kinda stuck at the moment...anyone has an idea of how I can achieve this? The image of the cloud is originally set at top:0 left:0
I think this code will be useful to u. Try this out! ``` $('.clouds').animate({ top: 0 }, { queue: false, duration: 90000 }); setInterval(function () { if ($(".clouds").position().top == 0) alert("Rain"); }, 5000); ``` for every 5 seconds, it will check for the position of a "cloud" class if it is zero it will give alert! for multiple clouds u can use below code ``` setInterval(function () { if ($(".clouds").position().top == 0) { $(".clouds").each(function () { if ($(this).position().top == 0) $(this).remove(); }); } }, 1000) ```
why not use a looping background image and modify the background-position css property? edit: I don't know if there's a jquery plugin to do this automatically, but it should be easy enough in old fashioned javascript with setInterval and modulus. for example, your background image is 400 pixels wide, the css would be: ``` body { background: transparent url(yourbackground.png) repeat-x scroll 0 0; } ``` and javascript would be: ``` var BGPosition = 0; var resetSize=400; function scrollBodyBG() { BGPosition = ++BGPosition % resetSize; $('body').css("background-position", (-1 * BGPosition) + "px 0px"); } var si = setInterval(scrollBodyBG,100) ``` Edit: Tested and working (without jquery) as ``` var BGPosition = 0; var resetSize=400; function scrollBodyBG() { BGPosition = ++BGPosition % resetSize; document.body.style.backgroundPosition = (-1 * BGPosition) + "px 0px"; } document.addEventListener("DOMContentLoaded",function() { setInterval(scrollBodyBG,100);},false); ``` obviously this would need to change for IE event listener support
Get Position of an element constantly changing
[ "", "javascript", "jquery", "jquery-animate", "" ]
I want to provide the user with a scaled-down screenshot of their desktop in my application. **Is there a way to take a screenshot of the current user's Windows desktop?** I'm writing in C#, but if there's a better solution in another language, I'm open to it. To clarify, I need a screenshot of the Windows Desktop - that's the wallpaper and icons only; no applications or anything that's got focus.
You're looking for [Graphics.CopyFromScreen](http://msdn.microsoft.com/en-us/library/fw1kt6f9.aspx). Create a new Bitmap of the right size and pass the Bitmap's Graphics object screen coordinates of the region to copy. There's also [an article](http://csharpnet.blogspot.no/2007/01/snap-it-how-to-take-screen-shot-using.html) describing how to programmatically take snapshots. **Response to edit**: I misunderstood what you meant by "desktop". If you want to take a picture of the desktop, you'll have to: 1. [Minimize all windows using the Win32API](https://stackoverflow.com/questions/785054/minimizing-all-open-windows-in-c/786506) (send a `MIN_ALL` message) first 2. Take the snapshot 3. Then undo the minimize all (send a `MIN_ALL_UNDO` message). --- **A better way to do this** would be not to disturb the other windows, but to copy the image directly from the desktop window. [GetDesktopWindow in User32](http://msdn.microsoft.com/en-us/library/ms633504(VS.85).aspx) will return a handle to the desktop. Once you have the window handle, get it's device context and copy the image to a new Bitmap. There's [an excellent example on CodeProject](http://www.codeproject.com/KB/system/snapshot.aspx) of how to copy the image from it. Look for the sample code about getting and creating the device context in the "Capturing the window content" section.
I get the impression that you are shooting for taking a picture of the actual desktop (with wallpaper and icons), and nothing else. 1) Call ToggleDesktop() in Shell32 using COM 2) Use Graphics.CopyFromScreen to copy the current desktop area 3) Call ToggleDesktop() to restore previous desktop state Edit: Yes, calling MinimizeAll() is belligerent. Here's an updated version that I whipped together: ``` /// <summary> /// Minimizes all running applications and captures desktop as image /// Note: Requires reference to "Microsoft Shell Controls and Automation" /// </summary> /// <returns>Image of desktop</returns> private Image CaptureDesktopImage() { //May want to play around with the delay. TimeSpan ToggleDesktopDelay = new TimeSpan(0, 0, 0, 0, 150); Shell32.ShellClass ShellReference = null; Bitmap WorkingImage = null; Graphics WorkingGraphics = null; Rectangle TargetArea = Screen.PrimaryScreen.WorkingArea; Image ReturnImage = null; try { ShellReference = new Shell32.ShellClass(); ShellReference.ToggleDesktop(); System.Threading.Thread.Sleep(ToggleDesktopDelay); WorkingImage = new Bitmap(TargetArea.Width, TargetArea.Height); WorkingGraphics = Graphics.FromImage(WorkingImage); WorkingGraphics.CopyFromScreen(TargetArea.X, TargetArea.X, 0, 0, TargetArea.Size); System.Threading.Thread.Sleep(ToggleDesktopDelay); ShellReference.ToggleDesktop(); ReturnImage = (Image)WorkingImage.Clone(); } catch { System.Diagnostics.Debugger.Break(); //... } finally { WorkingGraphics.Dispose(); WorkingImage.Dispose(); } return ReturnImage; } ``` Adjust to taste for multiple monitor scenarios (although it sounds like this should work just fine for your application).
Is there a way to take a screenshot of the user's Windows desktop?
[ "", "c#", "windows", "desktop", "screenshot", "" ]
I just graduated college and will be starting working in about a month and I was asked to familiarize myself with C++, C#, .NET framework for NT Services and web services. I'd appreciate recommendations on how to familiarize myself with these topics (books? internet links?) in a short time span. I don't expect to be an expert on it in a month but I don't want to be clueless either. I already know C++ and I consider myself to be fairly proficient in it and I know the basics of C# even though I haven't used it all that much. For C# I do own a book called O'Reilley *Programming C#*. Thanks!
I would start by pulling down Microsoft's [Visual Studio Express](http://www.microsoft.com/Express/) products. Your O'Reilly book is a perfectly good book to start with. Start reading blogs and listening to podcasts, to begin to familiarize yourself with all of the technologies out there that surround c#. You will be very excited about what you can learn. Here are some of the better ones: <http://www.hanselminutes.com/> <http://www.dotnetrocks.com/> <http://channel9.msdn.com/> <http://weblogs.asp.net/scottgu/> <http://weblogs.asp.net/> In addition, the MSDN library is an invaluable resource. You can almost always find what you need there. This is where the reference for the entire .NET framework lives. <http://msdn.microsoft.com/en-us/library/default.aspx> Happy hunting!
Nothing beats actually using the language. As much as some of the information sources already quoted would be very useful to check out, I'd say make sure that you at least try and write some concrete C#. The best place to start might be a non-trivial-but-not-too-large application that you have already written in something you know, and try to convert it to C#... even better if you can get somebody proficient in C# to peer-review your results to make suggestions where you could make better use of the language-specific features that may be new to you. Fundamentally, if you just read books and watch videos, you may feel like you actually know it, but it is nothing like doing it yourself (as my Uni maths classes taught me... a good teacher can make the impossible look trivial on a blackboard).
What's a quick way to familiarize myself with C#, .NET framework, etc?
[ "", "c#", ".net", "web-services", "nt", "" ]
I have a `JList` and I am wanting to get the text of an entry of that list at a specific index. Could someone inform me how to do this or should I restructure my code to `getValues` instead of `getIndices`?
``` JList dataList=(...) for(int i = 0; i < dataList.getModel().getSize(); i++) { System.out.println(dataList.getModel().getElementAt(i)); } ```
``` Object[] temp = jList1.getSelectedValues(); temp[i] = the object you want. ```
How can I get the text from a component in a JList?
[ "", "java", "string", "swing", "jlist", "" ]
ASP.NET is great for creating html. We send out a lot of html email messages. In the past we've been loading .html templates with key strings that are replaced to make the email more custom (ie. [[FirstName]] would be replaced with "John Doe"). However as we are adding more and more email campaigns the logic to customize the email is starting to get out of hand. Instead of a simple [[FirstName]] string replace we are tasked with something like [[ScholarshipList]] where the ScholarshipList is different for each user we send an email to. Ideally, at least in my mind, these email templates would be self contained .aspx pages. And would be invoked from our winform emailer application in a manner similar to ``` IEmailTemplate template = EmailTemplates.Load("ScholarshipList.aspx"); template.UserID=1234; string emailMessage = template.Render(); ``` Then the ScholarshipList.aspx page would look similar to any other asp.net page in that it can have server controls, runat="server" scripts and databind. I've seen this article <http://www.west-wind.com/presentations/aspnetruntime/aspnetruntime.asp> which looks promising. Has anyone used it before? It uses some remoting which ideally would be avoided, and has a limited error handling mechanisms. I thought I'd get some other feedback before I went to far down that road.
You could try this approach as well. <http://jamesewelch.com/2008/07/11/how-to-render-a-aspnet-user-control-within-a-web-service-and-return-the-generated-html/> If you hosted your templates in a webservice and then invoked them from your app.
A quick and dirty way to do it is to do a HttpWebRequest to the url and grab the output and use that, but thats not as nice as the anser from David...
Is there a way to use .aspx pages as templates for emails being sent from a winform application?
[ "", "c#", "asp.net", "winforms", "email", "" ]
I try to understand why a BeginInvoke method won't accept an anonymous method. ``` void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { if (InvokeRequired) { //Won't compile BeginInvoke(delegate(object sender, ProgressChangedEventArgs e) { bgWorker_ProgressChanged(sender, e); }); } progressBar1.Increment(e.ProgressPercentage); } ``` It tells me 'cannot convert from 'anonymous method' to 'System.Delegate' while when I cast the anonymous method to a delegate it does work ? ``` BeginInvoke((progressDelegate)delegate { bgWorker_ProgressChanged(sender, e); }); ```
The Delegate class is the base class for delegate types. However, only the system and compilers can derive explicitly from the Delegate class or from the MulticastDelegate class. It is also not permissible to derive a new type from a delegate type. **The Delegate class is not considered a delegate type**; it is a class used to derive delegate types. Source -- [MSDN](http://msdn.microsoft.com/en-us/library/system.delegate.aspx) Hence the need for the explicit cast to a derived-from-Delegate type. You'd encounter this particular compiler error when you pass an anonymous method for a parameter of System.Delegate type - fortunately this is a rare scenario. That's just too much flexibility. ``` delegate void MyDelegate(); static void DoSomething_Flexible(Delegate d) { d.DynamicInvoke(); } static void DoSomething_Usable(MyDelegate d) { d(); } static void Main(string[] args) { // requires explicit cast else compile error Error "Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type DoSomething_Flexible((MyDelegate) delegate { Console.WriteLine("Flexible is here!"); }); // Parameter Type is a .NET Delegate, no explicit cast needed here. DoSomething_Usable(delegate { Console.WriteLine("Usable is here!"); }); } ``` More on this at [this page by Ian Griffith](http://www.interact-sw.co.uk/iangblog/2004/02/16/anondelegates). (See the paras after the Notes header)
You need to tell the compiler what *type* of delegate to create, since `Invoke` (etc) just take `Delegate` (rather than something more specific). To apply to the largest audience, `MethodInvoker` is a handy delegate type ``` BeginInvoke((MethodInvoker) delegate(...) {...}); ``` However... `BackgroundWorker.ProgressChanged` fires on the UI thread automatically - so you don't even need this.
Anonymous methods and delegates
[ "", "c#", ".net", "delegates", ".net-2.0", "anonymous-methods", "" ]
the following linq statement returns a IOrderedEnumerable: ``` var list = from e in ritorno.Elements("dossier") orderby e.Element("name") select e; ``` How can i convert list to XElement? Thanks EDIT list is `IOrderedEnumerable<System.Xml.Linq.XElement>`
Do you want a single XElement to contain all the elements in the sequence? ``` XElement element = new XElement("container", list) ``` (Obviously change "container" to whatever you want the containing element to be called.) If that's *not* what you want, please elaborate.
You could do something like: ``` XElement xml = new XElement("dossiers", from e in ritorno.Elements("dossier") orderby e.Element("name") select new XElement("dossier", e.Value)); ``` which essentially is what Jon was trying to say ( I think).
Convert IOrderedEnumerable to XElement
[ "", "c#", ".net", "linq", "" ]
Without using extensions methods (LINQ). I am restricted to .NET 2.0 unfortunately. (Yeah, it sucks) Looking for something close to O(log(n)). Thanks for your help.
To find the first key that is greater than a given key you could use the list of keys `SortedList<T>.Keys` and perform a [Binary Search](http://en.wikipedia.org/wiki/Binary_search) or [Interpolation Search](http://en.wikipedia.org/wiki/Interpolation_search) on the keys. This will yield `O(log(n))` ([MSDN](http://msdn.microsoft.com/en-us/library/ms132319.aspx) states that a key look up is `O(1)`).
Binary search it for an O(n log n) lookup.
Generic SortedList, How to find the index of the first element that is greater than the search key?
[ "", "c#", "generics", "" ]
Is there a way without using arrays to write the following with a loop: ``` cout<<"This variable c1 ="c1 cout<<"This variable c2 ="c2 cout<<"This variable c3 ="c3 for(i=1,i<8,i++) cout<<"This variable c%d =",i<<**????**<< ``` This is obviously not what I Need to be done but is the easiest example I could think of with the same problem... So what I would like to do is change the variables in the loop, not the output! EDIT: Thanks a lot for all the input, here is a bit more of the code to help illustrate my problem...Im Using Cplex with c++. The loop will not end at seven but when a stop criteria is met ``` static void populatebyrow (IloModel model, IloNumVarArray x, IloRangeArray c) { IloExpr c1(env); IloExpr c2(env); IloExpr c3(env); IloExpr c4(env); c.add(c1>=n); c.add(c2>=n); ... model.add(c); } ``` I Want to add these expressions to an Array called c that will be an input for a model in cplex. Then after I get a result from Cplex I want to add an expression c(i) and solve it again... This until i get the values I want... IloExprArray could also be used somehow, but then I dont know how to add the expressions using this method: ``` for(i= 0,...) { c7 +=x[i]; } ```
If I understand correctly, you are trying to create variable names dynamically. AFAIK this is not possible with C++.
I'd recommend using an array for this. You should not be playing with dynamic variable names in a compiled language. ``` int c[] = {2, 5, 7, 9, 3, 4, 6, 5}; for (int i = 0; i < 8; i++) cout // and so on... ```
change variable name with a loop
[ "", "c++", "" ]
I have a method that returns a value, and I want this value to be the new location of a label in a windows form application. but I'm being told that a label's location is not a variable. objectA is the name of the label. ``` objectA.Location.X = (int)A.position; objectA.Refresh(); ``` how do I do this?
Use the `Left` property to change X coordinate of a `Label` ``` objectA.Left = 100; ```
the Location property is of type Point, which is a value type. Therefore, the property returns a copy of the location value, so setting X on this copy would have no effect on the label. The compiler sees that and generates an error so that you can fix it. You can do that instead : ``` objectA.Location = new Point((int)A.position, objectA.Location.Y); ``` (the call to Refresh is useless)
Update label location in C#?
[ "", "c#", "winforms", "label", "runtime", "" ]
Im trying to know the path of a dll.... several sites says that ive to use System.Reflection.Assembly.GetExecutingAssembly().Location BUT it returns a path in C:\Windows\Microsoft.Net ... etc... \File.Dll and i want c:\MyProyect\MiWeb\Bin\File.Dll any help ?
You can do this using: ``` string file = (new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).LocalPath; ```
The Location of the assembly changes based on redirects and shadow copy. Try using the Codebase property instead.
Get the Assembly path C#
[ "", "c#", ".net", "dll", "assemblies", "" ]
I will be parsing 60GB of text and doing a lot of insert and lookups in maps. I just started using boost::unordered\_set and boost::unordered\_map As my program starts filling in these containers they start growing bigger and bigger and i was wondering if this would be a good idea to pre allocate memory for these containers. something like mymap::get\_allocator().allocate(N); ? or should i just leave them to allocate and figure out grow factors by themselves? the codes look like this ``` boost::unordered_map <string,long> words_vs_frequency, wordpair_vs_frequency; boost::unordered_map <string,float> word_vs_probability, wordpair_vs_probability, wordpair_vs_MI; //... ... ... N = words_vs_frequency.size(); long y =0; float MIWij =0.0f, maxMI=-999999.0f; for (boost::unordered_map <string,long>::iterator i=wordpair_vs_frequency.begin(); i!=wordpair_vs_frequency.end(); ++i){ if (i->second >= BIGRAM_OCCURANCE_THRESHOLD) { y++; Wij = i->first; WordPairToWords(Wij, Wi,Wj); MIWij = log ( wordpair_vs_probability[Wij] / (word_vs_probability[Wi] * word_vs_probability[Wj]) ); // keeping only the pairs which MI value greater than if (MIWij > MUTUAL_INFORMATION_THRESHOLD) wordpair_vs_MI[ Wij ] = MIWij; if(MIWij > maxMI ) maxMI = MIWij; } } ``` Thanks in advance
I would try it both ways, which will let you generate hard data showing whether one method works better than the other. We can speculate all day about which method will be optimal, but as with most performance questions, the best thing to do is try it out and see what happens (and then fix the parts that actually need fixing). That being said, the Boost authors seem to be very smart, so it quite possibly will work fine as-is. You'll just have to test and see.
According to [the documentation](http://www.boost.org/doc/libs/1_37_0/doc/html/boost/unordered_map.html), both `unordered_set` and `unordered_map` have a method ``` void rehash(size_type n); ``` that regenerates the hashtable so that it contains at least `n` buckets. (It sounds like it does what `reserve()` does for STL containers).
optimizing boost unordered map and sets, C++
[ "", "c++", "c++11", "" ]
Is it crucial to close mysql connections efficiency wise, or does it automatically close after php file has run?
From the [documentation](http://us.php.net/function.mysql-connect): > Note: The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling mysql\_close(). If your script has a fair amount of processing to perform after fetching the result and has retrieved the full result set, you definitely should close the connection. If you don't, there's a chance the MySQL server will reach it's connection limit when the web server is under heavy usage. If you can't close the MySQL connection until near the end of the script, it's cleaner though unnecessary to do so explicitly. I'm not certain how fastcgi affects things. [One page](http://blog.andreineculau.com/2009/01/fastcgi-on-dreamhost/) claims that a build of PHP that supports fastcgi will create persistent connections, even for mysql\_connect. This contradicts the documentation in that the connection is closed when the process, rather than the script, ends. Rather than testing it, I'm going to recommend using mysql\_close(). Actually, I recommend using [PDO](http://www.php.net/pdo), if it's available.
Is it crucial? Not so much Is it considered to be a good practice to follow? Yes. I don't see why you wouldn't want to close it.
Is closing the mysql connection important?
[ "", "php", "mysql", "" ]
I have to write an SQL view that returns the time part of a datetime column as a string in the format hhmmss (apparently SAP BW doesn't understand hh:mm:ss). This code is the SAP recommended way to do this, but I think there must be a better, more elegant way to accomplish this ``` TIME = case len(convert(varchar(2), datepart(hh, timecolumn))) when 1 then /* Hour Part of TIMES */ case convert(varchar(2), datepart(hh, timecolumn)) when '0' then '24' /* Map 00 to 24 ( TIMES ) */ else '0' + convert(varchar(1), datepart(hh, timecolumn)) end else convert(varchar(2), datepart(hh, timecolumn)) end + case len(convert(varchar(2), datepart(mi, timecolumn))) when 1 then '0' + convert(varchar(1), datepart(mi, timecolumn)) else convert(varchar(2), datepart(mi, timecolumn)) end + case len(convert(varchar(2), datepart(ss, timecolumn))) when 1 then '0' + convert(varchar(1), datepart(ss, timecolumn)) else convert(varchar(2), datepart(ss, timecolumn)) end ``` This accomplishes the desired result, 21:10:45 is displayed as 211045. I'd love for something more compact and easily readable but so far I've come up with nothing that works.
you could use a user-defined function like: ``` create FUNCTION [dbo].[udfStrippedTime] ( @dt datetime ) RETURNS varchar(32) AS BEGIN declare @t varchar(32) set @t = convert( varchar(32), @dt, 108 ) set @t = left(@t,2) + substring(@t,4,2) RETURN @t END ``` then ``` select dbo.udfStrippedTime(GETDATE()) ``` the logic for the seconds is left as an exercise for the reader
**NOTE:** The question says that the column is of datatype `DATETIME`, not the newer (SQL Server 2008) `TIME` datatype. **ANSWER:** ``` REPLACE(CONVERT(VARCHAR(8),timecolumn,8),':','') ``` Let's unpack that. First, `CONVERT` formats the time portion of the datetime into a varchar, in format 'hh:mi:ss' (24-hour clock), as specified by the format style value of 8. Next, the `REPLACE` function removes the colons, to get varchar in format `'hhmiss'`. That should be sufficient to get a usable string in the format you'd need. --- **FOLLOW-UP QUESTION** (asked by the OP question) **Is an inline expression faster/less server intensive than a user defined function?** The quick answer is yes. The longer answer is: it depends on several factors, and you really need to measure the performance to determine if that's actually true or not. I created and executed a rudimentary test case: ``` -- sample table create table tmp.dummy_datetimes (c1 datetime) -- populate with a row for every minute between two dates insert into tmp.dummy_datetimes select * from udfDateTimes('2007-01-01','2009-01-01',1,'minute') (1052641 row(s) affected) -- verify table contents select min(c1) as _max , max(c1) as _min , count(1) as _cnt from tmp.dummy_datetimes _cnt _min _max ------- ----------------------- ----------------------- 1052641 2007-01-01 00:00:00.000 2009-01-01 00:00:00.000 ``` (Note, the udfDateTimes function returns the set of all datetime values between two datetime values at the specified interval. In this case, I populated the dummy table with rows for each minute for two entire years. That's on the order of a million ( 2x365x24x60 ) rows. Now, user defined function that performs the same conversion as the inline expression, using identical syntax: ``` CREATE FUNCTION [tmp].[udfStrippedTime] (@ad DATETIME) RETURNS VARCHAR(6) BEGIN -- Purpose: format time portion of datetime argument to 'hhmiss' -- (for performance comparison to equivalent inline expression) -- Modified: -- 28-MAY-2009 spencer7593 RETURN replace(convert(varchar(8),@ad,8),':','') END ``` NOTE: I know the function is not defined to be `DETERMINISTIC`. (I think that requires the function be declared with schema binding and some other declaration, like the `PRAGMA` required Oracle.) But since every datetime value is unique in the table, that shouldn't matter. The function is going to have to executed for each distinct value, even if it were properly declared to be `DETERMINISTIC`. I'm not a SQL Server 'user defined function' guru here, so there may be something else I missed that will inadvertently and unnecessarily slow down the function. Okay. So for the test, I ran each of these queries alternately, first one, then the other, over and over in succession. The elapsed time of the first run was right in line with the subsequent runs. (Often that's not the case, and we want to throw out the time for first run.) SQL Server Management Studio reports query elapsed times to the nearest second, in format hh:mi:ss, so that's what I've reported here. ``` -- elapsed times for inline expression select replace(convert(varchar(8),c1,8),':','') from tmp.dummy_datetimes 00:00:10 00:00:11 00:00:10 -- elapsed times for equivalent user defined function select tmp.udfStrippedTime(c1) from tmp.dummy_datetimes 00:00:15 00:00:15 00:00:15 ``` For this test case, we observe that the user defined function is on the order of 45% slower than an equivalent inline expression. HTH
Is there a better way to convert SQL datetime from hh:mm:ss to hhmmss?
[ "", "sql", "sql-server", "t-sql", "sap-bw", "" ]
In MS SQL Server, the Database Properties dialog has the "View Connection Properties" link over on the left. Clicking that brings the "Connection Properties" dialog with properties of the current connection, such as Authentication Method, Network Protocol, Computer Name, etc... Is there a way to get that information programmatically by running a sql query? What would that query look like?
SQL 2005 and after you interrogate [`sys.dm_exec_connections`](http://msdn.microsoft.com/en-us/library/ms181509.aspx). To retrieve your current connection properties you'd run: ``` select * from sys.dm_exec_connections where session_id = @@SPID ``` The field values depend on the protocol used to connect (shared memory, named pipes or tcp) but all contain information about authentication method used, protocol and client net address.
Yes you can, but it depends on which property you are after as the ones displayed in the connection properties UI come from several places. It uses several queries (such as `xp_msver` and `select suser_sname()`) to get hold of some properties, but it also uses the `xp_instance_regread` stored procedure to get hold of some values from the registry of the server. Pretty much everything that is done is management studio when interacting with the SQL engine can be done using SQL. Starting a profiler session and doing the actions in the UI will uncover what (sometimes obscure/undocumented/unsupported) SQL is being run.
Getting current connection properties in SQL Server
[ "", "sql", "sql-server", "database-connection", "" ]
I'm looking for a straightforward Java workflow engine that: * can handle both automated and manual (GUI-based) steps within a workflow * supports long-running, asynchronous tasks * provides support for restarting workflows in the event of a server crash * stores a full audit history of previously executed workflows * provides easy access to this audit history data Possible candidates include the new Drools Flow process engine in Drools 5, and OSWorkflow from OpenSymphony. From my current understanding, OSWorkflow seems to offer more of what I want (Drools Flow doesn't appear to store much in the way of an audit history); however, the most recent release of OSWorkflow was back in early 2006. Is it a mistake to now use OSWorkflow when it's no longer under active development? Does anyone have much experience with either/both of these frameworks? Are there any other workflow engines I should be looking at? All recommendations welcome - thanks.
Just to clarify how Drools Flow supports the requirements you are describing (refering to the [Drools Flow documentation](https://hudson.jboss.org/hudson/job/drools/lastSuccessfulBuild/artifact/trunk/target/docs/drools-flow/html/index.html)): * can handle both automated and manual (GUI-based) steps within a workflow Drools Flow uses (domain-specific) work items (Chapter 8) to interact with external systems. These could be automated services, or a human task management component (Chapter 9) for manual tasks. This human task component is fully pluggable but Drools Flow supports a WS-HumanTask implementation out of the box. Drools 5.1 will include web-based task lists, including custom task forms. * supports long-running, asynchronous tasks The engine allows you to start processes that can live for a long time. The process supports different kinds of wait states (work item nodes, event nodes, event wait nodes, sub-process, etc.) to model long-running processes. External tasks can be integrated synchronously or asynchronously. * provides support for restarting workflows in the event of a server crash The runtime state of all process instances can easily be stored in a data source by turning on persistence (Chapter 5.1). Therefore, all processes can simply be restored in the state they were in after a server crash. * stores a full audit history of previously executed workflows Drools Flow generates events about what is happening during the execution of your processes. By turning on audit logging (Chapter 5.3), these events can be stored in a database, providing a full audit history of whatever happened during execution. * provides easy access to this audit history data The history data is stored using a few simple database tables. These tables can be queried directly, or you could use it for generating custom reports (Chapter 12.1) that show the key performance indicators that are relevant for your application. Furthermore, we believe that a knowledge-oriented approach, allowing you to seamlessly combine processes with rules and event processing whenever necessary, will offer you more power and flexibility compared to aforementioned process-oriented engines. Kris Verlaenen Drools Flow Lead
I've not had any experience with the candidates you've mentioned but judging from the projects that I've worked on it might be worth looking at [jBPM](http://www.jboss.com/products/jbpm/). Quite a few developers I've worked with swear by it and I think it fits your criteria quite nicely.
Experience with Drools Flow and/or OSWorkflow?
[ "", "java", "workflow", "drools", "opensymphony", "osworkflow", "" ]
Are there any issues when passing 'this' to another object in the initializer list in the following code? ``` class Callback { public: virtual void DoCallback() = 0; }; class B { Callback& cb; public: B(Callback& callback) : cb(callback) {} void StartThread(); static void Thread() { while (!Shutdown()) { WaitForSomething(); cb.DoCallback(); } } }; class A : public Callback { B b; public: A() : b(*this) {b.StartThread();} void DoCallback() {} }; ``` If it is unsafe to do that, what's the best alternative?
If you are **extremely** careful this will work fine. You will get into a lot of trouble if you start calling virtual methods or using methods which depend on other objects in the type. But if you're just setting a reference this should work fine. A safer (but not completely safe) alternative is to set b later on once the constructor is completed. This won't eliminate vtable issues but will remove problems like accessing other member variables before they are constructed. ``` class A : public Callback { std::auto_ptr<B> spB; public: A() { spB.reset(new B(this)); spB->StartThread(); } }; ```
If the other class just stores the pointer/reference, like in your case, it is safe. But you have to be sure that the constructors/functions you pass `this` to are not trying to access the referenced object before `A`'s constructor finishes. The `A` object is not fully constructed yet and calling methods of `A` and accessing properties might lead to undefined results.
passing this from constructor initializer list
[ "", "c++", "" ]
I'm using boost::python to embed some python code into an app. I was able to get print statements or other expressions to be evaluated properly, but when I try to import modules, it is not importing and application is exiting. Further the globals() function call in the embedded code gives a runtime error too. ``` #include <boost/python.hpp> using namespace boost; using namespace boost::python; using namespace boost::python::api; int main(void) { Py_Initialize(); object main_module = import("__main__"); object main_namespace = main_module.attr("__dict__"); main_namespace["urllib2"] = import("urllib2"); object ignored = exec( "print 'time'\n", main_namespace); } ``` Here, I've tried to import urllib2 using the boost import function, this compiles and runs properly, but with the following exec statement, it gives an error. ``` object ignored = exec( "print urllib2\n" "print 'time'\n", main_namespace); ``` Or when I remove the boost import function and do the import from within the embedded code also, it gives an error. I tried using a try: except: block but that doesn't work either. Is this because the C++ app isn't able to find the location of the urllib2 py module or something? Is there a way to set the path of the module before trying to import? This is being built only for internal use, so some hard coding of the paths is acceptable. *Edit: More info:* This is what happens. I did a try .. catch and called the PyErr\_Print() when ever there is an exception, and got this as error all the time when there are module imports or even function calls. Error message: ``` Traceback (most recent call last): File "<string>", line 1, in <module> TypeError: 'NoneType' object does not support item assignment ``` Can anyone think of any reason?
That didn't help, but I found a different solution to my problem. My current code looks like this: ``` #include <boost/python.hpp> #include <iostream> using namespace std; using namespace boost; using namespace boost::python; using namespace boost::python::api; int main(void) { Py_Initialize(); boost::python::object http = boost::python::import("urllib2"); try { boost::python::object response = http.attr("urlopen")("http://www.google.com"); boost::python::object read = response.attr("read")(); std::string strResponse = boost::python::extract<string>(read); cout << strResponse << endl; } catch(...) { PyErr_Print(); PyErr_Clear(); } } ``` Anyways, thanks for the answer Jonas
If you haven't already, you need to ``` import sys sys.path.append("/home/user/whatever") ``` That took care of my problems a couple of years ago when embedding boost::python (Python v2.5). Edit: Poked around in old code. Perhaps this does the trick: ``` Py_SetProgramName(argv[0]); Py_InitializeEx(0); ``` Sounds unsure that you should really need the `Py_SetProgramName()`, but I faintly remember some fishy business there.
How do I import modules in boost::python embedded python code?
[ "", "c++", "boost-python", "" ]
I am running Blogengine.Net and have noticed that the tables are all created lower case (table name be\_settings) but a lot of the queries are written mixedcase (Select \* from be\_Settings). This works fine if your MySql instance is running on Windows or set for capatability with Windows. I am getting an error as my hosting provider MySql instance is case sensitive. Is there a setting I can change to fix this error through phpMyAdmin? I don't want to have to fish through all of the code and fix BlogEngine.Net if I don't have to.
If you are trying to solve this for BlogEngine.Net you can easily rename all of the tables to use CamelCase as all of the queries in BlogEngine.Net are written using CamelCase.
Case sensitivity in MySQL table names is specific to the OS. MySQL data is stored in files, which are subject to whatever rules the OS enforces. Linux IS case-sensitive, for example. There is a variable 'lower\_case\_table\_names' that can be manipulated, but it seems like you'd have to recreate all your tables. <http://dev.mysql.com/doc/refman/5.0/en/identifier-case-sensitivity.html>
Change MySql Case sensitivity with phpMyAdmin?
[ "", "c#", ".net", "mysql", "blogengine.net", "" ]
How can I run several PHP scripts from within another PHP script, like a batch file? I don't think include will work, if I understand what include is doing; because each of the files I'm running will redeclare some of the same functions, etc. What I want is to execute each new PHP script like it's in a clean, fresh stack, with no knowledge of the variables, functions, etc. that came before it. **Update**: I should have mentioned that the script is running on Windows, but not on a web server.
You could use the [exec()](http://ca.php.net/manual/en/function.exec.php) function to invoke each script as an external command. For example, your script could do: ``` <?php exec('php -q script1.php'); exec('php -q script2.php'); ?> ``` Exec has some security issues surrounding it, but it sounds like it might work for you.
// use exec <http://www.php.net/manual/en/function.exec.php> ``` <?php exec('/usr/local/bin/php somefile1.php'); exec('/usr/local/bin/php somefile2.php'); ?> ``` In the old days I've done something like create a frameset containing a link to each file. Call the frameset, and you're calling all the scripts. You could do the same with iframes or with ajax these days.
How can I run several PHP scripts from within a PHP script (like a batch file)?
[ "", "php", "" ]
**Description:** the query actually run have 4 results returned,as can be see from below, what I did is just concate the items then return, but unexpectedly,it's null. I think the code is self-explanatory: ``` DELIMITER | DROP FUNCTION IF EXISTS get_idiscussion_ask| CREATE FUNCTION get_idiscussion_ask(iask_id INT UNSIGNED) RETURNS TEXT DETERMINISTIC BEGIN DECLARE done INT DEFAULT 0; DECLARE body varchar(600); DECLARE created DATETIME; DECLARE anonymous TINYINT(1); DECLARE screen_name varchar(64); DECLARE result TEXT; DECLARE cur1 CURSOR FOR SELECT body,created,anonymous,screen_name from idiscussion left join users on idiscussion.uid=users.id where idiscussion.iask_id=iask_id; DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1; SET result = ''; OPEN cur1; REPEAT FETCH cur1 INTO body, created, anonymous, screen_name; SET result = CONCAT(result,'<comment><body><![CDATA[',body,']]></body>','<replier>',if(screen_name is not null and !anonymous,screen_name,''),'</replier>','<created>',created,'</created></comment>'); UNTIL done END REPEAT; CLOSE cur1; RETURN result; END | DELIMITER ; mysql> DELIMITER ; mysql> select get_idiscussion_ask(1); +------------------------+ | get_idiscussion_ask(1) | +------------------------+ | NULL | +------------------------+ 1 row in set (0.01 sec) mysql> SELECT body,created,anonymous,screen_name from idiscussion left join users on idiscussion.uid=users.id where idiscussion.iask_id=1; +------+---------------------+-----------+-------------+ | body | created | anonymous | screen_name | +------+---------------------+-----------+-------------+ | haha | 2009-05-27 04:57:51 | 0 | NULL | | haha | 2009-05-27 04:57:52 | 0 | NULL | | haha | 2009-05-27 04:57:52 | 0 | NULL | | haha | 2009-05-27 04:57:53 | 0 | NULL | +------+---------------------+-----------+-------------+ 4 rows in set (0.00 sec) ``` For those who don't think the code is self-explanatory: **Why the function returns `NULL`?**
Rename your variables and the input parameter, they're ambiguous. This query: ``` SELECT body, created, anonymous, screen_name FROM idiscussion LEFT JOIN users ON idiscussion.uid = users.id WHERE idiscussion.iask_id = iask_id ``` returns your previously declared variables (which are `NULL`), not the table columns. Prepend the variable names and the input parameter name with an underscore. Also you make an extra assignment to result: ``` FETCH cur1 INTO body, created, anonymous, screen_name; SET result = CONCAT(result,'<comment><body><![CDATA[',body,']]></body>','<replier>',if(screen_name is not null and !anonymous,screen_name,''),'</replier>','<created>',created,'</created></comment>'); ``` The handler sets `done` after the `FETCH` fails, but the `result` gets assigned nevertheless. Change your handler to: ``` DECLARE EXIT HANDLER FOR SQLSTATE '02000' RETURN result; ``` Finally: in `MySQL`, this can be done with a single query. There is no need to do it with a function. ``` SELECT GROUP_CONCAT(CONCAT(result,'<comment><body><![CDATA[',body,']]></body>','<replier>',if(screen_name is not null and !anonymous,screen_name,''),'</replier>','<created>',created,'</created></comment>') SEPARATOR '') FROM idiscussion LEFT JOIN users ON idiscussion.uid=users.id WHERE idiscussion.iask_id = @_iask_id ```
Keep in mind that concatenating any string together with a NULL returns NULL. Try this test: ``` mysql> SET @s = 'test string'; mysql> SET @s = CONCAT(@s, '<tag>', NULL, '</tag>'); mysql> SELECT @s; ``` This returns NULL. So as you loop through your cursor, if the `body` or `created` columns are NULL on any row, the `result` becomes NULL. Then on subsequent iterations of the loop anything concatenated with a NULL `result` has no effect; it stays NULL. Try something like this: ``` REPEAT FETCH cur1 INTO body, created, anonymous, screen_name; SET result = CONCAT(result, '<comment><body><![CDATA[', COALESCE(body, ''), ']]></body>', '<replier>', IF(COALESCE(anonymous, 0) != 0, COALESCE(screen_name, ''), ''), '</replier>', '<created>', COALESCE(created, ''), '</created></comment>' ); UNTIL done END REPEAT; ``` The `COALESCE()` function is a useful function in standard SQL. It returns its first non-NULL argument.
Why does this MySQL function return null?
[ "", "sql", "mysql", "stored-functions", "" ]
**EDIT: I got this working now. I have updated the code:** I've looked at a few examples in here, and they all look logical. But I can't get it to work. I have a class that extends my Data Access Layer (DAL). I would like to call parent class to retrieve DB results. What am I doig wrong? DAL class ``` class DAL { protected $username; // the username for db connect protected $pwd; // the pwd to use when connecting protected $host; // the host to which one connects protected $dbname; // the db to select public $conn; // reference to the db link resource public $db; // result of db_select public $query_result; // the stored result of the last query you ran public function __construct() { $this->username = ""; $this->pwd = ""; $this->host = ""; $this->dbname = ""; } public function connect() { /* connects to DB here */ } private function query($sql) { /* Executes the query here and stores the result in $this->query_result */ } public function getAllCountries() { $sql =" SELECT id, name FROM country"; //Process query $this->query($sql); if($this->query_result) return $this->query_result; } } ``` And this is my other class ``` class myOtherClass extends DAL{ public function __construct() { parent::__construct(); parent::connect(); } public function getCountryListBox() { $result = parent::getAllCountries(); if($result) { $selectbox = "<select id='countryListBox' name='countryListBox'>"; while ($row = mysql_fetch_array($result)) { $selectbox .= "<option value='".($row['id'])."'>".($row['name'])."</option>"; } $selectbox .= "</select>"; } else $selectbox = "Countries could not be retrievd from database."; return $selectbox; } } ``` This is the code in my template: ``` $sl = new myOtherClass(); echo '<form id="label_data_form">'; $sl->getCountryListBox(); echo '</form>'; ```
The difference between these: ``` // $result = parent::getAllCountries(); // Like this $result = this->getAllCountries(); // Or like this? ``` .. is probably best explained here: ``` class SuperFoo { function fubar () { echo "superfoo!"; } function fuz () { echo "superfuz!"; } } class SubBar extends SuperFoo { function fubar() { echo "subbar!"; } function demonstrate() { $this->fubar(); // "subbar!" parent::fubar(); // "superfoo!" $this->fuz(); // "superfuz!" parent::fuz(); // "superfuz!" } } $s = new SubBar(); $s->demonstrate(); ``` (okay, maybe not *best* explained..) Unless you particularly want the behaviour defined in the parent class, I'd always use `$this->...` since then you have the option of altering the behaviour if needed. --- The MySQL error seems to be caused by a problem with your SQL - the class inheritance looks to be working fine.
if your class 'myOtherClass' does not implement the 'getAllCountries()' method, the following should work: ``` $result = $this->getAllCountries(); ``` do not forget the $-sign before 'this'!
Problems with parent / inheritance in PHP
[ "", "php", "inheritance", "" ]
I need to check the browser's user-agent to see if it is IE6. However I shouldn't use scriptlets (we have a strict no scriptlets policy) to do this. Currently I use ``` <% String ua = request.getHeader( "User-Agent" ); boolean isMSIE = ( ua != null && ua.indexOf( "MSIE" ) != -1 ); %> <% if( isMSIE ){ %> <div> <% } %> ``` What is the cleanest way to do this using JSTL, EL, etc and not scriptlets?
``` <c:set var="browser" value="${header['User-Agent']}" scope="session"/> ```
``` <c:if test="${fn:contains(header['User-Agent'],'MSIE')}"></c:if> ```
How do you check the browser's user agent in a JSP page using JSTL, EL?
[ "", "java", "jsp", "browser", "cross-browser", "user-agent", "" ]
Complete newbie question here: I'm just playing with C# for the first time and want to make a Windows Forms application which stores some info in a database structure, but obviously don't want to require something like MySQL to be installed on each client's computer. How do I go about this?
You use a database that doesn't require an install. There are a few out there - there's [Microsoft SQL Server Compact](http://www.microsoft.com/Sqlserver/2005/en/us/compact.aspx), which frankly is badly named, as it won't support the more useful SQL functions like stored procedures, views and so on. There's also [VistaDB](http://www.vistadb.net/) which does support stored procs, but requires purchase if you want Visual Studio plugins.
You can use **SQLite**. It doesn't require any installation or server on the client's computers. Here is an [blog](http://www.mikeduncan.com/sqlite-on-dotnet-in-3-mins/) describing how to use it with .NET. It is easy to use, just add a reference to the **System.Data.SQLite.dll**. Here is an open source data provider for .NET: [System.Data.SQLite](http://sqlite.phxsoftware.com/) From [homepage](http://www.sqlite.org/): *"SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. SQLite is the most widely deployed SQL database engine in the world. The source code for SQLite is in the public domain.*"
Serverless Database in C#
[ "", "c#", "database", "" ]
I am using **Ubuntu 9.04** I have installed the following package versions: ``` unixodbc and unixodbc-dev: 2.2.11-16build3 tdsodbc: 0.82-4 libsybdb5: 0.82-4 freetds-common and freetds-dev: 0.82-4 ``` I have configured `/etc/unixodbc.ini` like this: ``` [FreeTDS] Description = TDS driver (Sybase/MS SQL) Driver = /usr/lib/odbc/libtdsodbc.so Setup = /usr/lib/odbc/libtdsS.so CPTimeout = CPReuse = UsageCount = 2 ``` I have configured `/etc/freetds/freetds.conf` like this: ``` [global] tds version = 8.0 client charset = UTF-8 ``` I have grabbed pyodbc revision `31e2fae4adbf1b2af1726e5668a3414cf46b454f` from `http://github.com/mkleehammer/pyodbc` and installed it using "`python setup.py install`" I have a windows machine with *Microsoft SQL Server 2000* installed on my local network, up and listening on the local ip address 10.32.42.69. I have an empty database created with name "Common". I have the user "sa" with password "secret" with full priviledges. I am using the following python code to setup the connection: ``` import pyodbc odbcstring = "SERVER=10.32.42.69;UID=sa;PWD=secret;DATABASE=Common;DRIVER=FreeTDS" con = pyodbc.connect(s) cur = con.cursor() cur.execute(''' CREATE TABLE testing ( id INTEGER NOT NULL IDENTITY(1,1), name NVARCHAR(200) NULL, PRIMARY KEY (id) ) ''') con.commit() ``` Everything **WORKS** up to this point. I have used SQLServer's Enterprise Manager on the server and the new table is there. Now I want to insert some data on the table. ``` cur = con.cursor() cur.execute('INSERT INTO testing (name) VALUES (?)', (u'something',)) ``` That fails!! Here's the error I get: ``` pyodbc.Error: ('HY004', '[HY004] [FreeTDS][SQL Server]Invalid data type (0) (SQLBindParameter)' ``` Since my client is configured to use UTF-8 I thought I could solve by encoding data to UTF-8. That works, but then I get back strange data: ``` cur = con.cursor() cur.execute('DELETE FROM testing') cur.execute('INSERT INTO testing (name) VALUES (?)', (u'somé string'.encode('utf-8'),)) con.commit() # fetching data back cur = con.cursor() cur.execute('SELECT name FROM testing') data = cur.fetchone() print type(data[0]), data[0] ``` That gives no error, but the data returned is not the same data sent! I get: ``` <type 'unicode'> somé string ``` That is, pyodbc won't accept an unicode object directly, but it returns unicode objects back to me! And the encoding is being mixed up! Now for the question: I want code to insert unicode data in a NVARCHAR and/or NTEXT field. When I query back, I want the same data I inserted back. That can be by configuring the system differently, or by using a wrapper function able to convert the data correctly to/from unicode when inserting or retrieving That's not asking much, is it?
I can remember having this kind of stupid problems using odbc drivers, even if that time it was a java+oracle combination. The core thing is that odbc driver apparently encodes the query string when sending it to the DB. Even if the field is Unicode, and if you provide Unicode, in some cases it does not seem to matter. You need to ensure that what is sent by the driver has the same encoding as your Database (not only server, but also database). Otherwise, of course you get funky characters because either the client or the server is mixing things up when encoding/or decoding. Do you have any idea of the charset (codepoint as MS like to say) that your server is using as a default for decoding data? ## Collation has nothing to do with this problem :) See [that MS page](http://msdn.microsoft.com/en-us/library/aa174903(SQL.80).aspx) for example. For Unicode fields, collation is used only to define the sort order in the column, **not** to specify how the data is stored. If you store your data as Unicode, there is an Unique way to represent it, that's the purpose of Unicode: no need to define a charset that is compatible with all the languages that you are going to use :) The question here is "what happens when I give data to the server that is *not* Unicode?". For example: * When I send an UTF-8 string to the server, how does it understand it? * When I send an UTF-16 string to the server, how does it understand it? * When I send a Latin1 string to the server, how does it understand it? From the server perspective, all these 3 strings are only a stream of bytes. The server cannot guess the encoding in which you encoded them. Which means that you *will* get troubles if your odbc client ends up sending *bytestrings* (an encoded string) to the server instead of sending *unicode* data: if you do so, the server will use a predefined encoding (that was my question: what encoding the server will use? Since it is not guessing, it must be a parameter value), and if the string had been encoded using a different encoding, *dzing*, data will get corrupted. It's exactly similar as doing in Python: ``` uni = u'Hey my name is André' in_utf8 = uni.encode('utf-8') # send the utf-8 data to server # send(in_utf8) # on server side # server receives it. But server is Japanese. # So the server treats the data with the National charset, shift-jis: some_string = in_utf8 # some_string = receive() decoded = some_string.decode('sjis') ``` Just try it. It's fun. The decoded string is supposed to be "Hey my name is André", but is "Hey my name is Andrテゥ". é gets replaced by Japanese テゥ Hence my suggestion: you need to ensure that pyodbc is able to send directly the data as Unicode. If pyodbc fails to do this, you will get unexpected results. And I described the problem in the Client to Server way. But the same sort of issues can arise when communicating back from the Server to the Client. If the Client cannot understand Unicode data, you'll likely get into troubles. ## FreeTDS handles Unicode for you. Actually, FreeTDS takes care of things for you and translates all the data to UCS2 unicode. ([Source](http://www.freetds.org/userguide/unicodefreetds.htm)). * Server <--> FreeTDS : UCS2 data * FreeTDS <--> pyodbc : encoded strings, encoded in UTF-8 (from `/etc/freetds/freetds.conf`) So I would expect your application to work correctly if you pass UTF-8 data to pyodbc. In fact, as this [django-pyodbc ticket](http://code.google.com/p/django-pyodbc/issues/detail?id=41) states, django-pyodbc communicates in UTF-8 with pyodbc, so you should be fine. ### FreeTDS 0.82 However, [cramm0](http://code.google.com/p/django-pyodbc/issues/detail?id=41#c1) says that FreeTDS 0.82 is not completely bugfree, and that there are significant differences between 0.82 and the official patched 0.82 version that can be found [here](http://freetds.sourceforge.net/). You should probably try using the patched FreeTDS --- **Edited**: *removed old data, which had nothing to do with FreeTDS but was only relevant to Easysoft commercial odbc driver. Sorry.*
I use UCS-2 to interact with SQL Server, not UTF-8. Correction: I changed the .freetds.conf entry so that the client uses UTF-8 ``` tds version = 8.0 client charset = UTF-8 text size = 32768 ``` Now, bind values work fine for UTF-8 encoded strings. The driver converts transparently between the UCS-2 used for storage on the dataserver side and the UTF-8 encoded strings given to/taken from the client. This is with pyodbc 2.0 on Solaris 10 running Python 2.5 and FreeTDS freetds-0.82.1.dev.20081111 and SQL Server 2008 ``` import pyodbc test_string = u"""Comment ça va ? Très bien ?""" print type(test_string),repr(test_string) utf8 = 'utf8:' + test_string.encode('UTF-8') print type(utf8), repr(utf8) c = pyodbc.connect('DSN=SA_SQL_SERVER_TEST;UID=XXX;PWD=XXX') cur = c.cursor() # This does not work as test_string is not UTF-encoded try: cur.execute('INSERT unicode_test(t) VALUES(?)', test_string) c.commit() except pyodbc.Error,e: print e # This one does: try: cur.execute('INSERT unicode_test(t) VALUES(?)', utf8) c.commit() except pyodbc.Error,e: print e ``` Here is the output from the test table (I had manually put in a bunch of test data via Management Studio) ``` In [41]: for i in cur.execute('SELECT t FROM unicode_test'): ....: print i ....: ....: ('this is not a banana', ) ('\xc3\x85kergatan 24', ) ('\xc3\x85kergatan 24', ) ('\xe6\xb0\xb4 this is code-point 63CF', ) ('Mich\xc3\xa9l', ) ('Comment a va ? Trs bien ?', ) ('utf8:Comment \xc3\xa7a va ? Tr\xc3\xa8s bien ?', ) ``` I was able to put in some in unicode code points directly into the table from Management Studio by the 'Edit Top 200 rows' dialog and entering the hex digits for the unicode code point and then pressing Alt-X
using pyodbc on linux to insert unicode or utf-8 chars in a nvarchar mssql field
[ "", "python", "sql-server", "unicode", "utf-8", "pyodbc", "" ]
I'm using the Qt library to show a slideshow on the second monitor when the user isn't using the second monitor. An example is the user playing a game in the first monitor and showing the slideshow in the second monitor. The problem is that when I open a new window in Qt, it automatically steals the focus from the previous application. Is there any way to prevent this from happening?
It took me a while to find it but I found it: `setAttribute(Qt::WA_ShowWithoutActivating);` This forces the window not to activate. Even with the `Qt::WindowStaysOnTopHint` flag
If you want to make floating preview box/ any other widget just use below ``` thumbnail = new QLabel; thumbnail->setAttribute(Qt::WA_ShowWithoutActivating); thumbnail->setParent(0); thumbnail->setWindowFlags(Qt::Tool | Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint); ``` Qt::Tool is important flag to make it work. I mean not stealing focus.
Show window in Qt without stealing focus
[ "", "c++", "qt", "focus", "window-management", "active-window", "" ]
I'm trying to change the description of an existing SharePoint group which shouldn't be a really tough job but unfortunately it doesn't work as expected. After running the corresponding method the group's description stays the same as before. Here is the code I use to change the description: ``` private void ResetGroupDescription(SPWeb rootWeb, string groupName, string groupDescription) { rootWeb.AllowUnsafeUpdates = true; SPGroup group = rootWeb.SiteGroups[groupName]; group.Description = groupDescription; group.Update(); rootWeb.Update(); rootWeb.AllowUnsafeUpdates = false; // Code-Update SPGroup checkGroup = rootWeb.SiteGroups[groupName]; Trace.WriteLine(checkGroup.Description); } ``` **UPDATE:** I added some more lines of code to my method and fetch the group I altered before one more time to check its description property. This shows me that the group's description was changed as expected. But when I try to validate this by checking the group's description on the group settings page (UI) of the corresponding site collection, the group's description is still the old value. **UPDATE 2:** So I did some more testing on that issue and try to change the title of the group instead of the its description. Strange to say, but this one works perfect. The renaming of the group is shown in the UI immediately.
I found a solution in another forum. The description shown in the UI is stored within the UserInformationList. The following code changes the group's description. ``` SPGroup g = web.SiteGroups["GroupName"]; SPFieldMultiLineText text = (SPFieldMultiLineText)web.SiteUserInfoList.Fields[SPBuiltInFieldId.Notes]; SPListItem groupItem = web.SiteUserInfoList.GetItemById(g.ID); groupItem[text.InternalName]= groupDescription; groupItem.Update(); ```
2 things: Do you want to change the description or the name of the group? There's a Name and a Description property.... Have you tried running it as a different user? i.e. SPSecurity.RunWithElevatedPrivileges.
Change description of a SharePoint group
[ "", "c#", "sharepoint", "" ]
I'll do some work on a line separated string. Which one will be faster, to split the text via String.split first and then walk on the resultant array or directly walk the whole text via a reg exp and construct the final array on the way?
Well, the best way to get your answer is to just take 2 minutes and write a loop that does it both ways a thousand times and check firebug to see which one is faster ;) I've had to optimize a lot of string munging while working on MXHR and in my experience, plain String methods are significantly faster than RegExps in current browsers. Use RegExps on the shortest Strings possible and do everything you possibly can with String methods. For example, I use this little number in my current code: ``` var mime = mimeAndPayload.shift().split('Content-Type:', 2)[1].split(";", 1)[0].replace(' ', ''); ``` It's ugly as hell, but believe it or not it's significantly faster than the equivalent RegExp under high load.
While this is 2½ years late, hopefully this helps shed some light on the matter for any future viewers: <http://jsperf.com/split-join-vs-regex-replace> (Includes benchmarks results for multiple browsers, as well the functional benchmark code itself)
Performance question: String.split and then walk on the array, or RegExp?
[ "", "javascript", "performance", "" ]
I have code like this: ``` <% foreach (var item in Model) { %> <tr> <td> <%= Html.Encode(item.Title) %> </td> <td> <%= Html.Encode(item.Capacity) %> </td> <td> <%= Html.Encode(item.Count) %> </td> </tr> <% } %> ``` My problem: Depending on user settings any combination of these columns (Title, Capacity, and/or Count) may be set to not show. How would I create this condition in my code?
On the controller side, you can store the settings in ViewData: ``` base.ViewData["TitleVisible"] = false; ``` ... in the view: ``` <% foreach (var item in Model) { %> <tr> <% if ((bool)ViewData["TitleVisible"]){ %> <td> <%= Html.Encode(item.Title) %> </td> <%}%> <td> <%= Html.Encode(item.Capacity) %> </td> <td> <%= Html.Encode(item.Count) %> </td> </tr> <% } %> ```
> Depending on user settings any > combination of these columns (Title, > Capacity, and/or Count) may be set to > not show. There are plenty of ways you can do this. Depends on how you record and store these conditions. ``` <%if(item.ShowTitle){%> <td> <%= Html.Encode(item.Title) %> </td> <%}%> ``` or ``` <%if(Session.Current.ShowTitle){%> <td> <%= Html.Encode(item.Title) %> </td> <%}%> ``` or create a helper that decides what to show in code: ``` <% foreach (var item in Model) { Html.CreateItem(item); }%> ``` or one of many other ways you could do it.
C# MVC: Optional columns in grid (foreach)
[ "", "c#", "asp.net-mvc", "" ]
I need to validate a `textbox` input and can only allow decimal inputs like: `X,XXX` (only one digit before decimal sign and a precision of 3). I'm using C# and try this `^[0-9]+(\.[0-9]{1,2})?$`?
``` ^[0-9]([.,][0-9]{1,3})?$ ``` It allows: ``` 0 1 1.2 1.02 1.003 1.030 1,2 1,23 1,234 ``` BUT NOT: ``` .1 ,1 12.1 12,1 1. 1, 1.2345 1,2345 ```
There is an alternative approach, which does not have I18n problems (allowing ',' or '.' but not both): [`Decimal.TryParse`](http://msdn.microsoft.com/library/9zbda557). Just try converting, ignoring the value. ``` bool IsDecimalFormat(string input) { Decimal dummy; return Decimal.TryParse(input, out dummy); } ``` This is significantly faster than using a regular expression, see below. (The overload of [`Decimal.TryParse`](http://msdn.microsoft.com/library/ew0seb73) can be used for finer control.) --- Performance test results: Decimal.TryParse: 0.10277ms, Regex: 0.49143ms Code (`PerformanceHelper.Run` is a helper than runs the delegate for passed iteration count and returns the average `TimeSpan`.): ``` using System; using System.Text.RegularExpressions; using DotNetUtils.Diagnostics; class Program { static private readonly string[] TestData = new string[] { "10.0", "10,0", "0.1", ".1", "Snafu", new string('x', 10000), new string('2', 10000), new string('0', 10000) }; static void Main(string[] args) { Action parser = () => { int n = TestData.Length; int count = 0; for (int i = 0; i < n; ++i) { decimal dummy; count += Decimal.TryParse(TestData[i], out dummy) ? 1 : 0; } }; Regex decimalRegex = new Regex(@"^[0-9]([\.\,][0-9]{1,3})?$"); Action regex = () => { int n = TestData.Length; int count = 0; for (int i = 0; i < n; ++i) { count += decimalRegex.IsMatch(TestData[i]) ? 1 : 0; } }; var paserTotal = 0.0; var regexTotal = 0.0; var runCount = 10; for (int run = 1; run <= runCount; ++run) { var parserTime = PerformanceHelper.Run(10000, parser); var regexTime = PerformanceHelper.Run(10000, regex); Console.WriteLine("Run #{2}: Decimal.TryParse: {0}ms, Regex: {1}ms", parserTime.TotalMilliseconds, regexTime.TotalMilliseconds, run); paserTotal += parserTime.TotalMilliseconds; regexTotal += regexTime.TotalMilliseconds; } Console.WriteLine("Overall averages: Decimal.TryParse: {0}ms, Regex: {1}ms", paserTotal/runCount, regexTotal/runCount); } } ```
Regular expression for decimal number
[ "", "c#", "regex", "decimal", "" ]
In my div i have a child div of class "someClass". I want to access that child by classname, not id. EDIT: Only in this particular div, not all the other divs with same classname
``` var childOfNamedDiv = $('#namedDiv>.someClass') ```
``` var div = $('.someClass'); ``` See [jQuery Selectors](http://docs.jquery.com/Selectors).
How to access specific div child of certain class?
[ "", "javascript", "jquery", "" ]
Is there a way to read Open Type fonts in Java the same way as I do with TrueType fonts? This works perfectly for TTF but I did not figure out yet how to do the same with Open Type fonts. ``` Font f = Font.createFont( Font.TRUETYPE_FONT, new FileInputStream("f.ttf") ); ``` Please note I cannot rely on installed fonts. I provide the font with my program but don't want to install it system-wide.
I don't think there is Open Type Font support in java (not free atleast), iText claimed to have such support, tried it a few month ago and it didn't work, what worked for me is a program called FontForge which I used to create a ttf from the otf which I then used.
[Java OpenType font support depends on your OS and JDK version.](http://mindprod.com/jgloss/opentype.html#JAVASUPPORT) Prior to Java 6, you can only use TrueType flavored OpenType fonts. With Java 6 you can use all OpenType fonts but you won't benefit from advanced typographic features like ligatures.
How to use Open Type Fonts in Java?
[ "", "java", "fonts", "opentype", "" ]
I have an ASP.Net MVC application with a model which is several layers deep containing a collection. I believe that the view to create the objects is all set up correctly, but it just does not populate the collection within the model when I post the form to the server. I have a piece of data which is found in the class hierarchy thus: ``` person.PersonDetails.ContactInformation[0].Data; ``` This class structure is created by LinqToSQL, and ContactInformation is of type `EntitySet<ContactData>`. To create the view I pass the following: ``` return View(person); ``` and within the view I have a form which contains a single text box with a name associated to the above mentioned field: ``` <%= Html.TextBox("person.PersonDetails.ContactInformation[0].Data")%> ``` The post method within my controller is then as follows: ``` [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create (Person person) { //Do stuff to validate and add to the database } ``` It is at this point where I get lost as person.PersonDetails.ContactInformation.Count() ==0. So the ModelBinder has created a ContactInformation object but not populated it with the object which it should hold (i.e ContactData) at index 0. My question is two fold: 1. Have I taken the correct approach.. i.e. should this work? 2. Any ideas as to why it might be failing to populate the ContactInformation object? Many thanks, Richard
I think that your model is too complex for the default model binder to work with. You could try using multiple parameters and binding them with prefixes: ``` public ActionResult Create( Person person, [Bind(Prefix="Person.PersonDetails")] PersonDetails details, [Bind(Prefix="Person.PersonDetails.ContactInformation")] ContactInformation[] info ) { person.PersonDetails = details; person.PersonDetails.ContactInformation = info; ... } ``` Or you could develop your own custom model binder that would understand how to derive your complex model from the form inputs.
If a property is null, then the model binder other could not find it or could not find values in the submitted form necessary to make an instance of the type of the property. For example, if the property has a non-nullable ID and your form does not contain any data for that ID , the model binder will leave the property as null since it cannot make a new instance of the type without knowing the ID. In other words, to diagnose this problem you must carefully compare the data in the submitted form (this is easy to see with Firebug or Fiddler) with the structure of the object you are expecting the model binder to populate. If any required fields are missing, or if the values are submitted in such a way that they cannot be converted to the type of a required field, then the entire object will be left null.
ASP.Net MVC - model with collection not populating on postback
[ "", "c#", "asp.net-mvc", "" ]
If I use "-O2" flag, the performance improves, but the compilation time gets longer. How can I decide, whether to use it or not? Maybe O2 makes the most difference in some certain types of code (e.g. math calculations?), and I should use it only for those parts of the project? EDIT: I want to emphasize the fact that setting -O2 for all components of my project changes the total compilation time from 10 minutes to 30 minutes.
I would recommend using -O2 most of the time, benefits include: * Usually reduces size of generated code (unlike -O3). * More warnings (some warnings require analysis that is only done during optimization) * Often measurably improved performance (which may not matter). If release-level code will have optimization enabled, it's best to have optimization enabled throughout the development/test cycle. Source-level debugging is more difficult with optimizations enabled, occasionally it is helpful to disable optimization when debugging a problem.
I'm in bioinformatics so my advice may be biased. That said, I *always* use the **`-O3`** switch (for release and test builds, that is; not usually for debugging). True, it has certain disadvantages, namely increasing compile-time and often the size of the executable. However, the first factor can be partially mitigated by a good build strategy and other tricks reducing the overall build time. Also, since most of the compilation is really I/O bound, the increase of compile time is often not *that* pronounced. The second disadvantage, the executable's size, often simply doesn't matter at all.
When to use -O2 flag for gcc?
[ "", "c++", "unix", "optimization", "gcc", "" ]
Simply querying running jobs using something like ``` select * from dba_jobs_running; ``` works fine when executed in my sqldevelopers SQL console. However, it does not work, when having exactly the same statement within a procedure. Compilation fails with ``` PL/SQL: ORA-00942: table or view does not exist ``` Any ideas? Is there something like a scope to be considered? Any suggestions are highly appreciated, thanks in advance :)
You probably need to do a direct GRANT of DBA\_JOBS\_RUNNING to the user that owns the procedure. Doing a GRANT via a role won't work.... the grant needs to be explicit. EDIT: Doing a SELECT from within a procedure requires subtly different permissions to doing a SELECT from outside a procedure (e.g. in SQL-Developer). The user that owns a procedure must have been explicitly granted rights to the table or view... if running a query from outside a view this is not the case (you can be granted the permission through a role for example) You need to connect as SYS and go: ``` GRANT SELECT ON SYS.DBA_JOBS_RUNNING TO <user-that-owns-proc>; ```
Procedures are executed without roles. One way to see if you can run a command in a procedure is to execute: ``` SQL> set role none; Role set ``` You will have the same set of rights as your procedures: ``` SQL> SELECT * FROM dba_jobs_running; SELECT * FROM dba_jobs_running ORA-00942: table or view does not exist ``` You have to grant select on the view directly to the user: ``` SQL> -- with dba account SQL> grant select on dba_jobs_running to a; Grant succeeded ``` You will then be able to compile the procedure: ``` SQL> -- with application schema SQL> CREATE OR REPLACE PROCEDURE test_dba AS 2 BEGIN 3 FOR cc IN (SELECT * FROM dba_jobs_running) LOOP 4 NULL; 5 END LOOP; 6 END test_dba; 7 / Procedure created ```
dba_jobs_running: table or view does not exist when trying to access from procedure
[ "", "sql", "oracle", "stored-procedures", "plsql", "ora-00942", "" ]
I have ``` <a href="test.php?id=2" class="confirm_delete">Click to proceed</a> ``` and following javascript. When I click on above link it displays the dialog box with 2 buttons. "return false;" stops the default event of link tag. But I need the functionality in which when I click "Yes, delete" to take me to other page by choosing href value of a onclicked anchor. I tried alert($(this).attr('id')); (as I thought I could pick up HREF value using "this.attr('href')") but it displays "dialog". How do I make it work so that when I click on a link having class name "confirm\_delete" it displays me dialog, and if I click cancel it stays on the page otherwise takes me to page according to href value. ``` $(".confirm_delete").click(function(){ $('<div id="dialog">Are you sure you want to delete?</div>').appendTo('body'); $("#dialog").dialog({ bgiframe: true, resizable: false, height:140, modal: true, overlay: { backgroundColor: '#000', opacity: 0.5 }, buttons: { 'Yes, Delete all items in recycle bin': function() { $(this).dialog('close'); $(this).remove(); alert($(this).attr('id')); }, Cancel: function() { $(this).dialog('close'); $(this).remove(); } } }); return false; }); ``` Thank you.
OK, I can retrieve value of HREF by **var url = $(this).attr('href');** just after the $(".confirm\_delete").click(function(){ line. It gives me "test.php?id=123" Only thing left is create/retrieve full url and redirecting to that url. Thanks
First off: try not to use underscores in class names. I've read somewhere they may cause problemsn... Well, here: ``` $('a.confirm-delete').click( function(event) { if( !confirm('are you sure you want to go?') ) return false; }); ``` here I've usedd the javascript confirm dialog. You can easily replace that with a jquery modal dialog. jrh
how to retrieve href value for an onclick event based on "class" selector in Javascript?
[ "", "javascript", "jquery", "onclick", "" ]
I use a `JTable` which has its own cell renderer and cell editor. Say, this table contains 2 columns and x rows: The first column contains a boolean value, its own cell rendering and cell editor (a radiobutton) The second column contains a string value, its own cell renderer: it makes it bold when the first column of the current row is set to true (radiobutton checked) All the values are correctly updated by the editor but the 2nd row does not become bold when the radio button is set to true... I have to check a radio button from a different row to see the changes Where can I fire thoses changes ? Cheers and thanks for your help --- *RadiobuttonTableCellEditor.java* ``` public class RadiobuttonTableCellEditor extends DefaultCellEditor implements ItemListener { JRadioButton rb = new JRadioButton(); public RadiobuttonTableCellEditor(JCheckBox pCheckBox) { super(pCheckBox); } public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { if (value == null) return null; rb.addItemListener(this); rb.setSelected((Boolean)value); return rb; } public void itemStateChanged(ItemEvent e) { super.fireEditingStopped(); } public Object getCellEditorValue() { rb.removeItemListener(this); return rb.isSelected(); } } ```
In your table model whenever your value changes you have to fire appropriate event. If your model is inherited from `AbstractTableModel` you can use several `fireXXX` methods. My guess is you should call them from `setValueAt` method. If you know exact column and row - you can call `fireTableCellUpdated`, otherwise you can you probably have to use `fireTableChanged` since you have to update different column. And of course you renderer should properly render new value.
I guess it could help people with a similar problem, make a `true` radiobutton unique in a row, you'll have to extend the `DefaultTableModel` to modify its behaviour especially the `setValueAt` method Cheers --- ``` /** * When <code>column</code> is the column that contains the Boolean (in fact the radio button): * If aValue == false and that it had a previous value set to true we don't do anything * If aValue == true and that it had a previous value set to false, we set all the other booleans to false and this one to true */ @Override public void setValueAt(Object aValue, int row, int column) { if (column == colonneBoutonradio) { if (((Boolean)aValue && !(Boolean)super.getValueAt(row, column))) for (int i = 0; i < this.getRowCount(); i++) // i==row permet de vérifier si la ligne courante est celle à modifier (et donc celle à mettre à true) super.setValueAt(i==row, i, colonneBoutonradio); } else super.setValueAt(aValue, row, column); } ```
Updating cell renderer after a DefaultCellEditor derived instance does its job
[ "", "java", "swing", "jtable", "" ]
this is my sql problem - there are 3 tables: ``` Names Lists ListHasNames Id Name Id Desc ListsId NamesId =-------- ------------ ---------------- 1 Paul 1 Football 1 1 2 Joe 2 Basketball 1 2 3 Jenny 3 Ping Pong 2 1 4 Tina 4 Breakfast Club 2 3 5 Midnight Club 3 2 3 3 4 1 4 2 4 3 5 1 5 2 5 3 5 4 ``` Which means that Paul (Id=1) and Joe (Id=2) are in the Football team (Lists.Id=1), Paul and Jenny in the Basketball team, etc... Now I need a SQL statement which returns the Lists.Id of a specific Name combination: In which lists are Paul, Joe and Jenny the only members of that list ? Answer only Lists.Id=4 (Breakfast Club) - but not 5 (Midnight Club) because Tina is in that list, too. I've tried it with INNER JOINS and SUB QUERIES: ``` SELECT Q1.Lists_id FROM ( SELECT Lists_Id FROM names as T1, listhasnames as T2 WHERE (T1.Name='Paul') and (T1.Id=T2.Names_ID) and ( ( SELECT count(*) FROM listhasnames as Z1 where (Z1.lists_id = T2.lists_Id) ) = 3) ) AS Q1 INNER JOIN ( SELECT Lists_Id FROM names as T1, listhasnames as T2 WHERE (T1.Name='Joe') and (T1.Id=T2.Names_ID) and ( (SELECT count(*) FROM listhasnames as Z1 WHERE (Z1.Lists_id = T2.lists_id) ) = 3) ) AS Q2 ON (Q1.Lists_id=Q2.Lists_id) INNER JOIN ( SELECT Lists_Id FROM names as T1, listhasnames as T2 WHERE (T1.Name='Jenny') and (T1.Id=T2.Names_ID) and ( (SELECT count(*) FROM listhasnames as Z1 WHERE (Z1.Lists_id = T2.lists_id) ) = 3) ) AS Q3 ON (Q1.Lists_id=Q3.Lists_id) ``` Looks a little bit complicated, uh? How to optimize that? I need only that Lists.Id in which specific names are in (and only these names and nobody else). Maybe with SELECT IN? Regards, Dennis
``` SELECT ListsId FROM ListHasNames a WHERE NamesId in (1, 2, 3) AND NOT EXISTS (SELECT * from ListHasNames b WHERE b.ListsId = a.ListsId AND b.NamesId not in (1, 2, 3)) GROUP BY ListsId HAVING COUNT(*) = 3; ``` **Edit**: Corrected thanks to Chris Gow's comment; the subselect is necessary to exclude lists that have other people on them. **Edit 2** Corrected the table name thanks to Dennis' comment
Using Carl Manaster's solution as a starting point I came up with: ``` SELECT listsid FROM listhasnames GROUP BY listsid HAVING COUNT(*) = 3 INTERSECT SELECT x.listsid FROM listhasnames x, names n WHERE n.name IN('Paul', 'Joe', 'Jenny') AND n.id = x.namesid ```
How to optimize m:n relation query on 3 tables
[ "", "sql", "database-design", "relation", "" ]
For example, I have an URL that looks for an image like this: > <http://example.com/img/foo.png> > <http://example.com/img/interface/menu/bar.png> > <http://example.com/static/users/avatars/small/3k5jd355swrx221.jpg> I don't want to redirect those. They should just pass through. But then, I have URLs like this: > <http://example.com/register/> > <http://example.com/my_account/my_picture/> > <http://example.com/contact/email/> All such URLs that don't request for an .png or .jpeg should be redirected to: > <http://example.com/index.php/x> Where x stands for everything after example.com/, so in this example for example: > <http://example.com/register/> to > <http://example.com/index.php/register/> > > <http://example.com/my_account/my_picture/> to > <http://example.com/index.php/my_account/my_picture/> > > <http://example.com/contact/email/> to > <http://example.com/index.php/contact/email/> (AcceptPathInfo is enabled) Is there any way to do that in the .htaccess? I only know how I could do this if I had always something like <http://example.com/someKindOfMarkerHere/stuff/stuff/stuff> but I don't want to have the someKindOfMarker there to detect if it's an URL that has to be rewritten. I don't know how to exclude them.
You can either exclude specific URLs: ``` RewriteEngine on RewriteCond %{REQUEST_URI} !^/index\.php$ RewriteRule !.*\.(jpeg|png)$ index.php%{REQUEST_URI} ``` Or you exclude any existing file: ``` RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php%{REQUEST_URI} ```
``` RewriteEngine On RewriteCond %{REQUEST_FILENAME} ^.+\.png$ [OR] RewriteCond %{REQUEST_FILENAME} ^.+\.jp(e)?g$ RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ index.php/%{REQUEST_URI} [NC,L] ```
How can I redirect every URL that's not requesting an JPEG or PNG image to index.php/x?
[ "", "php", ".htaccess", "mod-rewrite", "" ]
I want to add 1 year to a datetime-type column in every single row in a table. Adding using an UPDATE statement is easy for numeric types. ex: ``` UPDATE TABLE SET NUMBERCOLUMN = NUMBERCOLUMN + 1 ``` I'd like to do the same thing with a DATETIME-type... ``` UPDATE Procrastination SET DropDeadDueDate = DropDeadDueDate + ? ``` ...but I'm not sure what value to use. Is there a numeric value I could use that means "1 year"? Or is there a DATEADD function or similar in SQL Server? ADDITIONAL QUESTION I would like to do this for not one field, but for every field in the database of data type 'datetime'. Is there an easy way to select all fields of type 'datetime' and perform an update of adding x amount of years? I am new to sql so please be gentle...
There is in fact a DATEADD statement in T-SQL, you can find it [here](http://msdn.microsoft.com/en-us/library/ms186819.aspx) ``` UPDATE Procrastination SET DropDeadDueDate = DATEADD(yyyy,1,DropDeadDueDate) ``` EDIT: You could use *year*, *yy*, or *yyyy* for the first argument of DATEADD.
It could be done with a DATEADD() function like this: ``` UPDATE Procrastination SET DropDeadDueDate = DATEADD(yy, 1, DropDeadDueDate) ```
How can I use a SQL UPDATE statement to add 1 year to a DATETIME column?
[ "", "sql", "sql-server", "" ]
I am trying to combine the following two functions into one portable function: ``` void NeedleUSsim::FindIdxRho() { searchTmp = &ninfo->rho; double *p = std::find_if(tplRho_deg, tplRho_deg+sampleDim[2], &NeedleUSsim::GreaterThanOrEqualTo); while(p != tplRho_deg+sampleDim[2]) { idxRho = p - tplRho_deg; p = std::find_if(p+1, tplRho_deg+sampleDim[2], &NeedleUSsim::GreaterThanOrEqualTo); } } void NeedleUSsim::FindIdxDepth() { searchTmp = &ninfo->l; double *p = std::find_if(tplL, tplL+sampleDim[1], &NeedleUSsim::LessThanOrEqualTo); while(p != tplL+sampleDim[1]) { idxL = p - tplL; p = std::find_if(p+1, tplL+sampleDim[1], &NeedleUSsim::LessThanOrEqualTo); } } ``` Ideally, I want the parameters of the function to have tpl member to be passed as a pointer, with the size and rho/l passed as value. searchTmp is a file scope double precision pointer. Is there any easy way of passing &NeedleUSsim::GreaterThanOrEqualTo function as a parameter of the function that I'm trying to write easily? Thanks in advance for the advice.
The simplest way to make your code a bit more generic is the following : ``` template<typename ComparisonType> double* NeedleUSsim::FindIdx(double* containerBegin, double* containerEnd, ComparisonType comparison) { double* p = std::find_if(containerBegin, containerEnd, comparison); double* idx = 0; while(p != containerEnd) { idx = p - containerBegin; p = std::find_if(p+1, containerEnd, comparison); } return idx; } void NeedleUSsim::FindIdxRho() { searchTmp = &ninfo->rho; double* idx = FindIdx(tplRho_deg, tplRho_deg+sampleDim[2], &NeedleUSsim::GreaterThanOrEqualTo); if( idx != 0 ) { idxL = idx; } } void NeedleUSsim::FindIdxDepth() { searchTmp = &ninfo->l; double* idx = FindIdx(tplL, tplL+sampleDim[1], &NeedleUSsim::LessThanOrEqualTo); if( idx != 0 ) { idxRho = idx; } } ```
> Is there any easy way of passing &NeedleUSsim::GreaterThanOrEqualTo function as a parameter of the function that I'm trying to write easily? There's a couple ways to do this. 1. You can pass the function pointer around 2. You can create and pass a function object using run-time polymorphism 3. You can make your common function templated on a function object (compile time polymorphism) The first method is covered above by eJames. ## Option 2 The second method involves wrapping your comparison functions in some function-object hierarchy. A function object is an instance of a class with the () operator overloaded. This makes the instance callable: ``` class IComparator { public: virtual bool operator()(lhs, rhs) = 0; } class CComparatorLessThan : public IComparator { public: virtual bool operator()(lhs, rhs) {...} } class CComparatorGreaterThan : public IComparator { public: virtual bool operator()(lhs, rhs) {...} } ``` Your common function would take an ICompatator reference and the behavior would be dynamically bound at runtime. ## Option 3 The third method involves templatizing instead of creating an object hierarchy ``` template <class Comparator> void foo(...) { ... Comparator comparer; std::find_if(..., comparer); } ``` then calling foo would involve: ``` foo<CComparatorGreaterThan>(...); ``` This eliminates a lot of the runtime overhead of the second solution. Here you don't have to define the base class. You only have to have some kind of class that has operator() overloaded and will return bool.
combining similar functions into one common function involving passing function pointers as parameters
[ "", "c++", "" ]
I'm creating table for defining an individual's [BMI](http://en.wikipedia.org/wiki/Body_mass_index). The chart (as yet) doesn't take input (because I want to make the thing work stand-alone, first), but it does show (on parallel axes) the height in both metres and feet/inches. In order to do this I'm defining the metres' start point and range and then converting the defined metres variables into feet/inches, to do which I've come up with (please don't *laugh*...) the following: ``` <?php $m; // height in m $hInInches = ($m*3.2808399)*12; $hInImp = explode(".",$hInInches); $hInFt = $hInImp[0]; $hInInches = substr(12*$hInImp[1],0,2); ?> ``` I was wondering if anyone has any prettier, more economical, more accurate means by which this could be done, since this is being run inside of a for () loop to generate `x` numbers of rows (defined elswhere), and I'd like (if possible) to reduce the load...
Here is an approach, in psuedo-code: ``` inches_per_meter = 39.3700787 inches_total = round(meters * inches_per_meter) /* round to integer */ feet = inches_total / 12 /* assumes division truncates result; if not use floor() */ inches = inches_total % 12 /* modulus */ ``` You could pull out the `12` to a constant as well...
To me you should avoid the string manipulation functions as derobert already stated. In php the code should be similar to the following one: ``` <?php $m=2; // height in m $hInFeet= $m*3.2808399; $hFeet=(int)$hInFeet; // truncate the float to an integer $hInches=round(($hInFeet-$hFeet)*12); ?> ``` Just two multiply and a subtraction (plus a function call to round) are quite economic, and the code is quite readable too.
Prettifying a conversion from m(metres) to feet(') and inches ('')
[ "", "php", "unit-conversion", "" ]
*sigh* I'm sorry to say that I'm using Intel IPL (Image Processing Library) in some image processing code I'm working on. This is the tale of my struggle with getting my images to rotate correctly. 1. I have a source image. It has a size **(w, h)** which is not necessarily square. 2. It is going to be rotated by angle **theta**. 3. I've calculated the output size required to fit an image of size **(w, h)** rotated by angle **theta**. This size is **(dw, dh)**. I've allocated a destination buffer with that size. 4. I want to rotate the source image by angle **theta** about the source image's center **(w/2, h/2)** and have **that** rotated image be centered in my destination buffer. **iplRotate**() takes 2 shift parameters, **xShift** and **yShift**, which indicate the distance the image should be shifted along the x and y axis after the rotate is performed. The problem is I cannot get iplRotate to center the rotated image in the destination image. It's always off center. My best guess for what xShift and yShift **should be** is the following: * **xShift** = **dw** - **w** * **yShift** = **dh** - **h** But this doesn't work, and I'm not sure what else to do to calculate **xShift** and **yShift**. Does anyone have any suggestions for how to use iplRotate to do what I want? *One last bit of info:* I've attempted to use iplGetRotateShift() to calculate xShift and yShift, again, to no avail. I would imagine that this would work: ``` iplGetRotateShift(dw / 2.0, dh / 2.0, theta, &xShift, &yShift); ``` But it does not. --- **Edit:** I rewrote the code using Intel IPP 6.0 instead of IPL and I'm seeing identical wrong results. I can't imagine that Intel got rotation wrong in 2 different libraries, so I must be doing *something* wrong. --- **Edit:** I tried the following (IPP) code that Dani van der Meer suggested: ``` xShift = (dw - w) / 2.0; yShift = (dh - h) / 2.0; ippiAddRotateShift(w / 2.0, h / 2.0, angle, &xShift, &yShift); ``` Unfortunately, still no luck. That does not work either.
When using iplGetRotateShift you need to specify the center of rotation in the source image. This will work well if the size of the source and destination image is the same. In your case you want an extra shift to center the image in your destination image: ``` xShift = (dw - w) / 2.0; yShift = (dh - h) / 2.0; ``` To combine the two shift you need to use ippiAddRotateShift instead of ippiGetRotateShift. **Note**: These functions refer to the IPP library version 5.3 (the version I have). I am not sure that AddRotateShift is available in IPL. But you mentioned in the question that you tried the same using IPP, so hopefully you can use IPP instead of IPL. You get something like this ``` xShift = (dw - w) / 2.0; yShift = (dh - h) / 2.0; ippiAddRotateShift(w / 2.0, h / 2.0, angle, &xShift, &yShift); ``` If you use these shifts in the call to ippiRotate the image should be centered in the destination image. I hope this helps. **EDIT:** Here is the code I used to test (the change from w to dw and h to dh and the rotation angle are just random): ``` //Ipp8u* dst_p; Initialized somewhere else in the code //Ipp8u* src_p; Initialized somewhere else in the code int w = 1032; int h = 778; int dw = w - 40; // -40 is just a random change int dh = h + 200; // 200 is just a random change int src_step = w * 3; int dst_step = dw * 3; IppiSize src_size = { w, h }; IppiRect src_roi = { 0, 0, w, h }; IppiRect dst_rect = { 0, 0, dw, dh }; double xShift = ((double)dw - (double)w) / 2.0; double yShift = ((double)dh - (double)h) / 2.0; ippiAddRotateShift((double)w / 2, (double)h / 2, 37.0, &xShift, &yShift); ippiRotate_8u_C3R(src_p, src_size, src_step, src_roi, dst_p, dst_step, dst_rect, 37.0, xShift, yShift, IPPI_INTER_NN); ```
If it's still not working for you then can we confirm that the assumptions are valid? In particular point 3. where you calculate dw and dh. Mathematically dw = w \* |cos(theta)| + h \* |sin(theta)| dh = h \* |cos(theta)| + w \* |sin(theta)| so if theta = pi/6 say, then if w = 100 and h = 150 then presumably dw = 162? Does the incorrect position you're getting vary with theta? Presumably it works with theta=0? What about theta=pi/2 and theta=pi/4?
Why is iplRotate() not giving me correct results?
[ "", "c++", "windows", "image-processing", "intel-ipp", "" ]
When defining class attributes through "calculated" names, as in: ``` class C(object): for name in (....): exec("%s = ..." % (name,...)) ``` is there a different way of handling the numerous attribute definitions than by using an exec? getattr(C, name) does not work because C is not defined, during class construction...
How about: ``` class C(object): blah blah for name in (...): setattr(C, name, "....") ``` That is, do the attribute setting after the definition.
``` class C (object): pass c = C() c.__dict__['foo'] = 42 c.foo # returns 42 ```
Class attributes with a "calculated" name
[ "", "python", "exec", "class-attributes", "" ]
I want to build a report that is completely static in size and shape. I'm attempting to mimic a hand-entered report that someone in my organization has been building from a word doc for years. The critical piece appears to be fixing the number of rows that are produced in the various Table grids that fill the page. I would like them to always contain a set number of rows, whether data is present or not. It would seem that if I can just fix the size my tables, then all the other elements will not be forced to move because of stretching repeater sections. All my grids are backed by stored procedures, so I'm open to SQL tricks as well.
Sorry i did miss-read the question. If you know how many rows you need to return (say 20) maybe you could pad some bogus info into your records returned from the stored procedure. You might be able to count the records your query has returned before you send them back, and if you have less than 20 add some bogus ones to the record set, put something like 'NonDisp' or something in them. Then in the report put an iif statement into the cells that checks for this bogus info, if it is found change the cell to display nothing, otherwise show the valid values
Not a direct answer, but perhaps a workaround you might consider: perhaps you can insert a page break after the table grids that have dynamic sizes, so that all elements that follow it have a fixed position (relative to the top of the page).
SSRS - Producing a report that is not dynamic in size
[ "", "sql", "reporting-services", "reporting", "" ]
I want to compare two binary files. One of them is already stored on the server with a pre-calculated CRC32 in the database from when I stored it originally. I know that if the CRC is different, then the files are definitely different. However, if the CRC is the same, I don't know that the files are. So, I'm looking for a nice efficient way of comparing the two streams: one from the posted file and one from the file system. I'm not an expert on streams, but I'm well aware that I could easily shoot myself in the foot here as far as memory usage is concerned.
``` static bool FileEquals(string fileName1, string fileName2) { // Check the file size and CRC equality here.. if they are equal... using (var file1 = new FileStream(fileName1, FileMode.Open)) using (var file2 = new FileStream(fileName2, FileMode.Open)) return FileStreamEquals(file1, file2); } static bool FileStreamEquals(Stream stream1, Stream stream2) { const int bufferSize = 2048; byte[] buffer1 = new byte[bufferSize]; //buffer size byte[] buffer2 = new byte[bufferSize]; while (true) { int count1 = stream1.Read(buffer1, 0, bufferSize); int count2 = stream2.Read(buffer2, 0, bufferSize); if (count1 != count2) return false; if (count1 == 0) return true; // You might replace the following with an efficient "memcmp" if (!buffer1.Take(count1).SequenceEqual(buffer2.Take(count2))) return false; } } ```
I sped up the "memcmp" by using a Int64 compare in a loop over the read stream chunks. This reduced time to about 1/4. ``` private static bool StreamsContentsAreEqual(Stream stream1, Stream stream2) { const int bufferSize = 2048 * 2; var buffer1 = new byte[bufferSize]; var buffer2 = new byte[bufferSize]; while (true) { int count1 = stream1.Read(buffer1, 0, bufferSize); int count2 = stream2.Read(buffer2, 0, bufferSize); if (count1 != count2) { return false; } if (count1 == 0) { return true; } int iterations = (int)Math.Ceiling((double)count1 / sizeof(Int64)); for (int i = 0; i < iterations; i++) { if (BitConverter.ToInt64(buffer1, i * sizeof(Int64)) != BitConverter.ToInt64(buffer2, i * sizeof(Int64))) { return false; } } } } ```
Compare binary files in C#
[ "", "c#", "file", "compare", "" ]
I'm seeking an efficient way to display an SQL table queried via Hibernate in a JTable. ``` Query q = em.createNamedQuery("Files.findAll"); List rl = q.getResultList(); ``` It would probably be preferable to use the List returned by that (In this case, that would make a list of Files objects (where Files is an internal class, **not** java.io.File)), but I won't be picky as long as it is neat. I have one answer I worked up below, but that doesn't work very well. I'd going to end up having to write a TableModel for it if I keep going down this path.
There are a lots and lots of ways to do this, but are you looking for something that would automatically figure out the columns or what? If you used the java reflection pieces you can read the Hibernate annotations to find out the column names and populate the JTable that way... Otherwise this is just a straight forward piece of code that a. creates a JTable and TableModel, and b. populates the display with the database data. EDIT: I **think** this [example may cover walking the annotation tree and processing them](http://java.sys-con.com/node/48539/print). The specifics are the AnnotationProcessorFactory part iirc. EDIT 2: I also found this library which is [built to help lookup annotations at runtime](http://code.google.com/p/reflections/). One of their examples is looking up Entity classes in hibernate to build a resource list - I believe you could do something similar to find classes that that implement @column, or @basic etc. This should allow you via reflection to pretty easily do it, but as I said java's standard library already provides the ability to walk the annotation tree to find out the column names - at which point creating the JTable from that should be very easy to do in a programmatic way. EDIT 3: This code is all that and a bag of chips! From here you should easily be able to walk the list of maps and pull out *all* of the info you want, the value, its class type, the field name for the column headers... Note that it isn't particularly safe.. I've dropped out all of the error code I did while testing to keep it short... ``` List<Map> createTable(List queryResults) { List<Map> r = new LinkedList<Map>(); for (Object o : queryResults) { r.add(entityMap(o)); } return r; } Map entityMap(Object obj) throws Throwable { Map m = new HashMap(); for (Field field : getFields(obj.getClass())) { Method method = getMethod(field); Object value = method.invoke(obj); m.put(field, value); } return m; } List<Field> getFields(Class<?> clazz) { List<Field> fields = new LinkedList<Field>(); for (Field field : clazz.getDeclaredFields()) { Column col = field.getAnnotation(Column.class); if (col != null) fields.add(field); } return fields; } Method getMethod(Field field) throws NoSuchMethodException { Class<?> clazz = field.getDeclaringClass(); String name = "get" + uppercase(field.getName()); Method method = clazz.getMethod(name); return method; } String uppercase(String str) { return str.substring(0,1).toUpperCase() + str.substring(1); } ```
Did you take a look at the org.hibernate.metadata classes. These provide you metadata information about classes and collections. You can also make calls to SessionFactory.getClassMetadata(Class) to get the metadata information for the class in question.
Display Hibernate Query in JTable
[ "", "java", "hibernate", "swing", "" ]
How would you go about implementing the equivellent of a wait until complete method call in Java? Basically what I want to do is hava a method that sends a message over the network to a server application and waits till it gets the appropriate Ack message from the server with either an operation completed successfully or operation failed and an error message. I already have a non blocking version of my method which passes a callback class in which has a method that is called on callback. would it make sense to construct a callback class pass it in to my previous method and then perform a wait operation and on the callback have that class do a notify?
Short answer: Yes. I'm a fan of using what's in the class library already, what you describe sounds a lot like an Observer pattern, for which you have the Observer/Observable interfaces already, assuming you're using J2SE. EDIT: Something was wrong with my coffee :) Obviously, what I meant to say was check out what's in java.util.concurrent package, specifically the Future<> and ExecutorService classes.
Adding a .wait() to your callback class would be the easiest path. It can sit there spinning on some flag until your callback switches it, just be sure to include Thread.yield() or .sleep() in your loop. Saves having to rewrite an alternative blocking comms channel.
Implementing Synchronous network call in java waiting for an ack message?
[ "", "java", "asynchronous", "synchronous", "" ]
How do I restore my data from a backup table `table1_bu` into a new table `new_table1`, which has the same structure? I need to insert all the rows from `table1_bu` into `new_table1`.
``` INSERT INTO new_table1(Id, Field1) SELECT Id, Field1 FROM table1_bu ```
Assuming you want to use the same IDs in the new table: ``` SET IDENTITY_INSERT new_table1 ON; INSERT INTO new_table1 SELECT * FROM table1_bu; SET IDENTITY_INSERT new_table1 OFF; ``` PS: SELECT INTO (as suggested by some) also works, but it's slightly less flexible in my experience. Therefore I've gotten used to this way of doing things :)
Inserting multiple rows in SQL
[ "", "sql", "insert", "backup", "" ]
I have an abstract class with a couple pure virtual functions, and one of the classes I derive from it does not use one of the pure virtual functions: ``` class derivative: public base { public: int somevariable; void somefunction(); }; ``` anyways, when I try to compile it, I get an error (apparently, a class is still considered abstract if derive from an abstract class and don't override all pure virtual functions). Anyways, it seems pointless to define a function ``` int purevirtfunc(){return 0;} ``` just because it needs to be defined through a technicality. Is there anyway to derive a class from an abstract class and not use one of the abstract class's pure virtual functions?
If your derived class doesn't "use" the base class pure virtual function, then either the derived class should not be derived from the base, or the PVF should not be there. In either case, your design is at fault and needs to be re-thought. And no, there is no way of deleting a PVF.
A pure virtual class is an interface, one which your code will expect to be fulfilled. What would happen if you implemented that interface and didn't implement one of the methods? How would the code calling your interface know that you didn't implement the method? Your options are: 1. Implement the method as you describe (making it private would indicate that it shouldn't be used). 2. Change your class hierarchy to take into consideration the design change.
Is there a way to "delete" a pure virtual function?
[ "", "c++", "inheritance", "" ]
In normal C# desktop apss, you can launch a URL by saying: ``` System.Diagnostics.Process.Start("http://www.stackoverflow.com") ``` but System.Diagnostics.Process on windows mobile doesn't seems have that string overload.
This has worked for me in WindowsMobile: ``` try { System.Diagnostics.Process myProcess = new System.Diagnostics.Process(); myProcess.StartInfo.UseShellExecute = true; myProcess.StartInfo.FileName = url; myProcess.Start(); } catch (Exception e) {} ```
Looks like this blog has your solution <http://www.businessanyplace.net/?p=code#startapp> It uses the [CreateProcess](http://msdn.microsoft.com/en-us/library/ms682425.aspx) call
How do you launch a URL in the default browser from within a winmobile application?
[ "", "c#", "windows-mobile", "" ]
The following WPF UserControl called **DataTypeWholeNumber** which works. Now I want to make a UserControl called **DataTypeDateTime** and **DataTypeEmail**, etc. Many of the Dependency Properties will be shared by all these controls and therefore I want to put **their common methods into a BaseDataType** and have each of these UserControls inherit from this base type. However, when I do that, I get the ***error: Partial Declaration may not have different base classes***. So how can I implement inheritance with UserControls so shared functionality is all in the base class? ``` using System.Windows; using System.Windows.Controls; namespace TestDependencyProperty827.DataTypes { public partial class DataTypeWholeNumber : BaseDataType { public DataTypeWholeNumber() { InitializeComponent(); DataContext = this; //defaults TheWidth = 200; } public string TheLabel { get { return (string)GetValue(TheLabelProperty); } set { SetValue(TheLabelProperty, value); } } public static readonly DependencyProperty TheLabelProperty = DependencyProperty.Register("TheLabel", typeof(string), typeof(BaseDataType), new FrameworkPropertyMetadata()); public string TheContent { get { return (string)GetValue(TheContentProperty); } set { SetValue(TheContentProperty, value); } } public static readonly DependencyProperty TheContentProperty = DependencyProperty.Register("TheContent", typeof(string), typeof(BaseDataType), new FrameworkPropertyMetadata()); public int TheWidth { get { return (int)GetValue(TheWidthProperty); } set { SetValue(TheWidthProperty, value); } } public static readonly DependencyProperty TheWidthProperty = DependencyProperty.Register("TheWidth", typeof(int), typeof(DataTypeWholeNumber), new FrameworkPropertyMetadata()); } } ```
Ensure that you have changed the first tag in the xaml to also inherit from your new basetype So ``` <UserControl x:Class="TestDependencyProperty827.DataTypes.DataTypeWholeNumber" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" > ``` becomes ``` <myTypes:BaseDataType x:Class="TestDependencyProperty827.DataTypes.DataTypeWholeNumber" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:myTypes="clr-namespace:TestDependencyProperty827.DataTypes" > ``` --- So, to summarise the complete answer including the extra details from the comments below: * The base class should not include a xaml file. Define it in a single (non-partial) cs file and define it to inherit directly from Usercontrol. * Ensure that the subclass inherits from the base class both in the cs code-behind file and in the first tag of the xaml (as shown above).
``` public partial class MooringConfigurator : MooringLineConfigurator { public MooringConfigurator() { InitializeComponent(); } } <dst:MooringLineConfigurator x:Class="Wave.Dashboards.Instruments.ConfiguratorViews.DST.MooringConfigurator" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:dst="clr-namespace:Wave.Dashboards.Instruments.ConfiguratorViews.DST" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400"> <Grid x:Name="LayoutRoot" Background="White"> </Grid> </dst:MooringLineConfigurator> ```
How can a WPF UserControl inherit a WPF UserControl?
[ "", "c#", "wpf", "xaml", "user-controls", "" ]
I have a PHP page on a website that I'd like to be accessible *only* from another page on that website. If a user clicks a link to the page, or types the page's address, and does not come from the site's domain, I'd like the page to redirect the user to the index. Any ideas?
What you could do is use sessions. make the index set a variable ``` $_SESSION['visitedIndex'] = TRUE; ``` and testing for it in the other pages: ``` if(!$_SESSION['visitedIndex']) { header('location: ....'); } ``` make sure you do this before the first echo.
You could also create an internal service using a $hash = timestamp + internal secret key or your paricular rule. First page has a link <http://www.samesite.com/page_2.php?param=hash> Second page decodes the hash and check the timestamp against a given interval. Otherwise it refuses the display. As only you know the internal key is impossible to fake.
Redirect if link reached from external site
[ "", "php", "redirect", "" ]
I have a solution. I have an interface. I have several classes that implement the interface. I can use "Find All References" in order to find where the interface is implemented, but it also returns results where the interface is the return type, or where a class explicitly implements an interface's method. Is there a better way to quickly/easily find which classes implement the interface?
[Reflector](http://www.red-gate.com/products/reflector/) (which *used* to be free) will show you this; load the dll and find the interface (F3) - expand the "Derived Types" node.
Using VS2010, with [Productivity Power Tools](http://visualstudiogallery.msdn.microsoft.com/d0d33361-18e2-46c0-8ff2-4adea1e34fef) (free) installed: 1. Leave debug mode if necessary 2. Hover over a reference to the interface 3. Expand the drop down that appears 4. "Implemented By"
How can I find which classes implement a given interface in Visual Studio?
[ "", "c#", "visual-studio", "visual-studio-2008", "interface", "" ]
I have a webpage that has a Telerik RadComboBox on the page. One of the properties of this ComboBox is EmptyMessage, which fills the combobox with a message when an item is not selected. I am binding my combobox to a datasource at runtime and for some reason, it wipes this EmptyMessage away. Is there a way to keep my data items in tact and have the empty message there too? And default it to the empty message?
Seems like the accepted answer on Telerik says that you use client side script to prevent the text editing. [Telerik forum page](http://www.telerik.com/community/forums/aspnet-ajax/combobox/how-can-i-show-a-message-at-the-top-of-combobox-like-choose-an-item.aspx) ``` <telerik:Radcombobox ID="RadComboBox1" runat="server" AllowCustomText="True" EmptyMessage="-please select one-"> <Items> <telerik:RadComboBoxItem runat="server" Text="Item1"></telerik:RadComboBoxItem> <telerik:RadComboBoxItem runat="server" Text="Item2"></telerik:RadComboBoxItem> </Items> ``` ``` <script type="text/javascript"> function pageLoad() { var combo = $find("<%= RadComboBox1.ClientID %>"); var input = combo.get_inputDomElement(); input.onkeydown = onKeyDownHandler; } function onKeyDownHandler(e) { if (!e) e = window.event; e.returnValue = false; if (e.preventDefault) { e.preventDefault(); } } </script> ```
``` RadComboBox1.Items.Insert(0, New RadComboBoxItem("Select a continent")) ``` This will add "Select a continent" as the first item in the combobox.
Adding empty string to RadComboBox
[ "", "c#", "asp.net", "vb.net", "telerik", "radcombobox", "" ]
How can I check whether Adobe reader or acrobat is installed in the system? also how to get the version? ( In C# code )
``` using System; using Microsoft.Win32; namespace MyApp { class Program { static void Main(string[] args) { RegistryKey adobe = Registry.LocalMachine.OpenSubKey("Software").OpenSubKey("Adobe"); if(null == adobe) { var policies = Registry.LocalMachine.OpenSubKey("Software").OpenSubKey("Policies"); if (null == policies) return; adobe = policies.OpenSubKey("Adobe"); } if (adobe != null) { RegistryKey acroRead = adobe.OpenSubKey("Acrobat Reader"); if (acroRead != null) { string[] acroReadVersions = acroRead.GetSubKeyNames(); Console.WriteLine("The following version(s) of Acrobat Reader are installed: "); foreach (string versionNumber in acroReadVersions) { Console.WriteLine(versionNumber); } } } } } } ```
The only solution which works for me is: ``` var adobePath = Registry.GetValue( @"HKEY_CLASSES_ROOT\Software\Adobe\Acrobat\Exe", string.Empty, string.Empty); ``` Then I check if `adobePath != null` then Adobe reader is installed. This way I will get also the path to the acrobat reader executable.
Check Adobe Reader is installed (C#)?
[ "", "c#", "adobe-reader", "" ]
Take a look at [setAccessible](https://stackoverflow.com/questions/34571/whats-the-best-way-of-unit-testing-private-methods) - a way in Java to let you call private methods by reflections. Why didn't .NET implement such a feature yet?
[Here](https://web.archive.org/web/20090517053247/http://www.capdes.com/2007/02/example_call_private_method_w.html) is an example of doing that in .NET ``` using System; using System.Reflection; using System.Collections.Generic; public class MyClass { public static void Main() { try { Console.WriteLine("TestReflect started."); TestReflect test = new TestReflect(); Console.WriteLine("TestReflect ended."); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } ConsoleKeyInfo cki; do { Console.WriteLine("Press the 'Q' key to exit."); cki = Console.ReadKey(true); } while (cki.Key != ConsoleKey.Q); } } public class TestReflect { public TestReflect() { this.GetType().GetMethod("PublicMethod").Invoke(this, null); this.GetType().GetMethod("PrivateMethod", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(this, null); } public void PublicMethod() { Console.WriteLine("PublicMethod called"); } private void PrivateMethod() { Console.WriteLine("FTW!one1"); } } ```
You can use reflection to call private methods, though it isn't as straight forward as calling public methods. We've done this before for unit testing and have used the following posts as a how-to reference: <http://www.emadibrahim.com/2008/07/09/unit-test-private-methods-in-visual-studio/> <http://johnhann.blogspot.com/2007/04/unit-testing-private-methods.html>
Why isn't there a parallel to Java's setAccessible in .NET?
[ "", "java", ".net", "reflection", "" ]
I'm working on a simple build script that should get some constants from a java class file and use them as the version numbers in my file names. I use Eclipse and its own Ant, but put *bcel-5.2.jar* in my libs folder and into the classpath for the Ant call. ``` <target name="generate_version" depends="compile"> <loadproperties srcfile="${dir.dest}/MyVersion.class"> <classpath> <fileset dir="${dir.libs}"> <include name="**/bcel*.jar"/> </fileset> </classpath> <filterchain> <classconstants/> </filterchain> </loadproperties> </target> ``` But unfortunatly the ant task *loadproperties* fails: ``` build.xml:46: expected a java resource as source ``` After that I tried to run Ant from outside Eclipse, using this command line: ``` set ANT_HOME=C:\Program Files\Java\ant\apache-ant-1.7.1 "%ANT_HOME%\bin\ant.bat" ``` The result is ``` Buildfile: build.xml init: [echo] Building project. [echo] ant.home: C:\Program Files\Java\ant\apache-ant-1.7.1 [echo] ant.java.version: 1.6 [echo] ant.version: Apache Ant version 1.7.1 compiled on June 27 2008 compile: [javac] Compiling 262 source files to **********\build [javac] Note: Some input files use or override a deprecated API. [javac] Note: Recompile with -Xlint:deprecation for details. [javac] Note: Some input files use unchecked or unsafe operations. [javac] Note: Recompile with -Xlint:unchecked for details. generate_version: BUILD FAILED ********************\ant\build.xml:46: expected a java resource as source ``` I'm really lost now. Is it a bcel error? Is it an Ant incompatibility with my own bcel? One last hint: Removing the bcel classpath entry from the Ant target results in this: ``` Buildfile: build.xml init: [echo] Building project. [echo] ant.home: C:\Program Files\Java\ant\apache-ant-1.7.1 [echo] ant.java.version: 1.6 [echo] ant.version: Apache Ant version 1.7.1 compiled on June 27 2008 compile: [javac] Compiling 262 source files to ********************\build [javac] Note: Some input files use or override a deprecated API. [javac] Note: Recompile with -Xlint:deprecation for details. [javac] Note: Some input files use unchecked or unsafe operations. [javac] Note: Recompile with -Xlint:unchecked for details. generate_version: BUILD FAILED java.lang.NoClassDefFoundError: org/apache/bcel/classfile/ClassParser at org.apache.tools.ant.filters.util.JavaClassHelper.getConstants(JavaClassHelper.java:47) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ``` **UPDATE** After setting the Ant preferences in Eclipse, the error message changed: ``` BUILD FAILED *********************\build.xml:46: org.apache.bcel.classfile.ClassFormatException: is not a Java .class file at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:115) at org.apache.tools.ant.Task.perform(Task.java:348) at org.apache.tools.ant.Target.execute(Target.java:357) at org.apache.tools.ant.Target.performTasks(Target.java:385) at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1329) at org.apache.tools.ant.Project.executeTarget(Project.java:1298) at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41) at org.eclipse.ant.internal.ui.antsupport.EclipseDefaultExecutor.executeTargets(EclipseDefaultExecutor.java:32) at org.apache.tools.ant.Project.executeTargets(Project.java:1181) at org.eclipse.ant.internal.ui.antsupport.InternalAntRunner.run(InternalAntRunner.java:423) at org.eclipse.ant.internal.ui.antsupport.InternalAntRunner.main(InternalAntRunner.java:137) ``` Now I think it's maybe a version conflict between Ant and BCEL. Or BCEL and JDK1.6. Or Eclipse and BCEL and Ant or JDK... I'm lost. --- **ANSWER:** This is the comment found below > I should have mentioned this - you do not need to convert anything. Doc: "since Ant > 1.7, the character encoding ISO-8859-1 is used to convert from characters back to > bytes, so ONE HAS TO USE THIS ENCODING for reading the java class file." This is just a > convention to get round the fact that a character filter is being used on raw bytes. > ant.apache.org/manual/CoreTypes/… Using UTF-8 would be bad! – McDowell
Crap, I knew it! It comes down to file encoding issues. The files are still in ISO-8819-1, but I'm using UTF-8. The project is pretty aged and was created with the wrong encoding in place. Setting the parameter *encoding* in the *javac* and *loadproperties* Task fixes it. ``` <target name="generate_version" depends="compile"> <loadproperties encoding="iso-8859-1" srcfile="${dir.dest}/MyVersion.class"> <filterchain> <classconstants/> </filterchain> </loadproperties> </target> ``` I thought it got changed by our Subversion server, but I think I have to convert every single file to UTF-8 myself now... think that is another question for SO.
The [documentation for *loadproperties*](http://ant.apache.org/manual/Tasks/loadproperties.html) says that the nested *classpath* element is for use with the *resource* attribute - an alternative to using *srcfile*. Add the BCEL jar to your global classpath. In Eclipse, add it as a global entry to your classpath in the [runtime preferences](http://help.eclipse.org/ganymede/topic/org.eclipse.platform.doc.user/reference/ref-antruntimeprefs.htm). On the command line, use the [-lib](http://ant.apache.org/manual/running.html#options) switch. [![alt text](https://i.stack.imgur.com/g1LtZ.png)](https://i.stack.imgur.com/g1LtZ.png) (source: [eclipse.org](http://help.eclipse.org/ganymede/topic/org.eclipse.platform.doc.user/images/Image91_ant_prefs_1.png))
Ant loadproperties failed (bcel error?)
[ "", "java", "ant", "build-process", "bcel", "" ]
I'm writing a toy application that plays with the mouse cursor, and I'm trying to move it programmticly. Using either `Cursor.Position = ...` or Win32 interop calls work fine on a normal machine, but I'm having difficulties getting it to work under VMWare. Does anyone have any suggestions? ### EDIT To clarify: I've got a small windows forms application I've made running inside the VM, it has one button on it, when clicked it is supposed to move the mouse cursor inside the VM. I've used both the Cursor.Position method and the approach that **Wolf5** has suggested.
I have resolved the issue. In a desperate attempt to try *anything* i finally gave up and un-installed the mouse driver from the VM. After a reboot, my toy application works. The device was listed as a VMWare Pointing device, after the reboot it's coming up as an "unknown device", but the mouse still works. Albeit I a little on the nippy side.
Try this instead: ``` [DllImport("user32", SetLastError = true)] private static extern int SetCursorPos(int x, int y); public static void SetMousePos(Point p) { SetMousePos(p.X, p.Y); } public static void SetMousePos(int x, int y) { SetCursorPos(x, y); } ``` Of course you will have to make sure VMWARE has focus in the first place since it cannot set the mouse position of your mouse outside VMWARE.
Programaticly Move Mouse in VMWare C#
[ "", "c#", "mouse", "vmware", "" ]
I wan't to customize the icon displayed within the windows 7 taskbar. When my app is running, I can do it by changing main window icon but, when the app is pinned, the exe's icon is displayed. How can I set the taskbar icon for my app to an icon different from the one embedded within the exe ? Not tried, this [solution](https://stackoverflow.com/questions/219096/how-to-set-the-taskbar-grouping-icon/219128#219128) may work but looks dirty. --- Edit : Our app is compiled once but depending on config file, features are enabled or not so it's a product or another. We do not want to compile one exe for each product. The solution above may not work as many instances of my app can be installed in different pathes (so you end up with the same exe file name but different icons!), is this registry key poorly designed or am I missing something?
**EDIT** The info below is a bit obsolete; all new Windows 7 bits are now available as a managed API, available here: <http://code.msdn.microsoft.com/WindowsAPICodePack> There is a [series of articles](https://web.archive.org/web/20120425185455/http://blogs.microsoft.co.il:80/blogs/sasha/archive/2009/02/12/windows-7-taskbar-apis.aspx?) on the new Taskbar API by the debugging guru [Sasha Goldshtein](https://web.archive.org/web/20131104034659/http://blogs.microsoft.co.il:80/blogs/sasha/). You should have a look at the [Overlay Icons and Progress Bars API](https://web.archive.org/web/20130601234859/http://blogs.microsoft.co.il:80/blogs/sasha/archive/2009/02/16/windows-7-taskbar-overlay-icons-and-progress-bars.aspx). You can download the sample code from [Windows 7 Taskbar Developer Resources](https://learn.microsoft.com/en-us/samples/browse/) on Microsoft Code. What you're looking for is the `IMClient` sample: > The IMClient sample demonstrates how > taskbar overlay icons and taskbar > progress bars can light up an > application’s taskbar button instead > of relying on an additional dialog or > on an icon in the system notification > area (tray). > > [![alt text](https://i.stack.imgur.com/IXn0A.png)](https://i.stack.imgur.com/IXn0A.png) > (source: [microsoft.co.il](https://blogs.microsoft.co.il/blogs/sasha/image_thumb_1DD568AF.png)) > [![alt text](https://i.stack.imgur.com/AHkcv.png)](https://i.stack.imgur.com/AHkcv.png) > (source: [microsoft.co.il](https://blogs.microsoft.co.il/blogs/sasha/image_thumb_70B05613.png)) > [![alt text](https://i.stack.imgur.com/2r8bV.png)](https://i.stack.imgur.com/2r8bV.png) > (source: [microsoft.co.il](https://blogs.microsoft.co.il/blogs/sasha/image_thumb_51C9BC68.png)) I believe this should help you achieve what you want.
When you pin an application to the TaskBar, it simply creates a shortcut in the following directory: ``` C:\Users\<User Name>\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar ``` You should be able to identify where the shortcut is (ie, get KnownFolders and work from there. UserAppData should be the one), and then using P/Invoke (IShellLink), you can alter the icon that the shortcut is setup to use. The machine might need a reboot for this to take effect, but it should work. If you hold down Shift while right-clicking on the pinned application, and select Properties, you can see the Change Icon button for the shortcut. This is basically what you need to emulate with code. All of these things can definately be done with code, but whether you think they're any better than the registry setting is up to you.
Change pinned taskbar icon (windows 7)
[ "", "c#", ".net", "windows-7", "icons", "taskbar", "" ]
I have 100 of .gz files which I need to de-compress. I have couple of questions a) I am using the code given at <http://www.roseindia.net/java/beginners/JavaUncompress.shtml> to decompress the .gz file. Its working fine. Quest:- is there a way to get the file name of the zipped file. I know that Zip class of Java gives of enumeration of entery file to work upon. This can give me the filename, size etc stored in .zip file. But, do we have the same for .gz files or does the file name is same as filename.gz with .gz removed. b) is there another elegant way to decompress .gz file by calling the utility function in the java code. Like calling 7-zip application from your java class. Then, I don't have to worry about input/output stream. Thanks in advance. Kapil
a) Zip is an archive format, while gzip is not. So an entry iterator does not make much sense unless (for example) your gz-files are compressed tar files. What you want is probably: ``` File outFile = new File(infile.getParent(), infile.getName().replaceAll("\\.gz$", "")); ``` b) Do you only want to uncompress the files? If not you may be ok with using GZIPInputStream and read the files directly, i.e. without intermediate decompression. But ok. Let's say you really *only* want to uncompress the files. If so, you could probably use this: ``` public static File unGzip(File infile, boolean deleteGzipfileOnSuccess) throws IOException { GZIPInputStream gin = new GZIPInputStream(new FileInputStream(infile)); FileOutputStream fos = null; try { File outFile = new File(infile.getParent(), infile.getName().replaceAll("\\.gz$", "")); fos = new FileOutputStream(outFile); byte[] buf = new byte[100000]; int len; while ((len = gin.read(buf)) > 0) { fos.write(buf, 0, len); } fos.close(); if (deleteGzipfileOnSuccess) { infile.delete(); } return outFile; } finally { if (gin != null) { gin.close(); } if (fos != null) { fos.close(); } } } ```
Regarding A, the `gunzip` command creates an uncompressed file with the original name minus the `.gz` suffix. See the [man page](http://www.manpagez.com/man/1/gunzip/). Regarding B, Do you need gunzip specifically, or will another compression algorithm do? There's a [java port](http://www.7-zip.org/sdk.html) of the LZMA compression algorithm used by 7zip to create `.7z` files, but it will not handle `.gz` files.
decompress .gz file in batch
[ "", "java", "gzip", "compression", "" ]
it seems that most of the time, the speed gained is not worth it -- is it so? otherwise many people will do it for their most popular page. Is there real benefit of using a C program. I can think of a case where it is not important: when the network bottleneck on the server is quite bigger than the CPU bottleneck, then how fast the program runs becomes less important.
C is an excellent language. But it was designed for systems level programming not making web pages. PHP on the other hand was designed for making web pages. Use the right tool for the right job. In this case PHP. Also you're starting with a faulty premise. Namely that PHP won't be fast enough to deliver the page content. There are a multitude of websites out there that simply disagree with that statement. Maybe there is some corner case out there that C is the only choice for the job but I find it highly unlikely that you are going to run into that scenario.
When you use C as a hammer, everything looks like a thumb. As Jared stated above, use the right tools. You could do it all in C, many have. But the development speed of PHP vs C for the web is something you might look into also. Something that is pretty simple to do in PHP (dynamic array's for example) is something that is not simple in C.
is it worth it to compile a C program and run it instead of PHP page?
[ "", "php", "c", "" ]
Essentially I'm looking for something with the same behavior, configuration, logging levels as log4j, but with some of the missing functionality (e.g. formatted logging — see [here](https://stackoverflow.com/questions/920458/) and [here](https://stackoverflow.com/questions/946730/) for related SO threads.) Current nominees are [slf4j](http://www.slf4j.org/) and [log5j](http://code.google.com/p/log5j/).
I'm inclined toward SLF4J. * allows [parameterized logging](http://www.slf4j.org/faq.html#logging_performance) (formatting) * allows [consolidation of other frameworks](http://www.slf4j.org/legacy.html) (great for apps using many libraries, each logging to a different framework) log5j is good, but does not have near as much market penetration.
since a lot of frameworks already support slf4j you will only have to setup your logging once with slf4j. i use slf4j and it is super-easy to read + use.
Which log4j facade to choose?
[ "", "java", "logging", "log4j", "string-formatting", "" ]
Do "type-safe" and "strongly typed" mean the same thing?
No, not necessarily - although it depends on your definition of the terms, and there are no very clear and widely accepted definitions. For instance, dynamic programming languages are often type safe, but not strongly typed. In other words, there's no compile-time type information determining what you can and can't do with a type, but at execution time the runtime makes sure you don't use one type as if it were another. For example, in C# 4.0, you can do: ``` dynamic foo = "hello"; dynamic length = foo.Length; // Uses String.Length at execution time foo = new int[] { 10, 20, 30 }; length = foo.Length; // Uses Array.Length at execution time dynamic bar = (FileStream) foo; // Fails! ``` The last line is the key to it being type-safe: there's no safe conversion from an int array to a `FileStream`, so the operation fails - instead of treating the bytes of the array object *as if* they were a `FileStream`. EDIT: C# is normally both "strongly typed" (as a language) and type safe: the compiler won't let you attempt to make arbitrary calls on an object, and the runtime won't let you perform inappropriate conversions. I'm not entirely sure where unsafe code fits in - I don't know enough about it to comment, I'm afraid. Dynamic typing in C# 4 allows weakly typed but still type-safe code, as shown above. Note that `foreach` performs an implicit conversion, making it a sort of hybrid: ``` ArrayList list = new ArrayList(); list.Add("foo"); foreach (FileStream stream in list) { ... } ``` This will compile (there was [another question](https://stackoverflow.com/questions/949798) on this recently) but will fail at execution time. Ironically, that's because you're *trying* to be strongly typed with respect to the `stream` variable, which means you have to perform a cast on the result of the iterator.
Good question. Read [this](http://en.wikipedia.org/wiki/Strongly-typed_programming_language) wikipedia entry, here's an extract: > Benjamin C. Pierce, author of Types > and Programming Languages and Advanced > Types and Programming Languages, says, > "I spent a few weeks... trying to sort > out the terminology of "strongly > typed," "statically typed," "safe," > etc., and found it amazingly > difficult.... The usage of these terms > is so various as to render them almost > useless."
Do "type-safe" and "strongly typed" mean the same thing?
[ "", "c#", "types", "" ]
I needed a method to give me all but the last item in a sequence. This is my current implementation: ``` public static IEnumerable<T> SkipLast<T>(this IEnumerable<T> source) { using (IEnumerator<T> iterator = source.GetEnumerator()) { if(iterator.MoveNext()) while(true) { var current = iterator.Current; if(!iterator.MoveNext()) yield break; yield return current; } } } ``` What I need it for is to do something with all the items except the last one. In my case I have a sequence of objects with various properties. I then order them by date, and then I need to do an adjustment to all of them except the most recent item (which would be the last one after ordering). Thing is, I am not too into these enumerators and stuff yet and don't really have anyone here to ask either :p What I am wondering is if this is a good implementation, or if I have done a small or big blunder somewhere. Or if maybe this take on the problem is a weird one, etc. I guess a more general implementation could have been an `AllExceptMaxBy` method. Since that is kind of what it is. The [MoreLinq](http://code.google.com/p/morelinq/wiki/OperatorsOverview) has a `MaxBy` and `MinBy` method and my method kind of need to do the same, but return every item except the maximum or minimum one.
This is tricky, as "last element" isn't a Markov stopping point: you can't tell that you've got to the last element until you try to get the next one. It's doable, but only if you don't mind permanently being "one element behind". That's basically what your current implementation does, and it looks okay, although I'd probably write it slightly differently. An alternative approach would be to use `foreach`, always yielding the previously returned value unless you were at the first iteration: ``` public static IEnumerable<T> SkipLast<T>(this IEnumerable<T> source) { T previous = default(T); bool first = true; foreach (T element in source) { if (!first) { yield return previous; } previous = element; first = false; } } ``` Another option, closer to your code: ``` public static IEnumerable<T> SkipLast<T>(this IEnumerable<T> source) { using (IEnumerator<T> iterator = source.GetEnumerator()) { if(!iterator.MoveNext()) { yield break; } T previous = iterator.Current; while (iterator.MoveNext()) { yield return previous; previous = iterator.Current; } } } ``` That avoids nesting quite as deeply (by doing an early exit if the sequence is empty) and it uses a "real" while condition instead of `while(true)`
If you're using .NET 3.5, I guess you could use: ``` public static IEnumerable<T> SkipLast<T>(this IEnumerable<T> source) { return source.TakeWhile((item, index) => index < source.Count() - 1)) } ```
C#: SkipLast implementation
[ "", "c#", "extension-methods", "ienumerable", "implementation", "" ]
I have a code snippet similar to the one below that I would like to refactor into two different functions each with their own connection (for better maintenance): ``` Dim Conn, Sql, RS Set Conn = Server.CreateObject("ADODB.Connection") Conn.Open ConnString Sql = SELECT * FROM CLIENTS Set RS = Conn.Execute(sql) //'Do something with Clients Set RS = Nothing Sql = SELECT * FROM DEALERS Set RS = Conn.Execute(sql) //'Do something with Dealers Set RS = Nothing Conn.Close Set Conn = Nothing ``` Will having two functions (e.g. GetClients and GetDealers) each opening and closing their own connections have a major performance hit, opposite only opening and closing a single connection as illustrated above? If so, how would you refactor the code?
If I am not mistaken the connections are pooled so it should cost next to nothing to have each function open and close the connections.
1. Don't use select \* but specify columns you need. 2. [Use getrows](http://forums.aspfree.com/code-bank-54/getting-away-from-recordsets-use-getrows-230953.html). 3. Specify what you want to have from the database (Use joins and where clause). When you do all this your code will be optimal.
In Classic ASP, are there major performance consequences of having several connections open and close?
[ "", "sql", "asp-classic", "ado", "sqlconnection", "" ]
Is there any way to search for a particular package/function using keywords in the Python console? For example, I may want to search "pdf" for pdf related tasks.
The `pydoc -k` flag searches the documentation. ``` pydoc -k <keyword> Search for a keyword in the synopsis lines of all available modules. ``` From a terminal, run.. ``` $ pydoc -k pdf ``` ..for example: ``` $ pydoc -k pdf PdfImagePlugin wx.lib.pdfwin PIL.PdfImagePlugin ``` It doesn't search the contents of the documentation, but it searches all module names - if that's not enough, I'd suggest using Google or StackOverflow to search for "Python PDF module" or similar
You can use help to access the docstrings of the different modules you have imported, e.g., try the following: ``` help(math) ``` and you'll get an error, ``` import math help(math) ``` and you will get a list of the available methods in the module, but only AFTER you have imported it. It also works with individual functions, e.g. after importing math try: ``` help(math.sin) ``` To deal with pdf you will probably have to install a third party module. A quick search has led me to this result, which I haven't tried: <http://www.devshed.com/c/a/Python/Python-for-PDF-Generation/>
How to search help using python console
[ "", "python", "" ]
I saw comments in a previous question saying that it is best to use Prototype with Rails. However, my own experience is that Jquery is a superior Javascript library. Being new to Rails, I have not yet investigated how to use Jquery with Rails but I assumed this would work. Is it correct that this may be a problematic combination - especially in relation to Ajax - and that I may need to use Prototype instead?
I've worked on all my projects since 3 years with rails and (exclusively) jquery. Never really encountered any (serious) problems so far. There is a plugin called jrails, which acts as a drop-in replacement for prototype. <http://github.com/aaronchi/jrails/tree/master> Update: with it you can get all of the same default Rails helpers for javascript functionality using
I use both jQuery and Prototype with rails. jQuery for DOM manipulation and thickbox (my favorite light box plugin), but i use prototype for AJAX right now. no particular reason, just haven't wanted to use the jrails plugin yet. im sure i will do this in the future. if you use both, this should be in your head tag: ``` <%= javascript_include_tag 'prototype' %> <%= javascript_include_tag 'jquery' %> <script type="text/javascript"> var $j = jQuery.noConflict(); </script> ``` Then use jQuery with $j
Jquery + Rails problematic, is that true?
[ "", "javascript", "jquery", "ruby-on-rails", "prototypejs", "" ]
I have a script that is being inserted dynamically via another script. The code in that script is wrapped inside the `$(window).load()` event because it requires the images on the page to have all loaded. In some browsers it works fine, but in others it seems not to fire because the page has already finished loading by the time the code is run. Is there any way to check and see whether the page has already finished loading - either via jQuery or JavaScript? (including images) In this situation, I don't have access to the `onload` event of the original document (aside from altering it via the loaded script - but that would seem to present the same problem). Any ideas/solutions/advice would be greatly appreciated!
You could try setting up a handler that's invoked via a timeout that will check the images to see if their properties are available. Clear the timer in the `load` event handler so if the load event occurs first, the timer won't fire. If the properties aren't available, then the load event hasn't fired yet and you know that your handler will eventually be invoked. If they are, then you know that the load event occurred before your handler was set and you can simply proceed. Pseudocode ``` var timer = null; $(function() { $(window).load( function() { if (timer) { clearTimeout(timer); timer = null; } process(); }); timer = setTimeout( function() { if (checkAvailable()) process(); } }, 10*1000 ); // waits 10 seconds before checking }); function checkAvailable() { var available = true; $('img').each( function() { try { if (this.height == 0) { available = false; return false; } } catch (e) { available = false; return false; } }); return available; } function process() { ... do the real work here } ```
I wrote a plugin that may be of some use: <http://plugins.jquery.com/project/window-loaded>
How to tell whether the $(window).load()/window.onload event has already fired?
[ "", "javascript", "jquery", "onload", "" ]
I'm considering the use of `JiBX` for a project that will have to run on both Blackberry and RIM. While it seems like `J2ME` use of `JiBX` has been considered by the community (as per JiBX jira tickets), Android is relatively new. The question is, therefore, this: has anybody had any success (or issues, for that matter) using JiBX on Android, or any other libraries that need to modify your class bytecode at build-time? There have been discussions out there about how such libs should be runnable on Android (as compared to those using runtime bytecode instrumentation), but I haven't seen too many reports about people actually attempting to do this.
Ok, so I've decided to just write xml parsing code on top of XMLPull api, without any fancy tricks. If my schemas get any more complicated than they currently are (and I have time) I'd love to experiment with writing an ANTLR-based XML parser generator to generate actual Java code of the parsers for individual schemas. At the moment, afaik, java generation for mobile is much safer and better than bytecode-generation for mobile.
It will not work since android doesn't execute bytecodes. Android's java runtime uses a register based virtual machine (Dvalik) that executes .dex files instead of class files. In theory you could generate those instead of java bytecodes.
JiBX on Android (or any other build-time bytecode manipulating library)
[ "", "java", "xml", "android", "bytecode", "jibx", "" ]
I tried several Python IDEs (on Windows platform) but finally I found only Eclipse + PyDev meeting my needs. This set of tools is really comfortable and easy to use. I'm currently working on a quite bigger project. I'd like to have a possibility to use CVS or any other version control system which would be installed on my local harddrive (I recently moved my house and don't have yet an access to internet.) It doesn't matter for me if it'd be CVS - can also be any other version control system. It'd be great if it will be not too hard to configure with Eclipse. Can anyone give me some possible solution? Any hints? Regards and thanks in advance for any clues. Please forgive my English ;)
Last time I tried this, Eclipse did not support direct access to local repositories in the same way that command line cvs does because command line cvs has both client and server functionality whereas Eclipse only has client functionality and needs to go through (e.g.) pserver, so you would probably need to have a cvs server running. Turns out that I didn't really need it anyway as Eclipse keeps its own history of all changes so I only needed to do an occasional manual update to cvs at major milestones. [Eventually I decided not to use cvs at all with Eclipse under Linux as it got confused by symlinks and started deleting my include files when it "synchronised" with the repository.]
If you don't mind a switch to Subversion, Eclipse has its SubClipse plugin.
Eclipse + local CVS + PyDev
[ "", "python", "eclipse", "cvs", "pydev", "" ]
I am trying to build an XML document in C# with CDATA to hold the text inside an element. For example.. ``` <email> <![CDATA[test@test.com]]> </email> ``` However, when I get the InnerXml property of the document, the CDATA has been reformatted so the InnerXml string looks like the below which fails. ``` <email> &lt;![CDATA[test@test.com]]&gt; </email> ``` How can I keep the original format when accessing the string of the XML? Cheers
Don't use `InnerText`: use [`XmlDocument.CreateCDataSection`](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.createcdatasection.aspx): ``` using System; using System.Xml; public class Test { static void Main() { XmlDocument doc = new XmlDocument(); XmlElement root = doc.CreateElement("root"); XmlElement email = doc.CreateElement("email"); XmlNode cdata = doc.CreateCDataSection("test@test.com"); doc.AppendChild(root); root.AppendChild(email); email.AppendChild(cdata); Console.WriteLine(doc.InnerXml); } } ```
With `XmlDocument`: ``` XmlDocument doc = new XmlDocument(); XmlElement email = (XmlElement)doc.AppendChild(doc.CreateElement("email")); email.AppendChild(doc.CreateCDataSection("test@test.com")); string xml = doc.OuterXml; ``` or with `XElement`: ``` XElement email = new XElement("email", new XCData("test@test.com")); string xml = email.ToString(); ```
XML CDATA Encoding
[ "", "c#", "xml", "cdata", "" ]
It used to be that within a CodeIgniter model you couldn't access another model. ``` $this->load->model('bar'); $this->bar->something(); ``` Is this still valid, or have they changed it?
Those are some VERY long answers for a simple question. **Short answer:** This is now fully supported. Cross-load away if you feel like it!
I strongly disagree with the notion that a "model" should only encapsulate a database table with simple CRUD operations. As noted in the Wikipedia article: <http://en.wikipedia.org/wiki/Model-view-controller#As_a_design_pattern> ...that application layer is intended to do more than simply act as a single database table abstraction. Think about the meaning of the word "controller" -- it should act more as a director rather than being the entire application in and of itself. A "model" *is* a place for business logic. Most large scale applications in fact hold much of their business logic in the database itself (in the form of triggers, stored procedures, foreign keys, etc.). I think the misunderstanding of what a "model" is is partly caused by the same (over-)hype of "MVC", without carrying with it much understanding of the concepts themselves. Kinda like how empty "AJAX" is, or even more easy, "Web 2.0". For better or worse, plenty of script kiddies have jumped on the MVC wagon, and since the simple howtos and example scenarios don't do much more than tell you to put your database code in the "model", the misuse of that layer as only a database abstraction has become commonplace. Now you read posts all over the Internet calling it "unpure", "dirty", "hackish" to put any business logic in a model. That's WRONG. Misinformed. The easy example is to think about foreign keys: even if you only want your "model" to be a *database* model, if you want to be "pure", "correct" or what have you, you really should be enforcing referential integrity therein. Thanks to the lack of real foreign key support in MySQL for many years, web applications grew up without anyone worrying about referential integrity at all. Fits the script kiddie lifestyle I guess. Anyhow, for even this simplified view of a model to be able to maintain foreign key validity, a model then has to work with others (or, especially if a framework like CodeIgniter does not let you do so, you have to write queries to other tables, sometimes duplicating queries elsewhere - THAT is bad style). Therefore, I believe this to be a shortcoming of CodeIgniter. I understand that it might not be an easy fix, but it's certainly a disappointing oversight. So what I did was take the example code above and abstract it into a helper so that I now have a function that works almost identically to the normal $this->load->model() functionality. Here it is (put it into a helper that is auto-loaded and you can use it in any model): ``` /** * * Allow models to use other models * * This is a substitute for the inability to load models * inside of other models in CodeIgniter. Call it like * this: * * $salaries = model_load_model('salary'); * ... * $salary = $salaries->get_salary($employee_id); * * @param string $model_name The name of the model that is to be loaded * * @return object The requested model object * */ function model_load_model($model_name) { $CI =& get_instance(); $CI->load->model($model_name); return $CI->$model_name; } ```
Accessing CodeIgniter Models in Other Models
[ "", "php", "codeigniter", "" ]
I want to make an web application (platform) that does pretty straightforward stuff: Users can register, get an account, and therefore login on to the platform. I've installed Kohana. It would be cool to have a lightweight demo-project that makes use of these things in order to see how it's done. Are there any good ones available?
[Gallery3 Beta](http://gallery.menalto.com/gallery_3.0_beta_1_released) and [Argentum Invoice](http://www.argentuminvoice.com/) are both built on Kohana and have authentication.
A ready to download example based on kohana 3.2. <http://www.workinprogress.ca/kohana32/>
Are there any example projects that use Kohana with user registration and login authentification?
[ "", "php", "kohana", "" ]
C#: How should TCP socket buffer data be handled? As bytes or converted to an ascii string? I am using methods that are involved in parsing specific data from the returned tcp socket buffer, which practice would be best? Should I process/parse my data in it's raw byte form? Or should I process it after convert it to an ascii string since string datatypes have niftier text operations?
In general, as bytes. It's basically binary data - it's up to the protocol above TCP that to *interpret* that binary data appropriately. Now, what *is* your data? Are you in control of the protocol? If so, is it *meant* to be text data? Converting binary data for an image (for example) into ASCII is likely to be disastrous... but if it's a genuinely ASCII-only protocol, it's probably the right way to go. If you don't know the protocol, don't perform any conversions: they may well lose information unless you're very careful (e.g. using base64 instead of just an ASCII encoding). If you *do* know the protocol, that should dictate how you treat the data.
Actually the buufer data is aways "raw" bytes, so if you want to parse the content you'll have to convert the byte[] into a string. For exemple: ``` string myString = Encoding.ASCII.GetString(myBufferData); ```
C#: How should TCP socket buffer data be handled? As bytes or converted to an ascii string?
[ "", "c#", ".net", "sockets", "" ]
I have an existing PHP/MySQL application that I want to convert over to CakePHP. Unfortuaintly I can not change the column names and they do not follow the CakePHP standard. For example: One of the table names is called "user" and its not plural. The primary key is called "user\_id" instead of "id". The creation date is called 'generated' instead of "created", ect... I was hoping there would be a way to define aliases for table names and fields in the CakePHP model but I can't seem to find it. Any suggestions?
You can change the name of the table associated with a model, as well as the primary key: ``` class User extends AppModel { var $table = 'User'; var $primaryKey = 'id'; } ``` As far as the "`generated`" thing, I haven't found a way to override the "`created/modified`" defaults in CakePHP (other than going through the library source and hacking it directly). Are you able to add columns?
About "generated" you can insert/update values with callbacks like beforeSave. ``` <?php class User extends AppModel { var $table = 'user'; var $primaryKey = 'user_id' function beforeSave() { this->data['generated'] = date('Y-m-d H:i:s'); } } ?> ```
How do I use non-standard table / column names for the models while porting an existing php application to CakePHP?
[ "", "php", "mysql", "cakephp", "" ]
I am new to CSS and trying to achieve the following effect: I have a table with short text lines in each cell, I want to put 1-N small icons on the middle of the cells' borders. A small sketch that might help visualise it: <http://img200.imageshack.us/img200/6506/sketcha.jpg> I would be thankfull for any guidance.
Your best bet will probably be to use positon:relative on the box, put the icons inside, and use position:absolute to place them without them taking up space in the content. Like this: HTML: ``` <div id="wrapper"> <img id="icon1" src="/path/to/image.png" alt="alt text" /> <img id="icon2" src="/path/to/image.png" alt="alt text" /> </div> ``` CSS: ``` #wrapper { position:relative; z-index:1; } #wrapper img { position:absolute; top:-10px; width:20px; height:20px; z-index:10; } #icon1 { right:10px; } #icon2 { right:40px; } ``` Something like that. The actual dimensions would be based on the size and placement of the icons themselves, but this would get the job done.
if you don't want to go with absolute positioning then maybe do this: ``` <style type="text/css"> .box {width:200px; height:200px; border:solid 5px #ccc;} .icon1, .icon2 { display:block; width:30px; height:15px; background:black; margin-right:10px; margin-top: -10px; float:left;} </style> <div class="box"> <span class="icon1"></span> <span class="icon2"></span> </div> ```
Placing an Icon on the edge of a border
[ "", "javascript", "css", "" ]
I am using [Matcher.appendReplacement()](http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Matcher.html#appendReplacement(java.lang.StringBuffer,%20java.lang.String)) and it worked great until my replacement string had a $2 in it: > Note that backslashes ( \ ) and dollar > signs ($) in the replacement string > may cause the results to be different > than if it were being treated as a > literal replacement string. Dollar > signs may be treated as references to > captured subsequences as described > above, and backslashes are used to > escape literal characters in the > replacement string. Is there a convenience method somewhere that will escape all backslashes \ and dollar signs $ with a backslash? Or do I have to write one myself? It sounds like it's not that hard, just would be nice if they gave you one >:( **edit:** since they do give you one, I need to `replace(">:(", ":-)");`
Use [Matcher.quoteReplacement](http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html#quoteReplacement(java.lang.String)) on the replacement string. Unfortunately "ease of use" in this case conflicts with strong typing. [Explanation: An object of Java static type `java.lang.String` is any immutable sequence of `char`s. It doesn't tell you the format of that raw data. In this scenario we have text probably meaningful to the user, text encoded in a mini-language for replacement and text encoded in a mini-language for the pattern. The Java type system has no way of distinguishing these (although you can do fun things with annotation-based type checkers, often to avoid XSS or SQL/command injection vulnerabilities). For the pattern mini-language you can to a form of conversion with `Pattern.compile` although that is a specific use and most APIs methods ignore it (for ease of use). An equivalent `ReplacementText.compile` could be written. Further, you could ignore the mini-languages and go for libraries as "DSLs". But all this doesn't help casual ease of use.]
Here's another option: ``` matcher.appendReplacement(stringbuffer, ""); stringbuffer.append(replacement); ``` `appendReplacement()` handles the job of copying over the text between the matches, then `StringBuffer#append()` adds your replacement text *sans* adulterations. This is especially handy if you're generating the replacement text dynamically, as in Elliott Hughes' [Rewriter](http://elliotth.blogspot.com/2004/07/java-implementation-of-rubys-gsub.html).
Matcher.appendReplacement with literal text
[ "", "java", "regex", "" ]
hi i'm using swing and in my main frame(JFrame) i want that when ever user press + key one window lets say test should appear. my key listener works fine if i don't call the show method of the newly added JInternalFrame but when i call the show method of my JInternalFrame the KeyListener stops listening any more. i've tried a lot to solve it but all in vain so any help regarding this will be appreciated. thanks. this is my keyListener ``` _mainFrameKeyListener = new KeyListener() { public void keyPressed(KeyEvent arg0) { // TODO Auto-generated method stub System.out.println("the key pressed Id is : " + arg0.getKeyCode()); if(arg0.getKeyCode() == 107){ test Test = new test(); _mainDesktopPane.add(Test); Test.show(); } } public void keyReleased(KeyEvent arg0) { // TODO Auto-generated method stub } public void keyTyped(KeyEvent arg0) { // TODO Auto-generated method stub } }; ```
Sounds like you want a hot key instead of a key listener to avoid focus issues. ``` // Get the KeyStroke for our hot key KeyStroke plus = KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, 0, true); // Get the input map for our component // In this case we are interested in key strokes in the focussed window InputMap inputMap = panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); // Map the key stroke to our "action key" (see below) inputMap.put(plus, "my_action"); // Get the action map for our component ActionMap actionMap = panel.getActionMap(); // Add the required action listener to out action map actionMap.put("my_action", actionListener); ``` <http://helpdesk.objects.com.au/java/how-to-specify-a-hot-key-for-a-swing-application>
You would need to add the key listener to exactly the component that has focus (many components are actually composites). So use `JComponent.registerKeyboardAction` with a condition of `WHEN_IN_FOCUSED_WINDOW`. Alternatively use `JComponent.getInputMap(WHEN_IN_FOCUSED_WINDOW, true)` and `JComponent.getActionMap(true)` as described in the `registerKeyboardAction` API docs.
Problem with keylistener
[ "", "java", "swing", "" ]
I'm adding a function to my own personal toolkit lib to do simple CSV to HTML table conversion. I would like the **smallest possible piece of code to do this in C#**, and it needs to be able to handle CSV files in excess of ~500mb. So far my two contenders are * splitting csv into arrays by delimiters and building HTML output * search-replace delimiters with table th tr td tags Assume that the file/read/disk operations are already handled... i.e., i'm passing a string containing the contents of said CSV into this function. The output will consist of straight up simple HTML style-free markup, and yes the data may have stray commas and breaks therein. **update:** some folks asked. 100% of the CSV i deal with comes straight out of excel if that helps. ### Example string: ``` a1,b1,c1\r\n a2,b2,c2\r\n ```
Read All Lines into Memory ``` var lines =File.ReadAllLines(args[0]); using (var outfs = File.AppendText(args[1])) { outfs.Write("<html><body><table>"); foreach (var line in lines) outfs.Write("<tr><td>" + string.Join("</td><td>", line.Split(',')) + "</td></tr>"); outfs.Write("</table></body></html>"); } ``` or Read one line at a time ``` using (var inFs = File.OpenText(args[0])) using (var outfs = File.AppendText(args[1])) { outfs.Write("<html><body><table>"); while (!inFs.EndOfStream ) outfs.Write("<tr><td>" + string.Join("</td><td>", inFs.ReadLine().Split(',')) + "</td></tr>"); outfs.Write("</table></body></html>"); } ``` ... @Jimmy ... I created an extended version using LINQ. Here is the highlight ... (lazy eval for line reading) ``` using (var lp = args[0].Load()) lp.Select(l => "<tr><td>" + string.Join("</td><td>", l.Split(',')) + "</td></tr>") .Write("<html><body><table>", "</table></body></html>", args[1]); ```
probably not much shorter you can get than this, but just remember that any real solution would handle quotes, commas inside of quotes, and conversions to html entities. ``` return "<table><tr><td>"+s .Replace("\n","</td></tr><tr><td>") .Replace(",","</td><td>")+"</td></tr></table>"; ``` EDIT: here's (largely untested) addition of htmlencode and quote-matching. I htmlencode first, then all commas become '<' (which don't collide because the existing ones have been encoded already. ``` bool q=false; return "<table><tr><td>" + new string(HttpUtility.HtmlEncode(s) .Select(c=>c=='"'?(q=!q)?c:c:(c==','&&!q)?'<':c).ToArray()) .Replace("<", "</td><td>") .Replace("\n", "</td></tr><tr><td>") + "</td></tr></table>"; ```
Codegolf: Convert csv to HTML table with smallest amount of code in C#
[ "", "c#", "csv", "code-golf", "" ]
Duplicate: > [What to use var or object name type](https://stackoverflow.com/questions/236878/what-to-use-var-or-object-name-type) I couldn't understand the need of var keyword in C# 3.0 What is the advantage in using it. i saw [this](https://stackoverflow.com/questions/41479/use-of-var-keyword-in-c) question but did not understand the real purpose of using it
It's mostly present for LINQ, when you may use an anonymous type as the projection: ``` var query = from person in employees where person.Salary > 10000m select new { FullName=person.Name, person.Department }; ``` Here the type of `query` can't be declared explicitly, because the anonymous type has no name. (In real world cases the anonymous type often includes values from multiple objects, so there's no one named class which contains all the properties.) It's *also* practically useful when you're initializing a variable using a potentially long type name (usually due to generics) and just calling a constructor - it increases the information density (reduces redundancy). There's the same amount of information in these two lines: ``` List<Func<string, int>> functions = new List<Func<string, int>>(); var functions = new List<Function<string, int>>(); ``` but the second one expresses it in a more compact way. Of course this *can* be abused, e.g. ``` var nonObviousType = 999999999; ``` but when it's obvious what the type's variable is, I believe it can significantly increase readability.
The primary reason for its existence is the introduction of anonymous types in C#. You can construct types on the fly that don't have a name. How would you specify their name? The answer: You can't. You just tell the compiler to infer them for you: ``` var user = users.Where(u=> u.Name == "Mehrdad") .Select(u => new { u.Name, u.Password }); ```
Advantage of var keyword in C# 3.0
[ "", "c#", "variables", "" ]
Is there a full list of optimizations done by the [/optimize C# compiler key](http://msdn.microsoft.com/en-us/library/t0hfscdc(VS.71).aspx) available anywhere? EDIT: *Why is it disabled by default? Is it worth using in a real-world app?* -- it is disabled by default only in Debug configuration and Enabled in Release.
[Scott Hanselman has a blog post](http://www.hanselman.com/blog/ReleaseISNOTDebug64bitOptimizationsAndCMethodInliningInReleaseBuildCallStacks.aspx) that shows a few examples of what /optimize (which is enabled in Release Builds) does. As a summary: /optimize does many things with no exact number or definition given, but one of the more visible are method inlining (If you have a Method A() which calls B() which calls C() which calls D(), the compiler may "skip" B and C and go from A to D directly), which may cause a "weird" callstack in the Release build.
It is disabled by default for debug builds. For Release builds it is enabled. It is definitely worth enabling this switch as the compiler makes lots of tweaks and optimizations depending on the kind of code you have. For eg: Skipping redundant initializations, comparisons that never change etc. Note: You might have some difficulty debugging if your turn on optimization as the code you have and the IL code that is generated may not match. This is the reason it is turned on only for Release builds.
What is /optimize C# compiler key intended for?
[ "", "c#", "optimization", "compiler-construction", "" ]
I'm building an emailing system for a framework I'm developing. Thus far, I've got a generic MailMessage interface that every different type of email message will implement, something along the lines of ``` public interface MailMessage { public String[] getTo(); public void setTo(String[] to); public String getFrom(); public void setFrom(String from); ... // you can guess the setters/getters here ... } ``` I've then got a SimpleMailMessage that's exactly what you would expect as a simple implementation of the interface (no encryption or encoding, just plain text). I've created an MailMessageFactory interface that's used as an abstract factory. I've got a SimpleMailMessageFactory that implements the factory to produce instances of SimpleMailMessage. One type of email I'd like to the framework to send is an Alert mail message, that is essentially a regular mail message except with "[Alert]" prefixed to the subject line (Another might be a email containing a "list" of order items, but I'm not sure of where the responsibility falls for converting the list to a String for an email lies). I can either subclass the SimpleMailMessage and override the setSubject(String subject) method to something like ``` public class AlertMailMessage { ... public void setSuject(String subject) { this.to = "[Alert]" + to; } ... } ``` Or I can create a decorator: ``` public abstract class EmailDecorator implements MailMessage { protected MailMessage email; ... // delegate all implemented methods to email ... } public class AlertEmailDecorator extends EmailDecorator { public void setSubject(String subject) { email.setSubject("[Alert]" + subject); } } ``` Or I can just delegate adding the "[Alert]" string in the SimpleMailMessageFactory. Thoughts on what I have? I think the problem is that I might be too thoughtful and forward-thinking, but I want the perfect design.
A decorator seems a better option to me. I am thinking of, may be you need to append your subject line with, `Fwd:` or `Re:` as well, or may be you need to support signature where you will be adding a signature to the email body.
The decorator seems like the better option. However, why are you writing your own email framework for Java? Why not just use the JavaMail API?
Design: Emailing System in Java
[ "", "java", "design-patterns", "email", "decorator", "" ]