Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
If I'm deploying to servers with WebSphere 6.1 (Java 1.5), should I use IBM's JDK on my build box? Or will Sun's JDK compile to the same binary? If I should use IBM's, where can I get the Windows x64 version?
I would as much as possible try to keep development as close to production as possible. Ibm and Sun's JDK's certainly both satisfy the SDK certification, but they are by no means identical. Their instrumentation and memory management are at least slightly different. If nothing else, the bugs in the JDK will be differen...
It should not make any difference. It will probably not be exactly the same binary but 100% compatible. I assume you're using external libraries anyways like log4j or maybe hibernate or whatever and those are not built using the IBM JDK. There are differences in the JREs, however. For example, I remember that when I l...
Does it matter which vendor's JDK you build with?
[ "", "java", "build-process", "" ]
I am using the [`jquery-ui-dialog`](https://jqueryui.com/dialog/) plugin I am looking for way to refresh the page when in some circumstances when the dialog is closed. Is there a way to capture a close event from the dialog? I know I can run code when the close button is clicked but that doesn't cover the user closi...
I have found it! You can catch the close event using the following code: ``` $('div#popup_content').on('dialogclose', function(event) { alert('closed'); }); ``` Obviously I can replace the alert with whatever I need to do. **Edit:** As of Jquery 1.7, the bind() has become on()
I believe you can also do it while creating the dialog (copied from a project I did): ``` dialog = $('#dialog').dialog({ modal: true, autoOpen: false, width: 700, height: 500, minWidth: 700, minHeight: 500, position: ["center", 200], close: CloseFunction, overlay: { opacity:...
jquery-ui-dialog - How to hook into dialog close event
[ "", "javascript", "jquery", "jquery-ui", "modal-dialog", "jquery-ui-dialog", "" ]
I'm just starting to get into Django, and of course as of last night one of the two new Python versions went final (2.6 obviously ;)) so I'm wondering if 2.6 plus Django is ready for actual use or do the Django team need more time to finish with tweaks/cleanup? All the google searches I did were inconclusive, I saw bi...
The impression I get is that 2.6 should work fine with Django 1.0. As found here: <http://simonwillison.net/2008/Oct/2/whatus/>
Note that there is currently no python-mysql adapter for python2.6. If you need MySQL, stick with 2.5 for now.
Django and Python 2.6
[ "", "python", "django", "" ]
Anyone knows if is possible to have partial class definition on C++ ? Something like: file1.h: ``` class Test { public: int test1(); }; ``` file2.h: ``` class Test { public: int test2(); }; ``` For me it seems quite useful for definining multi-platform classes that have common functions be...
This is not possible in C++, it will give you an error about redefining already-defined classes. If you'd like to share behavior, consider inheritance.
Try inheritance Specifically ``` class AllPlatforms { public: int common(); }; ``` and then ``` class PlatformA : public AllPlatforms { public: int specific(); }; ```
Partial class definition on C++?
[ "", "c++", "" ]
Here's what I'd like to do: I want to create a library project that contains my Resource files (ie, UI Labels and whatnot). I'd like to then use the resource library both in my UI and in my Tests. (Ie, basically have a common place for my resources that I reference from multiple projects.) Unfortunately, because the ...
Not sure which version of Visual Studio you are using, so I will put steps for either one: VS 2008 - When you open the resx file in design view, there is an option at the top beside Add Resource and Remove Resource, called Access Modifier, it is a drop down where you can change the generated code from internal to publ...
Visual Studio 2008 allows you to select whether the generated resource class should be internal or public. There is also the [ResXFileCodeGeneratorEx](http://www.codeproject.com/KB/dotnet/ResXFileCodeGeneratorEx.aspx), which should do that for Visual Studio 2005.
Is there a way to make Strongly Typed Resource files public (as opposed to internal)?
[ "", "c#", "asp.net", ".net-2.0", "resources", "strong-typing", "" ]
Is there a destructor for Java? I don't seem to be able to find any documentation on this. If there isn't, how can I achieve the same effect? To make my question more specific, I am writing an application that deals with data and the specification say that there should be a 'reset' button that brings the application b...
Because Java is a garbage collected language you cannot predict when (or even if) an object will be destroyed. Hence there is no direct equivalent of a destructor. There is an inherited method called `finalize`, but this is called entirely at the discretion of the garbage collector. So for classes that need to explici...
Have a look at the [try-with-resources](http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) statement. For example: ``` try (BufferedReader br = new BufferedReader(new FileReader(path))) { System.out.println(br.readLine()); } catch (Exception e) { ... } finally { ... } ``` Here th...
Is there a destructor for Java?
[ "", "java", "garbage-collection", "destructor", "finalize", "" ]
When logging in C#, how can I learn the name of the method that called the current method? I know all about `System.Reflection.MethodBase.GetCurrentMethod()`, but I want to go one step beneath this in the stack trace. I've considered parsing the stack trace, but I am hoping to find a cleaner more explicit way, somethin...
Try this: ``` using System.Diagnostics; // Get call stack StackTrace stackTrace = new StackTrace(); // Get calling method name Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name); ``` one-liner: ``` (new System.Diagnostics.StackTrace()).GetFrame(1).GetMethod().Name ```
In C# 5, you can get that information using [caller info](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/caller-information): ``` //using System.Runtime.CompilerServices; public void SendError(string Message, [CallerMemberName] string callerName = "") { Console.WriteLine(callerName...
How can I find the method that called the current method?
[ "", "c#", ".net", "logging", "stack-trace", "system.diagnostics", "" ]
I wish to implement my software on a shareware basis, so that the user is given a maximum trial period of (say) 30 days with which to try out the software. On purchase I intend the user to be given a randomly-generated key, which when entered enables the software again. I've never been down this route before, so any a...
With regards to a random-generated key, how will you verify a key is legit or if a key is bogus if it is actually random? Have a look at the article "[Implementing a Partial Serial Number Verification System](http://www.brandonstaggs.com/2007/07/26/implementing-a-partial-serial-number-verification-system-in-delphi/)" a...
If your software is really useful, you'll certainly find cracked copies on P2P before you see your first order. This will happen no matter how sophisticated is the license enforcement code you are going to implement. That said, just store first-run date somewhere (may be registry, if on Windows) and after 30 days refu...
Incorporating shareware restrictions in C++ software
[ "", "c++", "time", "restriction", "shareware", "" ]
There are numerous times you have an interface that accepts similar type arguments that have a separate domain logic meaning: ``` public static class Database { public static bool HasAccess(string userId, string documentId) { return true; } } ``` Now it's quite easy to have someone key documentId instead of userId...
Interesting, but I suspect that in many cases (particularly seialization / RPC APIs) this will only add confustion/overhead. Also - a minor implementation detail, but given this approach I'd make the wrappers fully immutable, not just "internal set" immutable. TBH - I'd probably rather use unit tests for most of this....
I think you answered your own question - better data integrity and validation, better system
Is abstracting data type (sometimes) a good idea?
[ "", "c#", "design-patterns", "" ]
As a function argument I get a `vector<double>& vec` (an output vector, hence non-const) with unknown length and values. I want to initialise this vector to a specific length n with all zeroes. This will work ``` vec.clear(); vec.resize( n, 0.0 ); ``` And this will work as well: ``` vec.resize( n ); vec.assign( n, ...
``` std::vector<double>(n).swap(vec); ``` After this, vec is guaranteed to have size and capacity n, with all values 0.0. Perhaps the more idiomatic way since C++11 is ``` vec.assign(n, 0.); vec.shrink_to_fit(); ``` with the second line optional. In the case where `vec` starts off with more than `n` elements, wheth...
``` std::vector<double>(n).swap(vec); ``` This has the advantage of actually compacting your vector too. (In your first example, `clear()` does not guarantee to compact your vector.)
(re)initialise a vector to a certain length with initial values
[ "", "c++", "stl", "initialization", "" ]
I'm currently building a small web application that includes a fair amount of JavaScript. When I was prototyping the initial idea, I just hacked together a few functions to demonstrate how the application would eventually behave intending to go forward re-writing the JavaScript in an object-oriented nature. Now that I...
No, although I personally find OOP more tasty, it is a means to an end, and not an end in itself. There are many cases where procedural programming makes more sense than OOP, an converting for the sake of converting, could be, as you said, overkill.
No, let it be and move forward - that is more productive in my view .
Is it worth converting my functional JavaScript code to an object-oriented design?
[ "", "javascript", "software-design", "web-applications", "" ]
Consider the following method signatures: ``` public fooMethod (Foo[] foos) { /*...*/ } ``` and ``` public fooMethod (Foo... foos) { /*...*/ } ``` *Explanation: The former takes an array of Foo-objects as an argument - `fooMethod(new Foo[]{..})` - while the latter takes an arbitrary amount of arguments of type Foo,...
These methods are actually the same. This feature is called varargs and it is a compiler feature. Behind the scenes is is translates to the former version. There is a pitfall if you define a method that accepts Object... and you sent one parameter of type Object[]!
I'd like to add to Shimi's explanation to add that another restriction of the varargs syntax is that the vararg must be the last declared parameter. So you can't do this: ``` void myMethod(String... values, int num); ``` This means that any given method can only have a single vararg parameter. In cases where you want...
Object arrays in method signatures
[ "", "java", "arrays", "methods", "" ]
I got this error when I checked out my database from source control. It might sounds weird to check in the sql server database, but this was what I have done because this is just a personal project. Anyone knows how to fix this?
Here's my finding. As mentioned by other posters, you really don't want to check database files into and out of the source control. But if you absolutely need to, and you have done check in the database files and you are encountering the same error that I encountered, here is a workaround: First, detach the database...
You really don't want to be checking database files into and out of source control - in SQL Server you have to detach the files for this to even work and you run all kinds of risks. If you absolutely have to do this, you should version backups. I recommend versioning a script which creates the entire database (tables...
One or more files do not match the primary file of the database (error 5173)
[ "", "c#", "sql-server", "" ]
In C++, static library A is linked into dynamic libraries B and C. If a class, Foo, is used in A which is defined in B, will C link if it doesn't use Foo? I thought the answer was yes, but I am now running into a problem with xlc\_r7 where library C says Foo is an undefined symbol, which it is as far as C is concerned...
When you statically link, two modules become one. So when you compile C and link A into it, its as if you had copied all the source code of A into the source code of C, then compiled the combined source. So C.dll includes A, which has a dependency on B via Foo. You'll need to link C to B's link library in order to sati...
Sounds like it's probably the linker (ld/unix), as (most versions that I've used of) ld links the libraries in from left to right - and if there is a reference in the first one that is required by a later one the usual trick is to append the first library (or any required library) to the end of the command. It's a try...
Static and dynamic library linking
[ "", "c++", "linker", "aix", "" ]
I'm developing a little project plan and I came to a point when I need to decide what local databse system to use. The input data is going to be stored on webserver (hosting - MySQL DB). The idea is to build a process to download all necessary data (for example at midnight) and process them. However, there are going t...
I want to say Microsoft Sql 2005 Express, as it (almost) comes as the obvious choice when developing in .NET. But it all depends on what previous db skills you have. If you already know MySql and as you already said, the data should be exported back to MySql. Why not use MySql all the way?
For quick and dirty I'd go with [Sql Server Compact Edition.](http://www.microsoft.com/sql/editions/compact/default.mspx) Its an in-process implementation of Sql Server, so it doesn't require you install any other applications. Back in the day, you'd use an Access database for this kind of thing. But Access databases ...
Which database would you recommend to use with C# (.NET) application?
[ "", "c#", ".net", "database", "local", "" ]
Let's say I have the following `class X` where I want to return access to an internal member: ``` class Z { // details }; class X { std::vector<Z> vecZ; public: Z& Z(size_t index) { // massive amounts of code for validating index Z& ret = vecZ[index]; // even more code for d...
Yes, it is possible to avoid the code duplication. You need to use the const member function to have the logic and have the non-const member function call the const member function and re-cast the return value to a non-const reference (or pointer if the functions returns a pointer): ``` class X { std::vector<Z> vec...
For a detailed explanation, please see the heading "Avoid Duplication in `const` and Non-`const` Member Function," on p. 23, in Item 3 "Use `const` whenever possible," in [*Effective C++*, 3d ed](https://www.aristeia.com/books.html) by Scott Meyers, ISBN-13: 9780321334879. ![alt text](https://images-na.ssl-images-amaz...
How do I remove code duplication between similar const and non-const member functions?
[ "", "c++", "code-duplication", "c++-faq", "function-qualifier", "explicit-object-parameter", "" ]
Assuming I have an ArrayList ``` ArrayList<MyClass> myList; ``` And I want to call toArray, is there a performance reason to use ``` MyClass[] arr = myList.toArray(new MyClass[myList.size()]); ``` over ``` MyClass[] arr = myList.toArray(new MyClass[0]); ``` ? I prefer the second style, since it's less verbose, a...
Counterintuitively, the fastest version, on Hotspot 8, is: ``` MyClass[] arr = myList.toArray(new MyClass[0]); ``` I have run a micro benchmark using jmh the results and code are below, showing that the version with an empty array consistently outperforms the version with a presized array. Note that if you can reuse ...
As of [ArrayList in Java 5](http://java.sun.com/j2se/1.5.0/docs/api/java/util/ArrayList.html#toArray(T[])), the array will be filled already if it has the right size (or is bigger). Consequently ``` MyClass[] arr = myList.toArray(new MyClass[myList.size()]); ``` will create one array object, fill it and return it to ...
.toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])?
[ "", "java", "performance", "coding-style", "" ]
I will choose Java as an example, most people know it, though every other OO language was working as well. Java, like many other languages, has interface inheritance and implementation inheritance. E.g. a Java class can inherit from another one and every method that has an implementation there (assuming the parent is ...
Short answer: Yes it is possible. But you have to do it on purpose and no by chance ( using final, abstract and design with inheritance in mind, etc. ) Long answer: Well, inheritance is not actually for "code re-use", it is for class "specialization", I think this is a misinterpretation. For instance is it a very ba...
The problem with most example against inheritance are examples where the person is using inheritance incorrectly, not a failure of inheritance to correctly abstract. In the article you posted a link to, the author shows the "brokenness" of inheritance using Stack and ArrayList. The example is flawed because **a Stack ...
Is OOP & completely avoiding implementation inheritance possible?
[ "", "java", "oop", "" ]
I'm developing a website (in Django) that uses OpenID to authenticate users. As I'm currently only running on my local machine I can't authenticate using one of the OpenID providers on the web. So I figure I need to run a local OpenID server that simply lets me type in a username and then passes that back to my main ap...
The libraries at [OpenID Enabled](http://openidenabled.com/) ship with examples that are sufficient to run a local test provider. Look in the examples/djopenid/ directory of the python-openid source distribution. Running that will give you an instance of [this test provider](http://openidenabled.com/python-openid/trunk...
I have no problems testing with [myopenid.com](http://myopenid.com). I thought there would be a problem testing on my local machine but it just worked. (I'm using ASP.NET with DotNetOpenId library). The 'realm' and return url must contain the port number like '<http://localhost:93359>'. I assume it works OK because t...
How do you develop against OpenID locally
[ "", "python", "django", "openid", "" ]
I have a table with rowID, longitude, latitude, businessName, url, caption. This might look like: ``` rowID | long | lat | businessName | url | caption 1 20 -20 Pizza Hut yum.com null ``` How do I delete all of the duplicates, but only keep the one that has a URL (first priority), or keep the one...
Here's my looping technique. This will probably get voted down for not being mainstream - and I'm cool with that. ``` DECLARE @LoopVar int DECLARE @long int, @lat int, @businessname varchar(30), @winner int SET @LoopVar = (SELECT MIN(rowID) FROM Locations) WHILE @LoopVar is not null BEGIN --initialize the...
This solution is brought to you by "stuff I've learned on Stack Overflow" in the last week: ``` DELETE restaurant WHERE rowID in (SELECT rowID FROM restaurant EXCEPT SELECT rowID FROM ( SELECT rowID, Rank() over (Partition BY BusinessName, lat, long ORDER BY url DESC, caption DESC ) AS Rank ...
Remove Duplicates with Caveats
[ "", "sql", "sql-server", "duplicate-data", "" ]
I'd like to create a subset of Users that don't have a login... basically as a way to add a photographer field to photos without having a full blown account associated with that person (since in many cases, they'll never actually log in to the site). A caveat is that I'd also like to be able to enable an account for th...
A [user profile](http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users) (as returned by `django.contrib.auth.models.User.get_profile`) doesn't extend the User table - the model you specify as the profile model with the `AUTH_PROFILE_MODULE` setting is just a model which has a `For...
Users that can't login? Just given them a totally random password. ``` import random user.set_password( str(random.random()) ) ``` They'll never be able to log on.
Django UserProfile... without a password
[ "", "python", "database", "django", "django-authentication", "django-users", "" ]
I sometimes notice programs that crash on my computer with the error: "pure virtual function call". How do these programs even compile when an object cannot be created of an abstract class?
They can result if you try to make a virtual function call from a constructor or destructor. Since you can't make a virtual function call from a constructor or destructor (the derived class object hasn't been constructed or has already been destroyed), it calls the base class version, which in the case of a pure virtua...
As well as the standard case of calling a virtual function from the constructor or destructor of an object with pure virtual functions you can also get a pure virtual function call (on MSVC at least) if you call a virtual function after the object has been destroyed. Obviously this is a pretty bad thing to try and do b...
Where do "pure virtual function call" crashes come from?
[ "", "c++", "polymorphism", "virtual-functions", "pure-virtual", "" ]
I'm doing some experiments with Microsoft Dynamics CRM. You interact with it through web services and I have added a Web Reference to my project. The web service interface is very rich, and the generated "Reference.cs" is some 90k loc. I'm using the web reference in a console application. I often change something, rec...
The following is ripped from [this](http://communities.vmware.com/thread/47063) thread on the VMWare forums: Hi folks, We've found that sgen.exe does work. It'just that there is a couple of additional steps beyond pre-generating the serializer dll's that we missed in this thread. Here is the detailed instruction ## ...
You might wish to look into the [`Sgen.exe`](http://msdn.microsoft.com/en-us/library/bk3w6240(VS.80).aspx) tool that comes with .NET. There's also a handy little thing in Visual Studio's C# project properties "Build" page, at the very bottom, called "Build serialization assembly" that automatically runs `Sgen` for you.
Slow SoapHttpClientProtocol constructor
[ "", "c#", ".net", "performance", "xml-serialization", "soaphttpclientprotocol", "" ]
I'm doing some maintenance coding on a webapp and I am getting a javascript error of the form: "[elementname] has no properties" Part of the code is being generated on the fly with an AJAX call that changes innerHTML for part of the page, after this is finished I need to copy a piece of data from a hidden input field ...
"[elementname] has no properties" is javascript error speak for "the element you tried to reference doesn't exist or is nil" This means you've got one or more of a few possible problems: 1. Your page hasn't rendered yet and you're trying to reference it before it exists 2. You've got a spelling error 3. You've named ...
Make sure your code runs AFTER the page fully loads. If your code runs before the element you are looking for is rendered, this type of error will occur.
Javascript error: [elementname] has no properties
[ "", "javascript", "ajax", "" ]
What is the benefit of using singleton instead of global for database connections in PHP? I feel using singleton instead of global makes the code unnecessarily complex. ## Code with Global ``` $conn = new PDO(...); function getSomething() { global $conn; . . . } ``` ## Code with Singleton ``` class...
I know this is old, but Dr8k's answer was *almost* there. When you are considering writing a piece of code, assume it's going to change. That doesn't mean that you're assuming the kinds of changes it will have hoisted upon it at some point in the future, but rather that some form of change will be made. Make it a goa...
I'm not sure I can answer your specific question, but wanted to suggest that global / singleton connection objects may not be the best idea if this if for a web-based system. DBMSs are generally designed to manage large numbers of unique connections in an efficient manner. If you are using a global connection object, t...
Global or Singleton for database connection?
[ "", "php", "design-patterns", "singleton", "" ]
What is the best way to replace all '&lt' with `&lt;` in a given database column? Basically perform `s/&lt[^;]/&lt;/gi` Notes: * must work in [MS SQL Server](http://en.wikipedia.org/wiki/Microsoft_SQL_Server#SQL_Server_2005) 2000 * Must be repeatable (and not end up with `&lt;;;;;;;;;;`)
Some hacking required but we can do this with **LIKE**, **PATINDEX**, **LEFT** AND **RIGHT** and good old string concatenation. ``` create table test ( id int identity(1, 1) not null, val varchar(25) not null ) insert into test values ('&lt; <- ok, &lt <- nok') while 1 = 1 begin update test set v...
I think this can be done much cleaner if you use different STUFF :) ``` create table test ( id int identity(1, 1) not null, val varchar(25) not null ) insert into test values ('&lt; <- ok, &lt <- nok') WHILE 1 = 1 BEGIN UPDATE test SET val = STUFF( val , PATINDEX('%&lt[^;]%', val) + 3 , 0 , ';' )...
Perform regex (replace) in an SQL query
[ "", "sql", "sql-server", "regex", "sql-server-2000", "" ]
I'm making a simple jquery command: `element.html("&nbsp;&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;");` using the attributes/html method: <http://docs.jquery.com/Attributes/html> It works on my local app engine server, but it doesn't work once I push to the Google server. The element empties but d...
You could try generating the space during run-time, so it won't be trimmed or whatever happens during transport: ``` element.html(String.fromCharCode(32)); ```
This might not be a direct answer to your problem, but why are you even wanting to put in a heap of spaces? You can probably achieve the same result by just changing the `padding-left` or `text-indent` of that element. ``` element.css("textIndent", "3em"); ``` Using a heap of `&nbsp;`s is a very dodgy way to do inden...
.html() jQuery method bizzare bug - resolves to empty space locally, but not on production
[ "", "javascript", "jquery", "html", "google-app-engine", "" ]
For technical reasons, I can't use ClickOnce to auto-update my .NET application and its assemblies. What is the best way to handle auto-updating in .NET?
I think the [Updater Application Block](http://msdn.microsoft.com/en-us/library/ms978574.aspx) was something of a precursor to ClickOnce. Might be worth investigating. Looking at its source code might be enough to spark some ideas.
We have a product that's commercial/open source: [wyBuild & wyUpdate](http://wyday.com/wybuild/). It has patching ability and is dead simple to use. Edit: I'm getting voted down into the negative numbers, but my post wasn't just blatant selling. Our updater, wyUpdate, is open source, written in C# and is licensed unde...
What's the best way for a .NET winforms application to update itself without using ClickOnce?
[ "", "c#", ".net", "winforms", "compact-framework", "" ]
I have an application that reads a table from a database. I issue an SQL query to get a result set, based on a unique string value I glean from the results, I use a case/switch statement to generate certain objects (they inherit TreeNode BTW). These created objects get shunted into a Dictionary object to be used later...
To add to @[Brad](https://stackoverflow.com/questions/56224/creating-objects-driven-by-the-database-to-populate-a-treeview-very-slow-c#56264), only populate the tree as needed. That means hooking into the expand event of the tree nodes. This is similar to how Windows Explorer functions when dealing with network shares....
Is there a reason you are using the external dictionary? I would populate the tree directly as the data is queried. If you do require the dictionary, you could set the .Tag property of the tree node to point to the data in your dictionary.
Creating objects driven by the database to populate a Treeview - very slow
[ "", "c#", "dictionary", "object", "clone", "icloneable", "" ]
In C#, does anybody know why the following will compile: ``` int i = 1; ++i; i++; ``` but this will not compile? ``` int i = 1; ++i++; ``` (Compiler error: The operand of an increment or decrement operator must be a variable, property or indexer.)
you are running one of the operands on the result of the other, the result of a increment/decrement is a value - and you can not use increment/decrement on a value it has to be a variable that can be set.
For the same reason you can't say ``` 5++; ``` or ``` f(i)++; ``` A function returns a *value*, not a variable. The increment operators also return values, but cannot be applied to values.
Pre and post increment/decrement operators in C#
[ "", "c#", "" ]
Switch statement fallthrough is one of my personal major reasons for loving `switch` vs. `if/else if` constructs. An example is in order here: ``` static string NumberToWords(int number) { string[] numbers = new string[] { "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nin...
(Copy/paste of an [answer I provided elsewhere](https://stackoverflow.com/questions/9033/hidden-features-of-c/90432#90432)) Falling through `switch`-`case`s can be achieved by having no code in a `case` (see `case 0`), or using the special `goto case` (see `case 1`) or `goto default` (see `case 2`) forms: ``` switch ...
The "why" is to avoid accidental fall-through, for which I'm grateful. This is a not uncommon source of bugs in C and Java. The workaround is to use goto, e.g. ``` switch (number.ToString().Length) { case 3: ans += string.Format("{0} hundred and ", numbers[number / 100]); goto case 2; case 2: ...
Switch statement fallthrough in C#?
[ "", "c#", "switch-statement", "" ]
I have a page that has an iframe From one of the pages within the iframe I want to look back and make a panel on the default page invisible because it is overshadowing a popup I tried using Parent.FindControl but it does not seem to be working. I am positive I have the right id in the findcontrol because I used Fireb...
I didn't completely follow your problem, but I'll take my best shot. It sounds like you have an ASP.NET page, that has an iframe in it that refers to another ASP.NET page, and in that page that was requested by the iframe you want to modify the visibility of the item contained in the page that contains the iframe. If...
Parent document: ``` <body> <input type="text" id="accessme" value="Not Accessed" /> ... </body> ``` Document in iframe: ``` <head> ... <script type="text/javascript"> function setValueOfAccessme() { window.parent.document.getElementById("accessme").value = "Accessed"; ...
Parent.FindControl() not working?
[ "", "asp.net", "javascript", "findcontrol", "" ]
Is there a way to tell SQL Server 2008 Express to log every query (including each and every SELECT Query!) into a file? It's a Development machine, so the negative side effects of logging Select-Queries are not an issue. Before someone suggests using the SQL Profiler: This is not available in Express (does anyone kno...
SQL Server Profiler: * File → New Trace * The "General" Tab is displayed. * Here you can choose "Save to file:" so its logged to a file. * View the "Event Selection" Tab * Select the items you want to log. * TSQL → SQL:BatchStarting will get you sql selects * Stored Procedures → RPC:Completed will get you Stored Proce...
There is one more way to get information about queries that has been executed on MS SQL Server Express [described here](http://blog.sqlauthority.com/2008/01/03/sql-server-2005-last-ran-query-recently-ran-query/). Briefly, it runs smart query to system tables and gets info(text, time executed) about queries(or cached q...
Logging ALL Queries on a SQL Server 2008 Express Database?
[ "", "sql", "sql-server", "database", "logging", "ssms", "" ]
I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of? This is similar to what I'm actually doing: ``` import xml.etree.ElementTree as ET root = ET.Element('html') head = ET.SubElement(root,'head') script = ET.Sub...
I assume that you're actually creating an XML DOM tree, because you want to validate that what goes into this file is valid XML, since otherwise you'd just write a static string to a file. If validating your output is indeed your goal, then I'd suggest ``` from xml.dom.minidom import parseString doc = parseString("""...
Another way is using the [E Factory](http://codespeak.net/lxml/tutorial.html#the-e-factory) builder from lxml (available in [Elementtree](http://effbot.org/zone/element-builder.htm) too) ``` >>> from lxml import etree >>> from lxml.builder import E >>> def CLASS(*args): # class is a reserved word in Python ... r...
XML writing tools for Python
[ "", "python", "xml", "xhtml", "" ]
I've got a class named `BackgroundWorker` that has a thread constantly running. To turn this thread off, an instance variable named `stop` to needs to be `true`. To make sure the thread is freed when the class is done being used, I've added `IDisposable` and a finalizer that invokes `Dispose()`. Assuming that `stop = ...
Your code is fine, although locking in a finalizer is somewhat "scary" and I would avoid it - if you get a deadlock... I am not 100% certain what would happen but it would not be good. However, if you are safe this should not be a problem. Mostly. The internals of garbage collection are painful and I hope you never hav...
First off, a **severe warning**. Don't use a finalizer like you are. You are setting yourself up for some very bad effects if you take locks within a finalizer. Short story is don't do it. Now to the original question. ``` public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// F...
Finalizers and Dispose
[ "", "c#", "dispose", "idisposable", "finalizer", "disposable", "" ]
How can I create an Excel spreadsheet with C# without requiring Excel to be installed on the machine that's running the code?
You can use a library called ExcelLibrary. It's a free, open source library posted on Google Code: [ExcelLibrary](https://code.google.com/archive/p/excellibrary/) This looks to be a port of the PHP ExcelWriter that you mentioned above. It will not write to the new .xlsx format yet, but they are working on adding that...
If you are happy with the xlsx format, try my library, EPPlus. It started with the source from ExcelPackage, but since became a total rewrite. It supports ranges, cell styling, charts, shapes, pictures, named ranges, AutoFilter, and a lot of other stuff. You have two options: * [EPPlus 4](https://github.com/JanKallm...
How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?
[ "", "c#", ".net", "excel", "file-io", "" ]
Is it at the state where it is actually useful and can do more than rename classes?
CDT (C/C++ Development Tools - eclipse project) 5.0 has a bunch of new refactorings ``` * Declare Method * Extract Baseclass * Extract Constant * Extract Method * Extract Subclass * Hide Method * Implement Method * Move Field / Method * Replace Number * Separate Class * Generate Getters and Setters ``` There is a CDT...
There have been numerous efforts to provide refactoring tools for C++, most of them failed pretty early, because the creation of such tools requires the full ability to process C++ source code, i.e. you need a working and full c++ compiler in the first place to implement even the most basic forms of automated source to...
What is the state of C++ refactor support in Eclipse?
[ "", "c++", "eclipse", "refactoring", "" ]
At the moment I am working on a project admin application in C# 3.5 on ASP.net. In order to reduce hits to the database, I'm caching a lot of information using static variables. For example, a list of users is kept in memory in a static class. The class reads in all the information from the database on startup, and wil...
A pitfall: A static field is scoped per app domain, and increased load will make the server generate more app domains in the pool. This is not necessarily a problem if you only read from the statics, but you will get duplicate data in memory, and you will get a hit every time an app domain is created or recycled. Bett...
As long as you can expect that the cache will never grow to a size greater than the amount of available memory, it's fine. Also, be sure that there will only be one instance of this application per database, or the caches in the different instances of the app could "fall out of sync." Where I work, we have a homegrown...
Is it OK to use static variables to cache information in ASP.net?
[ "", "c#", "asp.net", "caching", "static-variables", "" ]
I want to write a program in which plays an audio file that reads a text. I want to highlite the current syllable that the audiofile plays in green and the rest of the current word in red. What kind of datastructure should I use to store the audio file and the information that tells the program when to switch to the ne...
This is a slightly left-field suggestion, but have you looked at Karaoke software? It may not be seen as "serious" enough, but it sounds very similar to what you're doing. For example, [Aegisub](http://www.aegisub.net/) is a subtitling program that lets you create subtitles in the SSA/ASS format. It has karaoke tools f...
How about a simple data structure that describes what next batch of letters consists of the next syllable and the time stamp for switching to that syllable? Just a quick example: [0:00] This [0:02] is [0:05] an [0:07] ex- [0:08] am- [0:10] ple
Which data structure for linking text with audio in Java
[ "", "java", "audio", "" ]
I'm trying to figure out the best way to determine whether I'm in the last iteration of a loop over a map in order to do something like the following: ``` for (iter = someMap.begin(); iter != someMap.end(); ++iter) { bool last_iteration; // do something for all iterations if (!last_iteration) { // ...
Canonical? I can't claim that, but I'd suggest ``` final_iter = someMap.end(); --final_iter; if (iter != final_iter) ... ``` **Edited** to correct as suggested by **[KTC](https://stackoverflow.com/questions/151046/c-last-loop-iteration-stl-map-iterator#151104).** (Thanks! Sometimes you go too quick and mess up on the...
Since C++11, you can also use std::next() ``` for (auto iter = someMap.begin(); iter != someMap.end(); ++iter) { // do something for all iterations if (std::next(iter) != someMap.end()) { // do something for all but the last iteration } } ``` Although the question was asked...
How can I detect the last iteration in a loop over std::map?
[ "", "c++", "stl", "iterator", "maps", "" ]
I want to split an arithmetic expression into tokens, to convert it into RPN. Java has the StringTokenizer, which can optionally keep the delimiters. That way, I could use the operators as delimiters. Unfortunately, I need to do this in PHP, which has strtok, but that throws away the delimiters, so I need to brew some...
As often, I would just use a regular expression to do this: ``` $expr = '(5*(7 + 2 * -9.3) - 8 )/ 11'; $tokens = preg_split('/([*\/^+-]+)\s*|([\d.]+)\s*/', $expr, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); $tts = print_r($tokens, true); echo "<pre>x=$tts</pre>"; ``` It needs a little more work to ac...
This might help. [Practical Uses of Tokenizer](http://c7y.phparch.com/c/entry/1/art,practical_uses_tokenizer)
Standard algorithm to tokenize a string, keep delimiters (in PHP)
[ "", "php", "algorithm", "parsing", "" ]
What characters are valid in a Java class name? What other rules govern Java class names (for instance, Java class names cannot begin with a number)?
You can have almost any character, including most Unicode characters! The exact definition is in [the Java Language Specification under section 3.8: Identifiers](http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.8). > An *identifier* is an unlimited-length sequence of *Java letters* and *Java digits*, ...
> Every programming language has its own set of rules and conventions for the kinds of names that you're allowed to use, and the Java programming language is no different. The rules and conventions for naming your variables can be summarized as follows: > > * Variable names are case-sensitive. A variable's name can be ...
Valid characters in a Java class name
[ "", "java", "class", "unicode", "naming-conventions", "invalid-characters", "" ]
py2exe does not work with the standard email module Hello. I am trying to use py2exe for converting a script into an exe. The build process shows this: --- The following modules appear to be missing ## ['email.Encoders', 'email.Generator', 'email.Iterators', 'email.MIMEBase', 'email.MIMEMultipart', 'email.MIMEText'...
If you don't have to work with py2exe, bbfreeze works better, and I've tried it with the email module. <http://pypi.python.org/pypi/bbfreeze/0.95.4>
Have a look at this question [how-to-package-twisted-program-with-py2exe](https://stackoverflow.com/questions/169897/how-to-package-twisted-program-with-py2exe) it seems to be the same problem. The answer given there is to explicitly include the modules on the command line to py2exe.
Python - Py2exe can't build .exe using the 'email' module
[ "", "python", "winapi", "py2exe", "" ]
I have built an application in C# that I would like to be optimized for multiple cores. I have some threads, should I do more? **Updated for more detail** * C# 2.0 * Run on Windows Vista and Windows Server 2003 **Updated again** * This code is running as a service * I do not want to have the complete code... my goa...
I'd generalize that writing a highly optimized multi-threaded process is a lot harder than just throwing some threads in the mix. I recommend starting with the following steps: 1. Split up your workloads into discrete parallel executable units 2. Measure and characterize workload types - Network intensive, I/O intens...
You might want to take a look at the parallel extensions for .NET <http://msdn.com/concurrency>
How to make my code run on multiple cores?
[ "", "c#", "multithreading", "multicore", "" ]
In .NET, under which circumstances should I use `GC.SuppressFinalize()`? What advantage(s) does using this method give me?
`SuppressFinalize` should only be called by a class that has a finalizer. It's informing the Garbage Collector (GC) that `this` object was cleaned up fully. The recommended `IDisposable` pattern when you have a finalizer is: ``` public class MyClass : IDisposable { private bool disposed = false; protected vi...
`SupressFinalize` tells the system that whatever work would have been done in the finalizer has already been done, so the finalizer doesn't need to be called. From the .NET docs: > Objects that implement the IDisposable > interface can call this method from > the IDisposable.Dispose method to > prevent the garbage col...
When should I use GC.SuppressFinalize()?
[ "", "c#", ".net", "garbage-collection", "idisposable", "suppressfinalize", "" ]
I need to upload some data to a server using HTTP `PUT` method in Python. From my brief reading of the `urllib2` docs, it only does HTTP `POST`. Is there any way to do an HTTP `PUT` in Python?
I've used a variety of python HTTP libs in the past, and I've settled on [requests](https://requests.readthedocs.io/) as my favourite. Existing libs had pretty useable interfaces, but code can end up being a few lines too long for simple operations. A basic PUT in requests looks like: ``` payload = {'username': 'bob',...
``` import urllib2 opener = urllib2.build_opener(urllib2.HTTPHandler) request = urllib2.Request('http://example.org', data='your_put_data') request.add_header('Content-Type', 'your/contenttype') request.get_method = lambda: 'PUT' url = opener.open(request) ```
Is there any way to do HTTP PUT request in Python?
[ "", "python", "http", "put", "" ]
I was thinking about obfuscating a commercial .Net application. But is it really worth the effort to select, buy and use such a tool? Are the obfuscated binaries really safe from reverse engineering?
You may not have to buy a tool - Visual Studio.NET comes with a community version of Dotfuscator. Other free obfuscation tools [are listed here](http://twit88.com/blog/2007/09/15/free-net-obfuscation-tools/), and they may meet your needs. It's possible that the obfuscated binaries aren't safe from reverse engineering,...
Remember that obfuscation is only a barrier to the casual examiner of your code. If someone is serious about figuring out what you wrote, you will have a very hard time stopping them. If you have secrets in your code (like passwords), you're doing it wrong. If you worried someone might produce your own software with ...
Should you obfuscate a commercial .Net application?
[ "", "c#", ".net", "obfuscation", "" ]
I'm stuck on a PHP 4 server, and I would like to start moving an old legacy project to modern Design Patterns, including Dependency Injection. Are there any dependency injection frameworks that will work with PHP 4?
i found [this](http://drip.tigris.org/) (drip), but it looks like it hasn't been updated in a few years.
Most dependency injection frameworks use reflection to determine dependencies. Since PHP4 doesn't have typehints, you can't really do this. Experiments have been made with using config files - Some times embedded in comments in the code (Often called annotations). While this works, I find it a bit clunky. In my opinion...
Is there a Dependency Injection framework for PHP4?
[ "", "php", "dependency-injection", "design-patterns", "php4", "" ]
I have inherited a c# class 'Button' (which I can't change) which clashes with the BCL class 'Windows.Forms.Button'. Normally, Id be very happy to go: ``` MyPackage.MyClass.Button; ``` But there are a large number or references to this class which is a pain to have to re-type. Is there any way to get the compiler (l...
Add this to the top of the file: ``` using MyButton = MyPackage.MyClass.Button; ``` Now you can reference your custom button using a distinct name. You may need to do something similar for the stock button if you use that anywhere in the same file.
if you want to use it by default, replace ``` using Windows.Forms; ``` with ``` using MyPackage.MyClass; ``` If you do that, you'll need to fully qualify all the buttons from Windows.Forms. Or, if you want to, you can alias the namespace ``` using My = MyPackage.MyClass; //... then My.Button b = ... ``` Or alias...
C# Default scope resolution
[ "", "c#", "linker", "alias", "scope-resolution", "name-clash", "" ]
I have two tables that are joined together. A has many B Normally you would do: ``` select * from a,b where b.a_id = a.id ``` To get all of the records from a that has a record in b. How do I get just the records in a that does not have anything in b?
``` select * from a where id not in (select a_id from b) ``` Or like some other people on this thread says: ``` select a.* from a left outer join b on a.id = b.a_id where b.a_id is null ```
``` select * from a left outer join b on a.id = b.a_id where b.a_id is null ```
How do I find records that are not joined?
[ "", "sql", "select", "join", "anti-join", "" ]
The following test fails: ``` #!/usr/bin/env python def f(*args): """ >>> t = 1, -1 >>> f(*map(lambda i: lambda: i, t)) [1, -1] >>> f(*(lambda: i for i in t)) # -> [-1, -1] [1, -1] >>> f(*[lambda: i for i in t]) # -> [-1, -1] [1, -1] """ alist = [a() for a in args] print(ali...
They are different, because the value of `i` in both the generator expression and the list comp are evaluated lazily, i.e. when the anonymous functions are invoked in `f`. By that time, `i` is bound to the last value if `t`, which is -1. So basically, this is what the list comprehension does (likewise for the genexp...
The lambda captures variables, not values, hence the code ``` lambda : i ``` will always return the value i is **currently** bound to in the closure. By the time it gets called, this value has been set to -1. To get what you want, you'll need to capture the actual binding at the time the lambda is created, by: ``` ...
Why results of map() and list comprehension are different?
[ "", "python", "closures", "list-comprehension", "late-binding", "generator-expression", "" ]
When running one of our software, a tester was faced with the data execution prevention dialog of Windows. We try to reproduce this situation on a developer computer for debugging purposes : with no success. Does anyone know how to find what may cause the DEP protection to kill the application? Is there any existing ...
The DEP dialog will typically only show when you try to execute code from a region that you're not marking as executable. This might be caused by 'thunks' in a library you're using, e.g. ATL windowing. This problem is fixed in ATL 8.0. A stack-trashing bug - for example, a buffer overrun - can also cause this problem,...
Potentially I would think any time you try to write to memory that isn't allocated this would be a possible result. Could be anything along the lines of deleting an object then using it, or writing a string into a buffer which is too small to hold it.
Track Data Execution Prevention (DEP)
[ "", "c++", "dep", "" ]
Eclipse is a really great editor, which I prefer to use, but the GUI design tools for Eclipse are lacking. On the other hand, NetBeans works really well for GUI design. Are there any tips, tricks or pitfalls for using NetBeans for GUI design and Eclipse for everything else on the same project? **EDIT:** I tried Maven...
Create your GUI with Netbeans. copy a Eclipse .project file (like below) into the project folder change the MyProjectName. Open Eclipse and import the project into your workspace, so you can open the projekt from your Eclipse workspace with Netbeans. Now you able to use Netbeans to create and change the GUI and editing...
MyEclipse offers an integration of the Netbeans GUI editor (Matisse) with Eclipse. See <http://www.myeclipseide.com/module-htmlpages-display-pid-5.html>
Using both Eclipse and NetBeans on the same project
[ "", "java", "eclipse", "netbeans", "" ]
I'm looking for a decent lexical scanner generator for C#/.NET -- something that supports Unicode character categories, and generates somewhat readable & efficient code. Anyone know of one? --- EDIT: I ***need*** support for **Unicode categories**, not just Unicode characters. There are currently 1421 characters in j...
GPLEX seems to support your requirements.
The two solutions that come to mind are [ANTLR](http://www.antlr.org) and [Gold](http://www.devincook.com/goldparser/). ANTLR has a GUI based grammar designer, and an excellent sample project in C# [can be found here](http://www.codeproject.com/KB/recipes/sota_expression_evaluator.aspx).
C#/.NET Lexer Generators
[ "", "c#", ".net", "parsing", "generator", "lexical-analysis", "" ]
I know it's possible, and I've seen simple examples in the documentation, but are they being used in the wild? I use attributes at the class and method level all the time, but have never used them on method parameters. What are some real-world examples, and the reasons for the usage? I'm not interested in seeing a te...
You can for example create a ValidatorAttribute for every parameter, then before calling the method, you can reflect the parameter attributes and do parameter validation. Then call the method if all ok.
(I've left this answer here in case others find it a useful intro to PostSharp, but it doesn't actually answer the question properly! I misread the question as asking about method attributes instead of class attributes. Doh. From what I remember, the generated SOAP classes use parameter attributes. LINQ to SQL uses ret...
Is there a practical example of how they have used attributes on method parameters in .NET?
[ "", "c#", ".net", "" ]
Where can I find a list of all types of bsd style socket errors?
In the documentation? For instance, for connect(), see: ``` % man connect ... ECONNREFUSED No-one listening on the remote address. EISCONN The socket is already connected. ENETUNREACH Network is unreachable. ```
You can also find a list of error codes (and a general description of their meaning) on the Open Group's pages for each function (like [connect](http://www.opengroup.org/onlinepubs/009695399/functions/connect.html), for example).
good resource for socket errors?
[ "", "c++", "c", "sockets", "" ]
By default, in C++, a single-argument constructor can be used as an implicit conversion operator. This can be suppressed by marking the constructor as explicit. I'd prefer to make "explicit" be the default, so that the compiler cannot silently use these constructors for conversion. Is there a way to do this in standa...
Nope, you have to do it all by hand. It's a pain, but you certainly should get in the habit of making single argument constructors explicit. I can't imagine the pain you would have if you did find a solution and then had to port the code to another platform. You should usually shy away from compiler extensions like thi...
If there was a pragma or command line option that made constructors explicit by default, how would you declare one that is not explicit? There would have to be another compiler-specific token or pragma to make it possible to declare an implicit conversion constructor.
Forcing single-argument constructors to be explicit in C++?
[ "", "c++", "" ]
I'm using [Enunciate](http://enunciate.codehaus.org) to build a prototype REST api and need to include a jar containing custom code as a library. My Ant Script looks like this: ``` <!--include all jars--> <path id="en.classpath"> <fileset dir="${lib}"> <include name="**/*.jar" /> </fileset> </path> <...
As it turns out one of the jars we're attempting to include has a dependency listed in it's Manifest file of a jar that Enunciate depends on (freemarker). Enunciate automatically excludes freemarker and at first glance it seems as though it automatically excludes anything that depends on freemarker as well. If we remov...
I never used enunciate, but as a quick hack you can add the jars to the war: ``` <jar jarfile="${dist}/${war.name}" update="true"> <fileset dir="${lib}"> <include name="**/*.jar" /> </fileset> </jar> ``` Note: you probably want to add the jars to the **WEB-INF/lib** directory, instead of the root direc...
Why do Jars get Excluded from Enunciate's Deployment?
[ "", "java", "ant", "war", "enunciate", "" ]
I have an array of a few million numbers. ``` double* const data = new double (3600000); ``` I need to iterate through the array and find the range (the largest value in the array minus the smallest value). However, there is a catch. I only want to find the range where the smallest and largest values are within 1,000...
The algorithm you describe is really O(N), but i think the constant is too high. Another solution which looks reasonable is to use O(N\*log(N)) algorithm the following way: ``` * create sorted container (std::multiset) of first 1000 numbers * in loop (j=1, j<(3600000-1000); ++j) - calculate range - remove from t...
This type of question belongs to a branch of algorithms called streaming algorithms. It is the study of problems which require not only an O(n) solution but also need to work in a single pass over the data. the data is inputted as a stream to the algorithm, the algorithm can't save all of the data and then and then it ...
Algorithm for finding the maximum difference in an array of numbers
[ "", "c++", "algorithm", "statistics", "" ]
Is it possible to find out who called a stored procedure? For example, say I get an error in `proc3`. From within that proc I want to know if it was called by `proc1` or `proc2`.
I would use an extra input parameter, to specify the source, if this is important for your logic. This will also make it easier to port your database to another platform, since you don't depend on some obscure platform dependent function.
There is no nice automatic way to do this (alas). So it really depends on how much you are prepared to (re)write your procs in order to be able to do this. If you have a logging mechanism, you might be able to read the log and work out who called you. For example, if you implement logging by inserting to a table, for...
Find out the calling stored procedure in SQL Server
[ "", "sql", "sql-server", "database", "stored-procedures", "sql-server-2005", "" ]
I can understand the use for one level of namespaces. But 3 levels of namespaces. Looks insane. Is there any practical use for that? Or is it just a misconception?
Hierarchical namespaces do have a use in that they allow progressively more refined definitions. Certainly a single provider may produce two classes with the same name. Often the first level is occupied by the company name, the second specifies the product, the third (and possibly more) my provide the domain. There ar...
Obviously it's a matter of opinion. But it really boils down to organization. For example, I have a project which has a plugin api that has functions/objects which look something like this: ``` plugins::v1::function ``` When 2.0 is rolled out they will be put into the v2 sub-namespace. I plan to only deprecate but ne...
When have we any practical use for hierarchical namespaces in c++?
[ "", "c++", "namespaces", "" ]
If my code throws an exception, sometimes - not everytime - the jsf presents a blank page. I´m using facelets for layout. A similar error were reported at this [Sun forumn´s post](http://forums.sun.com/thread.jspa?messageID=10237827), but without answers. Anyone else with the same problem, or have a solution? ;) Due t...
I think this largely depends on your JSF implementation. I've heard that some will render blank screens. The one we were using would throw error 500's with a stack trace. Other times out buttons wouldn't work without any error for the user. This was all during our development phase. But the best advice I can give you...
I fixed a similar problem in my `error.jsp` page today. This won't be exactly the same as yours, but it might point someone in the right direction if they're having a similar problem. My problem seemed to be coming from two different sources. First, the `message` exception property wasn't being set in some of the serv...
Blank Page in JSF
[ "", "java", "jsf", "facelets", "" ]
In java, I could do this with the 'final' keyword. I don't see 'final' in C#. Is there a substitute?
You're looking for the `sealed` keyword. It does exactly what the `final` keyword in Java does. Attempts to inherit will result in a compilation error.
Also be aware that "I don't think anybody will ever need to inherit from this" is not a good reason to use "sealed". Unless you've got a specific need to ensure that a particular implementation is used, leave the class unsealed.
How can I keep a class from being inherited in C#?
[ "", "c#", ".net", "inheritance", "" ]
I have got a C function in a static library, let's call it A, with the following interface : ``` int A(unsigned int a, unsigned long long b, unsigned int *y, unsigned char *z); ``` This function will change the value of y an z (this is for sure). I use it from within a dynamic C++ library, using extern "C". Now, her...
First of all, I am very grateful to everyone for your help. Thanks to the numerous ideas and clues you gave me, I have been able to finally sort out this problem. Your advices helped me to question what I took for granted. Short answer to my problem : The problem was that my C++ library used an old version of the C li...
It looks like a difference between the the way your C library and C++ compiler is dealing with *long longs*. My guess is that it is that the C library is probably pre C89 standard and actually treating the 64bit *long long* as a 32bit long. Your C++ library is handling it correctly and placing 64bits on the call stack ...
Why is my parameter passed by reference not modified within the function?
[ "", "c++", "c", "parameters", "linker", "pass-by-reference", "" ]
You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is: ``` # File: ftplib-example-1.py import ftplib ftp = ftplib.FTP("www.python.org") ftp.login("anonymous", "ftplib-example-1") data = [] ftp.dir(data.append) ftp.quit() for line in data: print "-", li...
Try using [`ftp.nlst(dir)`](https://docs.python.org/3/library/ftplib.html#ftplib.FTP.nlst). However, note that if the folder is empty, it might throw an error: ``` files = [] try: files = ftp.nlst() except ftplib.error_perm as resp: if str(resp) == "550 No files found": print "No files in this direct...
The reliable/standardized way to parse FTP directory listing is by using MLSD command, which by now should be supported by all recent/decent FTP servers. ``` import ftplib f = ftplib.FTP() f.connect("localhost") f.login() ls = [] f.retrlines('MLSD', ls.append) for entry in ls: print entry ``` The code above will ...
Using Python's ftplib to get a directory listing, portably
[ "", "python", "ftp", "portability", "" ]
Java SE 6 (64 bit only) is now on OS X and that is a good thing. As I understand it since Eclipse is still Carbon and thus 32 bit, it cannot be used for 1.6 on Leopard, only 1.5. Does anyone know if NetBeans 6.x can be used with Java SE 6 on Leopard utilizing its JVM?
Yes, you should be able to. A number of blogs have reported running Netbeans on 1.6 as well as the the problems they had with earlier versions of NB. The NB issue tracker also has a number of bugs that have been fixed that affected 1.6 on Mac OS. If you have trouble getting it to run, you might also try [the Netbeans...
Eclipse works with java 1.6, kinda. Ecplipse runs using the 1.5 vm, but it can compile code for 1.6 using the 1.6 java compiler. I have used netbeans for 1.6 development and it seems alright.
Does anyone know if NetBeans 6.x can be used with Java SE 6 on Leopard?
[ "", "java", "eclipse", "netbeans", "osx-leopard", "" ]
This PHP code... ``` 207 if (getenv(HTTP_X_FORWARDED_FOR)) { 208 $ip = getenv('HTTP_X_FORWARD_FOR'); 209 $host = gethostbyaddr($ip); 210 } else { 211 $ip = getenv('REMOTE_ADDR'); 212 $host = gethostbyaddr($ip); 213 } ``` Throws this warning... > **Warning:** gethostbyaddr() >...
on php.net it says the following: > The function `getenv` does not work if your Server API is ASAPI (IIS). > So, try to don't use `getenv('REMOTE_ADDR')`, but `$_SERVER["REMOTE_ADDR"]`. Did you maybe try to do it with `$_SERVER`?
Why don't you use ``` $_SERVER['REMOTE_ADDR'] ``` and ``` $_SERVER['HTTP_X_FORWARDED_FOR'] ```
Why is getenv('REMOTE_ADDR') giving me a blank IP address?
[ "", "php", "ip-address", "" ]
Given a string `"filename.conf"`, how to I verify the extension part? I need a cross platform solution.
You have to make sure you take care of file names with more then one dot. example: `c:\.directoryname\file.name.with.too.many.dots.ext` would not be handled correctly by `strchr` or `find.` My favorite would be the [boost filesystem library](http://www.boost.org/doc/libs/release/libs/filesystem/index.html) that have a...
Is this too simple of a solution? ``` #include <iostream> #include <string> int main() { std::string fn = "filename.conf"; if(fn.substr(fn.find_last_of(".") + 1) == "conf") { std::cout << "Yes..." << std::endl; } else { std::cout << "No..." << std::endl; } } ```
How to get file extension from string in C++
[ "", "c++", "string", "filenames", "file-extension", "" ]
I'm developing a web service whose methods will be called from a "dynamic banner" that will show a sort of queue of messages read from a sql server table. The banner will have a heavy pressure in the home pages of high traffic sites; every time the banner will be loaded, it will call my web service, in order to obtain...
It depends on a lot of things: * If there is little change in the data (think backend with "publish" button or daily batches), then I would definitely use static files (updated via push from the backend). We used this solution on a couple of large sites and worked really well. * If the data is small enough, memory cac...
I think caching is a reasonable approach and you can take it a step further and add a SQL Dependency to it. [ASP.NET Caching: SQL Cache Dependency With SQL Server 2000](http://www.c-sharpcorner.com/UploadFile/mosessaur/sqlcachedependency01292006135138PM/sqlcachedependency.aspx?ArticleID=3caa7d32-dce0-44dc-8769-77f8448...
Hints for a high-traffic web service, c# asp.net sql2000
[ "", "c#", "web-services", "high-load", "" ]
What is the difference between `#include` and `#import` in C++?
`#import` is a Microsoft-specific thing, apparently for COM or .NET stuff only. `#include` is a standard C/C++ preprocessor statement, used for including header (or occasionally other source code) files in your source code file.
**Import in VC++:** `#import` is for type libraries or .tlbs (COM stuff). The content of the type library is converted into C++ classes, mostly describing the COM interfaces for you automatically, and then it is included into your file. The `#import` directive was introduced by Microsoft as an extension to the C++ la...
C++ #include and #import difference
[ "", "c++", "visual-c++", "gcc", "import", "include", "" ]
I've written a little script to iterate across files in folders to count lines of code. The heart of the script is this function to count lines of whitespace, comments, and code. (Note that for the moment it is tailored to C# and doesn't know about multi-line comments). It just doesn't look very nice to me - has anyo...
I think what you have is fine, but here's some variety to mix it up. (This solution repeats your problem of ignoring trailing whitespace.) ``` type Line = | Whitespace = 0 | Comment = 1 | Code = 2 let Classify (l:string) = let s = l.TrimStart([|' ';'\t'|]) match s with | "" | "...
A better site for this might be [refactormycode](http://refactormycode.com/) - it's tailored exactly for these questions.
Can you improve this 'lines of code algorithm' in F#?
[ "", "c#", "algorithm", "f#", "" ]
When using IF statements in Python, you have to do the following to make the "cascade" work correctly. ``` if job == "mechanic" or job == "tech": print "awesome" elif job == "tool" or job == "rock": print "dolt" ``` Is there a way to make Python accept multiple values when checking for "equals to"? Fo...
``` if job in ("mechanic", "tech"): print "awesome" elif job in ("tool", "rock"): print "dolt" ``` The values in parentheses are a tuple. The `in` operator checks to see whether the left hand side item occurs somewhere inside the right handle tuple. Note that when Python searches a tuple or list using the `in...
You can use in: ``` if job in ["mechanic", "tech"]: print "awesome" ``` When checking very large numbers, it may also be worth storing off a set of the items to check, as this will be faster. Eg. ``` AwesomeJobs = set(["mechanic", "tech", ... lots of others ]) ... def func(): if job in AwesomeJobs: ...
Using OR comparisons with IF statements
[ "", "python", "comparison", "boolean", "" ]
Right now, I have two Eclipse projects - they both use Maven 2 for all their jar-dependency goodness. Inside Eclipse, I have project Foo included in project Bar's build path, so that I can use Foo's classes from project Bar. This works really well in Eclipse land, but when I try: ``` mvn compile ``` inside Bar's dir...
Maybe you are referencing the other project via Eclipse configure-> build path only. This works as long as you use Eclipse to build your project. Try running first `mvn install` in project Bar (in order to put Bar in your Maven repository), and then add the dependency to Foo's pom.xml. That should work!.
Check out the [m2eclipse](https://www.eclipse.org/m2e/) plugin. It will automatically and dynamically update the project build path when you change the pom. There is no need for running `mvn eclipse:eclipse`. The plugin will also detect if any dependency is in the same workspace and add that project to the build path....
Adding referenced Eclipse projects to Maven dependencies
[ "", "java", "eclipse", "maven-2", "" ]
When working with large and/or many Javascript and CSS files, what's the best way to reduce the file sizes?
In addition to using server side compression, using intelligent coding is the best way to keep bandwidth costs low. You can always use tools like [Dean Edward's Javascript Packer](http://dean.edwards.name/download/#packer), but for CSS, take the time to learn [CSS Shorthand](http://www.webcredible.co.uk/user-friendly-r...
[Minify](http://developer.yahoo.net/blog/archives/2007/07/high_performanc_8.html) seems to be one of the easiest ways to shrink Javascript. Turning on zip at the web server level can also help.
What is the best method to reduce the size of my Javascript and CSS files?
[ "", "javascript", "css", "jscompress", "" ]
I have created my own Tree implementation for [various reasons](https://stackoverflow.com/questions/144642/tree-directed-acyclic-graph-implementation) and have come up with two classes, a 'base' class that is a generic tree node that is chock full of logic and another class that extends that one which is more specialis...
So, after getting my copy of [Design Patterns](https://rads.stackoverflow.com/amzn/click/com/0201633612) and opening it for what I'm fairly sure is the first time ever I discovered what I want. It's called the [Factory Method](http://en.wikipedia.org/wiki/Factory_method) and it's mostly a perfect fit. It's still a bit...
In addition to the Factory pattern, I'd take a look at the Composite pattern - it tends to lend itself well to working with a Factory in tree-based situations. [Composite Design Pattern](http://en.wikipedia.org/wiki/Composite_pattern)
Is it OK to have object instantation 'hooks' in base classes?
[ "", "java", "inheritance", "" ]
## Summary Is that possible for webapps deployed on linux + tomcat5.5 to use/see all `/usr/share/java/` jars automatically? ## Details I'm packaging my java webapp for Ubuntu (yet the question is related to any linux-based distro) and going to make it depend on tomcat. I'm going to put context descriptor (an xml fi...
You should not do that. Java EE applications are the supposed to be self sufficient and not depend on any resources outside the deployment package other than those provided by the container. So you should take the libs you need from that directory and add it to your war or ear package. This guarantees that your applic...
According to [the Tomcat classloading documentation](http://tomcat.apache.org/tomcat-5.5-doc/class-loader-howto.html), you need to put any shared libs that should be available to all Tomcat apps in the $CATALINA\_BASE/shared/lib library -- so one way to do what you're looking to do is to move your libraries from /usr/s...
How to add /usr/share/java libs to webapp's classpath?
[ "", "java", "linux", "tomcat", "web-applications", "classpath", "" ]
Is the sorting algorithm used by .NET's `Array.Sort()` method a [stable](http://en.wikipedia.org/wiki/Stable_sort#Classification) algorithm?
From [MSDN](http://msdn.microsoft.com/en-us/library/6tf1f0bc.aspx): > This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal. The sort uses introspective sort. (Quicksort in versio...
Adding to [Rasmus Faber's answer](https://stackoverflow.com/questions/148074/net-is-arraysort-stable-sort#148081)… Sorting in LINQ, via [Enumerable.OrderBy](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.orderby.aspx) and [Enumerable.ThenBy](http://msdn.microsoft.com/en-us/library/system.linq.enumerabl...
Is the sorting algorithm used by .NET's `Array.Sort()` method a stable algorithm?
[ "", "c#", ".net", "" ]
I have a method which should be executed in an exclusive fashion. Basically, it's a multi threaded application where the method is invoked periodically by a timer, but which could also be manually triggered by a user action. Let's take an example : 1. The timer elapses, so the method is called. The task could take...
This looks reasonable if you are just interested in not having the method run in parallel. There's nothing to stop it from running immediately after each other, say that you pushed the button half a microsecond after the timer executed the Monitor.Exit(). And having the lock object as readonly static also make sense.
You could also use `Mutex` or `Semaphore` if you want it to work cross process (with a slight performance penalty), or if you need to set any other number than one of allowed simultaneous threads running your piece of code. There are other signalling constructs that would work, but your example looks like it does the ...
How to make a method exclusive in a multithreaded context?
[ "", "c#", ".net", "multithreading", "locking", "" ]
Which one should I use? ``` catch (_com_error e) ``` or ``` catch (_com_error& e) ```
The second. Here is my attempt at quoting Sutter "Throw by value, catch by reference" > Learn to `catch` properly: Throw exceptions by value (not pointer) and > catch them by reference (usually to `const`). This is the combination > that meshes best with exception semantics. When rethrowing the same > exception, pref...
Personally, I would go for the third option: ``` catch (const _com_error& e) ```
Which is correct? catch (_com_error e) or catch (_com_error& e)?
[ "", "c++", "exception", "com", "" ]
I'm sure this is a subject that's on most python developers' minds considering that Python 3 is coming out soon. Some questions to get us going in the right direction: 1. Will you have a python 2 and python 3 version to be maintained concurrently or will you simply have a python 3 version once it's finished? * Hav...
Here's the general plan for Twisted. I was originally going to blog this, but then I thought: why blog about it when I could get *points* for it? 1. **Wait until somebody cares.** Right now, nobody has Python 3. We're not going to spend a bunch of effort until at least one actual user has come forth and said "I ne...
The Django project uses the library [`six`](http://packages.python.org/six) to maintain a codebase that works simultaneously on Python 2 *and* Python 3 ([blog post](https://www.djangoproject.com/weblog/2012/aug/19/experimental-python-3-support/)). `six` does this by providing a compatibility layer that intelligently r...
How are you planning on handling the migration to Python 3?
[ "", "python", "migration", "python-3.x", "python-2to3", "" ]
I'm working with a webservice that offers almost duplicated code across two namesspaces. Lets say for example PigFeet and HorseFeet, both namespaces contain a Feet class and other code that works with the Feet class requires it to be part of that same namespace. Right now In my code I'm forced to do something like thi...
The namespace isn't the problem - it's simply that the 2 classes aren't related, so there's no inheritance chain that you can use for polymorphism. You'll need to look at something like [duck typing](http://www.deftflux.net/blog/page/Duck-Typing-Project.aspx), or an [adapter pattern](http://en.wikipedia.org/wiki/Adapt...
In your namespace imports you can assign an [alias](http://msdn.microsoft.com/en-us/library/aa664765(VS.71).aspx) to a specific namespace or member. ``` using PigFeet = PigFeet.Feet; using HorseFeet = HorseFeet.Feet; //now your sample code should look something like if( _animalType == AnimalType.Pig ) { //name...
Same class, different namespaces, a way to simplify?
[ "", "c#", "namespaces", "" ]
I have two tables, **Book** and **Tag**, and books are tagged using the association table **BookTag**. I want to create a report that contains a list of books, and for each book a list of the book's tags. Tag IDs will suffice, tag names are not necessary. Example: ``` Book table: Book ID | Book Name 28 | Dracula...
You can almost do it. The only problem I haven't resolved is the comma delimiter. Here is a query on a similar structure that separates the tags using a space. ``` SELECT em.Code, (SELECT et.Name + ' ' AS 'data()' FROM tblEmployeeTag et JOIN tblEmployeeTagAssignment eta ON et.Id = eta.Employee...
Unless you know what the tag ids/names are and can hard code them into your query, I'm afraid the answer is no.
Query showing list of associations in many-to-many relationship
[ "", "sql", "sql-server", "database", "" ]
I am trying to leverage ORM given the following requirements: 1) Using .NET Framework (latest Framework is okay) 2) Must be able to use Sybase, Oracle, MSSQL interchangeably 3) The schema is mostly static, BUT there are dynamic parts. I am somewhat familiar with SubSonic and NHibernate, but not deeply. I get th...
Acording to this blog you can in fact use [NHibernate with dynamic mapping](http://ayende.com/Blog/archive/2008/05/01/Dynamic-Mapping-with-NHibernate.aspx). It takes a bit of tweaking though...
We did some of the using NHibernate, however we stopped the project since it didn't provide us with the ROI we wanted. We ended up writing our own ORM/SQL layer which worked very well (worked since I no longer work there, I'm guessing it still works). Our system used a open source project to generate the SQL (don't re...
How can I leverage an ORM for a database whose schema is unknown until runtime?
[ "", "c#", ".net", "database", "orm", "dynamic", "" ]
I am working on a web application, where I transfer data from the server to the browser in XML. Since I'm danish, I quickly run into problems with the characters `æøå`. I know that in html, I use the `"&amp;aelig;&amp;oslash;&amp;aring;"` for `æøå`. however, as soon as the chars pass through JavaScript, I get black ...
Just specifying UTF-8 in the header is not enough. I'd bet you haven't saved your file as UTF-8. Any reasonably advanced text editor will have this option. Try that and I'm sure it'll work!
If you ever can't set the response encoding, you can use `\u` escape sequence in the JavaScript string literal to display these characters. ``` alert("\u00e6\u00f8\u00e5") ```
international characters in Javascript
[ "", "javascript", "unicode", "internationalization", "character-encoding", "" ]
I've heard that `SELECT *` is generally bad practice to use when writing SQL commands because it is more efficient to `SELECT` columns you specifically need. If I need to `SELECT` every column in a table, should I use ``` SELECT * FROM TABLE ``` or ``` SELECT column1, colum2, column3, etc. FROM TABLE ``` Does the ...
One reason that selecting specific columns is better is that it raises the probability that SQL Server can access the data from indexes rather than querying the table data. Here's a post I wrote about it: [**The real reason select queries are bad index coverage**](http://weblogs.asp.net/jgalloway/archive/2007/07/18/th...
Given **your** specification that you **are** selecting all columns, there is little difference **at this time**. Realize, however, that database schemas do change. If you use **`SELECT *`** you are going to get any new columns added to the table, even though in all likelihood, your code is not prepared to use or prese...
Which is faster/best? SELECT * or SELECT column1, colum2, column3, etc
[ "", "sql", "database", "performance", "select", "sqlperformance", "" ]
There are several different methods for converting floating point numbers to Integers in JavaScript. My question is what method gives the best performance, is most compatible, or is considered the best practice? Here are a few methods that I know of: ``` var a = 2.5; window.parseInt(a); // 2 Math.floor(a); // 2 ...
According to [**this website**](http://www.jibbering.com/faq/faq_notes/type_convert.html#tcParseIn): > parseInt is occasionally used as a means of turning a floating point number into an integer. It is very ill suited to that task because if its argument is of numeric type it will first be converted into a string and ...
Apparently double bitwise-not is the fastest way to floor a number: ``` var x = 2.5; console.log(~~x); // 2 ``` Used to be an article here, getting a 404 now though: <http://james.padolsey.com/javascript/double-bitwise-not/> ~~Google has it cached: `http://74.125.155.132/search?q=cache:wpZnhsbJGt0J:james.padolsey.co...
What is the best method to convert floating point to an integer in JavaScript?
[ "", "javascript", "variables", "types", "" ]
What is the best way to generate a Unique ID from two (or more) short ints in C++? I am trying to uniquely identify vertices in a graph. The vertices contain two to four short ints as data, and ideally the ID would be some kind of a hash of them. Prefer portability and uniqueness over speed or ease. There are a lot of...
A simple solution is to use a 64 bit integer where the lower 16 bits is the first vertex coordinate, next 16 bits is the second, and so on. This will be unique for all your vertices, though not very compact. So here's some half-assed code to do this. Hopefully I got the casts right. ``` uint64_t generateId( uint16_t ...
Sometimes the simplest things works best. Can you just add an id field to the Vertex object and assign it a number in order of construction? ``` static int sNextId = 0; int getNextId() { return ++sNextId; } ```
Generating a Unique ID in c++
[ "", "c++", "hash", "" ]
I have a method that periodically (e.g. once in every 10 secs) try to connect to a server and read some data from it. The server might not be available all the time. If the server is not available the method throws an exception. What would be the best way to implement a wrapper method that doesn't throw an exception e...
Keep track of when the last time you successfully reached the server was. If the server throws an exception, catch it and compare to the last time you reached the server. If that time is more than a minute, rethrow the exception.
In pseudocode. ``` //Create Timer //Start Timer bool connected = false; while (!connected) try { //Connect To DB connected = true; } catch (Exception ex) { if (more than 1 minute has passed) throw new Exception(ex); } } ```
Delaying an exception
[ "", "java", "exception", "" ]
I am writing a C# program which captures signals from a external device, and sends keystrokes to another application. I am using SendKeys and it works fine. SendKeys does "press" a key by holding and releasing it immediately. I would like to make it push key and release it at will. My question is : "is there a way to...
I don't think it's possible from .NET directly You could try using keybd\_event native call by p/invoking the function as described here: <http://pinvoke.net/default.aspx/user32.keybd_event> The MSDN for keybd\_event is here: <http://msdn.microsoft.com/en-us/library/ms646304(VS.85).aspx> Hope that helps!
The accepted answer uses `keybd_event` which is deprecated. The official API is now [`SendInput`](http://msdn.microsoft.com/en-us/library/ms646310%28VS.85%29.aspx). There's also a nice wrapper for it at <http://inputsimulator.codeplex.com>. None of the above, however, fully caters to the "key holding" scenario. This i...
How to push a key and release it using C#?
[ "", "c#", "keyboard", "" ]
I've created a web page that lets you input some information and then draws an image in a canvas element based on that info. I have it pretty much working the way I want except for the printing. Is there a way to print out the canvas element or is creating a new window to draw in, the only way to do it? Update: The ...
You could try something like this: ``` @media print { * { display:none; } #SOME-CANVAS-ID { display:block; } } ``` I'm not sure if a canvas is block by default, but you could try something along the lines of that and see if it works. The idea is that it will hide everything (\*) for print media, exce...
I'm not 100% sure of the support, but you can use CSS and put an attribute in the `<link>` tag for `media="print"`. In this CSS file, just hide the elements you don't want to show while printing: `display:none;`
Is it possible to print just the canvas element?
[ "", "javascript", "printing", "canvas", "" ]
Unquestionably, I would choose to use the STL for most C++ programming projects. The question was presented to me recently however, "Are there any cases where you wouldn't use the STL?"... The more I thought about it, the more I realized that perhaps there SHOULD be cases where I choose not to use the STL... For examp...
Projects with strict memory requirements such as for embedded systems may not be suited for the STL, as it can be difficult to control and manage what's taken from and returned to the heap. As Evan mentioned, writing proper allocators can help with this, but if you're counting every byte used or concerned with memory f...
The main reasons not to use STL are that: 1. Your C++ implementation is old and has horrible template support. 2. You can't use dynamic memory allocation. Both are very uncommon requirements in practice. For a longterm project rolling your own containers that overlap in functionality with the STL is just going to in...
To STL or !STL, that is the question
[ "", "c++", "stl", "containers", "" ]
I have an idea for how to solve this problem, but I wanted to know if there's something easier and more extensible to my problem. The program I'm working on has two basic forms of data: images, and the information associated with those images. The information associated with the images has been previously stored in a ...
My brain is fried at the moment, so I'm not sure I can advise for or against a database, but if you're looking for version-agnostic serialization, you'd be a fool to not at least check into [Protocol Buffers](http://code.google.com/apis/protocolbuffers/docs/overview.html). Here's a quick list of implementations I know...
[Sqlite](http://www.sqlite.org/) is what you want. It's a fast, embeddable, single-file database that has bindings to most languages. With regards to extensibility, you can store your models with default attributes, and then have a separate table for attribute extensions for future changes. A year or two down the roa...
Best (free) way to store data? How about updates to the file system?
[ "", "c#", "extensibility", "data-storage", "" ]
I haven't a clue about encryption at all. But I need it. How? Say you have a system of nodes communicating with each other on a network via asynchronous messages. The nodes do not maintain session information about other nodes (this is a design restriction). Say you want to make sure only your nodes can read the mess...
Your first thought should be channel security - either SSL/TLS, or IPSec. Admittedly, these both have a certain amount of setup overhead, IPSec more than SSL/TLS, especially when it comes to PKI etc. - but it more than pays for itself in simplicity of development, reliability, security, and more. Just make sure you'r...
> I haven't a clue about encryption at all. But I need it. How? **DANGER!** If you don't know much about cryptography, don't try to implement it yourself. Cryptography is *hard to get right*. There are many, many different ways to break the security of a cryptographic system beyond actually cracking the key (which is ...
What symmetric cypher to use for encrypting messages?
[ "", "python", "security", "encryption", "" ]
I have a table that has redundant data and I'm trying to identify all rows that have duplicate sub-rows (for lack of a better word). By sub-rows I mean considering `COL1` and `COL2` only. So let's say I have something like this: ``` COL1 COL2 COL3 --------------------- aa 111 blah_x aa 111 blah_...
Does this work for you? ``` select t.* from table t left join ( select col1, col2, count(*) as count from table group by col1, col2 ) c on t.col1=c.col1 and t.col2=c.col2 where c.count > 1 ```
With the data you have listed, your query is not possible. The data on rows 5 & 6 is not distinct within itself. Assuming that your table is named 'quux', if you start with something like this: ``` SELECT a.COL1, a.COL2, a.COL3 FROM quux a, quux b WHERE a.COL1 = b.COL1 AND a.COL2 = b.COL2 AND a.COL3 <> b.COL3 ORDER ...
What's the SQL query to list all rows that have 2 column sub-rows as duplicates?
[ "", "sql", "database", "platform-agnostic", "" ]
I use both ruby on rails and Java. I really enjoy using migrations when I am working on a rails project. so I am wondering is there a migrations like tool for Java? If there is no such tool is it a good idea to use migrations as a tool to control a database used by a Java project?
I've used Hibernate's SchemaUpdate to perform the same function as migrations. It's actually easier than migrations because every time you start up your app, it examines the database structure and syncs it up with your mappings so there's no extra rake:db:migrate step and your app can never be out of sync with the data...
For a **feature comparison** between * Flyway * Liquibase * c5-db-migration * dbdeploy * mybatis * MIGRATEdb * migrate4j * dbmaintain * AutoPatch have a look at <http://flywaydb.org> This should be a good start for you and anyone else to **select the right tool for the job**
Migrations for Java
[ "", "java", "ruby-on-rails", "migration", "" ]
I have a number of stored procs which I would like to all run simultaneously on the server. Ideally all on the server without reliance on connections to an external client. What options are there to launch all these and have them run simultaneously (I don't even need to wait until all the processes are done to do addi...
In the end, I created a C# management console program which launches the processes Async as they are able to be run and keeps track of the connections.
Is SSIS an option for you? You can create a simple package with parallel Execute SQL tasks to execute the stored procs simultaneously. However, depending on what your stored procs do, you may or may not get benefit from starting this in parallel (e.g. if they all access the same table records, one may have to wait for ...
Spawning multiple SQL tasks in SQL Server 2005
[ "", "sql", "sql-server", "sql-server-2005", "automation", "parallel-processing", "" ]
While it would be very convenient to use inline functions at some situations, Are there any drawbacks with inline functions? **Conclusion**: Apparently, There is nothing wrong with using inline functions. But it is worth noting the following points! * Overuse of inlining can actually make programs slower. Dependin...
It worth pointing out that the inline keyword is actually just a hint to the compiler. The compiler may ignore the inline and simply generate code for the function someplace. The main drawback to inline functions is that it can **increase the size of your executable** (depending on the number of instantiations). This ...
It could increase the size of the executable, and I don't think compilers will always actually make them inline even though you used the inline keyword. (Or is it the other way around, like what [Vaibhav](https://stackoverflow.com/questions/60830/what-is-wrong-with-using-inline-functions#60833) said?...) I think it's ...
What is wrong with using inline functions?
[ "", "c++", "inline-functions", "" ]
I've got a Win32 C++ app with a suite of unit tests. After the unit tests have finished running, I'd like a human-readable report on any unfreed memory to be automatically generated. Ideally, the report will have a stack with files & line number info for each unfreed allocation. It would be nice to have them generated ...
I played around with the CRT Debug Heap functions Mike B pointed out, but ultimately I wasn't satisfied just getting the address of the leaked memory. Getting the stacks like UMDH provides makes debugging so much faster. So, in my main() function now I launch UMDH using CreateProcess before and after I run the tests to...
To obtain this sort of information, we override new/delete and malloc/free, providing our own heap implementations that store stacktraces on allocation and produce a report when the heap is destroyed (as well as adding sentinels to detect buffer overruns). This is a fair bit of work the first time you do it. [This guy...
Memory leak detection while running unit tests
[ "", "c++", "winapi", "memory-leaks", "" ]
I have a multi-line string that I want to do an operation on each line, like so: ``` inputString = """Line 1 Line 2 Line 3""" ``` I want to iterate on each line: ``` for line in inputString: doStuff() ```
``` inputString.splitlines() ``` Will give you a list with each item, the [`splitlines()`](https://docs.python.org/3/library/stdtypes.html#str.splitlines) method is designed to split each line into a list element.
``` inputString.split('\n') # --> ['Line 1', 'Line 2', 'Line 3'] ``` This is identical to the above, but the string module's functions are deprecated and should be avoided: ``` import string string.split(inputString, '\n') # --> ['Line 1', 'Line 2', 'Line 3'] ``` Alternatively, if you want each line to include the...
How do I split a multi-line string into multiple lines?
[ "", "python", "string", "split", "" ]
I'm looking for a getopt library for c#. So far I found a few ([phpguru](http://www.phpguru.org/static/getopt.html), [XGetOptCS](http://69.10.233.10/KB/cs/XGetoptCS.aspx), [getoptfordotnet](http://www.codeproject.com/KB/cs/geoptfordotnet.aspx)) but these look more like unfinished attempts that only support a part of C'...
Here is a .NET Implementation of getopt: <http://www.codeplex.com/getopt>
Miguel de Icaza [raves about Mono.Options](http://tirania.org/blog/archive/2008/Oct-14.html). You can use the [nuget package](https://www.nuget.org/packages/Mono.Options/), or just copy the [single C# source file](https://github.com/mono/mono/blob/master/mcs/class/Mono.Options/Mono.Options/Options.cs) into your project...
GetOpt library for C#
[ "", "c#", "getopt", "" ]