Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have some global variables in a Python script. Some functions in that script call into C - is it possible to set one of those variables while in C and if so, how?
I appreciate that this isn't a very nice design in the first place, but I need to make a small change to existing code, I don't want to embark on major re... | I'm not a python guru, but I found this question interesting so I googled around. [This](https://mail.python.org/pipermail/python-list/2007-September/427041.html) was the first hit on "python embedding API" - does it help?
> If the attributes belong to the global
> scope of a module, then you can use
> "PyImport\_AddM... | For anyone coming here from Google, here's the direct method:
```
PyObject* PyEval_GetGlobals()
```
<https://docs.python.org/2/c-api/reflection.html>
<https://docs.python.org/3/c-api/reflection.html>
The return value is accessed as a dictionary. | How to access a Python global variable from C? | [
"",
"python",
"c",
""
] |
With VS2005, I want to create a DLL and automatically export all symbols without adding `__declspec(dllexport)` everywhere, and without hand-creating `.def` files. Is there a way to do this? | ## Short answer
You can do it with help of the new version of the CMake (any version cmake-3.3.20150721-g9cd2f-win32-x86.exe or higher).
Currently it's in the dev branch.
Later, the feature will be added in the release version of the cmake-3.4.
Link to the cmake dev:
[cmake\_dev](http://www.cmake.org/files/dev/)
L... | It can be done...
The way we do it here is to use the /DEF option of the linker to pass a ["module definition file"](https://learn.microsoft.com/en-us/cpp/build/reference/module-definition-dot-def-files?view=vs-2017) containing a list of our exports. I see from your question that you know about these files. However, w... | Export all symbols when creating a DLL | [
"",
"c++",
"windows",
"visual-studio",
"visual-studio-2005",
""
] |
I have 50+ kiosk style computers that I want to be able to get a status update, from a single computer, on demand as opposed to an interval. These computers are on a LAN in respect to the computer requesting the status.
I researched WCF however it looks like I'll need IIS installed and I would rather not install IIS o... | Unless you have plans to scale this to several thousand clients I don't think WCF performance will even be a fringe issue. You can easily host WCF services from windows services or Winforms applications, and you'll find getting something working with WCF will be fairly simple once you get the key concepts.
I've deploy... | WCF does not have to be hosted within IIS, it can be hosted within your Winform, as a console application or as windows service.
You can have each computer host its service within the winform, and write a program in your own computer to call each computer's service to get the status information.
Another way of doing i... | Communication between server and client for WinForms | [
"",
"c#",
".net",
"networking",
""
] |
Why does Resharper want you to change most variables to var type instead of the actual type in the code? | It's just an option. You can disable it:
ReSharper -> Options -> Code Inspection -> Inspection Severity -> Code Redundencies -> Use 'var' keyword where possible: change this to "Do not show"
There's also the context (lightbulb) option which will take you in each direction - this is under ReSharper -> Options -> Langu... | I saw a video from Hadi Hariri, where he was presenting Resharper 6.x. His reasoning was, if you are forcing a user to use "var", you are actually forcing him to name the variable in a more meaningful way, that way all the names are readable and make more sense. | Resharper: vars | [
"",
"c#",
".net",
"resharper",
""
] |
Is there ever a good reason to *not* declare a virtual destructor for a class? When should you specifically avoid writing one? | There is no need to use a virtual destructor when any of the below is true:
* No intention to derive classes from it
* No instantiation on the heap
* No intention to store with access via a pointer to a superclass
No specific reason to avoid it unless you are really so pressed for memory. | To answer the question explicitly, i.e. when should you *not* declare a virtual destructor.
**C++ '98/'03**
Adding a virtual destructor might change your class from being [POD (plain old data)](https://en.wikipedia.org/wiki/Passive_data_structure)\* or aggregate to non-POD. This can stop your project from compiling i... | When should you not use virtual destructors? | [
"",
"c++",
"virtual-functions",
"virtual-destructor",
""
] |
Is there an easy way to generate an array containing the letters of the alphabet in C#? It's not too hard to do it by hand, but I was wondering if there was a built in way to do this. | I don't think there is a built in way, but I think the easiest would be
```
char[] alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
``` | C# 3.0 :
```
char[] az = Enumerable.Range('a', 'z' - 'a' + 1).Select(i => (Char)i).ToArray();
foreach (var c in az)
{
Console.WriteLine(c);
}
```
yes it does work even if the only overload of Enumerable.Range accepts int parameters ;-) | Generating an array of letters in the alphabet | [
"",
"c#",
"alphabet",
""
] |
I have some old C code that I would like to combine with some C++ code.
The C code used to have has the following includes:
```
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include "mysql.h"
```
Now I'm trying to make it use C++ with iostream like this:
```
#include <windows.h>
#include <stdio.h>
#i... | The C `string.h` header and the C++ `string` header are not interchangeable.
Overall, though, your problem is that the file is getting properly compiled, but the wrong runtime library is getting linked in.
Dev-C++ uses GCC. GCC can correctly determine the language in a file based on file extension, but won't link the... | You need to link against your C++ runtime. It depends on your platform and compiler, but adding `-lc` to your linker command might do it.
So might linking using your C++ compiler rather than `ld`.
In any case, you probably have to link using the C++ compiler rather than `ld` if you want your C++ code to work correctl... | iostream linker error | [
"",
"c++",
"c",
"linker",
"iostream",
""
] |
I was wondering if there is a way to implement an action listener for a Jbutton without a name. For example, I have the following for loop that creates a button for each letter of the alphabet.
```
for (int i = 65; i < 91; i++){
alphabetPanel.add(new JButton("<html><center>" + (char)i));
}
```
Is there a way tha... | Your question is a little vague. it would be trivial to modify the loop to add a listener inside the loop:
```
ActionListener listener = something;
for (int i = 65; i < 91; i++){
JButton button = new JButton("<html><center>" + (char)i);
button.addActionListener( listener );
alphabetPanel.add(button);
}... | What is the problem of doing this?
```
for (int i = 65; i < 91; i++){
JButton button = new JButton("<html><center>" + (char)i));
button.addActionListener( new ButtonListener());
alphabetPanel.add(button);
}
```
...
```
class ButtonListener implements ActionListener {
ButtonListener() {
}
... | Java actionListener for a nameless JButton? | [
"",
"java",
"swing",
"jbutton",
"actionlistener",
""
] |
I'm using a PropertyGrid in a tool app to show a window to monitor an object in a remote app. Every second or so I get an update from the app with the state of any members that have changed, and I update the grid. I call Refresh() to make the changes take. This all works pretty well except one thing.
Say the object is... | This is not possible in the MS PropertyGrid. This component has too many unaccessible internals to give you the flexibility you are requesting and as you realized yourself it is not consistent (you have the issue for a property below the grid but not when it is above). That's why I created [Smart PropertyGrid.Net](http... | I`ve found an interesting hack:
you can manually select the grid items you changed and they will refresh :)
```
var panProp = categ.GridItems[3];
var tiltProp = categ.GridItems[4];
panProp.Select();
tiltProp.Select();
```
So I select items I need and than move the selection back | How to prevent scroll on Refresh in a PropertyGrid? | [
"",
"c#",
"propertygrid",
""
] |
How can I get the name of a file in in PHP? What I want to do is have a function take a string of a filename and then do some stuff if it's actually on the page.
```
function onThisPageFunction(fileNameFromFunction)
{
if(onThisPage == fileNameFromFunction)
{
do stuff
}
}
``` | There are two variables that will give you file names.
eg: you call /test/test1.php as the url and test1.php includes test2.php.
[`__FILE__`](http://pl.php.net/manual/en/language.constants.predefined.php) will give you the current file of the executing code, in this case it will return "test2.php"
[`$_SERVER['PHP_SE... | If I understand correctly you want `__FILE__`.
Ref: <http://php.net/manual/en/language.constants.predefined.php> | Getting the name of file in PHP | [
"",
"php",
""
] |
I've used MS Word automation to save a .doc to a .htm. If there are bullet characters in the .doc file, they are saved fine to the .htm, but when I try to read the .htm file into a string (so I can subsequently send to a database for ultimate storage as a string, not a blob), the bullets are converted to question marks... | On my system (using US-English) Word saves \*.htm files in the Windows-1252 codepage. If your system uses that codepage, then that is what you should read it in as.
```
string html = File.ReadAllText(originalFile, Encoding.GetEncoding(1252));
```
It is also possible that whatever you are using the view the results ma... | Did you try opening the file in binary mode. If you open in test mode I think it will chop up the unicode characters. | .NET: Convert .doc to .htm results in funky characters | [
"",
"c#",
"encoding",
""
] |
If I have 2 DataTables (dtOne and dtTwo) and I want to merge them and put them in another DataTable (dtAll). How can I do this in C#? I tried the Merge statement on the datatable, but this returns void. Does Merge preserve the data? For example, if I do:
```
dtOne.Merge(dtTwo);
```
Does dtOne change or does dtTwo ch... | The `Merge` method takes the values from the second table and merges them in with the first table, so the first will now hold the values from both.
If you want to preserve both of the original tables, you could copy the original first, then merge:
```
dtAll = dtOne.Copy();
dtAll.Merge(dtTwo);
``` | Instead of `dtAll = dtOne.Copy();` in [Jeromy Irvine's answer](https://stackoverflow.com/a/285500/979621) you can start with an empty `DataTable` and merge one-by-one iteratively:
```
dtAll = new DataTable();
...
dtAll.Merge(dtOne);
dtAll.Merge(dtTwo);
dtAll.Merge(dtThree);
...
```
and so on.
This technique is usefu... | Merge 2 DataTables and store in a new one | [
"",
"c#",
"datatable",
""
] |
In C++, is it safe to extend scope via a reference?
In code, what I mean is:
```
MyCLass& function badIdea()
{
MyClass obj1;
...
return obj1;
}
``` | It is NOT safe to extend the scope via reference. Objects in C++ are not reference counted when obj1 goes out of scope it will be deleted, refering to the result of badIdea() will only get you into trouble | The only place it's OK to extend a scope with a reference is with a `const` reference in `namespace` or function scope (not with class members).
```
const int & cir = 1+1; // OK to use cir = 2 after this line
```
This trick is used in [Andrei Alexandrescu's](http://erdani.org/) very cool [scope guard](http://www.ddj.... | In C++, is it safe to extend scope via a reference? | [
"",
"c++",
"reference",
"scope",
""
] |
I've got an array of `char*` in a file.
The company I work for stores data in flat files.. Sometimes the data is sorted, but sometimes it's not.
I'd like to sort the data in the files.
Now I could write the code to do this, from scratch.
Is there an easier way?
Of course an in-place sort would be the best option. I'm... | ```
template<size_t length> int less(const char* left, const char* right) {
return memcmp(left, right, length) < 0;
}
std::sort(array, array + array_length, less<buffer_length>);
``` | Use the GNU sort program (externally) if you can't fit the data into RAM: it will sort arbitrary sized files and the larger the file, the smaller the additional cost of creating the process. | Is there an easy way to sort an array of char*'s ? C++ | [
"",
"c++",
"sorting",
"in-place",
"external-sorting",
""
] |
> **Possible Duplicate:**
> [How do I mark a method as Obsolete/Deprecated? - C#](https://stackoverflow.com/questions/1759352/how-do-i-mark-a-method-as-obsolete-deprecated-c-sharp)
How do you mark a class as deprecated? I do not want to use a class any more in my project, but do not want to delete it before a period... | You need to use the `[Obsolete]` attribute.
Example:
```
[Obsolete("Not used any more", true)]
public class MyDeprecatedClass
{
//...
}
```
The parameters are optional. The first parameter is for providing the reason it's obsolete, and the last one is to throw an error at compile time instead of a warning. | As per Doak's answer, but the attribute's second parameter should be set to false if you want the code to compile:
```
[Obsolete("Not used any more", false)]
public class MyDeprecatedClass
{
//...
}
```
This will just throw warnings. | How to mark a class as Deprecated? | [
"",
"c#",
".net",
"oop",
"deprecated",
""
] |
Here's the goal: to replace all standalone ampersands with & but NOT replace those that are already part of an HTML entity such as .
I think I need a regular expression for PHP (preferably for preg\_ functions) that will match only standalone ampersands. I just don't know how to do that with preg\_replace. | You could always run `html_entity_decode` before you run `htmlentities`? Works unless you only want to do ampersands (and even then you can play with the charset parameters).
Much easier and faster than a regex. | PHP's `htmlentities()` has `double_encode` argument for this.
If you want to do things like that in regular expressions, then negative assertions come useful:
```
preg_replace('/&(?!(?:[[:alpha:]][[:alnum:]]*|#(?:[[:digit:]]+|[Xx][[:xdigit:]]+));)/', '&', $txt);
``` | regex (in PHP) to match & that aren't HTML entities | [
"",
"php",
"regex",
"pcre",
""
] |
I'm looking to implement something in Java along the lines of:
```
class Foo{
private int lorem; //
private int ipsum;
public setAttribute(String attr, int val){
//sets attribute based on name
}
public static void main(String [] args){
Foo f = new Foo();
f.setAttribute("lorem",1);
f.setAttribute("... | Here's how you might implement `setAttribute` using reflection (I've renamed the function; there are different reflection functions for different field types):
```
public void setIntField(String fieldName, int value)
throws NoSuchFieldException, IllegalAccessException {
Field field = getClass().getDeclared... | In general, you want to use Reflection. Here is a good introduction to the [topic with examples](http://web.archive.org/web/20081218060124/http://java.sun.com/developer/technicalArticles/ALT/Reflection/index.html)
In particular, the "Changing Values of Fields" section describes how to do what you'd like to do.
I note... | Setting variables by name in Java | [
"",
"java",
"reflection",
"eval",
""
] |
When obtaining the DPI for the screen under Windows (by using ::GetDeviceCaps) will the horizontal value always be the same as the vertical? For example:
```
HDC dc = ::GetDC(NULL);
const int xDPI = ::GetDeviceCaps(dc, LOGPIXELSX);
const int yDPI - ::GetDeviceCaps(dc, LOGPIXELSY);
assert(xDPI == yDPI);
::ReleaseDC(NUL... | It's possible for it to be different, but that generally only applies to printers. It can be safely assumed that the screen will always have identical horizontal and vertical DPIs. | I have never seen them be different, but on [this](http://msdn.microsoft.com/en-us/library/aa273854(VS.60).aspx) MSDN page I see a comment that suggests that they might be:
```
int nHorz = dc.GetDeviceCaps(LOGPIXELSX);
int nVert = dc.GetDeviceCaps(LOGPIXELSY);
// almost always the same in both directions, bu... | Windows GDI: horizontal/vertical DPI | [
"",
"c++",
"c",
"windows",
"gdi",
""
] |
I'm code reviewing a change one of my co-workers just did, and he added a bunch of calls to `Date.toMonth()`, `Date.toYear()` and other deprecated `Date` methods. All these methods were deprecated in JDK 1.1, but he insists that it's ok to use them because they haven't gone away yet (we're using JDK 1.5) and I'm saying... | Regarding the APIs, ... it is not specified they will be removed anytime soon.
[Incompatibilities in J2SE 5.0 (since 1.4.2)](http://java.sun.com/j2se/1.5.0/compatibility.html):
Source Compatibility
> [...]
> In general, the policy is as follows, except for any incompatibilities listed further below:
>
> Deprecated... | They're not going away. That said, they're usually deprecated because a) they're dangerous ala Thread.stop(), or b) there is a better or at least more accepted way to do it. Usually deprecated method javadoc will give you a hint as to the better way. In your case, Calendar is the recommended way to do this.
While it's... | When are API methods marked "deprecated" actually going to go away? | [
"",
"java",
"date",
""
] |
I'm sure there are different approaches to this problem, and I can think of some. But I'd like to hear other people's opinion on this. To be more specific I've built a widget that allows users to choose their location from a google maps map. This widget is displayed on demand and will probably be used every 1 out of 10... | ```
function loadJSInclude(scriptPath, callback)
{
var scriptNode = document.createElement('SCRIPT');
scriptNode.type = 'text/javascript';
scriptNode.src = scriptPath;
var headNode = document.getElementsByTagName('HEAD');
if (headNode[0] != null)
headNode[0].appendChild(scriptNode);
if... | You might want to take a look at jsloader: <http://www.jsloader.com/> | loading javascript dependencies on demand | [
"",
"javascript",
"google-maps",
""
] |
I heard a lot about makefiles and how they simplify the compilation process. I'm using VS2008. Can somebody please suggest some online references or books where I can find out more about how to deal with them? | A UNIX guy probably told you that. :)
You can use makefiles in VS, but when you do it bypasses all the built-in functionality in MSVC's IDE. Makefiles are basically the reinterpret\_cast of the builder. IMO the simplest thing is just to use Solutions. | The Microsoft Program Maintenance Utility (NMAKE.EXE) is a tool that builds projects based on commands contained in a description file.
[NMAKE Reference](http://msdn.microsoft.com/en-us/library/dd9y37ha.aspx) | How to use makefiles in Visual Studio? | [
"",
"c++",
"visual-studio",
"makefile",
""
] |
I need to test if a file is a shortcut. I'm still trying to figure out how stuff will be set up, but I might only have it's path, I might only have the actual contents of the file (as a byte[]) or I might have both.
A few complications include that I it could be in a zip file (in this cases the path will be an interna... | Shortcuts can be manipulated using the COM objects in SHELL32.DLL.
In your Visual Studio project, add a reference to the COM library "Microsoft Shell Controls And Automation" and then use the following:
```
/// <summary>
/// Returns whether the given path/file is a link
/// </summary>
/// <param name="shortcutFilenam... | You can simply check the extension and/or contents of this file. It contains a special GUID in the header.
Read [this document][1].
Link deleted, for me it goes to a porn site | How can I test programmatically if a path/file is a shortcut? | [
"",
"c#",
"shortcut",
""
] |
The following code
```
public class GenericsTest2 {
public static void main(String[] args) throws Exception {
Integer i = readObject(args[0]);
System.out.println(i);
}
public static <T> T readObject(String file) throws Exception {
return readObject(new ObjectInputStream(new FileIn... | I'd say it's the bug in the Sun compiler reported [here](https://bugs.java.com/bugdatabase/view_bug?bug_id=6302954) and [here](https://bugs.eclipse.org/bugs/show_bug.cgi?id=98379), because if you change your line to the one below it works with both, which seems to be exactly what is described in the bug reports.
```
r... | In this case, I'd say your code is wrong (and the Sun compiler is right). There is nothing in your input arguments to `readObject` to actually infer the type `T`. In that case, you're better off to let it return Object, and let clients manually cast the result type.
This should work (though I haven't tested it):
```
... | Bug in eclipse compiler or in javac ("type parameters of T cannot be determined") | [
"",
"java",
"eclipse",
"generics",
""
] |
It's simple enough to code up a class to store/validate something like `192.168.0.0/16`, but I was curious if a native type for this already existed in .NET? I would imagine it would work a lot like `IPAddress`:
```
CIDR subnet = CIDR.Parse("192.168.0.0/16");
```
Basically it just needs to make sure you're working wi... | No there is such native type in .NET, you will need to develop one your self. | You can use the code from GitHub to do just that:
<https://github.com/lduchosal/ipnetwork>
```
IPNetwork ipnetwork = IPNetwork.Parse("192.168.168.100/24");
Console.WriteLine("Network : {0}", ipnetwork.Network);
Console.WriteLine("Netmask : {0}", ipnetwork.Netmask);
Console.WriteLine("Broadcast : {0}", ipnetwork.Broa... | Is there native .NET type for CIDR subnets? | [
"",
"c#",
".net",
"ip-address",
"subnet",
"cidr",
""
] |
Can somebody please give me an example of a unidirectional @OneToOne primary-key mapping in Hibernate ? I've tried numerous combinations, and so far the best thing I've gotten is this :
```
@Entity
@Table(name = "paper_cheque_stop_metadata")
@org.hibernate.annotations.Entity(mutable = false)
public class PaperChequeSt... | Your intention is to have a 1-1 relationship between PaperChequeStopMetaData and PaperCheque? If that's so, you can't define the PaperCheque instance as the @Id of PaperChequeStopMetaData, you have to define a separate @Id column in PaperChequeStopMetaData. | I saved [this discussion](http://forum.hibernate.org/viewtopic.php?p=2381079) when I implemented a couple of @OneToOne mappings, I hope it can be of use to you too, but we don't let Hibernate create the database for us.
Note the GenericGenerator annotation.
Anyway, I have this code working:
```
@Entity
@Table(name =... | Need an example of a primary-key @OneToOne mapping in Hibernate | [
"",
"java",
"hibernate",
"annotations",
"one-to-one",
""
] |
**Executive Summary:** When assertion errors are thrown in the threads, the unit test doesn't die. This makes sense, since one thread shouldn't be allowed to crash another thread. The question is how do I either 1) make the whole test fail when the first of the helper threads crashes or 2) loop through and determine th... | Concurrency is one of those things that are very difficult to unit test. If you are just trying to test that the code inside each thread is doing what it is supposed to test, may be you should just test this code isolated of the context.
If in this example the threads collaborate to reach a result, may be you can test ... | The Google Testing Blog had an excellent article on this subject that's well worth reading: <http://googletesting.blogspot.com/2008/08/tott-sleeping-synchronization.html>
It's written in Python, but I think the principles are directly transferable to Java. | How do I perform a Unit Test using threads? | [
"",
"java",
"multithreading",
"unit-testing",
"junit",
""
] |
I am thinking it is a best practice to declare them as static, as it makes them invisible outside of the module.
What are your thoughts on this? | If it is truly an function which is internal only to that .c file, then yes. It should help avoid polluting the global namespace. Also, I think that the compiler is able to do some optimizations with calling conventions if the function is static since it knowns no other source file needs to know how to call it. This on... | For C++, a better than static is to put it in an unnamed (anonymous) namespace. This is the preferred way to prevent pollution of the Global namespace.
```
namespace {
void myLocalFunction() {
// stuff
}
}
``` | Do you declare your module specific functions as static? | [
"",
"c++",
"c",
"static",
"function",
""
] |
I am using freeglut for opengl rendering...
I need to draw an envelop looking like a cone (2D) that has to be filled with some color and some transparency applied.
Is the freeglut toolkit equipped with such an inbuilt functionality to draw filled geometries(or some trick)?
or is there some other api that has an inbui... | On Edit3: The way I understand your question is that you want to have OpenGL draw borders and anything between them should be filled with colors.
The idea you had was right, but a line strip is just that - a strip of lines, and it does not have any area.
You can, however, have the lines connect to each other to defin... | On the edit on colors:
OpenGL is actually a state machine. This means that the current material and/or color position is used when drawing. Since you probably won't be using materials, ignore that for now. You want colors.
```
glColor3f(float r, float g, float b) // draw with r/g/b color and alpha of 1
glColor4f(floa... | How to draw a filled envelop like a cone on OpenGL (using GLUT)? | [
"",
"c++",
"opengl",
"glut",
"freeglut",
""
] |
I have a class which looks something like this:
```
public class Test {
private static final Object someObject = new Object();
public void doSomething()
{
synchronized (someObject) {
System.out.println(someObject.toString());
}
}
}
```
Can I consider the object to be synchronized, or is there a pro... | By using a static object as your monitor object, only one thread using ANY instance of the Test class can get into the sync block. If the monitor object was not a static object, other threads holding different instances of the Test class could get into the sync block. | Here **someObject** is acting as a lock (monitor) for **all** objects of type Test. That is, if doSomething() is invoked on two separate instances of Test, one will block before the other completes. This is different from a synchronized method which which is mostly equivalent to the code above with **someObject** repla... | Static members need special synchronization blocks? | [
"",
"java",
"static",
"synchronization",
"locking",
""
] |
This is something that comes up so often I almost stopped thinking about it but I'm almost certain that I'm not doing this the best way.
The question: Suppose you have the following table
```
CREATE TABLE TEST_TABLE
(
ID INTEGER,
TEST_VALUE NUMBER,
UPDATED DATE,
FOREIGN_KEY INTEGER
);
```
What ... | Analytic functions are your friends
```
SQL> select * from test_table;
ID TEST_VALUE UPDATED FOREIGN_KEY
---------- ---------- --------- -----------
1 10 12-NOV-08 10
2 20 11-NOV-08 10
SQL> ed
Wrote file afiedt.buf
1* select * from test_table
SQL> ed
W... | Either use a sub-query
```
WHERE updated = (SELECT MAX(updated) ...)
```
or select the TOP 1 record with
```
ORDER BY updated DESC
```
In Oracle syntax this would be:
```
SELECT
*
FROM
(
SELECT * FROM test_table
ORDER BY updated DESC
)
WHERE
ROWNUM = 1
``` | Best way to select the row with the most recent timestamp that matches a criterion | [
"",
"sql",
"oracle",
""
] |
We've got an app with some legacy printer "setup" code that we are still using `PrintDlg` for. We use a custom template to allow the user to select which printer to use for various types of printing tasks (such as reports or drawings) along with orientation and paper size/source.
It works on XP and 32-bit Vista, but o... | I found a related post on the Microsoft forums: [On Vista x64, DocumentProperties fails from UAC-elevated process](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2677398&SiteID=1)
I've verified with a sample program that PrintDlg running as non-admin works. | I found a post on the Quicken Community forum: [Solution to Printing Problems Vista 64 Quicken 2008](http://www.quickencommunity.com/webx/Forums/Quicken%20Personal%20Finance%20Software%20Forum%20for%20Windows/Printing%20in%20Quicken/531/26?5), and the related FAQ: [What if I'm unable to print, or receive "Error communi... | Using PrintDlg on Vista x64 does not work, works fine on 32 bit and XP | [
"",
"c++",
"visual-studio-2008",
"printing",
"vista64",
""
] |
I am forking a number of processes and I want to measure how long it takes to complete the whole task, that is when all processes forked are completed. Please advise how to make the parent process wait until all child processes are terminated? I want to make sure that I stop the timer at the right moment.
Here is as a... | I'd move everything after the line "else //parent" down, outside the for loop. After the loop of forks, do another for loop with waitpid, then stop the clock and do the rest:
```
for (int i = 0; i < pidCount; ++i) {
int status;
while (-1 == waitpid(pids[i], &status, 0));
if (!WIFEXITED(status) || WEXITSTAT... | The simplest method is to do
```
while(wait() > 0) { /* no-op */ ; }
```
This will not work if `wait()` fails for some reason other than the fact that there are no children left. So with some error checking, this becomes
```
int status;
[...]
do {
status = wait();
if(status == -1 && errno != ECHILD) {
... | How to wait until all child processes called by fork() complete? | [
"",
"c++",
"linux",
"gcc",
"parallel-processing",
""
] |
I am using iText to generate PDF invoices for a J2EE web application and included on the page is an image read from a URL constructed from the request URL. In the development and test environments this works fine, but in production I get a java.io.IOException: is not a recognized imageformat.
If I paste the url into m... | Well,
If you ask for an image from a URL, it must actually point to the image. If the URL points to a web page that then redirects to another URL (or the return code from the URL is a redirection), then it is going to fail.
This is essentially due to the getInstance() method understanding how to use the HTTP location... | Is there a reason you have to get this using the URL?? Do you have to match the image that the url is pointing to? What if it changes or gets removed?
I am not sure of your requirement, but it may be easier to save the image from the url and place it somewhere within your project. Then you can add it to your pdf with:... | How do I retrieve an image using iText when the URL has redirects? | [
"",
"java",
"pdf-generation",
"itext",
""
] |
Okay i am working on someone elses code. They do alot of this:
```
char description[256];
description[0]=0;
```
I know this would put a \0 in the first spot of the character array. But is this even a safe way to erase a string?
Also visual studio keeps reporting memory leaks, and i've pretty much tied this done to t... | To *initialize* the string to 0, you could do:
```
char description[256] = {0};
```
that will assign 0 to every element of the array.
Just setting the first element to `0` (`'\0'`) does not erase it's contents. It doesn't even guarantee the entire string is set to the null character.
As stated by others, you can't ... | Setting the first element of the char array to \0 is enough to ensure that 'description' is a properly formatted, actual string. Elements 1 thru 255 can all be garbage, so long as element 0 is 0, description is a zero-length string.
You dont have to worry about memory leaks in the code posted above, because the array ... | Erasing a Char[] | [
"",
"c++",
"c",
"arrays",
"string",
"char",
""
] |
Is there an Iterator implementation that merges multiple iterators?
```
class MergedIterator<T> implements Iterator<T>
{
MergedIterator(Iterator<T>... iters)
....
}
```
And the next method should move on to `iters[1]` when `!iters[0].hasNext()` etc | I'd call that a ConcatenatedIterator myself - a MergedIterator should merge the results of several iterators e.g. based on sorting
Naming aside, I'm sure there'll be an implementation in a 3rd party library somewhere. Just off to check [Google collections](http://code.google.com/p/google-collections/)...
EDIT: Bingo ... | Commons Collections [IteratorChain](http://commons.apache.org/collections/apidocs/org/apache/commons/collections/iterators/IteratorChain.html) | is there a merged iterator implementation? | [
"",
"java",
"iterator",
""
] |
I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I **don't** want it to be restricted to a hardcoded list.
In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid s... | > The problem with all of the above
> mentioned ways is that str is
> considered a sequence (it's iterable,
> has **getitem**, etc.) yet it's
> usually treated as a single item.
>
> For example, a function may accept an
> argument that can either be a filename
> or a list of filenames. What's the
> most Pythonic way fo... | As of 2.6, use [abstract base classes](http://docs.python.org/library/abc.html#module-abc).
```
>>> import collections
>>> isinstance([], collections.Sequence)
True
>>> isinstance(0, collections.Sequence)
False
```
Furthermore ABC's can be customized to account for exceptions, such as not considering strings to be se... | Correct way to detect sequence parameter? | [
"",
"python",
"types",
"sequences",
""
] |
Ive recently been asked to recommend a .NET framework version to use in a (GUI based) project for an XP machine.
Can anyone explain the differences between all the .NET versions?
OR,
Does anyone have a good reference to a site that details (briefly) the differences? | Jon Skeet's book *C# In Depth* has one section describing versions of .NET in details. | The only reason to **not** go for the latest version is that it can complicate deployment.
.NET 2.0 is installed automatically via Windows Update, so you can expect it to be on the target computer when your deploy your application. .NET 3.5 is not being pushed automatically yet, so you need to distribute the framework... | Differences between .NET versions (predominantly c#) | [
"",
"c#",
".net",
"versions",
""
] |
For some reason I can't find a way to get the equivalents of sqlite's interactive shell commands:
```
.tables
.dump
```
using the Python sqlite3 API.
Is there anything like that? | You can fetch the list of tables and schemata by querying the SQLITE\_MASTER table:
```
sqlite> .tab
job snmptarget t1 t2 t3
sqlite> select name from sqlite_master where type = 'table';
job
t1
t2
snmptarget
t3
sqlite> .schema job
CREATE TABLE job (
id INTEGER PRIMARY KEY,
da... | In Python:
```
con = sqlite3.connect('database.db')
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())
```
Watch out for my other [answer](https://stackoverflow.com/a/33100538/236830). There is a much faster way using pandas. | List of tables, db schema, dump etc using the Python sqlite3 API | [
"",
"python",
"sqlite",
"dump",
""
] |
How can I make:
DELETE FROM foo WHERE id=1 AND **bar not contains id==1**
To elaborate, how can I remove a row with `id = 1`, from table `foo`, only if there is not a row in table `bar` with `id = 1`. | ```
DELETE FROM foo WHERE id=1 AND NOT EXISTS (SELECT * FROM bar WHERE id=1)
```
I'm assuming you mean that foo and bar are tables, and you want to remove a record from foo if it doesn't exist in bar. | using a join:
```
delete f
from foo f
left
join bar b on
f.id = b.id
where f.id = 1 and
b.id is null
``` | In SQL, how to delete a row from one table if it doesn't have a corresponding row in another table? | [
"",
"sql",
""
] |
In my app I've got a thread which displays for some time "please wait" dialog window, sometimes it is a very tiny amout of time and there is some glitch while drawing UI (I guess).
I get the exception "Thread was being aborted" and completly have no idea how get rid of it. I mean Catch that exception in some way, or i... | Do **not** use Thread.Abort. This method is reserved for when the .NET runtime needs to forcibly kill threads in order to unload your program.
You can only "safely" use this if you're about to unload an AppDomain and want to get rid of threads running in it first.
To get rid of a thread, write it in cooperative mode.... | use [SafeThread](http://www.codeproject.com/KB/threads/SafeThread.aspx) and set ShouldReportThreadAbort to false to make the problem go away...
a better solution would be to run this in the debugger with Debug >> Exceptions >> Thrown checked for all exception types, and figure out what is happening to abort your threa... | "Thread was being aborted" exception whilst displaying dialog | [
"",
"c#",
".net",
"multithreading",
".net-2.0",
""
] |
I am writing an unit test for a mvc web application that checks if a returned list of anonymous variables(in a jsonresult) is correct. therefore i need to iterate through that list but i cannot seem to find a way to do so.
so i have 2 methods
1) returns a json result . In that json result there is a property called d... | I think you mean "anonymous type" everywhere you've said "anonymous variable" - but you can still iterate over the list with `foreach`, just declaring the iteration variable as type `object`:
```
foreach (object o in myList)
{
// Not sure what you're actually trying to do in here...
}
```
If you need to check the... | Create an identical set of objects to the one you expect, then serialize both it and the result.Data of the action under unit test. Finally, compare the streams to see if they are identical. | Iterate through an anonymous variable in another scope than where it was created | [
"",
"c#",
".net",
"asp.net-mvc",
"unit-testing",
""
] |
I just happened to read [jQuery Intellisense Updates from Microsoft](http://www.west-wind.com/Weblog/posts/536756.aspx) and was wondering if there was any editor or eclipse plugin available which provides intellisense complete or code assist. Are there any? | I believe eclipse, with the **[Aptana](http://www.aptana.com/)** plugin, has some [JQuery support](http://www.aptana.com/blog/lorihc/jquery1.2.6_now_available).
As mentionned [here](http://www.aptana.com/docs/index.php/Getting_started_with_Aptana_and_jQuery), intellisense is supported:
> 5. Start coding.
>
> 1. As y... | Why not Visual Studio/Web Developer 2008 (or did I miss something)? The [express edition](http://www.microsoft.com/express/vwd/) is free. | Any opensource Javascript editor/javascript eclipse plugin with code assist | [
"",
"javascript",
"jquery",
""
] |
An [answer to one of my questions](https://stackoverflow.com/questions/61278/quick-and-dirty-way-to-profile-your-code#231614) included the following line of code:
```
label = std::safe_string(name); // label is a std::string
```
The intent seems to be a wrapper around a string literal (so presumably no allocation tak... | After searching [google code search](http://www.google.com/codesearch) (I should have thought of this first...) I found this:
```
//tools-cgi.cpp
string safe_string (const char * s)
{
return (s != NULL) ? s : "";
}
```
Which converts `NULL`s to zero length strings. Although this is not standard it's probably some... | There is no standard safe\_string. The safe\_string you're seeing in that answerer's response is from what looks like a private STL extensions utility library.
[Google for "stlext/stringext.h"](http://www.google.com/search?q=stlext%2Fstringext.h) and you'll see the same library referenced in a post on another forum. | What is std::safe_string? | [
"",
"c++",
"string",
""
] |
I am interested in writing a simplistic navigation application as a pet project. After searching around for free map-data I have settled on the [US Census Bureau TIGER](http://www.census.gov/geo/www/tiger/tgrshp2007/tgrshp2007.html) 2007 Line/Shapefile map data. The data is split up into zip files for individual counti... | First, I recommend that you use the [2008 TIGER files](http://www.census.gov/geo/www/tiger/tgrshp2008/tgrshp2008.html).
Second, as others point out there are a lot of projects out there now that already read in, interpret, convert, and use the data. Building your own parser for this data is almost trivial, though, so ... | [SharpMap](http://www.codeplex.com/SharpMap) is an open-source .NET 2.0 mapping engine for WinForms and ASP.NET. This may provide all the functionality that you need. It deals with most common GIS vector and raster data formats including ESRI shapefiles. | What is the best way to read, represent and render map data? | [
"",
"java",
".net",
"graphics",
"rendering",
"maps",
""
] |
Is it less efficient to use TEXT than varchar in an SQL database?
If so why?
If not why would you not just always use TEXT?
I'm not targetting a specific database here but oracle is probably the most relevant, although I'm testing on MySQL for the time being as part of a proof of concept. | From Microsoft [here](http://msdn.microsoft.com/en-us/library/ms187993.aspx)
> ntext, text, and image data types will
> be removed in a future version of
> Microsoft SQL Server. Avoid using
> these data types in new development
> work, and plan to modify applications
> that currently use them. Use
> nvarchar(max), var... | [PostgreSQL documentation says](http://www.postgresql.org/docs/current/static/datatype-character.html):
> Tip: There are no performance differences between these three types, apart from increased storage size when using the blank-padded type, and a few extra cycles to check the length when storing into a length-constr... | Databases: Are "TEXT" fields less efficient than "varchar"? | [
"",
"sql",
"variables",
"performance",
""
] |
I have the following code that sets a cookie:
```
string locale = ((DropDownList)this.LoginUser.FindControl("locale")).SelectedValue;
HttpCookie cookie = new HttpCookie("localization",locale);
cookie.Expires= DateTime.Now.AddYears(1);
Response.Cookies.Set(cookie);
```
However, when I try to read the cookie, t... | The check is done after a post back? If so you should read the cookie from the Request collection instead.
The cookies are persisted to the browser by adding them to Response.Cookies and are read back from Request.Cookies.
The cookies added to Response can be read only if the page is on the same request. | The most likely answer is seen on [this post](https://stackoverflow.com/questions/456807/asp-mvc-cookies-not-persisting/590258#590258)
> When you try to check existence of a cookie using Response object rather than Reqest, ASP.net automatically creates a cookie.
**Edit:** As a note, I ended up writing software that n... | Cookie loses value in ASP.net | [
"",
"c#",
"asp.net",
"cookies",
""
] |
I have to add either an embed tag for Firefox or an object tag for Internet Explorer with JavaScript to address the appropriate ActiveX / Plugin depending on the browser. The plugin could be missing and needs to get downloaded in this case. The dynamically added embed tag for Firefox works as expected. The dynamically ... | I needed to do this same thing and simply place all of the HTML needed for the OBJECT tag in a string in JavaScript and simply replace the innerHTML of a div tag with the OBJECT HTML and it works in IE just fine.
```
// something akin to this:
document.getElementById(myDivId).innerHTML = "<OBJECT id='foo' classid='CLS... | ```
var object = document.createelement('object')
object.setAttribute('id','name')
object.setAttribute('clssid','CLSID:{}')
```
And the same for other parameters. | How can I dynamically add an <object> tag with JavaScript in IE? | [
"",
"javascript",
"internet-explorer",
"dynamic-data",
"object-tag",
""
] |
I'm relatively new to NHibernate, but have been using it for the last few programs and I'm in love. I've come to a situation where I need to aggregate data from 4-5 databases into a single database. Specifically it is serial number data. Each database will have its own mapping file, but ultimately the entities all shar... | I don't know if this'll help, but I wouldn't be trying to do that, basically.
Essentially, I think you're possibly suffering from "golder hammer" syndrome: when you have a REALLY REALLY nice hammer (i.e. Hibernate (and I share your opinion on it; it's a MAGNIFICENT tool)), everything looks like a nail.
I'd generally ... | This might help;
[Using NHibernate with Multiple Databases](http://www.codeproject.com/KB/aspnet/NHibernateMultipleDBs.aspx)
From the article;
> Introduction
>
> ...
> described using NHibernate with
> ASP.NET; it offered guidelines for
> communicating with a single database.
> **But it is sometimes necessary to
> c... | NHibernate: One base class, several mappings | [
"",
"c#",
"nhibernate",
"oop",
"nhibernate-mapping",
""
] |
Can someone explain the main benefits of different types of references in C#?
* Weak references
* Soft references
* Phantom references
* Strong references.
We have an application that is consuming a lot of memory and we are trying to determine if this is an area to focus on. | Soft and phantom references come from Java, I believe. A long weak reference (pass true to C#'s WeakReference constructor) might be considered similar to Java's PhantomReference. If there is an analog to SoftReference in C#, I don't know what it is.
Weak references do not extend the lifespan of an object, thus allowin... | MSDN has a good explanation of [weak references](http://msdn.microsoft.com/en-us/library/ms404247.aspx). The key quote is at the bottom where it says:
> **Avoid using weak references as an**
> **automatic solution to memory**
> **management problems**. Instead, develop
> an effective caching policy for
> handling your... | Weak reference benefits | [
"",
"c#",
"winforms",
"memory",
"reference",
"weak-references",
""
] |
Greetings,
I have a particular object which can be constructed from a file, as such:
```
public class ConfigObj
{
public ConfigObj(string loadPath)
{
//load object using .Net's supplied Serialization library
//resulting in a ConfigObj object
ConfigObj deserializedObj = VoodooLo... | Your second option is what is called a [factory method](http://en.wikipedia.org/wiki/Factory_method_pattern) and is a common design technique. If you do use this technique, you may find that you need to know the type of class you will load before you actually load the class. If you run into this situation, you can use ... | There's nothing wrong with having a static method instead of a constructor. In fact, it has a [number of advantages](https://stackoverflow.com/questions/194496/static-method-or-instance-constructor). | Best Practice for Loading Object from Serialized XML in C# | [
"",
"c#",
".net",
"serialization",
"xml-serialization",
""
] |
Does anyone know what this means. Getting this in C# winforms applications:
> Not a legal OleAut date | It means that somewhere in the program is attempting to convert to or from an OLE Automation Date outside the valid range 1-January-4713 BC to 31-December-9999 AD. It might have slipped through because OLE Automation Dates are represented as a **double**.
Start by looking for any uses of the methods:
[DateTime.FromOA... | An OADate is represented as a double value whose value is the number of days from midnight on 30 december 1899 (negative values representing earlier dates).
This exception is thrown when trying to convert a value that is outside the valid range of Ole Automation dates to/from a .NET DateTime value (methods DateTime.Fr... | Meaning of exception in C# app: "Not a legal OleAut date"? | [
"",
"c#",
"winforms",
"datetime",
""
] |
Simple question, hopefully an easy way and just want to verify I'm doing it the correct / efficient way.
I have a class T object, which is typically put into a vector that is created in my main() function. It can be any kind of data, string, int, float.. etc. I'm reading from a file... which is inputted from the user ... | It looks like it will work fine, and I would say this is probably the best way to do it. But why are you asking here instead of just testing it yourself? | You made the old mistake of testing against eof in the condition.
EOF is not set until you try and read past the end of file. So this method will insert one extra value into the vector that you don't want.
```
template <class T, class U>
void get_list(vector<T>& v, const char *inputFile, U)
{
ifstream myFile("inpu... | C++ Opening a file and inputting data to a class object | [
"",
"c++",
"class",
"input",
"ifstream",
""
] |
In my database application I sometimes have to deal with `null` strings in the database. In most cases this is fine, but when it comes do displaying data in a form the Swing components - using `JTextField` for example - cannot handle null strings. (`.setText(null)` fails)
(**EDIT:** I just noticed that `JTextField` ac... | If you are using any ORM tool or somehow you map your DB fields to Java bean you can allways have:
```
public void setFoo(String str) {
this.foo = str != null ? str : "";
}
``` | From a SQL angle try:
```
select ISNULL(column_name,'') from ...
``` | Best practice for handling null strings from database (in Java) | [
"",
"java",
"database",
"swing",
""
] |
How can I replace Line Breaks within a string in C#? | Use replace with `Environment.NewLine`
```
myString = myString.Replace(System.Environment.NewLine, "replacement text"); //add a line terminating ;
```
As mentioned in other posts, if the string comes from another environment (OS) then you'd need to replace that particular environments implementation of [new line cont... | The solutions posted so far either only replace `Environment.NewLine` or they fail if the replacement string contains line breaks because they call `string.Replace` multiple times.
Here's a solution that uses a regular expression to make all three replacements in just one pass over the string. This means that the repl... | Replace Line Breaks in a String C# | [
"",
"c#",
".net",
"string",
""
] |
For a simple linked list in which random access to list elements is not a requirement, are there any significant advantages (performance or otherwise) to using `std::list` instead of `std::vector`? If backwards traversal is required, would it be more efficient to use `std::slist` and `reverse()` the list prior to itera... | As usual the best answer to performance questions is to [profile](https://stackoverflow.com/questions/61278/quick-and-dirty-way-to-profile-your-code) both implementations for your use case and see which is faster.
In general if you have insertions into the data-structure (other than at the end) then `vector` may be sl... | Default data structure to think of in C++ is the **Vector**.
Consider the following points...
**1] Traversal:**
List nodes are scattered everywhere in memory and hence list traversal leads to ***cache misses***. But traversal of vectors is smooth.
**2] Insertion and Deletion:**
Average 50% of elements must be sh... | Relative performance of std::vector vs. std::list vs. std::slist? | [
"",
"c++",
"data-structures",
"stl",
"performance",
"linked-list",
""
] |
How can I dynamically invoke a class method in PHP? The class method is not static. It appears that
```
call_user_func(...)
```
only works with static functions?
Thanks. | It works both ways - you need to use the right syntax
```
// Non static call
call_user_func( array( $obj, 'method' ) );
// Static calls
call_user_func( array( 'ClassName', 'method' ) );
call_user_func( 'ClassName::method' ); // (As of PHP 5.2.3)
``` | Option 1
```
// invoke an instance method
$instance = new Instance();
$instanceMethod = 'bar';
$instance->$instanceMethod();
// invoke a static method
$class = 'NameOfTheClass';
$staticMethod = 'blah';
$class::$staticMethod();
```
Option 2
```
// invoke an instance method
$instance = new Instance();
call_user_func(... | How do I dynamically invoke a class method in PHP? | [
"",
"php",
"callback",
""
] |
I have a C#/.NET program that can run both as a console application and as a service.
Currently I give it a command-line option to start as a console application, but I would like to avoid that.
Is it possible to programmatically detect whether my program is being started as a service?
If it was pure Win32, I could t... | Rasmus, [this is the earlier question](https://stackoverflow.com/questions/200163/am-i-running-as-a-service#200183).
From the answers it seems the most popular way is to use a simple command line option, or try accessing the Console object in a try catch block (in a Service the Console is not attached to the process a... | [Environment.UserInteractive](http://msdn.microsoft.com/en-us/library/system.environment.userinteractive.aspx) will do the magic. | C#/.NET: Detect whether program is being run as a service or a console application | [
"",
"c#",
".net",
"service",
""
] |
Given an amount of days, say 25, convert it into a duration text such as "3 Weeks, 4 Days"
C# and F# solutions would both be great if the F# variation offers any improvement over C#.
Edit: The solution should expand past weeks to include months and years. Bonus points for including centuries and so on. Extra bonus if... | This is a recursive solution. Note that a duration only really makes sense measured against a particular point in time on a given calendar because month and year lengths vary. But here is a simple solution assuming fixed lengths:
```
let divmod n m = n / m, n % m
let units = [
("Centuries", TimeSpan.TicksPerD... | ```
String.Format("{0} Weeks, {1} days", days / 7, days % 7);
``` | Converting Days into Human Readable Duration Text | [
"",
"c#",
"f#",
""
] |
As the title says. How would I create an instance of a class that is globally available(for example I have a functor for printing and i want to have a single global instance of this(though the possibility of creating more)). | Going to all the effort of making a singleton object using the usual pattern isn't addressing the second part of your question - the ability to make more if needed. The singleton "pattern" is very restrictive and isn't anything more than a global variable by another name.
```
// myclass.h
class MyClass {
public:
... | First off the fact that you want global variables is a 'code smell' (as Per Martin Fowler).
But to achieve the affect you want you can use a variation of the Singleton.
Use static function variables. This means that variable is not created until used (this gives you lazy evaluation) and all the variables will be des... | Global instance of a class in C++ | [
"",
"c++",
"singleton",
""
] |
I teach a C++ course using Visual Studio. One of my students has a Mac and was looking for an IDE to use on his machine. What would be good to recommend? | [Xcode](http://developer.apple.com/tools/xcode/) which is part of the MacOS Developer Tools is a great IDE. There's also [NetBeans](http://www.netbeans.org) and [Eclipse](http://www.eclipse.org) that can be configured to build and compile C++ projects.
[Clion](https://www.jetbrains.com/clion/) from JetBrains, also is ... | Emacs! Eclipse might work too. | C++ IDE for Macs | [
"",
"c++",
"macos",
"ide",
""
] |
I have a third party JavaScript plug-in but including the file breaks IntelliSense for jQuery amongst other things. The only way I can get IntelliSense back working with jQuery is by commenting out the plug-in. Is there a way I can hide the plug-in file from the IntelliSense parser? | Service Pack 1 added the following feature:
If you "anyfile.js" and "anyfile-vsdoc.js" in the same directory, then any references to "anyfile.js" will automagically be converted to a reference to "anyfile-vsdoc.js" behind the scenes.
Add an empty file next to your plugin with "-vsdoc" appended to the filename. That s... | You could always load it from your code-behind instead of the scriptmanager in
your aspx/master. That way the IntelliSense doesn't know it's there. Using ScriptManager.RegisterClientScriptInclude(..). | Is there any way to 'hide' a JavaScript file from IntelliSense in Visual Studio 2008? | [
"",
"asp.net",
"javascript",
"jquery",
"intellisense",
""
] |
On the PHP website, the only real checking they suggest is using `is_uploaded_file()` or `move_uploaded_file()`, [here](http://ca.php.net/manual/en/features.file-upload.php). Of course you usually don't want user's uploading any type of file, for a variety of reasons.
Because of this, I have often used some "strict" m... | Take a look at [mime\_content\_type](http://php.net/manual/en/function.mime-content-type.php) or [Fileinfo](http://php.net/manual/en/function.finfo-file.php). These are built-in PHP commands for determining the type of a file by looking at the contents of the file. Also check the comments on the above two pages, there ... | IMHO, all MIME-type checking methods are useless.
Say you've got which should have MIME-type `application/pdf`. Standard methods are trying to find something that looks like a PDF header (`%PDF-` or smth. like that) and they will return 'Okay, seems like this is a PDF file' on success. But in fact this doesn't means a... | How to check file types of uploaded files in PHP? | [
"",
"php",
"validation",
"file-upload",
"mime-types",
""
] |
I created a custom login page using Forms Authentication and using a sQL DB to store user data. I am able to create a session variable from the username, but wondering if it is possible to pull a separate field and create a session variable based on that. I would like the session variable to be based off a SalesNumber ... | Also keep in mind you can store an entire object in the session instead of seperate variables:
```
UserObject user = DAL.GetUserObject(userName);
Session["CurrentUser"] = user;
// Later...
UserObject user = Session["CurrentUser"] as UserObject;
// ...
```
To add on, you could wrap it in a nice property:
```
private ... | When you get the SalesNumber from your database query, just use
```
Session["SalesNumber"] = <the value of the SalesNumber column from the query>
```
Or is there something else I'm missing in the question...? | Asp.net Session Variable from SQL DB | [
"",
"c#",
"asp.net",
""
] |
Let's say I have an html form. Each input/select/textarea will have a corresponding `<label>` with the `for` attribute set to the id of it's companion. In this case, I know that each input will only have a single label.
Given an input element in javascript — via an onkeyup event, for example — what's the best way to f... | First, scan the page for labels, and assign a reference to the label from the actual form element:
```
var labels = document.getElementsByTagName('LABEL');
for (var i = 0; i < labels.length; i++) {
if (labels[i].htmlFor != '') {
var elem = document.getElementById(labels[i].htmlFor);
if (elem)
... | If you are using jQuery you can do something like this
```
$('label[for="foo"]').hide ();
```
If you aren't using jQuery you'll have to search for the label. Here is a function that takes the element as an argument and returns the associated label
```
function findLableForControl(el) {
var idVal = el.id;
label... | Find html label associated with a given input | [
"",
"javascript",
"html",
"label",
""
] |
Given a class:
```
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=20)
```
Is it possible, and if so how, to have a QuerySet that filters based on dynamic arguments? For example:
```
# Instead of:
Person.objects.filter(name__startswith='B')
# ... and:
Person.objec... | Python's argument expansion may be used to solve this problem:
```
kwargs = {
'{0}__{1}'.format('name', 'startswith'): 'A',
'{0}__{1}'.format('name', 'endswith'): 'Z'
}
Person.objects.filter(**kwargs)
```
This is a very common and useful Python idiom. | A simplified example:
In a Django survey app, I wanted an HTML select list showing registered users. But because we have 5000 registered users, I needed a way to filter that list based on query criteria (such as just people who completed a certain workshop). In order for the survey element to be re-usable, I needed fo... | In Django, how does one filter a QuerySet with dynamic field lookups? | [
"",
"python",
"django",
"django-models",
""
] |
pdb and winpdb both seem to be missing this essential (to me) feature. I saw something suggesting WingIDE has it but I'd prefer a solution that is free, and if I do have to pay, I'd prefer to pay for something that is better than Wing. | Please look what pydev in eclipse offers... | You should check out [Eric4](http://eric-ide.python-projects.org/)
It's a very good Python IDE with a builtin debugger.
The debugger has views for global variables, local variables and watchpoints. | Is there a free python debugger that has watchpoints? | [
"",
"python",
"debugging",
"pdb",
"watchpoint",
""
] |
I have a class which constructor takes a [Jakarta enums](http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/enums/Enum.html). I'm trying to find how I can easily inject it via an [Spring](http://www.springframework.org/) XML aplicationContext.
For example :
The enum :
```
public class MyEnum extends org.... | Check out the `<util:constant>` tag in Spring. It will require you to add the schema to your xml definition. So you would wind up with the following:
```
<bean id="myService" class="MyService">
<constructor-arg index="0">
<util:constant static-field="MyEnum.MY_FIRST_VALUE"/>
</constructor-arg>
</bean>
```
The... | I found a solution, but it is very verbose (far too much to my taste) :
```
<bean id="myService" class="MyService">
<constructor-arg index="0">
<bean class="MyEnum" factory-method="getEnum">
<constructor-arg value="MyFirstValue" />
</bean>
</constructor-arg>
</bean>
``` | How to inject a Jakarta enums in a Spring application context? | [
"",
"java",
"spring",
"enums",
""
] |
I just realized from an article in CACM that Doxygen works with Java (and several other languages) too. But Java has already the Javadoc tool. Can someone explain what are the pros and cons of either approach? Are they mutually exclusive? Is there a Maven plugin for Doxygen? | Doxygen has a number of features that JavaDoc does not offer, e.g. the class diagrams for the hierarchies and the cooperation context, more summary pages, optional source-code browsing (cross-linked with the documentation), additional tag support such as @todo on a separate page and it can generate output in TeX and PD... | I'd only use Doxygen with Java if you're new to Java and you've used Doxygen before, reducing the learning curve you'd experience with javadoc. If you haven't used Doxygen before, I'd stick with javadoc, since it was specifically designed with Java in mind. If you don't know either one, and you work in C++ (or other su... | Doxygen vs Javadoc | [
"",
"java",
"maven-2",
"documentation",
"doxygen",
""
] |
I am looking for some general advice about the mp3 format before I start a small project to make sure I am not on a wild-goose chase.
My understanding of the internals of the mp3 format is minimal. Ideally, I am looking for a library that would abstract those details away. I would prefer to use Python (but could be co... | I got three quality answers, and I thank you all for them. I haven't chosen any as the accepted answer, because each addressed one aspect, so I wanted to write a summary.
**Do you need to work in MP3?**
* Transcoding to PCM and back to MP3 is unlikely to result in a drop in quality.
* Don't optimise audio-quality pre... | If you want to do things low-level, use [pymad](https://spacepants.org/src/pymad/). It turns MP3s into a buffer of sample data.
If you want something a little higher-level, use the Echo Nest [Remix API](https://web.archive.org/web/20121003042054/http://code.google.com/p/echo-nest-remix/) (disclosure: I wrote part of i... | Python library to modify MP3 audio without transcoding | [
"",
"python",
"mp3",
"codec",
""
] |
Given a collection of user specified tags how do I determine which ones **are not** in the tags table with 1 SQL Statement?
Assuming a table schema `tags (id, tag)` and I'm using mysql, if there's an optimization I'm unaware of.
thanks | ```
SELECT Tag
FROM UserSpecifiedTags
LEFT OUTER JOIN AllTags ON UserSpecifiedTags.Tag = AllTags.Tag
WHERE AllTags.Tag IS NULL
```
This should return what you want. In my experience, executing a join and looking for rows which don't have a match is **much** quicker than using the `IN` operator. | ```
select * from canonical_list_of_tags where tag not in (select tag from used_tags)
```
At least that works in T-SQL for SQL Server ...
**Edit:** Assuming that the table `canonical_list_of_tags` is populated with the result of "*Given a collection of user specified tags*" | Which tags are not in the database? | [
"",
"sql",
"mysql",
""
] |
I have a <select>. Using JavaScript, I need to get a specific <option> from the list of options, and all I know is the value of the option. The option may or may not be selected.
Here's the catch: there are thousands of options and I need to do this a few hundred times in a loop. Right now I loop through the "options"... | I'd do it like this:
```
// first, build a reverse lookup
var optCount = mySelect.options.length;
var reverseLookup = {};
for (var i = 0; i < optCount; i++)
{
var option = mySelect.options[i];
if (!reverseLookup[option.value])
{
// use an array to account for multiple options with the same value
rev... | I would suggest not having thousands of options in your select.
Perhaps you could structure your data differently a select with thousands of entries to me seems wrong.
Perhaps your app requires this but it would not be typical usage of this element. | Is there any fast way to get an <option> from a <select> by value, using JavaScript? | [
"",
"javascript",
"html",
""
] |
In eclipse developing a java app, there are several class files that are generated by a custom ant script. This happens automatically, and it is set up as an export/publish dependency for /WEB-INF/classes.
With publishing it happens alright, however on exporting to .WAR these files just got missing.
Is there a way to a... | I'd suggest generating your war file using Ant.
I like my deliverables to be easy to generate using a simple toolchain, i.e. not need to fire up Eclipse to generate them; this way things are easier to automate and document.
six years after edit: I was an Ant man when I wrote this- today I'd probably suggest Maven | 1. Go to the project properties you will export.
2. Setup the Java EE Module Dependencies
Now they should exist in your exported war. | How to specify in Eclipse what to include in a .WAR file | [
"",
"java",
"eclipse",
"jakarta-ee",
""
] |
I have spent several hours trying to find a means of writing a cross platform password prompt in php that hides the password that is input by the user. While this is easily accomplished in Unix environments through the use of stty -echo, I have tried various means of passthru() and system() calls to make windows do the... | Here's a Windows solution, using the COM extension for PHP. I tested this on Windows XP with PHP 5.2.6.
```
<?php
$pwObj = new Com('ScriptPW.Password');
print "Password: ";
$passwd = $pwObj->getPassword();
echo "Your password is $passwd\n";
?>
``` | There doesn't seem to be an IOCTL or STTY extension for PHP. I found the following trick [here](http://www.usenet-forums.com/php-language/35386-hide-password-input-cli-php-script.html):
```
<?php
echo 'Password: ';
$pwd = preg_replace('/\r?\n$/', '', `stty -echo; head -n1 ; stty echo`);
echo "\n";
echo "Your password ... | Is it really not possible to write a php cli password prompt that hides the password in windows? | [
"",
"php",
"passwords",
""
] |
What I'm trying to do is run the same SQL select on many Oracle databases (at least a dozen), and display the output in a Gridview.
I've hacked together something that works but unfortunately it's very slow. I think its exacerbated by the fact that at least 1 of the dozen databases will invariably be unreachable or ot... | If you run the DataAdapter.Fill method on a DataTable object the table will be updated with the results from the query. So instead of creating new DataTable and DataSet objects and then copying the DataRows manually you can just add rows to the same table.
Try something like this (in untested C# code):
```
public voi... | could be a lot of factors causing it to be slow. What's the sql statement being executed that's running slow?
If anyone reading this is using sql server, Scott Mitchell just wrote a nice article to help solve this in sql server: **[Running the Same Query Against Multiple Databases](http://scottonwriting.net/sowblog/po... | good way to query many databases in ASP.NET | [
"",
"c#",
"asp.net",
"gridview",
"multiple-databases",
""
] |
In an earlier question about [how to return a string from a dialog window](https://stackoverflow.com/questions/280579/c-beginner-help-how-do-i-pass-a-value-from-a-child-back-to-the-parent-form), **yapiskan** suggested [overloading the child form's ShowDialog() method](https://stackoverflow.com/questions/280579/c-beginn... | Better to have a Public property/method and get the information.
What would you do if you would need 3..4..5 informations, having 5 parameters out? More clean to have accessors to get your information from the Dialog. | It should not be OK since .net framework does not use this design. In the case of OpenFileDialog class, it has a parameterless ShowDialog() method returning a DialogResult. Once this method called, user is supposed to get the selected files by using the FileName, FileNames, SafeFileName and SafeFileNames methods.
Let'... | Is it OK to overload ShowDialog() so that a child form returns information as an out parameter? | [
"",
"c#",
".net",
"winforms",
""
] |
I have an ASP.NET GridView which has columns that look like this:
```
| Foo | Bar | Total1 | Total2 | Total3 |
```
Is it possible to create a header on two rows that looks like this?
```
| | Totals |
| Foo | Bar | 1 | 2 | 3 |
```
The data in each row will remain unchanged as this is just to pretty ... | [This article](https://web.archive.org/web/20100201202857/http://blogs.msdn.com/mattdotson/articles/541795.aspx) should point you in the right direction. You can programmatically create the row and add it to the collection at position 0. | I took the accepted answer approach, but added the header to the existing GridView instead of a custom inherited GridView.
After I bind my GridView, I do the following:
```
/*Create header row above generated header row*/
//create row
GridViewRow row = new GridViewRow(0, -1, DataControlRowType.Header, DataContro... | ASP.NET GridView second header row to span main header row | [
"",
"c#",
"asp.net",
"gridview",
""
] |
How do I create a directory at a given path, and also create any missing parent directories along that path? For example, the Bash command `mkdir -p /path/to/nested/directory` does this. | On Python ≥ 3.5, use [`pathlib.Path.mkdir`](https://docs.python.org/library/pathlib.html#pathlib.Path.mkdir):
```
from pathlib import Path
Path("/my/directory").mkdir(parents=True, exist_ok=True)
```
For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on... | ## Python 3.5+:
```
import pathlib
pathlib.Path('/my/directory').mkdir(parents=True, exist_ok=True)
```
[`pathlib.Path.mkdir`](https://docs.python.org/library/pathlib.html#pathlib.Path.mkdir) as used above recursively creates the directory and does not raise an exception if the directory already exists. If you don't ... | How do I create a directory, and any missing parent directories? | [
"",
"python",
"exception",
"path",
"directory",
"operating-system",
""
] |
I want my application to clean all the temp files it used, the problem is that not all the temp files are under my control, so I just want to "brutally" unlock them in order to delete them programatically. | Take a look at [this](http://www.codeguru.com/Cpp/W-P/files/fileio/article.php/c1287/#more) article. I think that you'll struggle to do this in C# natively, even using interop, but writing a C++/CLI wrapper assembly may be a good compromise. Note also that the user needs to have the SE\_DEBUG privilege for this to work... | I've struggled with this as well, and ended up just shelling out to Unlocker's command line implementation. In my case it has to run many times daily and ends up unlocking thousands of files per day without any problem. | How can I unlock a file that is locked by a process in .NET | [
"",
"c#",
"temporary-files",
"file-locking",
""
] |
How do I remove empty elements from an array in JavaScript?
Is there a straightforward way, or do I need to loop through it and remove them manually? | **EDIT:** This question was answered almost nine years ago when there were not many useful built-in methods in the `Array.prototype`.
Now, certainly, I would recommend you to use the `filter` method.
Take in mind that this method will return you *a new array* with the elements that pass the criteria of the callback f... | ## A few simple ways:
```
var arr = [1,2,,3,,-3,null,,0,,undefined,4,,4,,5,,6,,,,];
arr.filter(n => n)
// [1, 2, 3, -3, 4, 4, 5, 6]
arr.filter(Number)
// [1, 2, 3, -3, 4, 4, 5, 6]
arr.filter(Boolean)
// [1, 2, 3, -3, 4, 4, 5, 6]
```
**or - (only for *single* array items of type "text")**
```
['','1','2',3,,'4',... | Remove empty elements from an array in Javascript | [
"",
"javascript",
"arrays",
""
] |
In a form, I added an overload of ShowDialog(). In Visual Studio, this overload shows up in Intellisense as the third version. How can I make my overloaded function appear as #1 (i.e. the default)? | As far as I know, there is no way to control the order of overloads in the overload selection intellisense tip. | You should use a plugin for that: one that accomplishes the required task is the Visual Assist from Tomato - <http://www.wholetomato.com/>
It does exactly what you want(among the other options): display the non-inherited members on the top of the suggestion list and(or) makes them bold | Is there a way in .NET to make your overload of a method appear first in the Intellisense dropdown? | [
"",
"c#",
".net",
"visual-studio",
"intellisense",
""
] |
Say you have a class declaration, e.g.:
```
class MyClass
{
int myInt=7;
int myOtherInt;
}
```
Now, is there a way in generic code, using reflection (or any other means, for that matter), that I can deduce that myInt has a default value assigned, whereas myOtherInt does not?
Note the difference between being init... | I compiled your code and load it up in ILDASM and got this
```
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 15 (0xf)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldc.i4.7
IL_0002: stfld int32 dummyCSharp.MyClass::myInt
IL_... | You might want to consider a nullable int for this behavior:
```
class MyClass
{
int? myInt = 7;
int? myOtherInt = null;
}
``` | Can you detect if a C# field has been assigned a default value? | [
"",
"c#",
"reflection",
"default",
""
] |
I have an HTML input box
```
<input type="text" id="foo" value="bar">
```
I've attached a handler for the '*keyup*' event, but if I retrieve the current value of the input box during the event handler, I get the value as it was, and not as it will be!
I've tried picking up '*keypress*' and '*change*' events, same pr... | Can you post your code? I'm not finding any issue with this. Tested on Firefox 3.01/safari 3.1.2 with:
```
function showMe(e) {
// i am spammy!
alert(e.value);
}
....
<input type="text" id="foo" value="bar" onkeyup="showMe(this)" />
``` | To give a ***modern*** approach to this question. This works well, including `Ctrl`+`v`. [GlobalEventHandlers.oninput](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput).
```
var onChange = function(evt) {
console.info(this.value);
// or
console.info(evt.target.value);
};
var input = d... | How to get the new value of an HTML input after a keypress has modified it? | [
"",
"javascript",
"html",
"dom",
""
] |
I'm relatively new to Javascript and was wondering if there's a quick way to shuffle content that is contained in multiple `<div>` tags. For example
```
<div id='d1'>
<span>alpha</span>
<img src='alpha.jpg'>
</div>
<div id='d2'>
<span>beta</span>
<img src='beta.jpg'>
</div>
<div id='d3'>
<span>gamma</span>
... | are you ok with using a javascript library like [jQuery](http://jquery.com)? here's a quick jQuery example to accomplish what you're after. the only modification to your HTML is the addition of a container element as suggested:
```
<div id="shuffle">
<div id='d1'>...</div>
<div id='d2'>...</div>
<div id='d... | A recent question was just closed as duplicate of this, but I feel I've got a better answer than any here. This method is very direct. There's no mucking with copying HTML, thus preserving changes to the DOM, styles, event handlers, etc.
To shuffle all the children of some parent element, select a random child and app... | Any way to shuffle content in multiple div elements | [
"",
"javascript",
"dom",
"dhtml",
""
] |
Up till now all my programming experience has been desktop development (mostly C/C++ with OpenGL/DirectX) but I'm interested in trying my hand at some web dev.
The two directions I'm considering are Ruby on Rails and ASP.net.
Which is most widely used?
Which would be a more marketable skill to have?
Thanks! | Why don't you take a few days or a week to experiment with Rails, just for fun? You might, like many other devs before, find a real liking for it and 'fall in love' with Ruby and revitalize your programming interest. If not you just embrace ASP.net which will feel more natural to you anyway.
Other commenters have not ... | PHP, Ruby On Rails, ASP.Net, or Java.
It's a religious choce and it depends on who you ask.
Everyone you ask will give you a different answer.
You should ask yourself how you want to work, PHP java and ASP all let you write markup that is interspersed with code or code that writes the markup for you.
To be honest i... | Moving from Desktop Development to Web Development | [
"",
"c#",
"asp.net",
"ruby-on-rails",
"ruby",
""
] |
I have a program that when it starts, opens a winform (it is the one specified in Application.Run(new ...). From this form I open another form:
```
OtherForm newForm=new OtherForm();
newForm.Show();
```
How can i communicate from the new winform with the form that opened it? So that I can add some items in it. | I think I have found the answer here:
<http://www.c-sharpcorner.com/UploadFile/mosessaur/winformsdelegates09042006094826AM/winformsdelegates.aspx>
I have to use delegates. In the second form I define:
```
public delegate void AddItemDelegate(string item);
public AddItemDelegate AddItemCallback;
```
And from the form... | The simplest way is to override the constructor, eg, `OtherForm newForm=new OtherForm(string title, int data);`. This also works for reference types (which would be a simple way to send the data back). | How to call the main program from a winform opened by it'? | [
"",
"c#",
"winforms",
""
] |
I am trying to export a Ruby framework via XML-RPC. However I am having some problems when trying to call a method from a class not directly added as a handler to the XML-RPC server. Please see my example below:
I have a test Ruby XML-RPC server as follows:
```
require "xmlrpc/server"
class ExampleBar
def bar()
... | Your client (s in you Python code) is a ServerProxy object. It only accepts return values of type boolean, integers, floats, arrays, structures, dates or binary data.
However, without you doing the wiring, there is no way for it to return another ServerProxy, which you would need for accessing another class. You could... | XML-RPC can't pass objects. The set of parameter types is limited (as jakber says). | Access Ruby objects with Python via XML-RPC? | [
"",
"python",
"ruby",
"xml-rpc",
"interop",
""
] |
while writing a custom attribute in C# i was wondering if there are any guidelines or best practices regarding exceptions in attributes.
Should the attribute check the given parameters for validity? Or is this the task of the user of the property?
In a simple test I did the exception was not thrown until i used GetCus... | Attributes are only actually constructed when you use reflection, so that's the only time you *can* throw an exception. I can't remember *ever* using an attribute and having it throw an exception though. Attributes usually provide data rather than real behaviour - I'd expect the code which *uses* the attribute to provi... | With a few exceptions with compiler-sepcific meaning (such as `[PrincipalPermission]` etc.) attributes can't interact directly with code without being asked to. However, if you use the AOP (Aspect Oriented Programming) tool "[PostSharp](http://www.postsharp.net/)", your aspect attributes *can* add behaviour to your cla... | Custom Attributes and Exceptions in .net | [
"",
"c#",
".net",
"exception",
"attributes",
""
] |
I am writing a multi-threaded Windows application in Microsoft Visual C# 2008 Express Edition. Recently, the debugger has been acting strangely.
While I am Stepping Over lines of code using the F10, sometimes it will interpret my Step Over (F10) command just like a Continue command (F5) and then the program will resum... | You ought to take a look at this [KB article](http://support.microsoft.com/default.aspx/kb/957912) and consider its matching hotfix.
EDIT: the hotfix does solve these kind of debugging problems. Unfortunately, the source code changes for the hotfix didn't make it back into the main branch and VS2010 shipped with the e... | I've seen this a few times. It generally happens when there's a context switch to another thread. So you might be stepping through thread with ID 11, you hit F10, and there's a pre-emptive context switch so now you're running on thread ID 12 and so Visual Studio merrily allows the code to continue.
There are some good... | Why does Microsoft Visual C# 2008 Express Edition debugger randomly exit? | [
"",
"c#",
"visual-studio",
"visual-studio-2008",
"multithreading",
"debugging",
""
] |
If you have a situation where you need to know where a boolean value wasn't set (for example if that unset value should inherit from a parent value) the Java boolean primitive (and the equivalent in other languages) is clearly not adequate.
What's the best practice to achieve this? Define a new simple class that is ca... | ```
Boolean a = true;
Boolean b = false;
Boolean c = null;
```
I would use that. It's the most straight-forward.
Another way is to use an enumeration. Maybe that's even better and faster, since no boxing is required:
```
public enum ThreeState {
TRUE,
FALSE,
TRALSE
};
```
There is the advantage of the f... | In Java 8, there is also the **Optional** option:
```
public static final Optional<Boolean> TRI_TRUE = Optional.of(true);
public static final Optional<Boolean> TRI_FALSE = Optional.of(false);
public static final Optional<Boolean> TRI_UNKNOWN = Optional.empty();
```
As a bonus, you will get all those *map* and *consum... | Best way to define true, false, unset state | [
"",
"java",
"boolean",
""
] |
I'm just interested in people's opinions. When using nullable types in C# what is the best practice way to test for null:
```
bool isNull = (i == null);
```
or
```
bool isNull = !i.HasValue;
```
Also when assigning to a non-null type is this:
```
long? i = 1;
long j = (long)i;
```
better than:
```
long? i = 1;
l... | Use the forms that were specially implemented for you by the C# team. If anyone objects, tell them Anders said it was okay.
What I'm saying, flippantly, is that a lot of work went into integrating nullable types into c# to give you a good programming experience.
Note that in terms of performance, both forms compile d... | I would use this:
```
long? i = 1;
...some code...
long j = i ?? 0;
```
That means, if *i* is **null**, than 0 will be assigned. | Using nullable types in C# | [
"",
"c#",
"nullable",
""
] |
I have a string that contains both double-quotes and backslashes that I want to set to a variable in Python. However, whenever I try to set it, the quotes or slashes are either removed or escaped. Here's an example:
```
>>> foo = 'baz "\"'
>>> foo
'baz ""'
```
So instead of `baz "\"` like I want I'm getting `baz ""`.... | You're being mislead by output -- the second approach you're taking actually does what you want, you just aren't believing it. :)
```
>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"
```
Incidentally, there's another string form which might be a bit clearer:
```
>>> print(r'baz "\"')
baz "\"
``` | Use a raw string:
```
>>> foo = r'baz "\"'
>>> foo
'baz "\\"'
```
Note that although it looks wrong, it's actually right. There is only one backslash in the string `foo`.
This happens because when you just type `foo` at the prompt, python displays the result of `__repr__()` on the string. This leads to the following... | Quoting backslashes in Python string literals | [
"",
"python",
"string",
""
] |
I am using Visual Studio 2008 SP1 (version 9.0.30729.1). My problem is that the only reporting-related toolbox items I see are 3 "Textbox" controls. Where are the other stuff? Do I need to add a reference to a different assembly?
Here are the steps I take:
1) Open Visual Studio
2) Add new project --> "Reports Appl... | My good sense tells me that something got corrupted in your installation.
Here's what I would try before attempting a repair (this happened recently):
I fixed this by going into my profile as follows:
C:\Documents and Settings\MYUSERNAME\Local Settings\Application Data\Microsoft\VisualStudio\8.0\ProjectAssemblies
T... | My problem was The Report Items Toolbox was showing multiple textboxes instead of valid Report controls.
Solution:
1) Close the visual studio 2005.
2) delete the folders under C:\Documents and Settings\\Local Settings\application Data\microsoft\visualStudio\
3) Open your visual studio 2005 project. It should work | No Report Items in toolbox (VS 2008 SP1) | [
"",
"c#",
"visual-studio-2008",
"report",
"toolbox",
""
] |
I have the following tuple, which contains tuples:
```
MY_TUPLE = (
('A','Apple'),
('C','Carrot'),
('B','Banana'),
)
```
I'd like to sort this tuple based upon the **second** value contained in inner-tuples (i.e., sort Apple, Carrot, Banana rather than A, B, C).
Any thoughts? | ```
from operator import itemgetter
MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=itemgetter(1)))
```
or without `itemgetter`:
```
MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=lambda item: item[1]))
``` | From [Sorting Mini-HOW TO](http://wiki.python.org/moin/HowTo/Sorting#head-d121eed08556ad7cb2a02a886788656dadb709bd)
> Often there's a built-in that will
> match your needs, such as str.lower().
> The operator module contains a number
> of functions useful for this purpose.
> For example, you can sort tuples based
> on... | Sorting a tuple that contains tuples | [
"",
"python",
"sorting",
"tuples",
""
] |
Is there a way to query the current DATEFORMAT SQLServer 2005 is currently using with T-SQL?
I have an application that reads pregenerated INSERT-statements and executes them against a database. To make the data to be inserted culture independent I store datetime-values represented in the invariant culture (month/day/... | Set Language and Set DateFormat only affect the current session. If you Disconnect from the database and connect again, the language and Dateformat are set back to their default values.
There is a 'trick' you could use to determine if the DateFormat is m/d/y, or d/m/y.
```
Select DatePart(Month, '1/2/2000')
```
This... | The following statement will perform a date parsing operation using a given date format (the @dateFormat variable) and then re enable the original date format.
```
declare @dateFormat nvarchar(3);
set @dateFormat = 'dmy';
declare @originalDateFormat nvarchar(3);
select @originalDateFormat = date_format from sys.dm_ex... | Setting and resetting the DATEFORMAT in SQLServer 2005 | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
"datetime",
""
] |
I need to change a static property on an object in our web application. The property has a default value that is hard-coded into the object. If I change the static property in my Application\_Start does that change stick:
A) Forever (well, until the app is recycled)
B) Until the object is GC'd then re-inialised by th... | The scope of a static variable is its AppDomain. So no, it won't get garbage collected - but if the AppDomain is recycled (which can happen a fair amount in ASP.NET) then you'll end up with a "new" static variable, effectively. | In my experience with our web apps here, the answer is A. As far as I know, a static class will never be GCed, it lives on for the life of the process (in this case, the ASP.NET worker process) | The effect of static properties in a web context | [
"",
"c#",
"asp.net",
""
] |
I am embarking on a new RIA project with Java on the backend. I'm the only developer, and the app is a line-of-business application. My current stack looks like this:
MySQL || Spring(JdbcTemplate for data access) || BlazeDS (remoting) || Flex(Cairngorm)
My question is: what changes can I make to improve productivity?... | *Manually coding SQL*
[Hibernate](http://www.hibernate.org/) is an option to cut this out.
One thing that may be of interest is Grails with the available Flex Plugin. It's built on Spring, Hibernate and BlazeDS, so it's all there for you. It was unbelieveably easy to get it remoting stored objects and responding to A... | I would seriously reconsider using Cairngorm. In my opinion it's a pretty bloated framework that introduces a lot of abstraction you'll never use. Check out:
<http://code.google.com/p/swizframework>
<http://www.spicefactory.org>
Both introduce the concept of dependency-injection into your Flex app.
Also +1 for Hiber... | How to boost productivity in my Flex/Java stack? | [
"",
"java",
"apache-flex",
"frameworks",
""
] |
I'm looking for a way to embed an image in a library (Windows-only). I don't want to go the 'traditional' way of putting it in the resources (because of special circumstances that make it not so convenient to mess around with the resource handle.
Ideally, there would be something like xpm files: a 'text' representatio... | Google for a bin2c utility (something like <http://stud3.tuwien.ac.at/~e0025274/bin2c/bin2c.c>). It takes a file's binary representation and spits out a C source file that includes an array of bytes initialized to that data.
Just link the file in and you have your image sitting in a chunk of memory.
Using this kind o... | [The Gimp](http://www.gimp.org/) can export to C files. I think that would be the easiest way to do it. | Embed image in code, without using resource section or external images | [
"",
"c++",
"visual-c++",
"mfc",
""
] |
I'm using T4 for generating repositories for LINQ to Entities entities.
The repository contains (amongst other things) a List method suitable for paging. The documentation for [Supported and Unsupported Methods](http://msdn.microsoft.com/en-us/library/bb738474.aspx) does not mention it, but you can't "call" `Skip` on ... | You can address this in the return type of ProvideDefaultSorting. This code does not build:
```
public IOrderedQueryable<int> GetOrderedQueryable()
{
IQueryable<int> myInts = new List<int>() { 3, 4, 1, 2 }.AsQueryable<int>();
return myInts.Where(i => i == 2);
}
```
This code builds, but is... | Paging depends on Ordering in a strong way. Why not tightly couple the operations? Here's one way to do that:
Support objects
```
public interface IOrderByExpression<T>
{
ApplyOrdering(ref IQueryable<T> query);
}
public class OrderByExpression<T, U> : IOrderByExpression<T>
{
public IQueryable<T> ApplyOrderBy(ref... | How to check for the presence of an OrderBy in a ObjectQuery<T> expression tree | [
"",
"c#",
"linq",
"generics",
"linq-to-entities",
"code-generation",
""
] |
Is it possible in plain JPA or JPA+Hibernate extensions to declare a composite key, where an element of the composite key is a sequence?
This is my composite class:
```
@Embeddable
public class IntegrationEJBPk implements Serializable {
//...
@ManyToOne(cascade = {}, fetch = FetchType.EAGER)
@JoinColum... | I believe that this is not possible with plain JPA. | Using @GeneratedValue for composite PKs is not specified withi JPA 2 spec.
From the JPA spec:
> 11.1.17 GeneratedValue Annotation
>
> The GeneratedValue annotation provides for the specification of
> generation strategies for the values of primary keys. The
> GeneratedValue annotation may be applied to a primary key ... | JPA Composite Key + Sequence | [
"",
"java",
"hibernate",
"jpa",
"composite-key",
""
] |
I have a program in which the user adds multiple objects to a scene. These objects are all represented as a classes.
Now I want the user to be able to save the scenario, so it can be loaded again.
Is there some genereic save method I can use, or do I have to write my own that saves the values of all properties and suc... | Assuming your objects have all values available as public properties, you can use an XMLSerializer to convert the object to an XML string, then use a XMLDeserializer to re-create the object.
There is an extension method to accomplish this [here](https://stackoverflow.com/questions/271398/post-your-extension-goodies-fo... | Usually one would use a database to do this kind of thing. That's probably the recommended practise.
However if you want a quick and dirty method you can serialise to Xml or Binary with relatively little code. Check out the System.Runtime.Serialization stuff. The trade-off of Xml or Binary is that versioning sucks big... | How to save the state of an C# app to be able to load later | [
"",
"c#",
".net",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.