Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Say I have the following code snippet in c# ``` static const bool DO_PERFORMANCE_CODE = false; if (DO_PERFORMANCE_CODE) { // performance monitoring code goes here } ``` Will that code get removed by the compiler? This is the functionality I'd like. Basically I want to mimic the conditional compilation stuff in C#...
When you build in "debug" the preprocessor variable DEBUG is defined. So, you can do this: ``` public void MyFunc() { //do release stuff #if DEBUG //do performance testing #endif //finish release stuff } ``` and it will be ignored by the compiler when you switch to Release mode. Alternatively, you can define your ow...
Defining your own symbols is probably cleaner, but I was curious as to what the compiler would do, so I did some experimenting (using VS 2008 in release mode). With this: ``` class Program { static void Main(string[] args) { bool foo = false; if (foo) { Console.WriteLine("...
Will conditionals that are always false be removed by compiler in C#
[ "", "c#", ".net", "performance", "" ]
Under what circumstances is an enum more appropriate than, for example, a Collection that guarantees unique elements (an implementer of java.util.Set, I guess...)? (This is kind of a follow up from my previous [question](https://stackoverflow.com/questions/478403/can-i-add-and-remove-elements-of-enumeration-at-runtime...
Basically when it's a well-defined, fixed set of values which are known at compile-time. You can use an enum as a set very easily (with [EnumSet](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/EnumSet.html)) and it allows you to define behaviour, reference the elements by name, switch on them etc.
When the elements are known up front and won't change, an enum is appropriate. If the elements can change during runtime, use a Set.
When to use Enum or Collection in Java
[ "", "java", "enums", "set", "" ]
I have an app which consists of several different assemblies, one of which holds the various interfaces which the classes obey, and by which the classes communicate across assembly boundaries. There are several classes firing events, and several which are interested in these events. My question is as follows: is it go...
You could put the event itself in an interface, so that A didn't need to know about C directly, but only that it has the relevant event. However, perhaps you mean that the instance of A doesn't have sight of an instance of C... I would try to steer clear of a centralised event system. It's likely to make testing harde...
What you could try is using the event brokering of either [NInject](http://ninject.org/ "NInject Homepage") or the [Unity Application Block](http://www.codeplex.com/unity "Unity Homepage"). This allows you to, for example: ``` [Publish("foo://happened")] public event EventHandler<FooArgs> FooHappened; [Subscribe("fo...
C# Best practice: Centralised event controller or not
[ "", "c#", "events", "architecture", "" ]
Given a variable `foo` of type `FooClass*` and a member variable in that class named `bar`, is the distance between `foo` and `&(foo->bar)` the same in any situation with some constraints: 1. `FooClass` is a non-POD type. 2. We know that `foo` will always point to an instance of `FooClass`, and not some subtype of it....
After you have compiled your program, **Yes\***. The offset will remain constant. There is one very important restriction, however: **foo must be pointing specifically to a FooClass object**. Not a class derived from FooClass, or anything else for that matter. The reason that C++ makes the POD distinction regarding ...
I'm no expert but i gonna try answering you anyway :) 1. FooClass is a non-POD type. This mean it could have more than one sections of `private`, `public` or `protected`. Within such a section, the order is that of the definition of the members, but across those sections, order is arbitrary and unspecified. 2. foo wil...
C++ experts: is the offset of a member variable to its class constant under these conditions?
[ "", "c++", "" ]
OK, I'm designing a site and thought I'd stick some jQuery in as I really need so js experience. Page with my problem is here: <http://new.focalpix.co.uk/moreinfo.php> JS in question is: ``` $(document).ready(function(){ $(".answer").css("display","none"); $("#maincontent a.animate").click(function() { ...
First, I'd suggest the following structure for your faq's: ``` <div id="faq"> <div class="qa" id="faq_greenandflies"> <span class="q">What is <a href="#faq_greenandflies">green and flies</a></span> <div class="a"> Super Pickle! </div> </div> <div class="qa" id="faq_redandbadforteeth"> <span...
You should be using the [.slideToggle()](http://docs.jquery.com/Effects/slideToggle) effect. ``` $(document).ready(function() { $(".answer").css("display","none"); $("#maincontent a.animate").click(function() { $("#maincontent .answer").slideToggle('slow'); }); }); ```
Getting my head around jQuery
[ "", "javascript", "jquery", "" ]
I am trying to write a JTextPane which supports some sort of coloring: as the user is typing the text, I am running some code that colors the text according to a certain algorithm. This works well. The problem is that the coloring operations is registered with the undo manager (a DefaultDocumentEvent with EventType.CH...
You could intercept the CHANGE edits and wrap each one in another UndoableEdit whose `isSignificant()` method returns `false`, before adding it to the UndoManager. Then each Undo command will undo the most recent INSERT or REMOVE edit, plus every CHANGE edit that occurred since then. Ultimately, I think you'll find th...
How are you trying to prevent the CHANGE events from reaching the undo manager? Can you not send the UndoManager a lastEdit().die() call immediately after the CHANGE is queued?
Hide certain actions from Swing's undo manager
[ "", "java", "swing", "undo", "" ]
I am programming with normal pointers, but I have heard about libraries like Boost that implement smart pointers. I have also seen that in Ogre3D rendering engine there is a deep use of shared pointers. What exactly is the difference between the three, and should I stick on using just a type of them?
Sydius outlined the types fairly well: * **Normal pointers** are just that - they point to some thing in memory somewhere. Who owns it? Only the comments will let you know. Who frees it? Hopefully the owner at some point. * **Smart pointers** are a blanket term that cover many types; I'll assume you meant scoped point...
the term "smart pointer" *includes* shared pointers, auto pointers, locking pointers and others. you meant to say auto pointer (more ambiguously known as "owning pointer"), not smart pointer. Dumb pointers (T\*) are never the best solution. They make you do explicit memory management, which is verbose, error prone, an...
Pointers, smart pointers or shared pointers?
[ "", "c++", "pointers", "" ]
I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python. I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like `"_-.() "`. What's the most elegant solution? The ...
You can look at the [Django framework](http://www.djangoproject.com) (but take their licence into account!) for how they create a "slug" from arbitrary text. A slug is URL- and filename- friendly. The Django text utils define a function, [`slugify()`](https://docs.djangoproject.com/en/4.0/ref/utils/#django.utils.text....
You can use list comprehension together with the string methods. ``` >>> s 'foo-bar#baz?qux@127/\\9]' >>> "".join(x for x in s if x.isalnum()) 'foobarbazqux1279' ```
Turn a string into a valid filename?
[ "", "python", "filenames", "slug", "sanitize", "" ]
I encountered a strange problem today. Whenever i put a breakpoint in one of my js files, the breakpoint is not hit. I use Visual Studio 2005 in combination with TFS. In ie the disable script options are both disabled. The only thing that changed is that I installed Visual Basic 6 for an old project, but I don't see ...
A collegue found the issue: the Just in time debugger was only set to handle Managed and native code, and no scripting. I just had to re-set it in the visual studio options pane.
In order for Javascript debugging to work the Visual Studio needs to be attached as a debugger to the IE process and it needs to be able to resolve the phyiscal path of the javascript file with the URL of the same script loaded in IE. Have you checked that when you start debugging in VS that it actually attaches to th...
JavaScript debugging issue with vs2005
[ "", "javascript", "debugging", "visual-studio-2005", "" ]
Suppose I have the following code: ``` class siteMS { ... function __CONSTRUCT() { require 'config.php'; $this->config = new siteMSConfig; ... } ... } ``` From inside the siteMSConfig class can I determine weather or not it is being called from inside the siteMS class?
Yes, but there's no "pretty" way to do it - you'll end up looking through a [backtrace](http://www.php.net/debug_backtrace) or something similar. It would be better to pass an (optional?) parameter to the `siteMSConfig` constructor like this: ``` class siteMSConfig { public function __construct($inSiteMS = false)...
Technically yes, you could use [debug\_backtrace](https://www.php.net/debug_backtrace) to figure out who your caller was. Writing a class which alters its behaviour based purely on where it called from is asking for a world of pain later on though. Why not parameterise the different behaviour, or make a subclass?
Is class being called from another class
[ "", "php", "oop", "" ]
Ok, I have an application written in C#. We have data in an SQL Server. Among that data we have user accounts, which will give access to the application. I've read around, and I know that you should salt and hash and possibly hash a bunch of times, etc. But, where do I do what? What do I send to and from the SQL Serve...
I agree with Joel Coehoorn completely, the best choice is to trust someone else's tried and true implementation. If, however, you're determined to roll your own security implementation, then my advice is the following: 1. Store the hash and salt in the database. 2. Generate the hash and the salt in your own code. That...
For C# + SQL Server, you can just use the MembershipProvider model, which will take care of all this for you. And IMO, the most important part of getting all this stuff right is *not doing it yourself*. Rather, rely on the mechanism provided by your platform. It's just so easy to get it wrong in a subtle way that *app...
C# and SQL Server: Passwords. Where to do what?
[ "", "c#", "sql-server", "encryption", "passwords", "hash", "" ]
Is there a way to use yield blocks to implement an `IEnumerator<T>` which can go backward (`MoveLast()`) as well as forward?
Not directly from the iterator block, no. However, the caller can always buffer the results, for example into a `List<T>`, or just call `Reverse()` - but this doesn't always apply.
No, the state machine generated by the C# compiler is strictly forward. It doesn't even make sense to go backwards in many cases. Imagine an iterator reading from a network stream - to go backwards, it would have to remember everything that it had ever read, because it couldn't rewind time and ask the network for the ...
Implementing a bidirectional enumerator in C#
[ "", "c#", "iterator", "ienumerator", "" ]
I have to do some work work with integers, but I am interested in treat them as binary data, in a way that for example I can take the 4 most significant bits of an 32 bit value. What I am trying to do is, I have several 32 bit value I want to take for example, in the first one 4 bits, the second one 6 bits and the last...
It seems that you don't need a library for that. Just bit shifting, logical and, or and xor should be sufficient for what you want to do. EDIT: Just to give an example. Suppose `a` is a 32-bit `int`, and you want to take the first 4 bit and store it in the lowest bit positions in another integer `b`, you could do this...
I always prefer to use bit-fields and let the compiler figure out all the bit shifts. It also makes it easier if you ever want to make a change. However, you have to be careful with signed integers and understand how the compiler treats them with respect to bitfields. Nonetheless... ``` union _type { struct {...
How to work with the data in Binary in C/C++
[ "", "c++", "c", "binary", "" ]
So, I have this situation where I need to see if an object is in my stl map. If it isn't, I am going to add it. ``` char symbolName[] = { 'H', 'e', 'l', 'l', 'o', '\0' }; map<string,TheObject> theMap; if (theMap.find(symbolName)==theMap.end()) { TheObject theObject(symbolName); theMap.insert(pa...
It can crash because of many reasons. Without knowing the definition of at least `TheObject`'s constructors, i think we are largely left to guess at the problem. So far, your code looks fine, but it can be simplified: ``` char symbolName[] = "Hello"; map<string,TheObject> theMap; theMap.insert(make_pair(symbolName, Th...
Why not just do it this way? ``` char symbolName[] = "hello"; theMap.insert(pair<string, TheObject>(symbolName, TheObject(symbolName))); ``` If your map is a `map<string, TheObject>` then you WILL get a core dump if you try to search for NULL: ``` // This will core dump: char *symbolName = NULL; // Oops! theMap.find...
Why does STL map core dump on find?
[ "", "c++", "gcc", "dictionary", "" ]
What is the difference between `compare()` and `compareTo()` methods in Java? Do those methods give the same answer?
From [JavaNotes](http://web.archive.org/web/20090126135350/http://leepoint.net/notes-java/data/expressions/22compareobjects.html): * `a.compareTo(b)`: **Comparable interface :** Compares values and returns an int which tells if the values compare less than, equal, or greater than. If your class objects have a ...
**`compareTo()`** is from the [**`Comparable`**](http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html) interface. **`compare()`** is from the [**`Comparator`**](http://java.sun.com/javase/6/docs/api/java/util/Comparator.html) interface. Both methods do the same thing, but each interface is used in a slight...
What is the difference between compare() and compareTo()?
[ "", "java", "compare", "compareto", "" ]
I have a report that I created with Crystal Reports 2008. This report uses upwards of 40 parameters to control the layout of the report. All the parameters are boolean and are defaulted to False in the saved report. The report is saved with the save data with the report option **unchecked** as I want to read the result...
When you have Save Data with Report selected the report does not try to hit the database. It's a static report with saved data. That's why this report doesn't error compared to when you try to pass parameters without saved data. The error suggests that one or more of the parameter values you're passing at runtime does...
This answer isn't mine, it is by a gentleman on the Crystal Reports forums. That posting can be found on the [SAP Forum](https://www.sdn.sap.com/irj/scn/thread?forumID=313&threadID=1211544) The answer there was: > When you have Save Data with Report > selected the report does not try to > hit the database. It's a stat...
ParameterFieldCurrentValueException when data not saved with a report and exporting to PDF
[ "", "c#", "crystal-reports", "parameters", "" ]
I'm developing a website in PHP and I have large JS files that I want to compress. So, I added this in my .htaccess file: ``` <FilesMatch "\.(js|css|html|htm|php|xml)$"> SetOutputFilter DEFLATE </FilesMatch> ``` It works great on my local wamp server install but once I move the files on my shared server, the DEFL...
Are you sure mod\_deflate is loaded and available? Apache doesn’t throw an error if you set it as filter although it is not loaded. You can use the [`apache_get_modules` function](http://docs.php.net/apache_get_modules) to see what modules are loaded.
Hmm, I guess you're right..I've checked my loaded modules with apache\_get\_modules() and mod\_deflate wasn't there. I also checked on my localhost and mod\_deflate was there. I've sent a ticket to support. I hope I'll get this done. Thank you for your help.
htaccess mod_deflate does not work on shared server
[ "", "php", "apache", ".htaccess", "gzip", "mod-deflate", "" ]
How do I access a Control in the `LayoutTemplate` of a `ListView` control? I need to get to `litControlTitle` and set its `Text` attribute. ``` <asp:ListView ID="lv" runat="server"> <LayoutTemplate> <asp:Literal ID="litControlTitle" runat="server" /> <asp:PlaceHolder ID="itemPlaceHolder" runat="server" /> ...
Try this: ``` ((Literal)lv.FindControl("litControlTitle")).Text = "Your text"; ```
The complete solution: ``` <asp:ListView ID="lv" OnLayoutCreated="OnLayoutCreated" runat="server"> <LayoutTemplate> <asp:Literal ID="lt_Title" runat="server" /> <asp:PlaceHolder ID="itemPlaceHolder" runat="server" /> </LayoutTemplate> <ItemTemplate> </ItemTemplate> </asp:ListView> ``` In codebehind: ...
Access a control inside a the LayoutTemplate of a ListView
[ "", "c#", "asp.net", "listview", "asp.net-3.5", "" ]
I have a List of a "complex" type - an object with a few string properties. The List itself is a property of another object and contains objects of a variety of types, as shown in this abbreviated class structure: ``` Customer { public List<Characteristic> Characteristics; . . . } Characteristic { publ...
Here's a generator implementation ``` public static IEnumerable<string> GetInterests(Customer customer) { foreach (Characteristic c in customer.Characteristics) { if (c.CharacteristicType == "Interest") yield return c.CharacteristicValue; } } ``` sadly 3.5 extension methods and lambda ...
I would do some of the work manualy. By doing a FindAll first, and then a Convert, you're looping through your collection twice. It doesn't seem neccessary. If all you want at the end of the day, is a List of CharacteristicValue then just loop through your original collection, and add the CharacteristicValue to a List ...
Method chaining generic list extensions
[ "", "c#", "generics", ".net-2.0", "findall", "convertall", "" ]
I'm looking for something like `break` for loops. Here's some example code (using Symfony's lime) where `stop()` would not let the class continue and `I_DONT_WANT_THIS_TO_RUN()` would not be executed. ``` $browser->isStatusCode(200) ->isRequestParameter('module', 'home') ->isRequestParameter('action', 'index') ...
Just return another class which will return $this for every method called. Example: ``` class NoMethods { public function __call($name, $args) { echo __METHOD__ . " called $name with " . count($args) . " arguments.\n"; return $this; } } class Browser { public function runThis() { ...
You could use [PHP exceptions](http://php.net/exceptions): ``` // This function would of course be declared in the class function stop() { throw new Exception('Stopped.'); } try { $browser->isStatusCode(200) ->isRequestParameter('module', 'home') ->isRequestParameter('action', 'index') ->cli...
How do you stop a PHP class from executing?
[ "", "php", "exception", "class", "" ]
As part of a numerical library test I need to choose base 10 decimal numbers that can be represented exactly in base 2. How do you detect in C++ if a base 10 decimal number can be represented exactly in base 2? My first guess is as follows: ``` bool canBeRepresentedInBase2(const double &pNumberInBase10) { //check...
I think what you are looking for is a number which has a fractional portion which is the sum of a sequence of negative powers of 2 (aka: 1 over a power of 2). I believe this should always be able to be represented exactly in IEEE floats/doubles. For example: 0.375 = (1/4 + 1/8) which should have an exact representati...
If you're checking to see if it's binary, it will always return true. If your method takes a `double` as the parameter, the number is already represented in binary (`double` is a binary type, usually 64 bits). Looking at your code, I think you're actually trying to see if it can be represented exactly as an integer, in...
How to detect if a base 10 decimal can be represented exactly in base 2
[ "", "c++", "" ]
What's the best way to debug Javascript on Internet Explorer?
Depends on what tools you have available to you. If you have a copy of Visual Studio, I'd use the [Visual Studio debugger](http://www.berniecode.com/blog/2007/03/08/how-to-debug-javascript-with-visual-web-developer-express/). It works pretty well. You'll need to try following the instructions in that link if you don't...
Using Microsoft Script Editor is an option too: See my answer [here.](https://stackoverflow.com/questions/8398/how-do-i-debug-javascript-in-visual-studio-2005#16855)
What's the best way to debug Javascript on IE?
[ "", "javascript", "internet-explorer", "debugging", "" ]
I need to generate a list of sequential numbers. I know Ruby you can do 1..10 or PHP you can do range(1, 10). Anything like that in .Net already, or do I have to write it? Thanks.
In C# (with .NET 3.0 or higher) this should do the job: ``` IEnumerable<int> myRange = Enumerable.Range(1, 10); ```
Would this work for you? ``` public List<int> Range(int start, int finish) { List<int> retList = new List<int>(); for(int i = start; i <= finish; i++) { retList.Add(i); } return retList; } ```
PHP range() function in .NET?
[ "", ".net", "php", "range", "" ]
Have you used the [OpenAccess ORM from Telerik](http://www.telerik.com/products/orm.aspx)? How does it compare to NHibernate? When should I consider using it over NHibernate?
I'm wondering the same thing myself. On one hand, there's NH with its free, open-source self, but with limited support options. On the other, a fairly new addition to a well-known tool provider's box, OA. OA costs money, but you get support. NH is free, but support has been known at least in my brief experience to be ...
I've not used it but one benefit obvious to me, is OpenAccess is supported by Telerik, where as nHibernate is supported by the community. Depending on your company this can be a deciding factor if your ready to embrace open source solutions with no guarentee of support. # Edit For the record I am a big supporter of n...
Compare and Contrast NHibernate and OpenAccess from Telerik
[ "", "c#", ".net", "nhibernate", "orm", "openaccess", "" ]
How do I write a query that outputs the row number as a column? This is DB2 SQL on an iSeries. eg if I have table Beatles: ``` John Paul George Ringo ``` and I want to write a statement, without writing a procedure or view if possible, that gives me ``` 1 John 2 Paul 3 George 4 Ringo ```
``` SELECT ROW_NUMBER() OVER (ORDER BY beatle_name ASC) AS ROWID, * FROM beatles ```
Check out the row\_number() function; you should be able to do this in DB2 via: ``` SELECT row_number(), first_name FROM beatles ``` I'm almost certain this is not part of the SQL standard though, so it is not likely to be portable should that ever be an issue.
How do I write a query that outputs the row number as a column?
[ "", "sql", "db2", "" ]
How can I garble JavaScript code before sending it to client-side? I don't want to expose functionalities. The code is already compressed using `jsmin`.
You could try some online obfuscator like this: <http://www.javascriptobfuscator.com/Default.aspx>
You need an obfuscator, [see this](http://www.javascriptobfuscator.com/Default.aspx) for an example. Anyone [determined](http://isc.sans.org/diary.html?storyid=1519) enough can always reverse it though, and tools [like this](https://addons.mozilla.org/en-US/firefox/addon/10345) can help.
Garble JavaScript code before sending to client-side
[ "", "javascript", "compression", "code-generation", "" ]
So, I have a decimalfield that can be 3 different values. In my view, I pass in a dictionary of values that contains the appropriate decimal values as keys. ``` {% for item in booklist %} {% for key, value in numvec.items %} {{item.number}} {% ifequals item.number {{key}} %} {{v...
According to [this](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#ifequal), it seems you can only compare strings. I'd make my own [template tag](http://www.mechanicalgirl.com/view/custom-template-tags-in-django/) if I were you.
It is not a bug and **it is possible** to achieve what you're trying to do. However, first of all few remarks about your code: * There is no "ifequals/endifequals" operator. You either use ["ifequal/endifequal"](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#ifequal) or ["if/endif"](http://docs.djangopr...
Django template ifequal comparison of decimals
[ "", "python", "django", "django-templates", "" ]
I'm working on a project and I'm just starting to do all the work necessary to globalize the application. One thing that comes up quite often is whether to globalize the exception messages, but ensuring that string.Format uses CultureInfo.CurrentCulture instead of CultureInfo.InvariantCulture. Additionally this would m...
Exception messages should rarely be displayed directly to the user. You need to think of the consumer for each string. Obviously pieces of text in the user interface need internationalizing, but if an exception message is *only* going to be seen by support (or is going to be visible to the user and then emailed to supp...
typically, I don't. Globalize strings that may be seen by a user, and you don't let your exception messages percolate up to the UI, right? Right? :)
Should Exception Messages be Globalized
[ "", "c#", "exception", "globalization", "" ]
I have an array in the form of '`int[][]`' that represents the co-ordinates of a small grid. Each co-ordinate has been assigned its own value. eg `array[0][4] = 28`...... I have two questions. Firstly, how do I iterate through all the stored values. Secondly, I want to be able to input a value and have its specific co...
You can iterate with either for loops or enhanced for loops: ``` for (int row=0; row < grid.length; row++) { for (int col=0; col < grid[row].length; col++) { int value = grid[row][col]; // Do stuff } } ``` or ``` // Note the different use of "row" as a variable name! This // is the *whole...
to iterate over the values use loops: ``` int[][] matrix //... for(int row[] : matrix) for(int cell : row){ //do something with cell } ``` to access the coordinates based on the value you would need some sort of double hashmap (look a at java.util.HashMap) but i am aware of nothing that does so d...
Java int[][] array - iterating and finding value
[ "", "java", "arrays", "iteration", "" ]
Is there a pattern where in WPF, I can build a simple UI form from an XML like definition file pulled from a database? It would allow the user to enter data into this form, and submit it back. The data would be sent back in an XML structure that would closely/exactly mimic the UI definition. The definition should inc...
Model View Presenter seems to suit WPF quite well, if you've not heard of it before check out the [Supervisor Controller](http://martinfowler.com/eaaDev/SupervisingPresenter.html) pattern, which is a subset of MVP (the author has renamed it to [Supervisor Controller](http://martinfowler.com/eaaDev/SupervisingPresenter....
Well if you wanted to roll something yourself, you can load and render dynamic XAML pretty easily. Rather than have users create XAML directly you could have a subset of it "mapped" to an XML format of your choosing that you XSL into valid XAML: ``` XmlReader tXml = XmlReader.Create(myXamlString); UIElement MyElement ...
Is there a MVC pattern for C# in WPF
[ "", "c#", "xml", "user-interface", "design-patterns", "project-planning", "" ]
Why would SDL\_Mixer not play music for certain mp3s? I am utilizing SDL\_Mixer for music playback in an application I am creating. On certain songs (entire albums actually), the music will simply not play without returning any errors. The music data loads successfully using Mix\_LoadMUS and when executing Mix\_PlayMu...
This actually wound up being a sound issue with that particular computer. Upon trying the same tests on another machine, the sound worked flawlessly. Just a quick note in case someone else encounters this issue.
Different implementations of the MP3 algorithm tolerate different levels of conformance to the format. Most of the music players are pretty tolerant, because most users would rather hear something choppy than nothing at all, but the playback libraries that are common tolerate much less. I'd recommend opening the offen...
Why would SDL_Mixer not play music for certain mp3s?
[ "", "c++", "audio", "sdl", "sdl-mixer", "" ]
Got a bit of a mind freeze at the moment. I have the following syntax:- ``` string[] repname = Thread.CurrentPrincipal.Identity.ToString().Split('\'); ``` and I get an error on the split character. Can anyone advise on how I can do the split using the \ character as the delimiter? Cheers
Use ``` Split('\\') ``` "\" is an [escape character](http://en.wikipedia.org/wiki/Escape_character).
\ is an excape character in C#. You need to do one of the following: ``` Split('\\'); ``` or ``` Split(@'\'); ```
string split based on char \
[ "", "c#", "c#-3.0", "c#-2.0", "" ]
Here is the scenario: I have two asp pages. a.aspx is layout and b.aspx is content. I want to display the contents of b.aspx inside a `<div>` on a.aspx. I know with PHP you can do it like so: ``` //a.php <html> <head> <title>test</title> </head> <body> <?PHP include "b.php"; ?> <...
Probably `Server.Execute` will help. ``` //a.aspx <html> <head> <title>test</title> </head> <body> <% Server.Execute("b.aspx"); %> </body> </html> //b.aspx Content String //result <html> <head> <title>test</title> </head> <body> Content String </body> </html> ``` B...
This scenario is handled by masterpages and or composing the page out of (user)controls in ASP.NET. As described at for instance [here](http://www.asp.net/Learn/master-pages/).
Is it possible to write the contents of b.aspx on a.aspx?
[ "", "php", "asp.net", "vb.net", "" ]
I am using this php code: ``` exec("unrar e file.rar",$ret,$code); ``` and getting an error code of illegal command ie 127 ... but when I am using this command through ssh its working ... because unrar is installed on the server ... so can anyone guess why exec is not doing the right stuff?
Try using the direct path of the application (/usr/bin/unrar of whatever), it sounds like php can't find the application.
If you have chrooted apache and php, you will also want to put /bin/sh into the chrooted environment. Otherwise, the exec() or passthru() will not function properly, and will produce error code 127, file not found.
illegal command error code 127 in php exec function
[ "", "php", "exec", "" ]
I created a utility function to return the expected single item from an generator expression ``` print one(name for name in ('bob','fred') if name=='bob') ``` Is this a good way to go about it? ``` def one(g): try: val = g.next() try: g.next() except StopIteration: ...
A simpler solution is to use tuple unpacking. This will already do everything you want, including checking that it contains exactly one item. Single item: ``` >>> name, = (name for name in ('bob','fred') if name=='bob') >>> name 'bob' ``` Too many items: ``` >>> name, = (name for name in ('bob','bob') if name=='...
For those using or interested in a third-party library, [`more_itertools`](https://github.com/erikrose/more-itertools) implements such a tool with native error handling: ``` > pip install more_itertools ``` **Code** ``` import more_itertools as mit mit.one(name for name in ("bob", "fred") if name == "bob") # 'bob'...
select single item from a collection : Python
[ "", "python", "iterator", "generator", "" ]
I'm using this code to reset the identity on a table: ``` DBCC CHECKIDENT('TableName', RESEED, 0) ``` This works fine most of the time, with the first insert I do inserting 1 into the Id column. However, if I drop the DB and recreate it (using scripts I've written) and then call DBCC CHECKIDENT, the first item insert...
As you pointed out in your question it is a [documented behavior](http://msdn.microsoft.com/en-us/library/aa258817(SQL.80).aspx). I still find it strange though. I use to repopulate the test database and even though I do not rely on the values of identity fields it was a bit of annoying to have different values when po...
You are right in what you write in the edit of your question. After running `DBCC CHECKIDENT('TableName', RESEED, 0)`: - Newly created tables will start with identity 0 - Existing tables will continue with identity 1 The solution is in the script below, it's sort of a poor-mans-truncate :) ``` -- Remove all reco...
DBCC CHECKIDENT Sets Identity to 0
[ "", "sql", "sql-server", "" ]
What is meant by "object serialization"? Can you please explain it with some examples?
Serialization is the conversion of an object to a series of bytes, so that the object can be easily saved to persistent storage or streamed across a communication link. The byte stream can then be deserialized - converted into a replica of the original object.
You can think of serialization as the process of converting an object instance into a sequence of bytes (which may be binary or not depending on the implementation). It is very useful when you want to transmit one object data across the network, for instance from one JVM to another. In Java, the serialization mechani...
What is object serialization?
[ "", "java", "serialization", "object-serialization", "" ]
I am wondering how I can define an object in C whose reference will be null? ``` // definition of foo ... void * bar = &foo; // bar must be null ``` There is some ways I could find to do it, but none fit my needs. ``` __attribute__((weak)) extern int foo; //not working with cygwin/gcc 3.4 __attribute__((at(0))) int...
You are trying to create a symbol with an address of zero. Your last example is probably the only way of doing this within the C compiler / language. The approach that is most likely to solve your problem is to look at the input file to the linker program. Most linkers allow you to define the label foo as zero. In a ...
I've got to be missing something, but what doesn't work about `void * bar = NULL`?
How to define an object whose address is null?
[ "", "c++", "c", "linker", "weak-references", "" ]
Consider these 3 table structures. Which will perform these queries the best. ## Structure 1 - TagID as int with a join table ``` Article ------- ArticleID int Article_Tag ------------ ArticleTagID int ArticleID int TagID int Tag --- TagID int TagText varchar(50) ``` ## Structure 2 - Tags only in Join table as str...
It depends if you ever want to be able to change the tag-text globally. You could, of course, issue a wide `UPDATE` on `Article_Tag`, but if you need to be able to do this, then being able to just update the value in `Tag` would be simpler. Some servers offer automatic updates (such as `ON UPDATE CASCADE` in SQL Server...
Using `TagText` as the primary key would have the advantage that you could get an articles tags with fewer joins: ``` SELECT * FROM Article_Tag WHERE Article_ID = ? ``` It would have the disadvantage that tag strings take more space than integers, so the storage for `Article_Tag` and its indexes would be larger. This...
Optimized Table structure for Tags table
[ "", "sql", "" ]
In C++, `sizeof('a') == sizeof(char) == 1`. This makes intuitive sense, since `'a'` is a character literal, and `sizeof(char) == 1` as defined by the standard. In C however, `sizeof('a') == sizeof(int)`. That is, it appears that C character literals are actually integers. Does anyone know why? I can find plenty of men...
Discussion on [same subject](http://bytes.com/groups/c/222894-sizeof-x-c-c) > "More specifically the integral promotions. In K&R C it was virtually (?) > impossible to use a character value without it being promoted to int first, > so making character constant int in the first place eliminated that step. > There were ...
The original question is "why?" The reason is that the definition of a literal character has evolved and changed, while trying to remain backwards compatible with existing code. In the dark days of early C there were no types at all. By the time I first learnt to program in C, types had been introduced, but functions...
Why are C character literals ints instead of chars?
[ "", "c++", "c", "char", "sizeof", "language-design", "" ]
Pretty self explanatory question. Is there any reason to use one or the other?
Count(\*) counts all records, including nulls, whereas Count(fieldname) does not include nulls.
Select count(\*) selects any row, select count(field) selects rows where this field is not null.
In SQL is there a difference between count(*) and count(<fieldname>)
[ "", "sql", "" ]
Given an example of calling two web services methods from a session bean, what if an exception is thrown between the calls to two methods? In the case of not calling the web services the transaction will rollback and no harm done. However, the web service will not rollback. Of course, even with a single web service the...
A number of techniques are evolving, but the problem is still sufficiently cutting edge that the standardization process has not yet provided us with a totally portable solution. Option one, you can make the web services transaction aware. This of course assumes you have control over them, although writing a transacti...
Web Services-Coordination (WS-C) and Web Services-Transaction (WS-T) specifications developed by Microsoft, BEA Systems and IBM are used in such cases as I know. You can start from reading [Web services transactions](http://www-128.ibm.com/developerworks/xml/library/x-transws/) and [A comparison of Web services transac...
Transaction rollback and web services
[ "", "java", "web-services", "transactions", "ejb", "rollback", "" ]
I recently started to learn about LINQ and came across the `OrderBy` extension method. This initially excited me because the syntax seemed much nicer than the `Sort` method that we use all over the place for Generic Lists. For example, when sorting a list of languages, we normally do something like: ``` neutralCultur...
That's the behaviour I would expect. Imagine if such a thing were possible: ``` var c = myCustomer; myCustomer.DoStuff(); if (c == myCustomer) // returns false!!! ``` Simply calling a method on an object (which is what an extension method looks like to the user of your framework) shouldn't change which instance the r...
I've written Sort variants using a selector before - it isn't hard... something like: ``` using System; using System.Collections.Generic; class Foo { public string Bar { get; set; } } static class Program { static void Main() { var data = new List<Foo> { new Foo {Bar = "def"}, ...
Extension method not updating object passed in
[ "", "c#", ".net", "linq", "" ]
I am writing some UI tests using Selenium and i have a JavaScript Tree control, using the Dojo toolkit. I have implemented a context menu for each node of the tree using the examples that Dojo provide, but I need the Selenium test to "invoke" the right click on the tree node, but I cannot get this to work. The tests s...
try this instead, reason what things didn't quite work is that the context menu is in fact bound to the oncontextmenu event. ``` function contextMenuClick(element){ var evt = element.ownerDocument.createEvent('MouseEvents'); var RIGHT_CLICK_BUTTON_CODE = 2; // the same for FF and IE evt.initMouseEvent('c...
Just for good measure, here is a bit of doco on the parameters: ``` var myEvt = document.createEvent('MouseEvents'); myEvt.initMouseEvent( 'click' // event type ,true // can bubble? ,true // cancelable? ,window // the event's abstract view (should always be window) ,1 ...
JavaScript simulate right click through code
[ "", "javascript", "selenium", "dojo", "mouseevent", "" ]
What would be the best way to write a generic copy constructor function for my c# classes? They all inherit from an abstract base class so I could use reflection to map the properties, but I'm wondering if there's a better way?
You can create a shallow copy **efficiently** with reflection by pre-compiling it, for example with `Expression`. For example, [like so](http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/d9722a51b04300a/0edae91abc1c0f1a#0edae91abc1c0f1a). For deep copies, serialization is the...
A copy constructor basically means you have a single parameter, which is the object you're going to copy. Also, do a deep copy, not a shallow copy. If you don't know what deep and shallow copies are, then here's the deal: Suppose you're copying a class that has a single row of integers as field. A shallow copy woul...
Generic C# Copy Constructor
[ "", "c#", "constructor", "copy", "" ]
I am querying information from [Active Directory](http://en.wikipedia.org/wiki/Active_Directory). I have code that works, but it's really slow. This is the code I currently use: ``` static void Main(string[] args) { SearchResultCollection sResults = null; try { //modify th...
The reason why your code is slow is that your [LDAP](http://en.wikipedia.org/wiki/LDAP) query retrieves every single user object in your domain even though you're only interested in one user with a common name of "Adit": ``` dSearcher.Filter = "(&(objectClass=user))"; ``` So to optimize, you need to narrow your LDAP ...
You can call [`UserPrincipal.FindByIdentity`](https://learn.microsoft.com/en-us/dotnet/api/system.directoryservices.accountmanagement.userprincipal.findbyidentity?view=netframework-4.8) inside `System.DirectoryServices.AccountManagement`: ``` using System.DirectoryServices.AccountManagement; using (var pc = new Princ...
How can I retrieve Active Directory users by Common Name more quickly?
[ "", "c#", "active-directory", "" ]
In the past, I have not really used namespaces, but in this project I am using SourceSafe which requires a project, which puts everything in namespaces... In the past, I have just been able to make a public static class in the App\_Code folder and access it frorm anywhere in my application, but now I cant seem to do t...
Either you include the namespace with a using directive: ``` using Personnel_Database.App_Code; // now you can use everything that is inside the Personnel_Database.App_Code namespace namespace Personnel_Database { ... ``` Or you use the fully quallified name of the utils class (including its namespace), e.g: ``` ...
You just need to add: ``` using Personnel_Database.App_Code; ``` to the top of your code-behind file. If you need access to it in the markup you can import it using: ``` <%@ Import Namespace="Personnel_Database.App_Code" %> ```
using a public static class in a 'Project' with defined namespaces
[ "", "c#", "asp.net", "static", "" ]
One of Steve McConnell's checklist items is that [you should not monkey with the loop index](http://www.matthewjmiller.net/files/cc2e_checklists.pdf) (Chapter 16, page 25, *Loop Indexes*, PDF format). This makes intuitive sense and is a practice I've always followed except maybe as I learned how to program back in the...
I think your articulation is great. Maybe it can be worded like so: > Since the logic can be expressed much > clearer, it should.
Well, this adds confusion for little purpose - you could just as easily write: ``` while(MyControl.TabPages.Count > 0) { MyControl.TabPages.Remove(MyControl.TabPages[0]); } ``` or (simpler) ``` while(MyControl.TabPages.Count > 0) { MyControl.TabPages.RemoveAt(0); } ``` or (simplest) ``` MyControl.TabPages....
Why is it bad to "monkey with the loop index"?
[ "", "c#", "for-loop", "" ]
I need to format a decimal value into a string where I always display at lease 2 decimals and at most 4. So for example ``` "34.49596" would be "34.4959" "49.3" would be "49.30" ``` Can this be done using the String.format command? Or is there an easier/better way to do this in Java.
You want java.text.DecimalFormat. ``` DecimalFormat df = new DecimalFormat("0.00##"); String result = df.format(34.4959); ```
Yes you can do it with `String.format`: ``` String result = String.format("%.2f", 10.0 / 3.0); // result: "3.33" result = String.format("%.3f", 2.5); // result: "2.500" ```
Java decimal formatting using String.format?
[ "", "java", "formatting", "decimal", "" ]
Parameters are used to protect you from malicious user input. But if the parameter expects a string, is it possible to write input that will be interpreted as sql, so malicious users can use things like 'DROP', 'TRUNCATE', etc...? Are there differences in protection between parameters in asp, asp.net, java and others...
Parameterized queries generally quote the parameter if it is a string behind the scene so that the normal SQL operators are not interpreted as such. This means that even if a user enters potentially malicious data it is simply treated as a string input and not interpreted as SQL operators/commands. There may be techni...
You need to be careful with your definitions. 'Parameters' can mean a number of things; parameters to a stored procedure, for example, don't protect you at all in and of themselves. To use Java as an example: ``` sql = "exec proc_SearchForUser '" + userNameToSearch + "'"; ``` is no better or worse than the raw ``` s...
From what do sql parameters protect you?
[ "", "sql", "database", "security", "parameters", "" ]
Here is the code to add a pfx to the Cert store. ``` X509Store store = new X509Store( StoreName.My, StoreLocation.LocalMachine ); store.Open( OpenFlags.ReadWrite ); X509Certificate2 cert = new X509Certificate2( "test.pfx", "password" ); store.Add( cert ); store.Close(); ``` However, I couldn't find a way to set permi...
To do it programmatically, you have to do three things: 1. Get the path of the private key folder. 2. Get the file name of the private key within that folder. 3. Add the permission to that file. See [this post](http://www.codeproject.com/script/Forums/View.aspx?fid=1649&msg=2062983) for some example code that does al...
This answer is late but I wanted to post it for anybody else that comes searching in here: I found an MSDN blog article that gave a solution using CryptoKeySecurity [here](http://blogs.msdn.com/b/cagatay/archive/2009/02/08/removing-acls-from-csp-key-containers.aspx), and here is an example of a solution in C#: ``` va...
How to set read permission on the private key file of X.509 certificate from .NET
[ "", "c#", ".net", "ssl", "ssl-certificate", "" ]
I'm beginning a new project in PHP and I'd love to get some feedback from other developers on their preferred strategy for PHP deployment. I'd love to automate things a bit so that once changes are committed they can be quickly migrated to a development or production server. I have experience with deployments using Ca...
For PHP, SVN with [Phing](http://phing.info/) build scripts are the way to go. Phing is similar to [ANT](http://ant.apache.org/) but is written in PHP, which makes it much easier for PHP developers to modify for their needs. Our deployment routine is as follows: * Everyone develops on the same local server at work, e...
I'm currently deploying PHP [using Git](https://stackoverflow.com/questions/279169/deploy-php-using-git#327315). A simple git push production is all that's needed to update my production server with the latest copy from Git. It's easy and fast because Git's smart enough to only send the diffs and not the whole project ...
What is your preferred php deployment strategy?
[ "", "php", "deployment", "capistrano", "" ]
I really like the format and type of links from [RubyFlow](http://rubyflow.com) for Ruby related topics. Is there an equivalent for Python that's active? There is a [PythonFlow](http://pythonflow.com), but I think it's pretty much dead. I don't really like <http://planet.python.org/> because there's lots of non-Python...
<http://www.reddit.com/r/Python> is my favorite source for Python news.
Possibly <http://www.planetpython.org/> or <http://planet.python.org/>.
Is there a Python news site that's the near equivalent of RubyFlow?
[ "", "python", "" ]
Having a friendly debate with a co-worker about this. We have some thoughts about this, but wondering what the SO crowd thinks about this?
One reason is there is no CLR support for a readonly local. Readonly is translated into the CLR/CLI initonly opcode. This flag can only be applied to fields and has no meaning for a local. In fact, applying it to a local will likely produce unverifiable code. This doesn't mean that C# couldn't do this. But it would gi...
I think it's a poor judgement on part of C# architects. readonly modifier on local variables helps maintain program correctness (just like asserts) and can potentially help the compiler optimize code (at least in the case of other languages). The fact that it's disallowed in C# right now, is another argument that some ...
Why does C# disallow readonly local variables?
[ "", "c#", "immutability", "language-design", "readonly", "" ]
``` #include <iostream> using namespace std; class Base { public: Base(){cout <<"Base"<<endl;} virtual ~Base(){cout<<"~Base"<<endl;} virtual void foo(){ cout<<"foo base"<<endl;} }; class Derived: private Base { public: Derived(){cout<<"Derived"<<endl;} virtual ~Derived...
> Why its not possible to create Derived object with base pointer???? Because the base is `private`. This explicitly forbids treating your class as a `Base` instance from the outside. Seen from the outside, your class `Derived` is *not* a subclass of `Base`, only from inside the class itself. The same counts for `pro...
You might want to take a look at [this faq](http://www.parashift.com/c++-faq-lite/private-inheritance.html) on c++ and inheritance. Sections [24.5](http://www.parashift.com/c++-faq-lite/private-inheritance.html#faq-24.5) and [24.6](http://www.parashift.com/c++-faq-lite/private-inheritance.html#faq-24.6) in particular.
Protected derived class
[ "", "c++", "inheritance", "" ]
Consider the tables: (`->` denotes a SQL defined relationship) ``` USER (userid, username, imageid->IMAGE.imageid) EVENT (eventid, userid->USER.userid, description) IMAGE (imageid, location) ``` Say I have a view (let's call it `vw_UserInfo`) defined as the following query. ``` SELECT u.*, i.* FROM users u INNER JOI...
No, because views (at least in SQL Server) are not really part of the constraints system (the existence or non-existence of a view should not affect the performance of any query not referencing the view). Indexed views (materialized views), however, might be able to contribute to performance. I'm not sure which, if any...
Relationships enforce data integrity, they have nothing to do with quick selection of data. That is the realm of indexes. In general, relationships (especially on tables with many of them) *slow down* data access (especially writes).
Do SQL Views retain relationship information in terms of performance?
[ "", "sql", "performance", "" ]
Hey stackoverflow community! I'm having an issue where a highly involved algorithmic program is using TOO LITTLE cpu utilization: somewhere between 3 and 4%. It is taking very long to return results, and I believe it's just not working hard enough. Do any of you geniuses have any ideas why this would occur - if anyth...
Obviously the database calls are causing delays. Isn't it an option to create smaller batches and test if that helps?? Maybe you could parallelize the algorithm as well to have a queue somewhere taking results and another thread cleaning out that queue? edit: There are also some other problem areas: * Database optim...
I would never recommend that someone use a JDBC driver with JNI if a type IV, 100% Java version is available. Google found [this](http://zentus.com/sqlitejdbc/) one. With that aside, I can't tell anything without more info. Are the app and the database running on the same hardware? What is so "intensive" about INSERT...
Too Little CPU Utilization in Java
[ "", "java", "cpu", "utilization", "" ]
``` string strLine;//not constant int index = 0; while(index < strLine.length()){//strLine is not modified}; ``` how many times `strLine.length()` is evaluated do we need to put use `nLength` with `nLength` assigned to `strLine.length()` just before loop
`length` will be evaluated every time you go via the loop, however since `length` is constant time (`O(1)`) it doesn't make much difference and adding a variable for storing this value will probably have a negligible effect with a small hit on code readability (as well as breaking the code if the string is ever changed...
length() is defined in headers which are included in your source file, so it can be inlined by compiler, it's internal calls also could be inlined, so if compiler would be able to detect that your string instance isn't changed in the loop then it can optimize access to length of a string, so it will be evaluated only o...
Condition evaluation in loops?
[ "", "c++", "loops", "evaluation", "conditional-statements", "" ]
I know I've seen this done before but I can't find the information anywhere. I need to be able to route with .html extensions in the Zend Framework. I.E. /controller/action.html should route to the appropriate controller / action. We have an idea to throw away the .html extension with our .htaccess file but I think c...
A quick search on google yielded the following tutorials: [Extending Zend Framework Route and Router for custom routing](http://my.opera.com/zomg/blog/2007/09/19/extending-zend-framework-route-and-router-for-custom-routing) [Routing and complex URLs in Zend Framework](http://codeutopia.net/blog/2007/11/16/routing-an...
This is the plugin I've used in several applications: ``` /** * Removes .html extension from URI, if present. */ class Application_Plugin_RemoveHtmlExtension extends Zend_Controller_Plugin_Abstract { public function routeStartup(Zend_Controller_Request_Abstract $request) { // remove ".html" from the ...
Zend Framework Routing: .html extension
[ "", "php", "zend-framework", "url", "url-routing", "" ]
I'm looking to make calls out to a subversion repository, but I would like to write it in C#. Does anyone know of any good libraries?
Have a look at [SharpSVN](http://sharpsvn.open.collab.net/). This is an open-source binding of the Subversion Client API for .Net 2.0 applications. For example, this library is used by the [AnkhSVN](http://ankhsvn.open.collab.net/) Visual Studio Add-In.
I recommend you look at the [Tortoise SVN source code](http://code.google.com/p/tortoisesvn/source/browse/). It is mostly in C++, but since it is all done in VS, it should be easy to wrap up and use much of the code again. You can also try [SubversionSharp](http://www.softec.st/en/OpenSource/ClrProjects/SubversionSha...
Does anyone know of a good C# API for Subversion?
[ "", "c#", ".net", "svn", "sharpsvn", "" ]
I was sitting here wondering if it's possible to write a greasemonkey script that would detect sites like payperclick and mute the audio so the ad isn't heard. I realize that I could accomplish the same thing in a better fashion by simply removing the ad text through a greasemonkey script but for purposes of curiousit...
The only way **I** can see this being possible is if: 1)the ad has its own "mute button" which called a javascript function...in which case you could just call that function yourself. 2) The plugin the ad is using for audio has a javascript API (same as 1) 3) IE only: some bizarre IE ActiveX thing that could probabl...
Other than completely stripping the <embed> element, it's a no-go; JavaScript simply doesn't have the power to access the volume controls of Flash media... yet. : )
Mute Audio from Javascript?
[ "", "javascript", "audio", "mute", "" ]
When embedding a flash object, is there a way to determine when it's fully loaded? That's my basic question, but for anyone interested in the details behind it: I am using the ([DOMWindow](http://swip.codylindley.com/DOMWindowDemo.html)) jQuery plugin. For those not familiar, it's a basic overlay the appears centered...
You should take a look at this page [Youtube Player Javascript API](http://code.google.com/apis/youtube/js_api_reference.html). Subscribing to the onStateChange Event and looking for it to return 5 appears to be what you want to do. I'll leave my original answer, in case it might still be handy. It is below. You may ...
It you're looking for a more general Flash reference, Flash makes available OnProgress, OnReadyStateChange and PercentLoaded as Javascript properties of the OBJECT or EMBED element. <http://www.adobe.com/support/flash/publishexport/scriptingwithflash/scriptingwithflash_03.html>
How to determine when an embedded flash object is loaded?
[ "", "javascript", "jquery", "flash", "" ]
EDIT: now the question becomes, how do I tell Sajax to use POST instead of GET? I've tried some examples from google but they are sketchy, and as I said, they didn't work. I know, we're all jQuery nuts around here. I've used the following code to try and find a limit to the amount of data that can be sent to the serve...
GET is limited in IE to 2083 chars see <http://support.microsoft.com/kb/208427> See [here](https://stackoverflow.com/questions/179264/what-is-the-optimum-limit-for-url-length-100-200) for url length for discussion.
I see this on the sajax examples: ``` $sajax_request_type = "GET"; sajax_init(); sajax_export("add_line", "refresh"); sajax_handle_client_request(); ``` I'm guessing you just change the GET to POST. ``` $sajax_request_type = "POST"; ```
AJAX browser-dependent limit on length of data sent? (SAJAX)
[ "", "php", "ajax", "xmlhttprequest", "cross-browser", "sajax", "" ]
Suppose I have a class ``` public class MyClass { private Set<String> set = new HashSet<String>(); //and many methods here } ``` is there a possibility to make an eclipse debugger stop at every line where set member is used?
I haven't used Eclipse for a while, but from what I remember this was possible in the Callisto release at least. If you set a breakpoint on the line containing the declaration, and then go into the advanced properties for that breakpoint, I believe you can set options for *modification* and *access* of that variable. ...
Yes. You can put a breakpoint at the expression ``` private String propString; ``` The breakpoint gets another symbol and shows the tool tip "Watchpoint [Acess and modification] " Whith Shift+Ctrl+I you can watch the value of a selected variable name when the debugger is in step mode. You also can change variable v...
Is there a possibility to break on every object reference in eclipse debugger?
[ "", "java", "eclipse", "debugging", "" ]
Visual Studio complains: **Warning 1 The designer must create an instance of type 'RentalEase.CustomBindingNavForm' but it cannot because the type is declared as abstract.** Visual Studio won't let me access the Designer for the form. The class already implements all abstract methods from the CustomBindingNavForm. Cus...
I haven't seen the content at urban potato (its down) but Me and [Smelch](https://stackoverflow.com/users/245808/smelch) came up with a solution. **`Form` itself inherits from an abstract class, so** what they dont tell you is that **its only the 1st level of inheritance that can't be abstract, the 2nd on down can.** ...
You can solve this using an attribute on your abstract class like the following ``` [TypeDescriptionProvider(typeof(AbstractControlDescriptionProvider<MyBaseFormEf, Form>))] ``` This will work for every case where you need it. The AbstractControlDescriptionProvider is below ``` public class AbstractControlDescriptio...
The designer must create an instance of...cannot because the type is declared abstract
[ "", "c#", ".net", "winforms", "abstract", "" ]
Is there a way to pass a call back function in a Java method? The behavior I'm trying to mimic is a .Net Delegate being passed to a function. I've seen people suggesting creating a separate object but that seems overkill, however I am aware that sometimes overkill is the only way to do things.
If you mean somthing like .NET anonymous delegate, I think Java's anonymous class can be used as well. ``` public class Main { public interface Visitor{ int doJob(int a, int b); } public static void main(String[] args) { Visitor adder = new Visitor(){ public int doJob(int a, ...
Since Java 8, there are lambda and method references: * [Oracle Docs: Lambda Expressions](http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html) * [Oracle Docs: Method References](http://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html) For example, if you want a functional interf...
Callback functions in Java
[ "", "java", "callback", "function-pointers", "" ]
In my C# application, I have a large struct (176 bytes) that is passed potentially a hundred thousand times per second to a function. This function then simply takes a pointer to the struct and passes the pointer to unmanaged code. Neither the function nor the unmanaged code will make any modifications to the struct. ...
I did some very informal profiling, and the results indicate that, for my particular application, there is a modest performance gain for passing by reference. For by-value I got about 10,050,000 calls per second, whereas for by-reference I got about 11,200,000 calls per second. Your mileage may vary.
Before you ask whether or not you should pass the struct by reference, you should ask yourself why you've got such an enormous struct in the first place. Does it *really* need to be a struct? If you need to use a struct at some point for P/Invoke, would it be worth having a struct *just* for that, and then the equivale...
In .Net, when if ever should I pass structs by reference for performance reasons?
[ "", "c#", ".net", "optimization", "" ]
**Note: solution at the end** If I attempt to do a HTTP POST of over 1024 characters, it fails. Why? Here is a minimal example: recipient.php: ``` <?php if (strlen(file_get_contents('php://input')) > 1000 || strlen($HTTP_RAW_POST_DATA) > 1000) { echo "This was a triumph."; } ?> ``` sender.php: ``` <?php funct...
You can convince PHP's curl backend to stop doing the 100-continue-thing by setting an explicit request header: ``` curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); ``` This way you can post a request however long you would ever want and curl will not do the dual phase post. I've [blogged about this](http://w...
## First thoughts... The manual page for [curl\_setopt](http://php.net/curl_setopt) says of CURLOPT\_POSTFIELDS > "The full data to post in a HTTP "POST" > operation. To post a file, prepend a > filename with @ and use the full path. > This can either be passed as a > urlencoded string like > 'para1=val1&para2=val2&....
PHP HTTP POST fails when cURL data > 1024
[ "", "php", "http", "post", "curl", "" ]
I've been trying to grok the org.apache.commons.beanutils library for a method/idiom to evaluate for equality *all* properties between 2 instances i.e. a generic equals() method for beans. Is there a simple way to do this usnig this library? Or am I going about this the wrong way? Thanks.
Try [EqualsBuilder.reflectionEquals()](https://commons.apache.org/proper/commons-lang/javadocs/api-3.3.2/org/apache/commons/lang3/builder/EqualsBuilder.html#reflectionEquals%28java.lang.Object,%20java.lang.Object,%20boolean%29) of [commons-lang](http://commons.apache.org/lang/). EqualsBuilder has a set of methods to in...
To answer your question directly, you could use reflection to do equality checking of beans. There are a few snags you need to be aware of. There are rules regarding the behaviour of equals() and hashcode(). These rules talk about symmetry, consitency and reflexiveness which may be hard to do when your equals method b...
how to generically compare entire java beans?
[ "", "java", "javabeans", "" ]
I like to keep javascript debugging enabled in my browser so when I'm developing my own code I can instantly see when I've made an error. Of course this means I see errors on apple.com, microsoft.com, stackoverflow.com, cnn.com, facebook.com. Its quite fun sometimes to see just how much awful code there is out there b...
Firebug lets you enable/disable debugging for different domains.
Script Debugging in IE7 is controlled by a registry key. (An addon could probably toggle it. I just don't know of any.) So, how I handle this is to write a registry script to turn it on or off. Then, I put a link to those scripts on my windows quick-launch bar and change their icons to be more appropriate. Then, I can...
How to suppress javascript errors for sites I'm not developing?
[ "", "javascript", "debugging", "internet-explorer", "" ]
So my 2009 new years resolution is to learn Java. I recently acquired "Java for Dummies" and have been following along with the demo code in the book by re-writing it using Eclipse. Anyway, every example in the book that uses a relative path does not seem to read the .txt file it's supposed to read from. Here is the s...
You need `"src/Hankees.txt"` Your file is in the source folder which is not counted as the working directory.\ Or you can move the file up to the root directory of your project and just use `"Hankees.txt"`
A project's build path defines which resources from your source folders are copied to your output folders. Usually this is set to Include all files. New run configurations default to using the project directory for the working directory, though this can also be changed. This code shows the difference between the work...
How do relative file paths work in Eclipse?
[ "", "java", "eclipse", "file-io", "relative-path", "" ]
I've gotten a request to show a person's local time based on their phone number. I know our local GMT offset, so I can handle USA phones via a database table we have that links US zip\_code to GMT offset (e.g. -5). But I've no clue how to convert non-US phone numbers or country names (these people obviously don't have ...
Florida has two time zones, but many countries only have one. You need this table: <http://en.wikipedia.org/wiki/List_of_country_calling_codes> . Parse the country code out of the phone number by looking for the 1 and the area code for NANPA countries (those countries using the same 1+area code allocation as the USA), ...
Local time is one thing but, if you have worldwide customers, there are also local habits to take into account. People typically go to bed earlier in Norway than in Spain (and they are in the same time zone).
Calculating person's time zone (GMT offset) based on phone number?
[ "", "sql", "oracle", "timezone-offset", "" ]
I was writing a toString() for a class in Java the other day by manually writing out each element of the class to a String and it occurred to me that using reflection it might be possible to create a generic toString() method that could work on ALL classes. I.E. it would figure out the field names and values and send t...
Apache commons-lang [ReflectionToStringBuilder](http://commons.apache.org/proper/commons-lang//apidocs/org/apache/commons/lang3/builder/ReflectionToStringBuilder.html) does this for you. ``` import org.apache.commons.lang3.builder.ReflectionToStringBuilder // your code goes here public String toString() { return ...
Another option, if you are ok with JSON, is Google's GSON library. ``` public String toString() { return new GsonBuilder().setPrettyPrinting().create().toJson(this); } ``` It's going to do the reflection for you. This produces a nice, easy to read JSON file. Easy-to-read being relative, non tech folks might find ...
Java toString() using reflection?
[ "", "java", "performance", "reflection", "tostring", "" ]
I want to make sure a file path set via query string does not go outside of the desired subdirectory. Right now, I am checking that: 1. The path does not start with "`/`", to prevent the user from giving an absolute path. 2. The path does not contain "`..`", to prevent the user from giving a path that is outside of th...
Call ``` $path = realpath("sample/$path"); ``` Then check that the resulting path starts with the directory you're expecting.
``` <?php // Current path information $path = $_GET['path']; $vroot = "sample"; // Validate that the $path is a subfolder of $vroot $vroot = realpath($vroot); if(substr(realpath($path), 0, strlen($vroot)) != $vroot or !is_dir($path)) {lid! exit("Invalid path"); } else { echo ...
How do I make sure a file path is within a given subdirectory?
[ "", "php", "security", "sanitization", "" ]
I have a file called **hellowf.cs** ``` class MyFirstApp { static void Main() { System.Windows.Forms.MessageBox.Show("Hello, Mono+WinForms!"); } } ``` On Ubuntu 8.10, I do the following ``` gmcs hellowf.cs -r:System.Drawing.dll -r:System.Windows.Forms.dll mono hellowf.exe ``` ... and it looks like this: [a...
Finally I have found a workaround. This seems to be a bug in Mono related to font rendering. It happens when "**Full**" hinting is turned on. I usually have it that way. Changing it to "**Slight**" or "**Medium**" in `System->Preferences->Appearance->Fonts->Details` fixes the problem. Thanks for the help!
Works OK on opensuse 11.0, mono 2.0.1. Please, edit your question and put the mono version you are using.
C# Mono+Winforms MessageBox problem
[ "", "c#", ".net", "winforms", "mono", "" ]
Ugh ok I'm terrible at explaining things, so I'll just give you the quotes and links first: [Problem 4b](http://sqlzoo.net/3.htm) (near bottom): > 4b. List the film title and the leading actor for all of 'Julie Andrews' films. > > > movie(id, title, yr, score, votes, director) > > actor(id, name) > > casting(movi...
There are wonderful ways of doing this with subqueries, but it appears that t this point in the tutorial you're only working with JOINs. The following is how you would do it with only JOINs: ``` SELECT movie.title, a2.name FROM actor AS a1 JOIN casting AS c1 ON (a1.id = c1.actorid) JOIN movie ON (c1.movieid ...
You want to match movies to two potentially separate rows in the `casting` table: one row where Julie Andrews is the actor, and the second row which may or may not be Julie Andrews, but which is the lead actor for the film. > Julie <---> cast in <---> a movie <---> starring <---> Lead actor So you need to join to the...
How do I list the first value from a three-way joined table query?
[ "", "mysql", "sql", "mysql-5.0", "" ]
How to decide whether to choose a Replication or Mirroring in SQL Server 2005 to provide data availabilty and performance at the same time. --- To be more specific about my SQL server architecture, I have an active/active cluster of 2 nodes which are used for load balancing, and I have another server for replication,...
It turns out that Database mirroing prevents data to be accessed directly, mirrored data are only accessable through a database snapshot, so reports from snapshot data will not be up to date so, I will use Database Transactional Replication to provide high availabilit and load balancing.
It depends on the level (hot, warm, cold) of standby availability you require. > Various mechanisms in SQL Server > provide database-level redundancy, > such as backup/restore, log shipping, > and database mirroring (in SQL Server > 2005 and later). Database mirroring is > the only mechanism that provides a > real-tim...
Mirroring vs Replication
[ "", "sql", "sql-server-2005", "" ]
I'm trying to debug javascript code just by adding a breakpoint in VS2008, but the debugger's not stopping. Do I have to do some special setup in order to enable javascript debugging? Or does the code have to be in a separate js file?
Did you uncheck the checkboxes in the settings Tools-->Internet Options-->Advanced-->Browsing [heading]-->Uncheck "Disable Script Debugging (Internet Explorer)" and Uncheck "Disable Script Debugging (Other)" Sometimes you need to restart the browser to get VS2008 to recognize that it has made some changes. Have you ...
Any particular browser? Mainly it works with IE, and needs script debugging enabled in the IE internet options (advanced => browsing).
Javascript Debugging in Visual Studio 2008
[ "", "javascript", "visual-studio-2008", "debugging", "" ]
I have written a program that will etablish a network connection with a remote computer using TCPClient I am using it to transfer files in 100k chunks to a remote .net application and it inturn then writes them to the HardDrive. All file transfers work good except when it comes to ZIP files - it is curious to note that...
Well, you haven't shown any code so it's kinda tricky to say exactly what's wrong. The *usual* mistake is to assume that Stream.Read reads all the data you ask it to instead of realising that it might read less, but that the amount it *actually* read is the return value. In other words, the code shouldn't be: ``` by...
The actual code would be helpful. Are you using BinaryReader / BinaryWriter? (i.e. data based rather than text based). You could try using a hex file compare (e.g. [Beyond Compare](http://www.scootersoftware.com/)) to compare the original and copy and see if that gives you any clues.
C# Reading 'Zip' files with FileStream
[ "", "c#", "zip", "filestream", "tcpclient", "" ]
One meme that gets stressed with Java development is always use ArrayList over Vector. Vector is deprecated. That may be true, but Vector and Hashtable have the advantage that they are synchronized. I am working with a heavily concurrent oriented application, wouldn't it benefit to use objects that are synchronized li...
The problem with Vector and Hashtable is that they're only locally synchronized. They won't break (as in corrupt data) in a concurrent application, however, due to the local synchronization (e.g. get is synchronized, but only until get returns), you'll be wanting to perform your own synchronization anyway for situation...
[ConcurrentHashMap](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ConcurrentHashMap.html) is [way faster](http://www.ibm.com/developerworks/java/library/j-jtp07233.html#N10244) than Hashtable. It's **concurrent**, not just synchronized. It admits multiple readers/writers at once. There is no such 'concu...
Use Hashtable, Vector or HashMap or ArrayList in Java
[ "", "java", "vector", "" ]
Is there support for lambda expressions from C++ 0x in Visual Studio 2008 SP1? Example below throws me syntax errors. Is there any '-Cpp0x' flag for compiler or something? ``` #include <algorithm> #include <iostream> #include <ostream> #include <vector> using namespace std; int main() { vector<int> v; for (int...
See [Stackoverflow question #146381](https://stackoverflow.com/questions/146381/visual-studio-support-for-new-c-c-standards) Simply put: no. Visual Studio 2010 will support C++0x to some extent, but I'm unsure if that will include lambda expressions.
You can... kind of. The Visual C++ 2008 *compiler* doesn't support lambdas, but you **can** certainly use the Visual C++ 2010 *compilers* from Visual Studio 2008!! Just install Visual C++ 2010 Express, and then open Visual Studio 2008 and go to: > Tools`->`Options`->`Project and Solutions`->`VC++ Directories and th...
Lambda expressions support in VS2008 SP1
[ "", "c++", "visual-studio-2008", "lambda", "c++11", "" ]
How can I convert a `List<MyObject>` to an `IEnumerable<MyObject>` and then back again? I want to do this in order to run a series of LINQ statements on the List, e. g. `Sort()`
``` List<string> myList = new List<string>(); IEnumerable<string> myEnumerable = myList; List<string> listAgain = myEnumerable.ToList(); ```
A `List<T>` is an `IEnumerable<T>`, so actually, there's no need to 'convert' a `List<T>` to an `IEnumerable<T>`. Since a `List<T>` is an `IEnumerable<T>`, you can simply assign a `List<T>` to a variable of type `IEnumerable<T>`. The other way around, not every `IEnumerable<T>` is a `List<T>` offcourse, so then you'll...
Freely convert between List<T> and IEnumerable<T>
[ "", "c#", "linq", "list", "ienumerable", "" ]
Are there any documents/tutorials on how to clip or cut a large image so that the user only sees a small portion of this image? Let's say the source image is 10 frames of animation, stacked end-on-end so that it's really wide. What could I do with Javascript to only display 1 arbitrary frame of animation at a time? I'...
This can be done by enclosing your image in a "viewport" div. Set a width and height on the div (according to your needs), then set `position: relative` and `overflow: hidden` on it. Absolutely position your image inside of it and change the position to change which portions are displayed. To display a 30x40 section o...
In answer to : Alas, JavaScript simply isn't capable of extracting the properties of the image you'd require to do something like this. However, there may be salvation in the form of the HTML element combined with a bit of server-side scripting. ... ``` < ? (open php) $large_image = 'path/to/large_image'; $full_w = ...
Programmatically Clip/Cut image using Javascript
[ "", "javascript", "image", "" ]
I am now debugging a program that utilizes many different threads. There is an exception that is thrown from time to time. The problem is that there is no way to know what thread caused the problem... Is there an easy way to get the stack trace after the exception is thrown? I thought about simply writing a debug me...
Unless I'm very much mistaken, you need to know which thread triggered the exception in order to use the Visual Studio debugger's call stack view, which is obviously the catch-22 situation you're in at the moment. One thing I would try is to see if you can get the debugger to break when the exception is thrown (using ...
This is trivially easy with [WinDBG](http://www.microsoft.com/whdc/devtools/debugging/default.mspx "Microsoft: Debugging Tools for Windows"), which is free from Microsoft. You will also want to install symbols for your version of [Windows](http://www.microsoft.com/whdc/devtools/debugging/symbolpkg.mspx#d "Microsoft: Sy...
Get the stack trace when an exception is thrown
[ "", "c++", "visual-studio-2008", "debugging", "" ]
I'm looking for the best approach to getting an XML document from a JDBC resultset. The structure of the XML isn't awfully important, but it should be fairly speedy. For clearification, I would like the data from the resultset and only enough metadata to identify the data (field names essentially). I'm working with My...
Are you looking to convert the ResultSet table into XML? I don't know of any thirdparty tool, but tt is not very difficult to roll one of your own. Your two options are to either have a constant format: ``` <ResultSet> <MetaData> <Column name="...." type="..."/> .... <MetaData> <Data> <Row><Cell val...
By using WebRowSet, once can convert the entire ResultSet into XML. The XML generated by WebRowSet is far clear and simple, i am not sure about the speed, since it also depends upon driver implementations. Here is a good article on [WebRowSet using Oracle](http://www.jdbctutorial.net/jdbc-rowset/Jdbc-WebRowSet-Generat...
Best Way to get XML from a JDBC resultset
[ "", "java", "xml", "jdbc", "" ]
What values should I pass to create an efficient `HashMap` / `HashMap` based structures for N items? In an `ArrayList`, the efficient number is N (N already assumes future grow). What should be the parameters for a `HashMap`? ((int)(N \* 0.75d), 0.75d)? More? Less? What is the effect of changing the load factor?
Regarding the load factor, I'll simply quote from the [HashMap javadoc](http://java.sun.com/javase/6/docs/api/java/util/HashMap.html): > As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflecte...
I ran some [unit tests](http://blog.scottlogic.com/2012/08/14/efficient-map-initialization-in-java.html) to see if these answers were correct and it turned out that using: ``` (int) Math.ceil(requiredCapacity / loadFactor); ``` as the initial capacity gives what you want for either a `HashMap` or a `Hashtable`. By "w...
HashMap initialization parameters (load / initialcapacity)
[ "", "java", "collections", "hashmap", "" ]
I am now designing an SNMP library. The problem is caused by a special function like this, \*\*\* GetTable(string id) This function may return Variable[,] which is a two dimensional array sometimes, but also Variable[,,] and arrays with more dimensions. So I believe it is not reasonable to return fixed array such as ...
As a general rule, returning a custom type allows for greater flexibility in the representation of your data. I'd also favour providing your own methods for accessing the data in this collection, rather than exposing multidimensional arrays. I generally avoid using multidimensional rectangular arrays myself. In many c...
Well, you could return `Array` and let the caller check the `.Rank`? Of course, returning an array may not be the best option in the first place (depending on the scenario): [Arrays considered somewhat harmful](http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx)
How to design this method if it returns multi-dimensional arrays?
[ "", "c#", ".net", "arrays", "methods", "multidimensional-array", "" ]
I'm new to unit testing using nunit (and Java development in general). When creating unit tests for private methods on classes, it looks as though the test file must be in the same package as the class being tested. What is the typical way of avoiding exporting the APIs of the unit tests? Can I make the classes/test me...
The test file does not necessarily have to be in the same package as the class being tested. In fact, it is a good practice to have the test files in a completely separate package, allowing them to test the public API without being concerned with package-level implementation details. Alternately, you can set up your b...
I can tell IntelliJ or Ant not to package JUnit tests in the deployment. I have tests in a separate directory from the source code, which is what makes it possible. Don't mingle source and test classes together. Keep them separate to make it easier for the tool/script you use to deploy.
Creating nunit tests without exporting them with the api
[ "", "java", "unit-testing", "tdd", "nunit", "" ]
I'm new to unit testing and nUnit (2.48). I'd like to write a test method where the failure case is that it deadlocks. Is this possible? Obviously nUnit doesn't know by default how long the method should take to execute, so would I have to write code to do the work on a separate thread and then abort it and throw and e...
It is possible but it might not be the best thing to do. Unit tests aren't really suitable for testing concurrency behaviour, unfortunately there aren't many test-methods that are suitable. NUnit doesnt do anything with threads. You could write tests that start several threads and then test their interaction. But thes...
Well its certainly possible to test for a deadlock by running your code on another thread and seeing if it returns in a timely fashion. Here's some (very basic) example code: ``` [TestFixture] public class DeadlockTests { [Test] public void TestForDeadlock() { Thread thread = new Thread(ThreadFunct...
Testing for a deadlock with nUnit
[ "", "c#", "unit-testing", "nunit", "deadlock", "" ]
I have some special cells in my Excel workbooks which are managed by my Excel Add-in. I want to prevent users from changing content of those cells, but I also want to know, what value users wanted to enter to those cells. On the SheetChange event I can check what users entered to my special cells, but how do I determin...
How about something like this, which is in VBA, but should be fairly easy to translate to C# ``` Option Explicit ' We are monitoring cell B2... Private initialB2Value As Variant ' holds the value for reinstatement when the user changes it Private Sub Worksheet_Activate() ' record the value before the user makes an...
Perhaps it would suit to capture the value on entering the cell: ``` Option Explicit Dim LastText As String Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, _ ByVal Target As Excel.Range) LastText = Target.Value End Sub Private Sub Workbook_SheetChange(ByVal Sh As Object, _ ByVal Sou...
How can I determine new & previous cell value on SheetChange event in Excel?
[ "", "c#", "excel", "vsto", "" ]
A program written in Visual C/C++ 2005/2008 might not compile with another compiler such as GNU C/C++ or vice-versa. For example when trying to reuse code, which uses windows.h, written for a particular compiler with another, what are the differences to be aware of? Is there any information about how to produce code w...
The first thing to do when trying to compile code written for MSVC to other compilers is to compile it with Microsoft-extensions switched off. (Use the /Za flag, I think). That will smoke out lots of things which GCC and other compilers will complain about. The next step is to make sure that Windows-specific APIs (MFC...
Remember the argument that if you want your web page to work on different browsers, then you should write standards-compliant HTML? Same goes for compilers. At the language level, if your code compiles without warnings on GCC with -std=c89 (or -std=c++98 for C++), -pedantic -Wall, plus -Wextra if you're feeling brave...
What are the practical differences between C compilers on Windows?
[ "", "c++", "c", "winapi", "cross-platform", "" ]
I'm trying to decide whether it is better to use static methods for loading/saving objects, or use constructor/instance methods instead. So, say for object `Project`, the instance version would be ``` public Project(path) { // Load project here } public void Save(path) { // Save project here } ``` And the static ver...
Neither. Favor extracting persistence logic from your domain model and into a separate layer of classes. (from a comment left in ChrisW's answer) Regarding the details of the domain object leaking into another class: you can restrict the visibility of those details, if your language permits, by using package-privacy/i...
If there is no state to be maintained, only behavior, then use the static approach. However, if the Project object needs to have state, then the constructor/instance method should be used.
Constructors or Static Methods for Loading and Saving Objects?
[ "", "c#", ".net", "design-patterns", "architecture", "" ]
I'm currently writing a C#-class in my ASP.NET (3.5) application to handle all database-queries. Some of the methods are there to make a select-query to the database. Inside the method i simply have a `SqlDataReader r = command.ExecuteReader();` to fetch the data. I now want `r` to be returned by the method, but when ...
You can use a datatable and SqlDataAdapter: ``` using(SqlDataAdapter adap = new SqlDataAdapter(cmd)) { adap.fill(myDataTable); } return myDataTable; ```
Typically, the results are either stuffed into a collection or a datatable. Datatables are a little easier from the perspective of not having to instantiate objects and storing them.
Storing an SqlDataReader-object in C#/ASP.NET?
[ "", "c#", "asp.net", "database", "class", "sqldatareader", "" ]
I'm currently in the creation of a javascript function library. Mainly for my own use, but you can never be sure if someone else ends up using it in their projects, I'm atleast creating it as if that could happen. Most methods only work if the variables that are passed are of the correct datatype. Now my question is:...
Some small remarks on type checking - it's actually not that complicated: Use `typeof` to check for primitives and `instanceof` to check for specific object types. Example: Check for strings with ``` typeof x === 'string' ``` or ``` typeof x === 'string' || x instanceof String ``` if you want to include string ob...
The problem with type checking is that its actually quite hard to do. For example:- ``` var s = new String("Hello World!"); alert(typeof s); ``` What gets alerted? Ans: "object". Its true its a daft way to initialise a string but I see it quite often none-the-less. I prefer to attempt conversions where necessary or j...
What is the best way to tell users of my library functions that passed variables are not of the correct type
[ "", "javascript", "typechecking", "" ]
Is there a way for a Java GUI application to respond to system shutdown or logoff events, other than to use JNI? (On Windows, the JNI would use WM\_QUERYENDSESSION, on Linux?) The method should allow the program to prompt users to save, etc., and then continue the logoff process.
As far as I know, there's no way in Java to catch the system shutdown or logoff events. You can, however, catch when the JVM is terminating by [adding a shutdown hook](http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)). AWT's [WindowAdapter](http://java.sun.com/javase/6/do...
I think that Runtime.getRuntime().addShutdownHook should provide the functionality you need.
Java: Handle logoff or shutdown on Windows and Linux
[ "", "java", "windows", "linux", "swing", "" ]
I've decided I want to get more into native code development with C++. I'm trying to decide if I would be better served using CodeGear C++ Builder 2009 or Visual Studio 2008. I currently use Delphi 2007, so I'm very comfortable with C++ Builder's IDE (its the same as Delphi), as well as the VCL and RTL. I've never bee...
Coming from Delphi, you'll find the VCL straightforward to use with C++ Builder. There are a few oddities, like C++ doesn't hide the fact that TObjects are all really pointers (which Delphi hides from you), and some things like array properties are accessed differently. Two or three years back, I was looking for any w...
Visual Studio and MFC are not the same. I use Studio all the time and I avoid MFC like the plague. You can use WTL, ATL, Win32 or any number of libraries to create apps without MFC.
C++ Builder or Visual Studio for native C++ development?
[ "", "c++", "visual-studio", "c++builder", "" ]
There are three tables, Students, Classes, Student\_Class Is it possible to select students who are not registered in any classes without using NOT IN? e.g. Select studentname from Students Where studentid NOT IN (Select Distinct studentid From Student\_Class)
There are three methods: 1. `SELECT StudentName FROM Students WHERE StudentID NOT IN (SELECT StudentID FROM StudentClass)`; 2. `SELECT StudentName FROM Students s WHERE NOT EXISTS (SELECT StudentID FROM StudentClass WHERE StudentID = s.StudentID)`; and 3. `SELECT StudentName FROM Students s LEFT OUTER JOIN StudentClas...
I really don't know why you don't want to use NOT IN, but here's one other option... ``` SELECT Studentname FROM Students LEFT JOIN Student_Class ON Student_Class.StudentID = Student.ID WHERE Student_Class.StudentID IS NULL ```
Selecting records from a many-to-many design
[ "", "sql", "t-sql", "" ]
What is the best way to handle several different onload scripts spread across many pages? For example, I have 50 different pages, and on each page I want to set a different button click handler when the dom is ready. Is it best to set onclicks like this on each individual page, ``` <a id="link1" href="#" onclick="my...
Have you thought about making a class for each type of behavior you'd like to attach to an element? That way you could reuse functionality between pages, just in case there was overlap. For example, let's say that on some of the pages you want to a have button that pops up some extra information on the page. Your html...
I would use [JQuery's](http://docs.jquery.com/How_jQuery_Works) *document ready* if possible ``` $(document).ready(function() { // jQuery goodness here. }); ```
Best Practices for onload Javascript
[ "", "javascript", "onload", "" ]
### Question --- I'm trying to build a quick and easy ASP.NET page that redirects a user to a new URL using a meta redirect. Only trouble is that I need to also pass along the GET values of the current request. I've found a way to do this programatically in the code behind using the HtmlMeta object. However, I'd like...
Maybe this code inside the head tag will be what you need: ``` <%= string.Format("<meta http-equiv='refresh' content='10;url=http://contact.test.net/main.aspx?{0}' />", Request.QueryString.ToString()) %> ``` **However**, I wouldn't advise you to do it this way. For example, this URL: ``` http:/mysite.with.metaredire...
Have you tried adding the whole meta tag programmatically? Once you get the to run server-side, add your new tag dynamically on Page\_Load() and you can specify all its attributes. The process is well described here: <http://www.howtoadvice.com/SetMetaTags>
Edit HTML Meta Tag w/ ASP.NET
[ "", "c#", "asp.net", "html", "" ]
Since I received no positives answers to my [last](https://stackoverflow.com/questions/285237/does-a-javascriptable-ftp-upload-javaflash-applet-exist) question. I will try to write a Java FTP upload applet myself. My question is: "Can you recommend a Java FTP client library for me to use?" I want it to be: * stable ...
Check out Apache [commons-net](http://commons.apache.org/net/), which contains FTP utilities. Off the top of my head I'm not sure if it meets all of your requirements, but it's certainly free!
ftp4j is the best one, both for features and license: <http://www.sauronsoftware.it/projects/ftp4j/>
What Java FTP client library should I use?
[ "", "java", "ftp", "client", "" ]