Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I saw this reply from Jon on [Initialize generic object with unknown type](https://stackoverflow.com/questions/386500/initialize-generic-object-with-unknown-type): > If you want a single collection to > contain multiple unrelated types of > values, however, you will have to use > `List<object>` I'm not comparing `Arr...
You'll be able to use the LINQ extension methods directly with `List<object>`, but not with `ArrayList`, unless you inject a `Cast<object>()` / `OfType<object>` (thanks to `IEnumerable<object>` vs `IEnumerable`). That's worth quite a bit, even if you don't need type safety etc. The speed will be about the same; struct...
One big benefit to using `List<object>` is that these days most code is written to use the generic classes/interfaces. I suspect that these days most people would write a method that takes a `IList<object>` instead of an `IList`. Since `ArrayList` doesn't implement `IList<object>` you wouldn't be able to use an array l...
ArrayList vs List<object>
[ "", "c#", ".net", "list", "arraylist", "" ]
I am trying to write a JavaScript function that will return its first argument(function) with all the rest of its arguments as preset parameters to that function. So: ``` function out(a, b) { document.write(a + " " + b); } function setter(...) {...} setter(out, "hello")("world"); setter(out, "hello", "world")()...
First of all, you need a partial - [**there is a difference between a partial and a curry**](https://stackoverflow.com/questions/218025/what-is-the-difference-between-currying-and-partial-application) - and here is all you need, *without a framework*: ``` function partial(func /*, 0..n args */) { var args = Array.pr...
Is [curried javascript](http://www.crockford.com/javascript/www_svendtofte_com/code/curried_javascript/index.html) what you're looking for?
How can I pre-set arguments in JavaScript function call? (Partial Function Application)
[ "", "javascript", "functional-programming", "" ]
I have a dialog in MFC with a CStatusBar. In a separate thread, I want to change the pane text of status bar. However MFC complains with asserts? How is it done? An example code would be great.
You could post a private message to the main frame window and 'ask' it to update the status bar. The thread would need the main window handle (don't use the CWnd object as it won't be thread safe). Here is some sample code: ``` static UINT CMainFrame::UpdateStatusBarProc(LPVOID pParam); void CMainFrame::OnCreateTestT...
Maybe this can help you: [How to access UI elements from a thread in MFC.](http://www.codeguru.com/forum/showthread.php?t=312454) I don't code C++/MFC myself but I had experienced the similar problem in C# which is known as Cross-thread GUI update.
How to change pane text of status bar from a thread in MFC?
[ "", "c++", "multithreading", "mfc", "thread-safety", "" ]
Is there any way to change style of text, format the text inside a Javascript Alert box. e.g. changing its colour, making it bold, etc.? Also, if there an Alert avalaible with a 'Yes', 'No' button instead of an 'OK'/'Cancel' one?
**No**, I'm afraid that is not possible. With JavaScript, you are limited to only 3 popup boxes: `alert`, `prompt` and `confirm`. If you want to make a more featured popup, you should try using one of the many that exist written in JavaScript, which are built from JavaScript Libraries, such as [this](http://dev.icebu...
The best you can do for formatting is the new line character `\n`.
Colour of Text in a Javascript Alert
[ "", "javascript", "css", "alerts", "" ]
I was going through some code and came across a scenario where my combobox has not been initialized yet. This is in .NET 2.0 and in the following code, this.cbRegion.SelectedValue is null. ``` int id = (int)this.cbRegion.SelectedValue; ``` This code threw a null reference exception instead of an invalid cast exceptio...
It has to do with [Boxing](http://www.csharphelp.com/archives/archive100.html) and unboxing. It is trying to pull an int out of the box (unbox), but the object is null, so you get a null reference exception before it ever gets the change to cast.
If you compile ``` object o = null; int a = (int)o; ``` and look at the MSIL code, you'll see something like ``` ldnull ... unbox.any int32 ``` Now the behavior for unbox.any is specified as follows: > InvalidCastException is thrown if obj > is not a boxed type. > > NullReferenceException is thrown if > obj is a n...
Why does casting a null to a primitive(ie: int) in .net 2.0 throw a null ref exception and not a invalid cast exception?
[ "", "c#", ".net", ".net-2.0", "casting", "" ]
I'm trying to make a pull down menu post a form when the user selects (releases the mouse) on one of the options from the menu. This code works fine in FF but Safari, for some reason, doesn't submit the form. I re-wrote the code using jquery to see if jquery's .submit() implementation handled the browser quirks better....
The code would be: ``` <form id="setlang_form" method="post" action="{% url django.views.i18n.set_language %}"> <fieldset> <select name="language" onchange="formSubmit(this)"> {% for lang in interface_languages %} <option value="{{ lang.code }}" {% ifequal lang.code LANGUAGE_CODE %}selected="select...
You should probably use the `onchange` event of the `<select>` instead (or as well).
Firefox handles xxx.submit(), Safari doesn't ... what can be done?
[ "", "javascript", "django", "django-templates", "" ]
I am crash-learning PHP for a project, and I have a ton of stupid questions to make. The first is the following. I have a structure like this: * index.php * header.php * images/ * data + data.php Now, the problem is that I want to include the header.php file in the data.php file. That is no problem. The problem I ...
Try including the file like such: ``` <?php include($_SERVER['DOCUMENT_ROOT'].'/data/data.php/'); ?> ``` The `DOCUMENT_ROOT` will return the path of the root folder, located on the web server of your website.
Many people use something like this. The `dirname(__FILE__)` will return the directory of the current script. Then you concatenate that to relative path to the script you are including. ``` require(realpath(dirname(__FILE__).'/lib/Database.php')); ```
Header page in PHP that takes the application directory into account
[ "", "php", "path", "" ]
I've got a Django application that works nicely. I'm adding REST services. I'm looking for some additional input on my REST strategy. Here are some examples of things I'm wringing my hands over. * Right now, I'm using the Django-REST API with a pile of patches. * I'm thinking of falling back to simply writing view fu...
> I'm thinking of falling back to simply > writing view functions in Django that > return JSON results. * Explicit * Portable to other frameworks * Doesn't require patching Django
Please note that REST does not just mean JSON results. REST essentially means exposing a resource-oriented API over native but full-fledged HTTP. I am not an expert on REST, but here are a few of the things Rails is doing. * URLs should be good, simple names for resources * Use the right HTTP methods + HEAD, GET, PO...
Adding REST to Django
[ "", "python", "django", "apache", "rest", "" ]
I need to read a properties files that's buried in my package structure in `com.al.common.email.templates`. I've tried everything and I can't figure it out. In the end, my code will be running in a servlet container, but I don't want to depend on the container for anything. I write JUnit test cases and it needs to wo...
When loading the Properties from a Class in the package `com.al.common.email.templates` you can use ``` Properties prop = new Properties(); InputStream in = getClass().getResourceAsStream("foo.properties"); prop.load(in); in.close(); ``` (Add all the necessary exception handling). If your class is not in that packag...
To add to Joachim Sauer's answer, if you ever need to do this in a static context, you can do something like the following: ``` static { Properties prop = new Properties(); InputStream in = CurrentClassName.class.getResourceAsStream("foo.properties"); prop.load(in); in.close() } ``` (Exception handling elided...
Loading a properties file from Java package
[ "", "java", "properties-file", "" ]
I have an interface method ``` public void Execute(ICommand command); ``` which needs to pass known subtypes of `ICommand` to an apropriate `Handle(SpecificCommand command)` method implementation and do some generic handling of unknown types. I am looking for a universal (i.e. not requiring a giant switch) method o...
The cast is emitted at compile-time, so you need to know the type at compile-time. The overloading is also determined at compile-time - so by the time you actually know the concrete type to use, it's too late. I don't see that you'd actually be duplicating any *logic* by using delegates. Alternatively, if you do it wi...
Well, the "correct" answer is that Handle() should be a method in ICommand, so that instead of `Handle(command)`, you'd be saying `command.Handle()`.
In C#, how can I downcast a previously upcasted object without knowing it's type?
[ "", "c#", ".net", "inheritance", "casting", "" ]
What is the correct output (meaning correct by the ECMA standard) of the following program? ``` function nl(x) { document.write(x + "<br>"); } nl(Function.prototype); nl(Function.prototype.prototype); nl(Function.prototype.prototype == Object.prototype); nl(Function.prototype.prototype.prototype); ``` Chrome and IE6 ...
What you're doing here isn't really walking the prototype chain - [this question](https://stackoverflow.com/questions/383201/relation-between-prototype-and-prototype-in-javascript) might help you understand what is actually going on. I didn't bother to check the ECMA spec, but here is my take on the issue: * **Functio...
**Function.prototype** From [ECMAScript Language Specification](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf): > **15.3.3.1 Function.prototype** > > The initial value of Function.prototype is > the Function prototype object (section > 15.3.4). > > **15.3.4 Properties of the Function Proto...
Correct prototype chain for Function
[ "", "javascript", "constructor", "prototype", "" ]
Please feel free to correct me if I am wrong at any point... I am trying to read a [CSV](http://en.wikipedia.org/wiki/Comma-separated_values) (comma separated values) file using .NET file I/O classes. Now the problem is, this CSV file may contain some fields with soft carriage returns (i.e. solitary \r or \n markers r...
It probably is. In terms of order, it goes through each char once only, so it would be O(n) (where n is the length of the stream) so that's not a problem. To read a single character a BinaryReader is your best bet. What I would do is make a class ``` public class LineReader : IDisposable { private Stream stream; ...
You might want to look at using an ODBC/OleDB connection to do this. If you point the data source of an oledb connection to a directory containing csv files, you can then query it as if each CSV was a table. check http://www.connectionstrings.com/?carrier=textfile>connectionstrings.com for the correct connection stri...
What's the most efficient way of implementing ReadLine() on a binary stream?
[ "", "c#", ".net", "vb.net", "" ]
With a vector defined as `std::vector<std::string>`, Wondering why the following is valid: ``` if ( vecMetaData[0] != "Some string" ) { ... ``` But not this: ``` switch ( vecMetaData[1] ) { ... ``` Visual studio complains : ``` error C2450: switch expression of type 'std::basic_string<_Elem,_Traits,_Ax>' ...
switch() needs an integral type (like int, char, ...) string is not an integral type, neither does string have an implicit conversion to an integral type, so it can't be used in a switch statement
It is valid because the first will call the operator!= of std::string, which will accept a const char\* as an argument. That, however, doesn't mean that std::string also has an operator some\_integral\_type() that will return a integral expression which switch needs. Using operators in C++ does not necassary invoke th...
STL Vector comparison issue
[ "", "c++", "stl", "" ]
I have a simple database with two tables. Users and Configurations. A user has a foreign key to link it to a particular configuration. I am having a strange problem where the following query always causes an inner join to the Configuration table regardless of the second parameter value. As far as I can tell, even thou...
I dont think it will work like that. I suggest splitting it into 2 distinct queries. There are probably better ways, but it would require more 'plumbling'.
Replace .Single() with SingleOrDefault() and Linq will switch to a left outer join. I don't know if in your case it will do it, but in some cases it does. Edit dint's see the Single was for the entire query and not for the configuration part: try this: ``` UserConfiguration = (loadConfiguration && c.Configurati...
LINQ To SQL Weird Join Issue
[ "", "c#", "linq-to-sql", "inner-join", "" ]
When a function is attached to an object and called: ``` function f() { return this.x; } var o = {x: 20}; o.func = f; o.func(); //evaluates to 20 ``` `this` refers to the object that the function was called as a method of. It's equivalent to doing `f.call(o)`. When the function is called not as part of an object, `t...
The global object is actually the window so you can do ``` if (this === window) ```
The below should work since using Function.call with a value of null will invoke it in the global scope. ``` this === ((function () { return this; }).call(null)) ``` A simpler variant, ``` this === (function () { return this; })() ``` will also work, but I think the first makes the intent clearer.
JavaScript - check if in global context
[ "", "javascript", "object", "global", "" ]
What is the most efficient way to display the last 10 lines of a very large text file (this particular file is over 10GB). I was thinking of just writing a simple C# app but I'm not sure how to do this effectively.
Read to the end of the file, then seek backwards until you find ten newlines, and then read forward to the end taking into consideration various encodings. Be sure to handle cases where the number of lines in the file is less than ten. Below is an implementation (in C# as you tagged this), generalized to find the last ...
I'd likely just open it as a binary stream, seek to the end, then back up looking for line breaks. Back up 10 (or 11 depending on that last line) to find your 10 lines, then just read to the end and use Encoding.GetString on what you read to get it into a string format. Split as desired.
Get last 10 lines of very large text file > 10GB
[ "", "c#", "text", "large-files", "" ]
We have an application that uses a dual monitor setup - User A will work with Monitor 1, and user B will work with Monitor 2 simultaneously. Monitor 2 is a touch screen device. Now, the problem is, when User A types something in his screen, if User B tries to do something, User A will end up in losing the focus from h...
It is possible with some elbow grease. Paste this code in the form that you show on the touch screen: ``` protected override CreateParams CreateParams { get { const int WS_EX_NOACTIVATE = 0x08000000; CreateParams param = base.CreateParams; param.ExStyle |= WS_EX_NOACTIVATE; return param; } } ``` T...
To me, it sounds like you might want 2 PC's... or maybe host a VM on the PC, and give the VM access to the second monitor via a USB video "card" (not quite the right term). Mmost modern VM's allow USB transfer. Most times, multi-head displays are either used to give a single user lots of screen real-estate, or as a di...
How to solve this focus problem with a dual monitor application?
[ "", "c#", ".net", "windows", "winforms", "multiple-monitors", "" ]
I want to dive more into the unit testing concepts. An open source project which will illustrate the best practices in unit testing is required.
I work on [CruiseControl](http://cruisecontrol.sourceforge.net/) (original Java version) and I think it is worth considering as a source of study for a few reasons: 1. Lots of unit tests. Certainly not the highest coverage but there are plenty to look at. 2. Diverse technology. There are pojos, tag libs, velocity macr...
The source code for [NUnit](http://www.nunit.org) (.NET unit testing software) would be worth a look.
Which opensource java or .net project has best unit test coverage?
[ "", "java", ".net", "unit-testing", "" ]
How can i convert an array of bitmaps into a brand new image of TIFF format, adding all the bitmaps as frames in this new tiff image? using .NET 2.0.
Start with the first bitmap by putting it into an Image object ``` Bitmap bitmap = (Bitmap)Image.FromFile(file); ``` Save the bitmap to memory as tiff ``` MemoryStream byteStream = new MemoryStream(); bitmap.Save(byteStream, ImageFormat.Tiff); ``` Put Tiff into another Image object ``` Image tiff = Image.FromStrea...
Came across this post after a bit of searching on Google. I tried the code that was in the post by a'b'c'd'e'f'g'h', but that didn't work for me. Perhaps, I was not doing something correctly. In any case, I found another post that saved images to multi page tiffs. Here is the link to the post: [Adding frames to a Mult...
Convert bitmaps to one multipage TIFF image in .NET 2.0
[ "", "c#", ".net", ".net-2.0", "drawing", "tiff", "" ]
From <http://www.jibbering.com/faq/faq_notes/closures.html> : > Note: ECMAScript defines an internal [[prototype]] property of the internal Object type. This property is not directly accessible with scripts, but it is the chain of objects referred to with the internal [[prototype]] property that is used in property ac...
I believe you are right in most cases. Every object has a hidden `[[Prototype]]` property, which is used for inheritance. Functions additionally have a public `prototype` property, which is used only when the function is used as constructor: When an object is constructed using `new`, the `[[Prototype]]` property of th...
To answer your question directly: logically it is an object's private copy of the `prototype` property of its constructor. Using metalanguage this is how objects are created: ``` // not real JS var Ctr = function(...){...}; Ctr.prototype = {...}; // some object with methods and properties // the object creation sequ...
Relation between [[Prototype]] and prototype in JavaScript
[ "", "javascript", "ecma262", "" ]
In my application, there are 10-20 classes that are instantiated once[\*]. Here's an example: ``` class SomeOtherManager; class SomeManagerClass { public: SomeManagerClass(SomeOtherManager*); virtual void someMethod1(); virtual void someMethod2(); }; ``` Instances of the classes are contained in one obje...
I think there are two separate problems here. One problem is: how does TheManager *name* the class that it has to create? It must keep some kind of pointer to "a way to create the class". Possible solutions are: * keeping a separate pointer for each kind of class, with a way to set it, but you already said that you d...
Assuming a class (plugin1) which inherits from SomeManagerClass, you need a class hierarchy to build your types: ``` class factory { public: virtual SomeManagerClass* create() = 0; }; class plugin1_factory : public factory { public: SomeManagerClass* create() { return new plugin1(); } }; ``` Then you can ass...
How to design a simple C++ object factory?
[ "", "c++", "factory", "" ]
I have a unicode string like "Tanım" which is encoded as "Tan%u0131m" somehow. How can i convert this encoded string back to original unicode. Apparently urllib.unquote does not support unicode.
%uXXXX is a [non-standard encoding scheme](http://en.wikipedia.org/wiki/Percent-encoding#Non-standard_implementations) that has been rejected by the w3c, despite the fact that an implementation continues to live on in JavaScript land. The more common technique seems to be to UTF-8 encode the string and then % escape t...
``` def unquote(text): def unicode_unquoter(match): return unichr(int(match.group(1),16)) return re.sub(r'%u([0-9a-fA-F]{4})',unicode_unquoter,text) ```
How to unquote a urlencoded unicode string in python?
[ "", "python", "unicode", "character-encoding", "urllib", "w3c", "" ]
Are there any 'good' resources for porting a VB.NET winforms application to C#? I'm sure there are is software that just translates the code, but I'm looking to refactor the code at the same time. Keeping it in its current form is problematic, since it uses some of the 'bad design' practices that VB.NET allows, and wou...
Based on my experience working with some large applications that mix VB and C# projects, I would recommend leaving it in VB.NET. If there are problems with the design, then fix them, but converting the whole thing to C# sounds like a messy, unnecessary distraction to me. The non-stylistic differences between the two l...
If you use something like Reflector or Anakrino, its output is based on the IL rather than the original source. Whether or not it produces code that's any better is open for debate... But you could try it out, anyway. :)
Porting VB.NET Winforms Application to C#
[ "", "c#", ".net", "vb.net", "winforms", "" ]
I'm trying to get a list of processes currently owned by the current user (`Environment.UserName`). Unfortunately, the `Process` class doesn't have any way of getting the UserName of the user owning a process. How do you get the UserName of the user which is the owner of a process using the `Process` class so I can co...
The CodeProject article [How To Get Process Owner ID and Current User SID](http://www.codeproject.com/KB/cs/processownersid.aspx) by [Warlib](http://www.codeproject.com/script/Membership/Profiles.aspx?mid=856529) describes how to do this using both WMI and using the Win32 API via PInvoke. The WMI code is much simpler ...
Thanks, your answers put me on the proper path. For those who needs a code sample: ``` public class App { public static void Main(string[] Args) { Management.ManagementObjectSearcher Processes = new Management.ManagementObjectSearcher("SELECT * FROM Win32_Process"); foreach (Management.Managem...
How do you get the UserName of the owner of a process?
[ "", "c#", ".net", "process", "" ]
I've got a big file on which I'm opening a FileInputStream. This file contains some files each having an offset from the beginning and a size. Furthermore, I've got a parser that should evaluate such a contained file. ``` File file = ...; // the big file long offset = 1734; // a contained file's offset long size = 256...
It sounds like what you really want is a sort of "partial" input stream - one a bit like the ZipInputStream, where you've got a stream within a stream. You could write this yourself, proxying all InputStream methods to the original input stream making suitable adjustments for offset and checking for reading past the e...
First, [FileInputStream.skip() has a bug](https://bugs.java.com/bugdatabase/view_bug?bug_id=6294974) which may make the file underneath skip beyond the EOF marker of the file so be wary of that one. I've personally found working with Input/OutputStreams to be a pain compared to using FileReader and FileWriter and you'...
Good design: How to pass InputStreams as argument?
[ "", "java", "inputstream", "" ]
I would like to load a specific ConfigurationSection but the way the CLR loads the assemblies is giving me some trouble: My CustomConfigurationSection definition is on a specific assembly which cannot be found by the overall process of assembly loading, because I'm using an external tool which basically loads my assem...
If you know the path to your assembly, then you should try ConfigurationManager.OpenExeConfiguration(exePath).
If your assembly is needed to deserialize your custom configuration section, but the CLR can't find the assembly, then I think you're out of luck (or am I misunderstanding the problem?). Is there any way you can get the CLR to find your assembly (providing a hint path maybe)? If not, maybe you'd be better off using a ...
How to: Use a ConfigurationSection without loading it via the GetSection call
[ "", "c#", "configurationsection", "" ]
I understand that .NET FileStream's Flush method only writes the current buffer to disk, but dependent on Windows' disk driver and the hard disk firmware this is no guarantee that the data is actually physically written to disk. Is there a .NET or Win32 method that can give me this guarantee? So if there is power loss...
Under Windows, look at [FlushFileBuffers](http://msdn.microsoft.com/en-us/library/aa364439(v=vs.85).aspx) (Win32 API).
Stefan S. said: > I understand that .NET FileStream's Flush method only writes the current buffer to disk No, .NET FileStream's Flush only writes the .NET buffers to the OS cache, it does not flush the OS cache to disk. Sadly the MSDN doc on this class doesn't say that. For .NET < 4.0, you'll have to call Flush + Win...
How to ensure all data has been physically written to disk?
[ "", "c#", ".net", "filestream", "flush", "" ]
The customer wants us to "log" the "actions" that a user performs on our system: creation, deletion and update, mostly. I already have an aspect that logs the trace, but that works at a pretty low level logging every method call. So if a user clicked on the button "open medical file" the log would read: 1. closePrevio...
Sounds like your client wants an audit trail of the user's actions in the system. Consider that at each action's entry point (from the web request) to start an audit entry with an enum/constant on the action. Populate it with information user has provided if possible. At exit/finally, indicate in the audit if it is s...
I recently post-processed logs to generate summary. You may want to consider that approach, especially if #2 and #3 in the above logs are generated at different places and the desired result would require to carry around state from one place to another.
Logging user actions
[ "", "java", "struts", "logging", "aspectj", "" ]
I'm building a CMS in PHP and one dread I have is that the users will have to fill the data in from existing Word (and Excel, but nevermind that) documents. Now, I've seen what happens when they carelessly copy and paste from Word to a textarea: the database got filled with crap markup. Now, I could certainly strip al...
Sadly most of the HTML editor controls I've used either: 1. Have a button to strip out various elements of mark up (word, html, script, etc) 2. Strip out **all** markup on paste via JavaScript. If you leave it to a button, then generally the non-technical users will forget to press it because they don't (some would s...
I have found FCKEditor to handle text yanked and thrown at it from Word documents, much better than tinyMCE.
How do I remove Word markup crap when inserting to a form?
[ "", "php", "ms-word", "tinymce", "textarea", "fckeditor", "" ]
How do I make the computer's internal speaker beep in C# without external speakers?
In .Net 2.0, you can use [`Console.Beep`](https://learn.microsoft.com/en-us/dotnet/api/system.console.beep). ``` // Default beep Console.Beep(); ``` You can also specify the frequency and length of the beep in milliseconds. ``` // Beep at 5000 Hz for 1 second Console.Beep(5000, 1000); ```
Use [`System.Media.SystemSounds`](https://learn.microsoft.com/en-us/dotnet/api/system.media.systemsounds) to get the sounds for various events, then [Play](https://learn.microsoft.com/en-us/dotnet/api/system.media.systemsound.play) them: ``` System.Media.SystemSounds.Beep.Play(); System.Media.SystemSounds.Asterisk.Pla...
How can I make the computer beep in C#?
[ "", "c#", ".net", "audio", "beep", "" ]
I have a function that, among other things, takes in an object and a Type, and converts the object into that Type. However, the input object is often a double, and the type some variation of int (uint, long, etc.). I want this to work if a round number is passed in as a double (like 4.0), but to throw an exception if a...
This seems to do what you ask. I have only tested it for doubles, floats and ints. ``` public int GetInt(IConvertible x) { int y = Convert.ToInt32(x); if (Convert.ToDouble(x) != Convert.ToDouble(y)) throw new ArgumentException("Input was not an integer"); return y; } ```
``` int intvalue; if(!Int32.TryParse(inObject.ToString(), out intvalue)) throw InvalidArgumentException("Not rounded number or invalid int...etc"); return intvalue; //this now contains your value as an integer! ```
Check for any int type in C#?
[ "", "c#", "reflection", "casting", "types", "" ]
I'm trying to implement paging using row-based limiting (for example: `setFirstResult(5)` and `setMaxResults(10)`) on a Hibernate Criteria query that has joins to other tables. Understandably, data is getting cut off randomly; and the reason for that is explained [here](https://developer.jboss.org/wiki/HibernateFAQ-Ad...
You can achieve the desired result by requesting a list of distinct ids instead of a list of distinct hydrated objects. Simply add this to your criteria: ``` criteria.setProjection(Projections.distinct(Projections.property("id"))); ``` Now you'll get the correct number of results according to your row-based limiting...
I am using this one with my code. Simply add this to your criteria: > criteria.setResultTransformer(Criteria.DISTINCT\_ROOT\_ENTITY); that code will be like the select distinct \* from table of the native sql.
How to get distinct results in hibernate with joins and row-based limiting (paging)?
[ "", "java", "hibernate", "paging", "criteria", "distinct", "" ]
I am trying to debug a problem where a user clicks on the button and the UI just dies. I know, good luck. The logs just end after the user clicks the button so i'm thinking there may be some exception/error that we are not logging. Maybe an OutOfMemoryError. Any suggestions on how to proceed? to get more information....
Which version of java and what machine? In any case, here's the scoop: the event queue thread runs somewhat separately from the main thread. In Java < 5 there was a bug that made it difficult to capture events from that thread, so some exceptions just went away. In Java 5, there's a new method `Thread.setDefaultUncaug...
Try redirecting standard output - you'll probably see the exception stack trace there.
Java swing UI crash debugging
[ "", "java", "swing", "" ]
When we talk about the .NET world the CLR is what everything we do depends on. What is the minimum knowledge of CLR a .NET programmer must have to be a good programmer? Can you give me one/many you think is/are the most important subjects: GC?, AppDomain?, Threads?, Processes?, Assemblies/Fusion? I will very much appr...
Most of those are way deeper than the kind of thing many developers fall down on in my experience. Most misunderstood (and important) aspects in my experience: * Value types vs reference types * Variables vs objects * Pass by ref vs pass by value * Delegates and events * Distinguishing between language, runtime and fr...
A *great* programmer cannot be measured by the quantity of things he knows about the CLR. Sure it's a nice beginning, but he must also know OOP/D/A and a lot of other things like Design Patterns, Best Practices, O/RM concepts etc. Fact is I'd say a "great .Net programmer" doesn't necessary need to know much about the ...
What is the minimum knowledge of CLR a .NET programmer must have to be a good programmer?
[ "", "c#", ".net", "clr", "" ]
Is there a way to have different application settings per each build configuration? I would like to be able to batch build a few configurations with different settings, instead of having to change the settings and build, rinse repeat. Thanks in advance!
I don't know much about the appsettings architecture (I've never really used it), but you can define different values for constants using a bit of MSBuild magic. Create two .cs files, Constants1.cs and Constants2.cs (or name them after your configurations). In each file, define a class called Constants (or whatever) ...
Besides all these, MS promised to add this feature in VS 2010.
C# VS.NET 2008 Changing settings per configuration
[ "", "c#", ".net", "visual-studio-2008", "appsettings", "" ]
This is about a school assignment so I'm trying to do things by the book. I feel like I'm getting the grips of Java, but good programming practice, design patterns, etc. are all rather new to me. I've made my model and it works fine. It contains a student class which contains a number of fields with student informatio...
the GUI should worry about all the interface stuff. I guess you have a class that is your GUI for doing 'stuff' to the student with your JLabels. Just pass your student instance to this class and let it do what it needs to do. When it is done it will call a controller method to do whatever needs to be done. OOD deals ...
Note that the Swing components all use the MVC pattern internally, so they already have a model. This is more relevant with complex widgets like JTable, where you definitely want your model to implement the `TableModel` interface. The big question is how to reconcile your domain model with the internal models of the i...
MVC in Java
[ "", "java", "model-view-controller", "" ]
As of SQL Server 2005, you used to be able to open a flat file in SQL Management Studio off the right click menu for any database table. Once opened, you could add or update records right there in the grid. Now that SQL Server 2008 is out, Microsoft has hidden that feature, at least from the right-click menu. Where d...
It's replaced by "Edit Top 200 Rows". You can change that command in the Tools > Options > SQL Server Object Explorer > Commands. But once you right-click a table, choose "Edit Top 200 Rows", hunt on the toolbar for a button called "Show SQL Pane". From here you can edit the query so the grid shows a subset of the dat...
Changed the value in options to 0 and you can open the entire table.
Where did Open Table go in SQL Server 2008?
[ "", "sql", "database", "sql-server-2008", "" ]
Basically what the title says... I need to have an image that when clicked, I call script.php for instance and in that PHP script file, I get the image coordinates where the mouse was clicked. Is this possible? **EDIT:** After a couple of answers I realized I didn't describe my problem correctly... The thing is, I...
If you can't: 1. use JavaScript, or 2. use input type="image", or 3. add any attributes to your img tag (to do things like create an image map) then, no, you won't be able to do what you describe.
If you use an input type="image", which works like a button, it will send you x and y coordinates of the mouse click (submits form too). More info here: <http://www.htmlhelp.com/reference/html40/forms/input.html#image> Long time since I used it, but I did make it work for a "where's the ball?" competition on a site m...
Is it possible to get the image mouse click location with PHP?
[ "", "php", "image", "mouse", "click", "location", "" ]
I don't know if this is too specific a question, if that is possible, but I'm having to port an app that uses Castle Windsor to Unity so that there isn't a reliance on non-microsoft approved libraries. I know I know but what are you going to do. Anyway I've managed it but I'm not happy with what I've got. In Windsor I...
Cool. This feature is not in unity yet but if you felt a bit ambitious you could setup your own convention based registration. Found below is a snipped that works for the executing assembly and interfaces. Good luck. P.S. This feels like a big hack, I would probably continue just registering all types by hand. ``` us...
Check [this](http://autoregistration.codeplex.com/) out: ``` var container = new UnityContainer(); container .ConfigureAutoRegistration() .LoadAssemblyFrom("Plugin.dll") .IncludeAllLoadedAssemblies() .ExcludeSystemAssemblies() .ExcludeAssembl...
Castle Windsor to Unity - can you auto-configure in Unity the same way you can in CW?
[ "", "c#", "dependency-injection", "castle-windsor", "unity-container", "" ]
I'm a C programmer trying to understand C++. Many tutorials demonstrate object instantiation using a snippet such as: ``` Dog* sparky = new Dog(); ``` which implies that later on you'll do: ``` delete sparky; ``` which makes sense. Now, in the case when dynamic memory allocation is unnecessary, is there any reason ...
On the contrary, you should always prefer stack allocations, to the extent that as a rule of thumb, you should never have new/delete in your user code. As you say, when the variable is declared on the stack, its destructor is automatically called when it goes out of scope, which is your main tool for tracking resource...
Though having things on the stack might be an advantage in terms of allocation and automatic freeing, it has some disadvantages. 1. You might not want to allocate huge objects on the Stack. 2. Dynamic dispatch! Consider this code: ``` #include <iostream> class A { public: virtual void f(); virtual ~A() {} }; cl...
C++ Object Instantiation
[ "", "c++", "instantiation", "" ]
Let's say I've got an object `Customer` with a couple properties (`ID`, `FirstName`, `LastName`). I've got the default constructor `Customer()`, but then I've also got a `Customer(DataRow dr)`, since I load this object from a database and that's a simple way to do it. I frequently come to a point where I want to set u...
Simplest solution seems to be: construct another function that does the job you want to do and have both constructors call that function.
I'm concerned that what you do not get is not about constructors, but about Single Responsibility Principle and Loose Coupling. For instance, the code that you show above means: * your domain model contains data access code * you are not reusing any code from a base class which may be injected with the data-access lo...
overloading constructors and reusing code
[ "", "c#", "oop", "constructor", "" ]
The following test case fails in rhino mocks: ``` [TestFixture] public class EnumeratorTest { [Test] public void Should_be_able_to_use_enumerator_more_than_once() { var numbers = MockRepository.GenerateStub<INumbers>(); numbers.Stub(x => x.GetEnumerator())...
The WhenCalled() api lets you dynamically resolve return values. Changing the test case to the following will allow it to pass: ``` numbers.Stub(x => x.GetEnumerator()) .Return(null) .WhenCalled(x => x.ReturnValue = new List<int> { 1, 2, 3...
The statement ``` numbers.Stub(x => x.GetEnumerator()).Return(new List<int> { 1, 2, 3 }.GetEnumerator()); ``` is identical to ``` var enumerator = new List<int> { 1, 2, 3 }.GetEnumerator(); numbers.Stub(x => x.GetEnumerator()).Return(enumerator); ``` In your test, you are telling Rhino Mocks to give the identical `...
Mocking GetEnumerator() method of an IEnumerable<T> types
[ "", "c#", "mocking", "rhino-mocks", "" ]
I just wrote the following C++ function to programmatically determine how much RAM a system has installed. It works, but it seems to me that there should be a simpler way to do this. Am I missing something? ``` getRAM() { FILE* stream = popen("head -n1 /proc/meminfo", "r"); std::ostringstream output; int b...
On Linux, you can use the function `sysinfo` which sets values in the following struct: ``` #include <sys/sysinfo.h> int sysinfo(struct sysinfo *info); struct sysinfo { long uptime; /* Seconds since boot */ unsigned long loads[3]; /* 1, 5, and 15 minute load averages */ uns...
There isn't any need to use `popen()`. You can just read the file yourself. Also, if their first line isn't what you're looking for, you'll fail, since `head -n1` only reads the first line and then exits. I'm not sure why you're mixing C and C++ I/O like that; it's perfectly OK, but you should probably opt to go all C...
How do you determine the amount of Linux system RAM in C++?
[ "", "c++", "linux", "ram", "" ]
I have a logging table which has three columns. One column is a unique identifier, One Column is called "Name" and the other is "Status". Values in the Name column can repeat so that you might see Name "Joe" in multiple rows. Name "Joe" might have a row with a status "open", another row with a status "closed", anothe...
I would create a second table named something like "Status\_Precedence", with rows like: ``` Status | Order --------------- Closed | 1 Hold | 2 Waiting | 3 Open | 4 ``` In your query of the other table, do a join to this table (on `Status_Precedence.Status`) and then you can `ORDER BY Status_Precedence.Or...
If you don't want to create another table, you can assign numeric precedence using a SELECT CASE ``` Select Name, Status, Case Status When 'Closed' then 1 When 'Hold' then 2 When 'Waiting' then 3 When 'Open' Then 4 END as StatusID From Logging Order By Status...
SQL Precedence Query
[ "", "sql", "operator-precedence", "" ]
I have the following scenario I have a main form as MDI parent and MDI child form, the child form shows a new form (I called it mydialog). I want to access specific function in the MDI child form from mydialog so I tried to set the Owner property in the mydialog object but exception occured (circular reference exceptio...
> > so I tried to set the Owner property in the mydialog object but exception occured (circular reference exception) There should be no exception when setting the Owner property. Can you paste the exception ? Also could you paste your code that sets this value ? Have you set other properties like MDIParent / etc ? ED...
Can you show us the code you were using to show the dialog, One of the ShowDialog methods takes a parent object as a parameter which may do what you are looking for.
Passing data between forms
[ "", "c#", "winforms", "" ]
I have need to select a number of 'master' rows from a table, also returning for each result a number of detail rows from another table. What is a good way of achieving this without multiple queries (one for the master rows and one per result to get the detail rows). For example, with a database structure like below: ...
Normally, I'd go for the two grids approach - however, you might also want to look at FOR XML - it is fairly easy (in SQL Server 2005 and above) to shape the parent/child data as xml, and load it from there. ``` SELECT parent.*, (SELECT * FROM child WHERE child.parentid = parent.id FOR XML PATH('child'),...
It can be done with a single query like this: ``` select MasterTable.MasterId, MasterTable.Name, DetailTable.DetailId, DetailTable.Amount from MasterTable inner join DetailTable on MasterTable.MasterId = DetailTable.MasterId order by MasterTable.MasterId ``` ...
Efficient Way To Query Nested Data
[ "", "c#", ".net", "sql-server", "sql-server-2008", "" ]
I would like to be able to submit a form in an **HTML source (string)**. In other words I need at least the ability to generate POST parameters **from a string containing HTML source of the form**. This is needed in unit tests for a Django project. I would like a solution that possibly; * Uses only standard Python lib...
You should re-read the [documentation about Django's testing framework](http://docs.djangoproject.com/en/dev/topics/testing/), specifically the part about testing views (and forms) with [the test client](http://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client). The test client acts as a simple w...
Since the Django test framework does this, I'm not sure what you're asking. Do you want to test a Django app that has a form? * In which case, you need to do an initial GET * followed by the resulting POST Do you want to write (and test) a Django app that submits a form to another site? Here's how we test Django ap...
How do I submit a form given only the HTML source?
[ "", "python", "django", "testing", "parsing", "form-submit", "" ]
I've got a sql query (using Firebird as the RDBMS) in which I need to order the results by a field, EDITION. I need to order by the contents of the field, however. i.e. "NE" goes first, "OE" goes second, "OP" goes third, and blanks go last. Unfortunately, I don't have a clue how this could be accomplished. All I've eve...
``` Order By Case Edition When 'NE' Then 1 When 'OE' Then 2 When 'OP' Then 3 Else 4 End ```
``` SELECT /*other fields*/ CASE WHEN 'NE' THEN 1 WHEN "OE" THEN 2 WHEN "OP" THEN 3 ELSE 4 END AS OrderBy FROM /*Tables*/ WHERE /*conditions*/ ORDER BY OrderBy, /*other fields*/ ```
Ordering SQL query by specific field values
[ "", "sql", "firebird", "" ]
I'm writing a basic crawler that simply caches pages with PHP. All it does is use `get_file_contents` to get contents of a webpage and regex to get all the links out `<a href="URL">DESCRIPTION</a>` - at the moment it returns: ``` Array { [url] => URL [desc] => DESCRIPTION } ``` The problem I'm having is figuring out...
First of all, regex and HTML don't mix. Use: ``` foreach(DOMDocument::loadHTML($source)->getElementsByTagName('a') as $a) { $a->getAttribute('href'); } ``` Links that may go outside your site start with protocol or `//`, i.e. ``` http://example.com //example.com/ ``` `href="google.com"` is link to a local file. ...
Let's first consider the properties of local links. These will either be: * *relative* with no *scheme* and no *host*, or * *absolute* with a scheme of 'http' or 'https' and a *host* that matches the machine from which the script is running That's all the logic you'd need to identify if a link is local. Use the...
Web crawler links/page logic in PHP
[ "", "php", "hyperlink", "logic", "web-crawler", "" ]
Anyone got any insight as to select x number of non-consecutive days worth of data? Dates are standard sql datetime. So for example I'd like to select 5 most recent days worth of data, but there could be many days gap between records, so just selecting records from 5 days ago and more recent will not do.
Following the approach [Tony Andrews](https://stackoverflow.com/questions/308650/select-x-most-recent-non-consecutive-days-worth-of-data#308670) suggested, here is a way of doing it in T-SQL: ``` SELECT Value, ValueDate FROM Data WHERE ValueDate >= ( SELECT CONVERT(DATETIME, MIN(TruncatedDate)) ...
This should do it and be reasonably good from a performance standpoint. You didn't mention how to handle ties, so you can add the WITH TIES clause if you need to do that. ``` SELECT TOP (@number_to_return) * -- Write out your columns here FROM dbo.MyTable ORDER BY MyDateColumn DESC ```
Select X Most Recent Non-Consecutive Days Worth of Data
[ "", "sql", "sql-server", "sql-server-2005", "datetime", "" ]
C# 3.0 introduced the `var` keyword. And when compiled, the compiler will insert the right types for you. This means that it will even work on a 2.0 runtime. So far so good. But the other day I found a case where, the `var` keyword would be replaced with just object and thus not specific enough. Say you have something ...
I think I see the problem. DataRowCollection is non-generic and thus the only thing the compiler knows is that contains objects of type Object. If it had been a generic datastructure this would have worked.
This: ``` using System; namespace Test { public class X { public String Bleh; } public class Y : X { public String Blah; } public static class Program { public static void Main() { var y = SomeFunctionThatReturnsY(); // y. <-- t...
In C# when is the var keyword different from typing it out?
[ "", "c#", "var", "" ]
I have a class which is not thread safe: ``` class Foo { /* Abstract base class, code which is not thread safe */ }; ``` Moreover, if you have foo1 and foo2 objects, you cannot call foo1->someFunc() until foo2->anotherFunc() has returned (this can happen with two threads). This is the situation and it can't be ...
Instead of just checking that a particular thread is finished or not, why not create a fake `Foo` to be invoked by your wrapper in which the functions record the time at which they were actually started/completed. Then your yield thread need only wait long enough to be able to distinguish the difference between the rec...
You might want to check out [*CHESS: A Systematic Testing Tool for Concurrent Software*](http://Research.Microsoft.Com/CHESS/) by Microsoft Research. It is a testing framework for multithreaded programs (both .NET and native code). If I understood that correctly, it replaces the operating system's threading libraries ...
How to write an automated test for thread safety
[ "", "c++", "multithreading", "unit-testing", "testing", "" ]
Are there C++ compilers already supporting [C++0x](http://en.wikipedia.org/wiki/C%2B%2B0x) [lambda](http://en.wikipedia.org/wiki/Lambda_calculus) expressions?
[Visual Studio 2010 CTP](https://connect.microsoft.com/VisualStudio/content/content.aspx?ContentID=9790) supports it already. **Update:** It is now [Visual Studio 2010 Beta 2](http://msdn.microsoft.com/en-us/vstudio/dd582936.aspx)
g++ has support since [4.5](http://gcc.gnu.org/gcc-4.5/changes.html). Status for C++11 support in gcc can be found [here](http://gcc.gnu.org/projects/cxx0x.html#lambdas).
What C++ compilers are supporting lambda already?
[ "", "c++", "lambda", "" ]
Recently I used a class that inherits from a collection instead of having the collection instantiated within the class, is this acceptable or does it create unseen problems further down the road? Examples below for the sake of clarity: ``` public class Cars : List<aCar> ``` instead of something like: ``` public clas...
The problem with this is that your Cars class will still have the interface it inherits from List, which may allow operations you don't want.
That depends on the final purpose of your class. If it is only going to work as your own implementation of a collection use inheritance. If not, include a a collection as a property. The second option is more versatile: * As you can only inherit from one class, you might need to inherit from another class rather than ...
Classes with Collections as Properties vs. Classes Inheriting Collections
[ "", "c#", "class", "inheritance", "" ]
What is the best way to close an ASPX page from the code-behind? I have a button event handler that I want to close the page after the user has clicked an ASP.NET button on the page. I have tried to programmatically add a JavaScript method that contains a `window.close()` command to the `OnClientClick` event to close ...
**UPDATE:** I have taken all of your input and came up with the following solution: In code behind: ``` protected void Page_Load(object sender, EventArgs e) { Page.ClientScript.RegisterOnSubmitStatement(typeof(Page), "closePage", "window.onunload = CloseWindow();"); } ``` In aspx page: ``` function CloseWin...
You would typically do something like: ``` protected void btnClose_Click(object sender, EventArgs e) { ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true); } ``` However, keep in mind that different things will happen in different scenerios. Firefox won't let you close a window ...
Programmatically close aspx page from code behind
[ "", "c#", "asp.net", "" ]
I am a 10year+, C++ linux/windows developer and I have been asked to estimate the effort to port the windows application to OS X. I haven't developed on OS X before,so I don't know what to expect. It is a C++/Qt application, so I want to ask: what are the de facto tools like editor, IDE, compiler, make tool, etc ? Wh...
As jakber already [posted](https://stackoverflow.com/questions/366923/need-advice-on-windows-to-os-x-port-estimation-and-cost-of-dev-on-os-x#366983), XCode is the standard IDE for MacOSX, and is free (comes with the install DVD or can be downloaded from apple. The XCode IDE is quite different from that of Visual Studi...
You're in luck that your app is in Qt, TrollTech has a lot of documentation on how to do this; developing on OS X can be very similar to developing on Linux, make sure to check out the MacPorts project (<http://www.macports.org>), which is like apt-get/yum for Mac. Your toolchain is the usual suspects - gcc/make/autoco...
Need advice on Windows to OS X Port Estimation and cost of dev. on OS X
[ "", "c++", "macos", "qt", "" ]
Not every website exposes their data well, with XML feeds, APIs, etc How could I go about extracting information from a website? For example: ``` ... <div> <div> <span id="important-data">information here</span> </div> </div> ... ``` I come from a background of Java programming and coding with Apache XMLBean...
There are several Open Source HTML Parsers out there for Java. I have used [JTidy](http://jtidy.sourceforge.net/) in the past, and have had good luck with it. It will give you a DOM of the html page, and you should be able to grab the tags you need from there.
[Here's an article](http://www.manageability.org/blog/stuff/screen-scraping-tools-written-in-java) that has a couple of screen scraping tools written in java. In general, it sounds like you want to take a look at [regular expressions](http://www.regular-expressions.info/), which do the pattern matching you're looking ...
Extracting Information from websites
[ "", "java", "html", "html-content-extraction", "" ]
I have a database that hold's a user's optional profile. In the profile I have strings, char (for M or F) and ints. I ran into an issue where I try to put the sex of the user into the property of my Profile object, and the application crashes because it doesn't know how to handle a returned null value. I've tried cas...
rotard's answer (use `Is<ColumnName>Null()`) only works for typed data sets. For untyped data sets, you have to use one of the patterns in the following code. If this code isn't definitive, let me know and I'll edit it until it is. This is an extremely common question that there should really be only one right answer ...
nullable types were designed just for this purpose! use 'as char?' instead of '(char?)' ``` class Foo { char? sex; } Foo object; object.sex = dt.Rows[0]["Sex"] as char?; ```
What is the best practice for handling null int/char from a SQL Database?
[ "", "c#", "sql-server", "dbnull", "" ]
I'm looking for some information on Routing in MVC with C#. I'm currently very aware of the basics of routing in MVC, but what i'm looking for is somewhat difficult to find. Effectively, what I want to find is a way of defining a single route that takes a single parameter. The common examples I have found online is a...
You can construct the routes as you like ``` routes.MapRoute( "Default", "{controller}.mvc/{action}/{param1}/{param2}/{param3}" new { controller = "Default", action="Index", param1="", param2="", param3=""}); ``` Also, [look at this post](http://chriscavanagh.wordpress.com/2008/03/11/aspnet-routing-goodby...
If you want to have a different parameter name *and* keep the same routing variable, use the FromUri attribute like so: ``` public ActionResult MyView([FromUri(Name = "id")] string parameterThatMapsToId) { // do stuff } ``` In your routes, all you need is: ``` routes.MapRoute( "Default", "{controller}.mvc/{ac...
MVC Routing - Parameter names question
[ "", "c#", "asp.net-mvc", "model-view-controller", "routes", "url-routing", "" ]
I have a VS solution, with the following projects. -GUI -DataAccess -BusinessLogic -BusinessObjects but where should the main model class reside? This is usually a cache of a set of objects which are the results from the data access layer and the GUI using virtual grids to view data inside the model. The questi...
This is a subjective question, but often to enforce that your model objects don't have direct dependencies to infrastructure, people often put them in a separate project. you also need to consider what other projects might use these model objects. Another option for splitting up functionality into separate deployable ...
I tend to have * `Justice.Project.Core` — the POCO domain model — i.e., business objects) * `Justice.Project.Data` — NHibernate mappings etc., where the persistence scheme resides * `Justice.Project.Services` — repositories, as well as business logic which cannot easily be fit into the business objects * `Justice.Proj...
where does the model go?
[ "", "c#", "winforms", "model-view-controller", "mvp", "" ]
given the following class ... ``` public class Category { public string Name {get;set;} public Category ParentCategory {get;set;} } ``` What the most efficient way to output the following from a collection (`IList<Category>`) of Category objects? ``` + Parent Category ++ Sub Category ++ Sub Category 2 + Parent C...
You may wish to consider reversing your relationship. If a node can get to its parent but not vice versa, you have to have *all* the leaf nodes in order to print out the full tree. Compare this to the situation where you have each node know about its children - then you only need the root node.
A small recursive function can do it for you. ``` static void recurseCategories(ref List<Category> cl, Category start, int level) { foreach (Category child in cl) { if (child.ParentCategory == start) { Console.WriteLine(new String(' ', level) + child.Name); recurseCategories(ref cl, child, leve...
How to iterate hierarchical data and output the hierarchy using C#
[ "", "c#", ".net", "" ]
I am writing a (very small) framework for checking pre- and postconditions of methods. Entry points are (they could be easily be methods; that doesn't matter): ``` public static class Ensures { public static Validation That { get { ... } } } public static class Requires { public static Validation ...
Any solution that is found here would be slower than the actual checks. Also, since it would not be build into the compiler like `ConditionalAttribute`, the parameters would still be calculated. If the postconditions could be very complicated, such as ``` Ensures.That.IsPositive(ExpensiveCalculation(result)); ``` You...
Is this anything that the normal [ConditionalAttribute](http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx) doesn't do for you, aside from working on a property instead of a method? You may well need to change the way things are called so that you've got methods instead of properties -...
Is it possible in .Net to call some code only from debug builds of client assemblies?
[ "", "c#", "build", "debugging", "release", "conditional-compilation", "" ]
I've added the following code to my masterpage (Page\_Load) so once a user logs out they will not be able to use the back button to see the page they were previously at. ``` Response.Buffer = true; Response.ExpiresAbsolute = DateTime.Now.AddDays(-1); Response.Expires = -1; Response.CacheControl = "no-cache"; ``` ...
Is the objective to prevent an un-authenticated user from surreptitiously visiting a previously-used computer and seeing what the authenticated user was doing? If the latter, then you should redirect the user to a logout page that has a window.close(); command along with strong language about this being a **requirement...
See: * [Disabling Back button on the browser](https://stackoverflow.com/questions/87422/disabling-back-button-on-the-browser) * [Is there a way to keep a page from rendering once a person has logged out but hit the "back" button?](https://stackoverflow.com/questions/64059/is-there-a-way-to-keep-a-page-from-rendering-o...
Warning: Page Has Expired
[ "", "c#", "back-button", "" ]
Any simple, but secure script available for **Flash > MySQL DB** integration? I need something for a Login DB. Exchanging variables with **PHP** is nice and easy, but obviously insecure. **via Remoting?** I've got the [Flash 8 remoting components installed](http://blog.vixiom.com/2007/04/17/actionscript-20-flash-remo...
Afaik it is impossible to talk to a MySQL server directly via ActionScript (unless someone has written a package that actually handless the net stuff, but I haven't seen one yet). May I also point out that your remark about "insecure because of PHP" is not really accurate? It is even worse when you actually do everyth...
Whether you use Flash or PHP, you're still using HTML form technology / specificaion to do the GET/POST, thus using Flash is just as secure (or insecure) as using PHP, Perl, CGI, etc. If you want some level of security on your logins, you should consider getting an SSL license for the site.
Simple secure way for Flash to MySQL Database
[ "", "php", "mysql", "flash", "actionscript", "database-connection", "" ]
While learning different languages, I've often seen objects allocated on the fly, most often in Java and C#, like this: ``` functionCall(new className(initializers)); ``` I understand that this is perfectly legal in memory-managed languages, but can this technique be used in C++ without causing a memory leak?
Your code is valid (assuming functionCall() actually guarantees that the pointer gets deleted), but it's fragile and will make alarm bells go off in the heads of most C++ programmers. There are multiple problems with your code: * First and foremost, who owns the pointer? Who is responsible for freeing it? The calling...
Yes, as long as you deallocate the memory inside the function. But by no means this is a best practice for C++.
Passing newly allocated data directly to a function
[ "", "c++", "memory-leaks", "" ]
I'm reading all the files in a single directory and I want to filter on JPG,JPEG,GIF and PNG. Both capital and small letters. Those are the only files to be accepted. I am currently using this: ``` $testPics = takeFiles($picsDir, "([^\s]+(?=\.(jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF))\.\2)"); ``` and the function takeFil...
I think something is wrong with your regex. Try testing regexes here first: <https://www.regexpal.com/> I think this one might work for you: `/^.*\.(jpg|jpeg|png|gif)$/i` Note the /i at the end - this is the "case insensitive" flag, saves you having to type out all permutations :)
How about using [glob()](http://www.php.net/glob) instead? ``` $files = glob($dir . '*.{jpg,gif,png,jpeg}',GLOB_BRACE); ```
Checking for file-extensions in PHP with Regular expressions
[ "", "php", "regex", "" ]
How can I split by word boundary in a regex engine that doesn't support it? python's re can match on \b but doesn't seem to support splitting on it. I seem to recall dealing with other regex engines that had the same limitation. example input: ``` "hello, foo" ``` expected output: ``` ['hello', ', ', 'foo'] ``` a...
(\W+) can give you the expected output: ``` >>> re.compile(r'(\W+)').split('hello, foo') ['hello', ', ', 'foo'] ```
One can also use re.findall() for this: ``` >>> re.findall(r'.+?\b', 'hello, foo') ['hello', ', ', 'foo'] ```
Split by \b when your regex engine doesn't support it
[ "", "python", "regex", "" ]
Without using plpgsql, I'm trying to urlencode a given text within a pgsql SELECT statement. The problem with this approach: ``` select regexp_replace('héllo there','([^A-Za-z0-9])','%' || encode(E'\\1','hex'),'g') ``` ...is that the encode function is not passed the regexp parameter, unless there's another way to c...
``` select regexp_replace(encode('héllo there','hex'),'(..)',E'%\\1','g'); ``` This doesn't leave the alphanumeric characters human-readable, though.
Here is pretty short version, and it's even "pure SQL" function, not plpgsql. Multibyte chars (including 3- and 4-bytes emoji) are supported. ``` create or replace function urlencode(in_str text, OUT _result text) returns text as $$ select string_agg( case when ol>1 or ch !~ '[0-9a-za-z:/@._?#-]+' ...
urlencode with only built-in functions
[ "", "sql", "postgresql", "urlencode", "" ]
What are the real differences between anonymous type(var) in c# 3.0 and dynamic type(dynamic) that is coming in c# 4.0?
An anonymous type is a real, compiler-generated type that is created for you. The good thing about this is that the compiler can re-use this type later for other operations that require it as it is a POCO. My understanding of dynamic types is that they are late-bound, meaning that the CLR (or DLR) will evaluate the ob...
You seem to be mixing three completely different, orthogonal things: * *static vs. dynamic* typing * *manifest vs. implicit* typing * *named vs. anonymous* types Those three aspects are completely independent, they have nothing whatsoever to do with each other. *Static vs. dynamic* typing refers to *when* the type c...
Anonymous Type vs Dynamic Type
[ "", "c#", ".net", "dynamic", "anonymous-types", "" ]
I am attempting to get a DropDownList to AutoPostBack via an UpdatePanel when the selected item is changed. I'm going a little stir-crazy as to why this isn't working. Does anyone have any quick ideas? ASPX page: ``` <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always" ChildrenAsTriggers="true" > ...
I was able to get it to work with what you posted. This is the code I used... Basically what you had but I am throwing an exception. ``` <asp:ScriptManager ID="smMain" runat="server" /> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always" ChildrenAsTriggers="true" > <ContentTemplat...
EnableViewState="true" in UpdatePannel will definitely resolve the problem.
ASP.NET DropDownList AutoPostback Not Working - What Am I Missing?
[ "", "c#", "asp.net", "updatepanel", "autopostback", "" ]
I'been doing some inheritance in js in order to understand it better, and I found something that confuses me. I know that when you call an 'constructor function' with the new keyword, you get a new object with a reference to that function's prototype. I also know that in order to make prototypal inheritance you must ...
> 1) Why if all new objects contain a > reference to the creator function's > prototype, fido.prototype is > undefined? All new objects do hold a reference to the prototype that was present on their constructor at the time of construction. However the property name used to store this reference is not `prototype` as it...
You cannot change an object's prototype once it's been instantiated with `new`. In your example above, lines like ``` fido.prototype = new KillerDog(); ``` simply creates a new attribute named `prototype` on the object `fido`, and sets that attribute to a new `KillerDog` object. It's no different than ``` fido.foo ...
Javascript Prototypal Inheritance?
[ "", "javascript", "inheritance", "prototype", "prototypal-inheritance", "" ]
What do you like to have in the C++ cheat sheet?
I found [this one](http://web.archive.org/web/20090823155413/http://www.sfu.ca/~vwchu/projects/CPPQuickRef.pdf) that seems to be detailed enough. It covers basics of templates, inheritance, operators, exceptions, etc. It has a lot of information in a very small space.
The O'Reilly book [C++ Pocket Reference](http://oreilly.com/catalog/9780596004965/) would be one such useful tool. > The C++ Pocket Reference is a memory > aid for C++ programmers, enabling them > to quickly look up usage and syntax > for unfamiliar and infrequently used > aspects of the language. The book's > small s...
Is there any cheatsheet available for C++?
[ "", "c++", "" ]
I am using a third-party DLL. For some particular cases, a function in the DLL is throwing an exception. Is it possible to debug the DLL in the Visual Studio? After [the answer from Andrew Rollings](https://stackoverflow.com/questions/349918/debugging-a-third-party-dll-in-visual-studio/349925#349925), I am able to vie...
If the DLL is in a [.NET](http://en.wikipedia.org/wiki/.NET_Framework) language, you can decompile it using a tool like [.NET Reflector](http://en.wikipedia.org/wiki/.NET_Reflector) and then debug against the source code. Or you could ask the vendor if source code is available. That's probably the easiest way.
Building on Andrew's answer, you just treat the decompiled source code as a new library within your project and set breakpoints in the source. Remove all references to the 3rd party DLL so that it is the decompiled code that is executing. Other things: * You may be breaking the law by decompiling the code, or breachi...
Debugging a third-party DLL in Visual Studio?
[ "", "c#", ".net", "debugging", "dll", "" ]
Is it possible to create a new process on windows with a different user account? I know there are a context menu "Run as" but I want do it from Java. I have the username and the password.
You need to write a DLL using the [Java Native Interface (JNI)](http://en.wikipedia.org/wiki/Java_Native_Interface) as you cannot do this with pure Java code. The DLL itself needs to call the **[CreateProcessAsUser](http://msdn.microsoft.com/en-us/library/ms682429(VS.85).aspx)** function to create a process in the con...
There is a program called "runas.exe." You could run that process and supply the appropriate arguments for your process and username/password. I think that's the simplest method.
How can I create a new process with another User Account on Windows?
[ "", "java", "windows", "process", "account", "" ]
I was looking at Stack Overflow question *[What is the difference between abstract function and virtual function?](https://stackoverflow.com/questions/391483)*, and I was wondering whether every abstract function should be considered to be a virtual function in C# or in general? I was a bit puzzled by the "you must ov...
Yes. From section 10.6.6 of the [C# 3.0 spec](http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc): > When an instance method declaration > includes an abstract modifier, that > method is said to be an abstract > method. Although an abstract method is...
It ***has*** to be virtual (and Jon Skeet has already whipped out the spec to prove that it *is*), because, given a reference to the abstract base class, the concrete derived class's implementation must be called. For example, given the classic Animal hierarchy: ``` abstract class Animal{ public abstract void Spea...
Is every abstract function virtual in C#, in general?
[ "", "c#", "oop", "" ]
Using MySQL syntax and having a table with a row like: ``` mydate DATETIME NULL, ``` Is there a way to do something like: ``` ... WHERE mydate<='2008-11-25'; ``` I'm trying but not really getting it to work.
Nevermind found an answer. Ty the same for anyone who was willing to reply. ``` WHERE DATEDIFF(mydata,'2008-11-20') >=0; ```
Uh, `WHERE mydate<='2008-11-25'` *is* the way to do it. That should work. Do you get an error message? Are you using an ancient version of MySQL? Edit: The following works fine for me on MySQL 5.x ``` create temporary table foo(d datetime); insert into foo(d) VALUES ('2000-01-01'); insert into foo(d) VALUES ('2001-0...
In SQL how to compare date values?
[ "", "sql", "mysql", "compare", "where-clause", "" ]
Is the LAMP (Linux, Apache, MySQL, PHP / Ruby / Python) stack appropriate for Enterprise use? To be clear, by "Enterprise", I mean a large or very large company, where security, robustness, availability of skill sets, Total Cost of Ownership (TCO), scalability, and availability of tools are key considerations. Said an...
"but where it's a core platform for systems like CRM and HR, as well as for internal and external websites" First, find a LAMP CRM or HR application. Then find a customer for the LAMP CRM or HR application. Sadly, there aren't a lot of examples of item 1. Therefore, your case is proven. It can't be used for enterpri...
> Something ubiquitous will be seen as more "valid" than something exotic / esoteric in this kind of environment. Although I personally wouldn't recommend PHP due to the many flaws in the language, it's most certainly ubiquitous. With the advent of phusion passenger, Rails support amongst shared-hosting companies is g...
Is the LAMP stack appropriate for Enterprise use?
[ "", "php", "ruby", "lamp", "system-design", "" ]
I know the rule is to NEVER throw one during a destructor, and I understand why. I would not dare do it. But even the C++ Faq Lite says that this rule is good 99% of the time. What is the other 1% that they fail to delve into? [Link to the C++ Faq Lite bullet point on throwing from ~():](http://www.parashift.com/c++-f...
Just don't do it. If the stars and planets align in such a way that you find you need to... Still don't do it.
Wow, I was about to vote Juan up until I saw the part about never using exceptions. Okay, first of all, Juan has it correct. If, *for whatever reason*, you end up in that situation of two exceptions chasing one another up the stack, C++ will simply throw up its hands and its last meal and terminate abnormally. So, thr...
When is it OK to throw an exception from a destructor in C++?
[ "", "c++", "exception", "" ]
I have this C# extension method that will extend any dictionary where the *Value* type is an *IList*. When I write the equivalent code in VB.Net I get the following compile error: > *"Extension method 'Add' has some type constraints that can never be satisfied".* I find this really puzzling as the **same** type const...
The problem only happens when `<System.Runtime.CompilerServices.Extension()>` is present. The VB compiler imposes a restriction that the constraints must be verifiable with the first argument alone. Since the first argument for the extension method (`Dictionary(Of KeyType, ListType)`) is dependant upon the third argume...
The reason is explained here: <http://msdn.microsoft.com/en-us/library/bb385206.aspx> The VB compiler might be a little pickier in this case because it has to support optional parameters. There are no optional parameters in C# (yet).
C# to VB.Net: Why does this fail to compile when converted to VB?
[ "", "c#", "vb.net", "visual-studio-2008", "generics", ".net-3.5", "" ]
I have a method which should be delayed from running for a specified amount of time. Should I use ``` Thread thread = new Thread(() => { Thread.Sleep(millisecond); action(); }); thread.IsBackground = true; thread.Start(); ``` Or ``` Timer timer = new Timer(o => action(), null, millisecond, -1); ``` I had r...
One difference is that `System.Threading.Timer` dispatches the callback on a thread pool thread, rather than creating a new thread every time. If you need this to happen more than once during the life of your application, this will save the overhead of creating and destroying a bunch of threads (a process which is very...
use [`ThreadPool.RegisterWaitForSingleObject`](http://msdn.microsoft.com/en-us/library/system.threading.threadpool.registerwaitforsingleobject(v=vs.110).aspx) instead of timer: ``` //Wait 5 seconds then print out to console. //You can replace AutoResetEvent with a Semaphore or EventWaitHandle if you want to execute t...
Compare using Thread.Sleep and Timer for delayed execution
[ "", "c#", "multithreading", "timer", "sleep", "delayed-execution", "" ]
What is a good way to implement keyboard handling? In any language, where I write a keyboard-interactive program (such as a tetris game), I end up having some code that looks like this: ``` for event in pygame.event.get(): if event.type == KEYDOWN: if False: pass #make everything an elif e...
You could create a dictionary where the keys are the input and the value is a function that handles the keypress: ``` def handle_quit(): quit() def handle_left(): curpiece.shift(-1, 0) shadowpiece = curpiece.clone(); setupshadow(shadowpiece) def handle_right(): curpiece.shift(1, 0) shadowpiece = cu...
in addition to [superjoe30's answer](https://stackoverflow.com/questions/312263/effective-keyboard-input-handling#312270), you can use two levels of mapping (two dictionaries) * key => command string * command string => function I think this would make it easier to allow user-defined mappings. i.e. so users can map t...
Effective Keyboard Input Handling
[ "", "python", "user-interface", "keyboard", "user-input", "interactive", "" ]
I have rules set to move some email messages into different folders. I would like this to still show the envelope in the notification area but there is no option in the rules wizard to do this. It looks like I would either have to have the rule "run a script" or "perform a custom action" allowing either vba or c/c++ re...
You can also achieve it *not* by using a rule, *but* doing the rule-like action in code. For example: ``` Private Sub Application_NewMailEx(ByVal EntryIDCollection As String) Dim mai As Object Dim strEntryId For Each strEntryId In Split(EntryIDCollection, ",") Set mai = Application.Session.GetItemF...
Check out [MailAlert](http://www.bettasoft.net/), an Outlook plug-in that does exactly that. It still works in Outlook 2007 (although I've had some instabilities since I installed it again recently, which may or may not be related).
Display Outlook icon in notification area for messages, not in inbox
[ "", "c++", "vba", "scripting", "outlook", "" ]
In order to reference a member of a class in XML comments/documentation, you have to use the following tag: ``` <see cref="member"/> ``` It is better explained [here](http://msdn.microsoft.com/en-us/library/acd0tfbe.aspx). **How do you reference an *indexer*?** I mean, a member like this one: ``` internal object t...
``` <see cref="P:System.Collections.ArrayList.Item(System.Int32)" /> ```
``` <see cref="this[int]" /> ```
How to reference an indexer member of a class in C# comments
[ "", "c#", "documentation", "" ]
A combo box is an auto-complete text box that is also a dropdown (i.e., you can choose from a list if you prefer). "Best" means combination of: stable, look/feel, API / customizability, maturity.
I like the [Yahoo UI Autocomplete widget](http://developer.yahoo.com/yui/autocomplete/). It does not provide the dropdown natively, but a dropdown button can be added with [a few lines of code](http://tech.groups.yahoo.com/group/ydn-javascript/message/30178).
[ExtJS](http://extjs.com/) has a [very powerful combo box](http://www.extjs.com/deploy/dev/docs/?class=Ext.form.ComboBox) that provides [dropdown, auto-complete, and filtering of choices](http://extjs.com/deploy/dev/examples/form/combos.html). You can also enable [pagination](http://extjs.com/deploy/dev/examples/form/f...
Best javascript combo box?
[ "", "javascript", "user-interface", "combobox", "autocomplete", "" ]
I just came across this idiom in some open-source Python, and I choked on my drink. Rather than: ``` if isUp: return "Up" else: return "Down" ``` or even: ``` return "Up" if isUp else "Down" ``` the code read: ``` return isUp and "Up" or "Down" ``` I can see this is the same result, but is this a typical...
The "a and b or c" idiom was the canonical way to express the ternary arithmetic if in Python, before [PEP 308](http://www.python.org/dev/peps/pep-0308/) was written and implemented. This idiom fails the "b" answer is false itself; to support the general case, you could write ``` return (a and [b] or [c])[0] ``` An ...
You should read [Using the and-or trick](http://www.diveintopython.net/power_of_introspection/and_or.html) (section 4.6.1) of *Dive Into Python* by Mark Pilgrim. It turns out that the and-or trick has major pitfalls you should be aware of.
Is this idiom pythonic? (someBool and "True Result" or "False Result")
[ "", "coding-style", "python", "" ]
I have a factory that builds the objects with longest lifetime in my application. These have types, lets say, `ClientA` and `ClientB`, which depend on `Provider` (an abstract class with many possible implementations), so both clients have a reference to Provider as member. According to the command-line arguments, the ...
It's very simple with a shared ownership smart pointer: ``` App AppFactory::buildApp() { boost::shared_ptr<Provider> provider; if (some condition) { provider.reset(new ProviderX()); } else { provider.reset(new ProviderY()); } ClientA clientA(provider); ClientB cli...
make provider an instance variable of AppFactory. then make provider a smart pointer or delete it in AppFactory's dtor.
Trouble with Factory and dynamic allocation in C++
[ "", "c++", "design-patterns", "factory", "" ]
I want to make a table that simply has two integer columns to serve as a mapping table between two different data sets and I wish to put the correct constraints on it. I initially set the two columns as a compound primary key, but then realized that represents a many to many, only keeping duplicate many to many mappin...
Create a Primary Key on one column and another separate unique constraint or unique index, on the other. ``` CREATE TABLE [dbo].[test]( [x] [int] NOT NULL, [y] [int] NOT NULL, CONSTRAINT [PK_test] PRIMARY KEY CLUSTERED ( [x] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, ...
Creating another table is done to create a many to many relationship, so you probably shouldn't have created it (unless I am missing something). One to one mandatory is the same as having the two tables as a single table. The only acceptable one to one is optional, and you simply have to relate the two tables, no thir...
A Proper One-to-One Mapping Table
[ "", "sql", "mapping", "one-to-one", "" ]
How do I get the sequence number of the row just inserted?
insert ... returning. ``` declare s2 number; begin insert into seqtest2(x) values ('aaa') returning seq into s2; dbms_output.put_line(s2); end; ``` "seq" here refers to the name of the column whose value you want to store into variable s2. in python: ``` myseq=curs.var(cx_Oracle.NUMBER) curs.prepare("ins...
**Edit:** as Mark Harrison pointed out, this assumes that you have control over how the id of your inserted record is created. If you have full control and responsibility for it, this *should* work... --- Use a stored procedure to perform your insert and return the id. eg: for a table of names with ids: ``` PROCEDU...
Oracle: How do I get the sequence number of the row just inserted?
[ "", "sql", "oracle", "" ]
I do have to say I'm fairly inexperienced when it comes to C++, don't be too harsh on me. Recently stumbled unto the wonders of the win32 API and have chosen to practice using it (I'd rather not use MFC/wxWidgets/etc at this point, just for educational purposes). Well, my real question is: How do you properly code yo...
The biggest problem I faced back when I used the Win32 API (have since moved on to Linux and cross-platform solutions) were the callbacks. Especially the winproc one, AKA the message pump. I found [this](http://www.winterdom.com/dev/cpp/class.html), which should be a good hint. I did what that page suggests when I roll...
I program in C++ for a living. I like C++. That said, your life will be so much easier if you do your windows GUI in something .Net, e.g., C#. Win32 is very low-level and you will be building tons of stuff that you will get for free with the .Net libraries. Win32 is not a wonder, anymore. :-) If you want to learn C++...
C++ developing a GUI - classes?
[ "", "c++", "user-interface", "winapi", "class", "" ]
I just finished watching the Google clean code video on YouTube (see [link](http://googletesting.blogspot.com/), first article) about removing `if` statements from your code and using polymorphism instead. After watching the video I had a look at some code that I was writing before watching the video and noticed some ...
Just a cautionary note here after seeing some of these (technically correct) reponses, just getting rid of an If statement should not be your sole aim, the aim should be to make your code extensible, maintainable and simple, if that means getting rid of an if statement, great, but it shouldn't be an aim in an of itself...
You will actually be implementing something like the Strategy pattern. Start by defining a super class lets call it AbstractTableInfoCommand. This class may be abstract but must specify a method called runTableInfoCommand(). You can then define several sub classes that each implement runTableInfoCommand() method. Your...
How would you refactor this conditional to use polymorphism?
[ "", "c#", ".net", "polymorphism", "" ]
I need to do a number of network-related things in C++ that I would normally do with `ifconfig` in Linux, but I'd like to do it without parsing the output of a group of system calls. Which C or C++ libraries can I use to tell if a network adapter is up or down, read or change an adapter's IP address and netmask, and ch...
Basically you need to make a bunch of ioctl calls using a socket handle (SIOCGIFADDR, SIOCADDRT). You can find sample programs that use it in the Linux kernel source under Documentation/networking. Some other links that might be helpful: * [Network Interface operations on AIX](http://www.ibm.com/developerworks/aix/lib...
You can always look at ifconfig's source code to see how they did it in the first place: <http://archive.ubuntu.com/ubuntu/pool/main/n/net-tools/net-tools_1.60.orig.tar.gz>
How do you change an IP address in C++?
[ "", "c++", "linux", "networking", "" ]
Let's say I have some code like this ``` if(isset($_GET['foo'])) //do something if(isset($_GET['bar'])) //do something else ``` If a user is at example.com/?foo=abc and clicks on a link to set bar=xyz, I want to easily take them to example.com/?foo=abc&bar=xyz, rather than example.com/?bar=xyz. I can think of a...
Here's one way.... ``` //get passed params //(you might do some sanitizing at this point) $params=$_GET; //morph the params with new values $params['bar']='xyz'; //build new query string $query=''; $sep='?'; foreach($params as $name=>$value) { $query.=$sep.$name.'='.urlencode($value); $sep='&'; } ```
If you are updating the query string you need ot make sure you don't do something like ``` $qs="a=1&b=2"; $href="$qs&b=4"; $href contains "a=1&b=2&b=4" ``` What you really want to do is overwrite the current key if you need to . You can use a function like this. (disclaimer: Off the top of my head, maybe slightly bug...
Persistent HTTP GET variables in PHP
[ "", "php", "http", "get", "methods", "" ]
We have a stored procedure that runs nightly that in turn kicks off a number of other procedures. Some of those procedures could logically be run in parallel with some of the others. * How can I indicate to SQL Server whether a procedure should be run in parallel or serial — ie: kicked off of asynchronously or blockin...
I had to research this recently, so found this old question that was begging for a more complete answer. Just to be totally explicit: **TSQL does *not*** (by itself) **have the ability to launch other TSQL operations asynchronously**. That doesn't mean you don't still have a lot of options (some of them mentioned in o...
Create a couple of SQL Server agent jobs where each one runs a particular proc. Then from within your master proc kick off the jobs. The only way of waiting that I can think of is if you have a status table that each proc updates when it's finished. Then yet another job could poll that table for total completion and...
Start stored procedures sequentially or in parallel
[ "", "sql", "sql-server", "t-sql", "sql-server-2000", "parallel-processing", "" ]
I am looking to refactor a c# method into a c function in an attempt to gain some speed, and then call the c dll in c# to allow my program to use the functionality. Currently the c# method takes a list of integers and returns a list of lists of integers. The method calculated the power set of the integers so an input ...
This returns one set of a powerset at a time. It is based on python code [here](http://groups.google.com/group/comp.lang.python/browse_thread/thread/d9211cd6c65e1d3a/). It works for powersets of over 32 elements. If you need fewer than 32, you can change long to int. It is pretty fast -- faster than my previous algorit...
Also, be sure that moving to C/C++ is really what you need to do for speed to begin with. Instrument the original C# method (standalone, executed via unit tests), instrument the new C/C++ method (again, standalone via unit tests) and see what the real world difference is. The reason I bring this up is that I fear it m...
C data structure to mimic C#'s List<List<int>>?
[ "", "c#", "c", "data-structures", "refactoring", "" ]
I have a macro that looks like this: ``` #define coutError if (VERBOSITY_SETTING >= VERBOSITY_ERROR) ods() ``` where ods() is a class that behaves similarly to cout, and VERBOSITY\_SETTING is a global variable. There are a few of these for different verbosity settings, and it allows the code to look something l...
You could try - temporarily - modifying the macro to something like this, and see what doesn't compile... ``` #define coutError {} if (VERBOSITY_SETTING >= VERBOSITY_ERROR) ods() ``` The 'else' clauses should now give errors.
Don't bother trying to find all of the locations in your code where a logic error is occurring -- fix the problem at its source! Change the macro so that there's no possibility of error: ``` #define coutError if(VERBOSITY_SETTING < VERBOSITY_ERROR); else ods() ``` Note that what I've done here is inverted the test, a...
Finding statement pattern in c++ file
[ "", "c++", "parsing", "macros", "" ]
OK - I have an interesting one here. I'm working on a tetris clone (basically to "level-up" my skills). I was trying to refactor my code to get it abstracted the way I wanted it. While it was working just fine before, now I get a segmentation fault before any images can be blitted. I've tried debugging it to no avail. ...
Look at line 15 to 18 of Surface.cpp: ``` surface = SDL_DisplayFormatAlpha( tempSurface ); surface = tempSurface; } SDL_FreeSurface( tempSurface ); ``` I assume it segfaults because when you use this surface later, you are actually operating on tempSurface because of this line: ``` surface = tempSurface; ```...
I don't have SDL installed on my machine, but after looking through the code. I noticed this in the Output.cpp file: ``` display = new Surface(); ``` You do nothing. The constructor for this is empty. (surface is not initialized). Then in Output::initalize() you do: ``` display->surface = SDL_SetVideoMode( 800, 60...
Segmentation fault using SDL with C++, trying to Blit images
[ "", "c++", "sdl", "" ]
I'm refactoring a 500-lines of C++ code in main() for solving a differential equation. I'd like to encapsulate the big ideas of our solver into smaller functions (i.e. "SolvePotential(...)" instead of 50 lines of numerics code). Should I code this sequentially with a bunch of functions taking **very long** parameters ...
Neither. "Move all my code from one single function to one single class" is not OOP. One of the fundamental rules of OOP is that a class should have *one single area of responsibility*. This is not a single responsibility, it is around 15: ``` SolverPotential::solve(){ SolvePotential::interpolate() SolverPotential::co...
Write it sequentially and then refactor if there's something you think you can reuse or would make it clearer. Also, a SolvePotential class doesn't make a lot of sense since a class should be an Object with the method SolvePotential.
Object-oriented or sequential?
[ "", "c++", "oop", "" ]
I've created a new J2SE project in NetBeans, and I can run it from the IDE, but when I try to run it using Ant on the command line, I get the following problem: <snip> ``` run: [java] Exception in thread "main" java.lang.NoClassDefFoundError: IndexBuilder [java] Java Result: 1 ``` <snip> Based on the snip...
When you are running it from the command line, you are actually invoking [Apache Ant](http://ant.apache.org). The reason you are getting the ClassNotFound Exception is because ${javac.classpath} and all the other properties are not being properly populated. That is why your code runs from within the Netbeans context. N...
The error you're getting means that one of the following is true: * The class `IndexBuilder` cannot be found on the classpath * A necessary (for class loading) dependency of `IndexBuilder` cannot be found on the classpath That is, when loading the class, it's possible (even likely) that the class **can** be found but...
NoClassDefFoundError on command-line with new NetBeans project
[ "", "java", "netbeans", "ant", "" ]
I'm trying to build my first generic list and have run into some problems. I understand the declaration looks like " `List<T>` ", and I have `using System.Collections.Generic;` at the top of my page. However, Visual Studio doesn't recognize the `T` variable. What am I missing?
`List<T>` means `List<WhateverTypeYouWantItToBeAListOf>`. So for example: If I have an Employee Class, and I wanted a collection of Employees, I could say: ``` List<Employee> employeeList = new List<Employee>(); ``` I could then add `Employee` Objects to that list, and have it be Type-safe and extend to however many...
You need to substitute `T` for another Type such as `int`, `string` or a class of your creation: ``` List<int> values = new List<int>(); values.Add(1); values.Add(2); int secondNumber = values[1]; // Yay! No casting or boxing required! ```
What are Generic Collections in C#?
[ "", "c#", ".net", "generics", "" ]
I want to build a nice API (C#) to make it easier for people to consume, I think I've seen this before and want to know how to do this: ``` MyNamespace.Cars car = null; if(someTestCondition) car = new Honda(); else car = new Toyota(); car.Drive(40); ``` Is this possible? If so, what needs to be do...
``` Interface Car { void Drive(int miles); } class Honda : Car { ... } class Toyota : Car { ... } ```
You could do this a couple of different ways. You could declare an abstract base class or you could have an interface that your object implement. I believe the "C#" preferred method would be to have an interface. Something like: ``` public interface ICar { public Color Color { get; set; } void Drive(int speed...
How do I implement this type of OOP structure?
[ "", "c#", ".net", "oop", "" ]