Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Is there some easy way to handle multiple submit buttons from the same form? For example:
```
<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
<input type="submit" value="Send" />
<input type="submit" value="Cancel" />
<% Html.EndForm(); %>
```
Any idea how to do this in ASP.NET Framework Beta? All ... | Here is a mostly clean attribute-based solution to the multiple submit button issue based heavily on the post and comments from [Maarten Balliauw](http://blog.maartenballiauw.be/post/2009/11/26/supporting-multiple-submit-buttons-on-an-aspnet-mvc-view.aspx).
```
[AttributeUsage(AttributeTargets.Method, AllowMultiple = ... | Give your submit buttons a name, and then inspect the submitted value in your controller method:
```
<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
<input type="submit" name="submitButton" value="Send" />
<input type="submit" name="submitButton" value="Cancel" />
<% Html.EndForm(); %>
```
posting ... | How do you handle multiple submit buttons in ASP.NET MVC Framework? | [
"",
"c#",
"html",
"asp.net-mvc",
"http-post",
"form-submit",
""
] |
In javascript you can easily create objects and Arrays like so:
```
var aObject = { foo:'bla', bar:2 };
var anArray = ['foo', 'bar', 2];
```
Are similar things possible in PHP?
I know that you can easily create an array using the array function, that hardly is more work then the javascript syntax, but is there a si... | For simple objects, you can use the associative array syntax and casting to get an object:
```
<?php
$obj = (object)array('foo' => 'bar');
echo $obj->foo; // yields "bar"
```
But looking at that you can easily see how useless it is (you would just leave it as an associative array if your structure was that simple). | There was a [proposal to implement this array syntax](http://wiki.php.net/rfc/shortsyntaxforarrays). ~~But it was declined.~~
---
**Update**ย ย ย ย The shortened syntax for arrays has been rediscussed, accepted, and is now on the [way be released with PHP 5.4](https://wiki.php.net/todo/php54).
But there still is no shor... | Does PHP feature short hand syntax for objects? | [
"",
"php",
"object",
""
] |
I'm trying to match the parts of a version number (Major.Minor.Build.Revision) with C# regular expressions. However, I'm pretty new to writing Regex and even using Expresso is proving to be a little difficult. Right now, I have this:
```
(?<Major>\d*)\.(?<Minor>\d*)\.(?<Build>\d*)\.(?<Revision>\d*)
```
This works, bu... | ```
(?<Major>\d*)\.(?<Minor>\d*)(\.(?<Build>\d*)(\.(?<Revision>\d*))?)?
```
Makes the third and fourth parts optional. | I know this isn't a regex, but [System.Version](http://msdn.microsoft.com/en-us/library/system.version.aspx) does all the work for you. | Matching version number parts with regular expressions | [
"",
"c#",
"regex",
"version",
""
] |
I have a table for which I want to select top the 5 rows by some column A. I also want to have a 6th row titled 'Other' which sums the values in column A for all but the top 5 rows.
Is there an easy way to do this? I'm starting with:
```
select top 5
columnB, columnA
from
someTable t
order by
columnA d... | Not tested, but try something like this:
```
select * from (
select top 5
columnB, columnA
from
someTable t
order by
columnA desc
union all
select
null, sum(columnA)
from
someTable t
where primaryKey not in (
select top 5
... | ```
select top 5 columnB, columnA
from someTable
order by columnA desc
select SUM(columnA) as Total
from someTable
```
Do the subtraction on the client side. | SQL Server 2005 - Select top N plus "Other" | [
"",
"sql",
"sql-server",
""
] |
So I have this code that takes care of command acknowledgment from remote computers, sometimes (like once in 14 days or something) the following line throws a null reference exception:
```
computer.ProcessCommandAcknowledgment( commandType );
```
What really bugs me is that I check for a null reference before it, so ... | What are the other thread(s) doing?
Edit: You mention that the server is single threaded, but another comment suggests that *this portion* is single threaded. If that's the case, you could still have concurrency issues.
Bottom line here, I think, is that you either have a multi-thread issue or a CLR bug. You can gues... | Based on the information you gave, it certainly appears impossible for a null ref to occur at that location. So the next question is "How do you know that the particular line is creating the NullReferenceException?" Are you using the debugger or stack trace information? Are you checking a retail or debug version of the... | Strange nullreference exception | [
"",
"c#",
".net",
"nullreferenceexception",
""
] |
I want to use dynamic mocks when testing a Silverlight application. I have tried Moq and Rhino but these frameworks assemblies cannot be added to a silverlight project as they are incompatible with the silverlight runtime.
Is there an existing silverlight mock framework (or patch for moq) that will allow me to use moc... | The latest release of Moq has a fully supported silverlight version as well... | There is a working version of Rhino Mocks delivered by [Ayende Rahien](http://ayende.com/projects/rhino-mocks/downloads.aspx), I've tried this out over the last week and it works correctly in the Silverlight runtime. Great to see that mock objects are now available in Silverlight. | Is there any C# Dynamic Mock framework available for Silverlight? | [
"",
"c#",
"silverlight",
"unit-testing",
"mocking",
""
] |
Unmanaged languages notwithstanding, is F# really better than C# for implementing math? And if that's the case, why? | I think most of the important points were already mentioned by someone else:
1. F# lets you solve problems in a way mathematicians think about them
2. Thanks to higher-order functions, you can use simpler concepts to solve difficult problems
3. Everything is immutable by default, which makes the program easier to unde... | F# has many enormous benefits over C# in the context of mathematical programs:
* F# interactive sessions let you run code on-the-fly to obtain results immediately and [even visualize them](http://fsharpnews.blogspot.com/2010/02/f-for-visualization-video-tutorial.html), without having to build and execute a complete ap... | Is F# really better than C# for math? | [
"",
"c#",
"math",
"f#",
""
] |
I had a Dataset with some data in it. When I tried to write this DataSet into a file, everything was OK. But When I tried to write it into a MemoryStream, the XML file declaration was lost.
The code looks like:
```
DataSet dSet = new DataSet();
//load schema, fill data in
dSet.WriteXML("testFile.xml");
MemoryStream st... | It wasn't dropped. Simply not included. Though it is highly recommend the xml declaration is not a required element of the xml specification.
<http://msdn.microsoft.com/en-us/library/ms256048(VS.85).aspx>
You can use XmlWriter.WriteStartDocument to include the xml declaration in the stream like so:
```
MemoryStream ... | I try your solution with DataTable and don't work correctly.
```
using (MemoryStream stream = new MemoryStream()) {
using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8)) {
writer.WriteStartDocument(); //<?xml version="1.0" encoding="utf-8"?>
writer.WriteRaw("\r\n"); //endline
... | Lost XML file declaration using DataSet.WriteXml(Stream) | [
"",
"c#",
"dataset",
""
] |
I've tried figuring out this problem for the last 2 days with no luck. I'm simply trying to create an annotation based JUnit test using the spring framework along with hibernate.
My IDE is netbeans 6.5 and I'm using hibernate 3, spring 2.5.5 and JUnit 4.4.
Here's the error I'm getting:
```
Testcase: testFindContacts... | The `java.lang.NoSuchMethodError` always indicates that the version of a class that was on your compiler's classpath is different from the version of the class that is on your runtime classpath (had the method been missing at compile-time, the compile would have failed.)
In this case, you had a different version of `o... | Definitely you have different versions of your ClassWriter class at runtime than compile time. | No Such Method Error when creating JUnit test | [
"",
"java",
"hibernate",
"spring",
"junit",
"netbeans6.5",
""
] |
I am not trying to make this a preference question, I am really wondering what people's experiences are with using jQuery and Rails or jRails for development. Most rails users including myself up to now have been using Prototype. However, I am mixing in a lot of jQuery plugins since they are so easy to use and extend.
... | In Rails it really all comes down to the helper methods. Are you using any prototype helper methods? If so then you must use jRails to switch to jQuery. But if not then it really does not matter. They are both great. I used prototype a lot before and it is great. But I prefer the selector way of doing things with jQuer... | jRails is great if you are using rjs templates if you want to maintain a "consistent" codebase between generated and handwritten. However, I personally have seen jRails not know how to really decently handle ajax form generators.
My biggest recommendation is to have jRails for "when you need it", and get more comforta... | jRails vs. Prototype | [
"",
"javascript",
"jquery",
"ruby-on-rails",
"prototypejs",
""
] |
I have a question about tables in MySQL.
I'm currently making a website where I have files for people to download. Now I want to make a table in MySQL that will store the latest downloads, like if someone downloads file1.zip then it will add a row in the table with the filename and date, so that I can show on the fron... | Look at [triggers](http://dev.mysql.com/doc/refman/5.0/en/triggers.html) to delete automatically the old rows. | This can be solved by using a trigger (MySQL 5 required) or setting up a cron job or something similar, that periodically checks the number of rows in the tables. | Possible to set max rows in MySQL table? | [
"",
"php",
"mysql",
""
] |
I'm currently considering the use of Reflection classes (ReflectionClass and ReflectionMethod mainly) in my own MVC web framework, because I need to automatically instanciate controller classes and invoke their methods without any required configuration ("convention over configuration" approach).
I'm concerned about p... | Don't be concerned. Install [Xdebug](http://www.xdebug.org/) and be sure where the bottleneck is.
There is cost to using reflection, but whether that matters depends on what you're doing. If you implement controller/request dispatcher using Reflection, then it's just one use per request. Absolutely negligible.
If you... | I benchmarked these 3 options (the other benchmark wasn't splitting CPU cycles and was 4y old):
```
class foo {
public static function bar() {
return __METHOD__;
}
}
function directCall() {
return foo::bar($_SERVER['REQUEST_TIME']);
}
function variableCall() {
return call_user_func(array('foo... | PHP 5 Reflection API performance | [
"",
"php",
"performance",
"reflection",
""
] |
I have already googled for this
```
I have a Table with following structure in SQL 2000
ID ContactName Designation
1 A CEO
2 B ABC
3 C DEF
4 D GHI
```
I need the Output as follows
```
ContactName1 Contactname2 ContactName3 ContactName4
A CEO B ABC C ... | It occurs to me that a lot of the examples are for cross tab queries involving aggregation, which yours does not appear to need. While I do not necessarily condone Dynamic SQL, the below should give you the results you want.
```
Create table #Contacts (id int)
Declare @ContactTypes int
Declare @CAD varchar(100)
Declar... | You need to use a [PIVOTED Table](http://msdn.microsoft.com/en-us/library/aa172756.aspx) | Cross Tab Query Required SQL 2000 | [
"",
"sql",
"crosstab",
""
] |
Alright so here is the deal. I am trying to make a application that's a GUI application yet has no GUI. So when the application starts, it has a small form with a login screen (I have done this part).
This the code for the `main()` in which the form runs but as soon as it is closed, I dispose of it.
```
static void M... | If you want to make the foreground thread wait you can use a WaitHandle.
<http://msdn.microsoft.com/en-us/library/system.threading.waithandle.aspx> | Drop all that thread stuff and do it all in a form that implements the system tray icon. Put your timer in that form and everything you want is done.
Something like
```
LoginForm login = new LoginForm();
if(login.ShowDialog()==DialogResult.OK)
{
Application.Run(new SystemTrayForm());
}
``` | Timer doesn't "loop" | [
"",
"c#",
"timer",
""
] |
I'm trying to change the alt of the image, I'm clicking by
selecting the image's class (***`add_answer`***)
**Note:** ***`.add_answer`*** shows up multiple times inside different containing `div`'s
```
jQuery(function(){ // Add Answer
jQuery(".add_answer").click(function(){
var count = $(this).attr("al... | you can use the parent div as the scope:
```
$('.add_answer',$(this).parent('div:first')).attr('alt',count);
``` | This should work:
```
$(this).parent("div").find(".add_answer").attr("alt", count);
``` | jquery select class inside parent div | [
"",
"javascript",
"jquery",
""
] |
I'm writing some unit tests which are going to verify our handling of various resources that use other character sets apart from the normal latin alphabet: Cyrilic, Hebrew etc.
The problem I have is that I cannot find a way to embed the expectations in the test source file: here's an example of what I'm trying to do..... | A tedious but portable way is to build your strings using numeric escape codes. For example:
```
wchar_t *string = L"ืืื ืืืจืืืข";
```
becomes:
```
wchar_t *string = "\x05d3\x05d5\x05e0\x05d3\x05d0\x05e8\x05df\x05de\x05e2";
```
You have to convert all your Unicode characters to numeric escapes. That way your source c... | You have to tell GCC which encoding your file uses to code those characters into the file.
Use the option `-finput-charset=charset`, for example `-finput-charset=UTF-8`. Then you need to tell it about the encoding used for those string literals at runtime. That will determine the values of the wchar\_t items in the st... | How can I embed unicode string constants in a source file? | [
"",
"c++",
"unit-testing",
"string",
"unicode",
"constants",
""
] |
As far as I am aware there is no inbuilt polygon functionality for Python. I want to create a 3D map and figured that polygons would be the best way to go about it.
Not wanting to reinvent the wheel I did some googling and found that there's a lot of Python stuff out there, but I couldn't find what I wanted. Thus befo... | One of the most complete geography/mapping systems available for Python that I know about is [GeoDjango](http://geodjango.org/). This works on top of the [Django](http://www.djangoproject.com/), an MVC framework. With it comes a large collection of polygon, line and distance calculation tools that can even take into ac... | I think you mean Polyhedron, not Polygon .. and you might wanna look at [vpython](http://vpython.org/) | 3D Polygons in Python | [
"",
"python",
"3d",
"polygon",
""
] |
If I open and close a socket by calling for instance
```
Socket s = new Socket( ... );
s.setReuseAddress(true);
in = s.getInputStream();
...
in.close();
s.close();
```
Linux states that this socket is still open or at least the file descriptor for the connection is presen. When querying the open files for this proce... | If those sockets are all in the TIME\_WAIT state, this is normal, at least for a little while. Check that with netstat; it is common for sockets to hang around for a few minutes to ensure that straggling data from the socket is successfully thrown away before reusing the port for a new socket. | You may also want to check `/proc/<pid>/fd`, the directory will contain all of your currently opened file descriptors. If a file disappears after you closed the socket you will not run into any problems (at least not with your file descriptors :). | Is there a file descriptor leak when using sockets on a linux platform? | [
"",
"java",
"linux",
"sockets",
"file-descriptor",
""
] |
Which method do you think is the "best".
* Use the `System.IO.Packaging` namespace?
* Use interop with the Shell?
* Third party library for .NET?
* Interop with open source unmanaged DLL?
[I can target Framework 3.5; best = easiest to design, implement, and maintain.]
I am mostly interested in why you think the chos... | I've always used [SharpZipLib](http://www.icsharpcode.net/OpenSource/SharpZipLib/)
Forgot the why part: Mainly because its been around for a long time. It is well documented, and has an intuitive API. Plus it's open source if you're into that type of thing. | [DotNetZip](http://www.codeplex.com/DotNetZip) is very simple to use. I like it because it is fully-managed - no shell interaction required. The programming model is simpler and cleaner than that for the shell. Also it is simpler than SharpZipLib as well as the Packaging classes added in .NET 3.0. It is free, small, ac... | What is the best/easiest way to create ZIP archive in .NET? | [
"",
"c#",
".net",
"zip",
""
] |
I'm developing an `ASP.Net MVC` site and on it I list some bookings from a database query in a table with an `ActionLink` to cancel the booking on a specific row with a certain `BookingId` like this:
**My bookings**
```
<table cellspacing="3">
<thead>
<tr style="font-weight: bold;">
<td>Date</... | You could do it like this:
* mark the `<a>` with a class, say "cancel"
* set up the dialog by acting on all elements with class="cancel":
```
$('a.cancel').click(function() {
var a = this;
$('#myDialog').dialog({
buttons: {
"Yes": function() {
window.location = a.href;
... | jQuery provides a method which store data for you, no need to use a dummy attribute or to find workaround to your problem.
Bind the click event:
```
$('a[href*=/Booking.aspx/Change]').bind('click', function(e) {
e.preventDefault();
$("#dialog-confirm")
.data('link', this) // The important part .data(... | Passing data to a jQuery UI Dialog | [
"",
"javascript",
"jquery",
"asp.net-mvc",
"jquery-ui",
"jquery-ui-dialog",
""
] |
In C# 3.0, I have a property which is suppose to contain the version of the class. The version number is simply the date and time of compilation. Right now, I have the following code:
```
public DateTime Version
{
get { return DateTime.UtcNow; }
}
```
Obviously, this is wrong since this property returns me the cu... | C# doesn't have the concept of macros; however, you can use other tools in your build script (csproj / NANT / etc) to manipulate the source before it compiles. I use this, for example, to set the revision number to the current SVN revision.
A cheap option is a pre-build event (you can do this via the project propertie... | You can retreive it from the dll itself ([Source: codinghorror](http://www.codinghorror.com/blog/archives/000264.html))
```
private DateTime RetrieveLinkerTimestamp() {
string filePath = System.Reflection.Assembly.GetCallingAssembly().Location;
const int c_PeHeaderOffset = 60;
const int c_Li... | How can I get the current DateTime from the Precompiler in C#? | [
"",
"c#",
".net",
"c-preprocessor",
""
] |
What are all the things one needs to be careful about when coding in a multicore environment?
For example, for a singleton class, it is better to create a global object and then return its reference than a static object.
i.e
Rather than having
```
MyClass & GetInstance()
{
static Myclass singleMyclass;
return singl... | My first answer addressed your example of singleton initialisation, but as you emphasised in an edit to your question, you are after more general pit falls of C++ as we move to multi-core and multi-threaded applications. The following is a real surprise when you first encounter it. Though not C++ specific, it definitel... | You must be careful with initialisation of statics. The order of initialisation can play havoc in complex system where static objects do lots of things in their constructors.
The first approach is better as singletons are created on demand, but you need some locking to make it thread safe.
The second approach is thre... | c++; things to take care in multicore environment | [
"",
"c++",
"multithreading",
""
] |
In the python program I'm writing, I've got a thread which iterates over a large structure in memory and writes it incrementally into a file-like object. I've got another thread which takes a file-like object and writes it to disk. Is there an easy way to connect the two, such that any data input from the first thread ... | Use [`shutil`'s `copyfileobj()`](http://docs.python.org/library/shutil.html#shutil.copyfileobj) function:
```
import shutil
import subprocess
proc = subprocess.Popen([...], stdin=subprocess.PIPE)
my_input = get_filelike_object('from a place not given in the question')
shutil.copyfileobj(my_input, proc.stdin)
```
N... | You should use the [Queue](http://docs.python.org/library/queue.html) module for sharing sequential data across threads. You would have to make a file-like Queue subclass, where .read and .write mutually block each other, with a buffer in-between.
OTOH, I wonder why the first thread can't write to the real file in the... | Is there a simple way in Python to create a file which can be written to in one thread and read in a different one? | [
"",
"python",
""
] |
I have set the FlushMode property on an NHibernate session to FlushMode.Never, but when I call session.Save(User), a call gets made to the database anyway. Is this how this is supposed to work? I would think that it shouldn't do an insert until I call Flush().
Edit:
I found the issue, I changed the primary key to guid... | You were using a native generator, right?
The problem with this lies in the fact that, since it's the DB that generates the ID, NHibernate needs a round trip to fetch it. As an example, for Server's identity fields the actual INSERT statement must be executed before SCOPE\_IDENTITY() returns a valid key. And the only ... | I found the issue, I was using an identity as the primary key. Changing it to guid worked. | NHibernate FlushMode on Save | [
"",
"c#",
"nhibernate",
""
] |
Consider the following code:
```
private static void WriteProcesses(StreamWriter sw, DateTime d) {
sw.WriteLine("List of processes @ " + d.ToString());
Process[] localAll = Process.GetProcesses().Where(o => o.ProcessName.ToLower() != "svchost");
if(localAll.Length... | Change
```
Process[] localAll = Process.GetProcesses().Where(o => o.ProcessName.ToLower() != "svchost");
```
to
```
Process[] localAll = Process.GetProcesses().Where(o => o.ProcessName.ToLower() != "svchost").ToArray();
```
`Where` is returning an `IEnumerable<Process>` on which you can call `ToArray` to convert to... | I think you'd be better off to just deal with it as an IEnumerable
```
private static void WriteProcesses(StreamWriter sw, DateTime d) {
sw.WriteLine("List of processes @ " + d.ToString());
var localAll = Process.GetProcesses()
.Where(o => o.ProcessName.ToLower() != "svchost"); ... | Correct use of Lambda query | [
"",
"c#",
".net",
"linq",
"lambda",
""
] |
I get the following error:
```
Unhandled Exception: System.IO.IOException: The parameter is incorrect.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.__Error.WinIOError()
at System.Console.set_OutputEncoding(Encoding value)
at (my program)
```
when I run the following line of ... | Encoding.Unicode is UTF-16 which uses 2 bytes to encode all characters. The ASCII characters (English characters) are the same in UTF-8 (single bytes, same values), so that might be why it works.
My guess is that the Windows Command Shell doesn't fully support Unicode. Funny that the Powershell 2 GUI does support UTF-... | According to the list of [Code Page Identifiers on MSDN](http://msdn.microsoft.com/en-us/library/dd317756(VS.85).aspx), the UTF-16 and UTF-32 encodings are managed-only:
```
1200 utf-16 Unicode UTF-16, little endian byte order (BMP of ISO 10646); available only to managed applications
1201 unicodeFFFE Unico... | "The parameter is incorrect" when setting Unicode as console encoding | [
"",
"c#",
"encoding",
""
] |
I have an object not written by myself that I need to clone in memory. The object is not tagged `ICloneable` or `Serializable` so deep cloning through the interface or serialization will not work. Is there anyway to deep clone this object? A non-safe win32 API call maybe? | FYI Interfaces marked as `ICloneable` are not necessarily deep copied. It is up to the implementer to implement `ICloneable` and there is no guarantee they will have cloned it.
You say the object doesn't implement `ISerializable` but does it have the `Serializable` attribute?
Creating a deep copy via binary serializa... | The "deep" is the tricky bit. For a shallow copy, you could use reflection to copy the fields (assuming none are readonly, which is a big assumption) - but it would be very hard to get this to work (automatically) otherwise.
The other option is to provide the serializer yourself (and serialize to deep-clone) - a "seri... | Can I deep clone a c# object not tagged ICloneable or Serializable? | [
"",
"c#",
"clone",
""
] |
The last I used was [weka](http://www.cs.waikato.ac.nz/ml/weka/)
. The last I heard java was coming up with an API (JDM) for it. Can anyone share their experiences with the tools. I am mostly interested in using the tools for classification/clustering (weka does a decent job here) and the tool should have good API supp... | I have used Weka for text classification. It was nice. The [book](http://www.cs.waikato.ac.nz/~ml/weka/book.html) is also nice. The idea of a framework where you can keep the data representation and modify the algorithm is great. | I am using [RapidMiner](http://rapid-i.com/content/blogcategory/38/69/) (formerly YALE from Univ. of Dortmund). Its a Java-based open source tool and implements most of the popular classifier/clustering methods. And it also ships with algorithms implemented for the Weka toolkit, so there are more options there. Comes w... | What data mining application to use? | [
"",
"java",
"data-mining",
""
] |
Does anyone know of a way to issue commands to a hard drive within Java? Does Java even support this kind of hardware interaction?
For example, if I have a SCSI hard drive that I would like to inquiry, is there a pre-existing Java method to do this, or would I have to write my own?
<http://en.wikipedia.org/wiki/SCSI>... | Java doesn't support talking directly to hardware like that. However, you can use JNI to call a C/C++ function from Java that can. | Three words "JNI or JNA". I strongly recommend taking a look at the latter to see if it suits your situation, instead of just opting for JNI. | issuing hard drive commands with java | [
"",
"java",
"hard-drive",
"scsi",
""
] |
Hopefully a simple question. Take for instance a Circularly-linked list:
```
class ListContainer
{
private listContainer next;
<..>
public void setNext(listContainer next)
{
this.next = next;
}
}
class List
{
private listContainer entry;
<..>
}
```
Now since it's a circularly-linked list, when a s... | Garbage collectors which rely solely on reference counting are generally vulnerable to failing to collection self-referential structures such as this. These GCs rely on a count of the number of references to the object in order to calculate whether a given object is reachable.
Non-reference counting approaches apply a... | Circular references is a (solvable) problem if you rely on counting the references in order to decide whether an object is dead. No java implementation uses reference counting, AFAIK. Newer Sun JREs uses a mix of several types of GC, all mark-and-sweep or copying I think.
You can read more about garbage collection in ... | How does Java Garbage collector handle self-reference? | [
"",
"java",
"garbage-collection",
""
] |
Here the context for my question:
A common technique is to declare the parameter of a method as a Lambda expression rather than a delegate. This is so that the method can examine the expression to do interesting things like find out the names of method calls in the body of the delegate instance.
Problem is that you l... | Everywhere that you're using the term "lambda expression" you actually mean "expression tree".
A lambda expression is the bit in source code which is
```
parameters => code
```
e.g.
```
x => x * 2
```
Expression trees are instances of the [System.Linq.Expressions.Expression](http://msdn.microsoft.com/en-us/library... | I don't believe it's possible to achieve what you'd like here. From the comments in your code it looks like you are attempting to capture the name of the property which did the assignment in MethodThatTakesExpression. This requires an expression tree lambda expression which captures the contexnt of the property access.... | Is it possible to cast a delegate instance into a Lambda expression? | [
"",
"c#",
"lambda",
"resharper",
"expression-trees",
""
] |
What is it best to handle pagination? Server side or doing it dynamically using javascript?
I'm working on a project which is heavy on the ajax and pulling in data dynamically, so I've been working on a javascript pagination system that uses the dom - but I'm starting to think it would be better to handle it all serve... | The right answer depends on your priorities and the size of the data set to be paginated.
**Server side pagination is best for:**
* Large data set
* Faster initial page load
* Accessibility for those not running javascript
**Client side pagination is best for:**
* Small data set
* Faster subsequent page loads
So i... | Doing it on client side will make your user download all the data at first which might not be needed, and will remove the primary benefit of pagination.
The best way to do so for such kind of AJAX apps is to make AJAX call the server for next page and add update the current page using client side script. | Pagination: Server Side or Client Side? | [
"",
"javascript",
"pagination",
"client-side",
"server-side",
""
] |
I'm pointing the .Net command line WSDL utility that ships with Visual Studio 2005 at a web service implemented in Java (which I have no control over) and it spits out the following error:
```
WSDL : error WSDL1: Unable to cast object of type 'System.Xml.XmlElement'
to type 'System.Web.Services.Description.ServiceDes... | Try specifying the option **protocol [SOAP12](http://msdn.microsoft.com/en-us/library/microsoft.web.services3.soap12_properties.aspx)**
/protocol:protocol ([as show on MSDN](http://msdn.microsoft.com/en-us/library/7h3ystb6.aspx))
Specifies the protocol to implement. You can specify SOAP (default), HttpGet, HttpPost, ... | Is this an XSD File? files have dependencies. Download the dependency files and place them side/by/side with the XSD you downloaded.
I would assume visual studio may fetch dependencies.
If this doesn't solve it, please provide more details. | .Net WSDL command line utility error | [
"",
"c#",
".net",
"visual-studio-2005",
"soap",
"wsdl.exe",
""
] |
What is the proper place to explain error handling in a try-catch statement? It seems like you could put explanatory comments at either the beginning of the try block or the catch block.
```
// Possible comment location 1
try
{
// real code
}
// Possible comment location 2
catch
{
// Possible comment locati... | I usually do the following. If there's only one exception being handled, I usually don't bother since it should be self-documenting.
```
try
{
real code // throws SomeException
real code // throws SomeOtherException
}
catch(SomeException se)
{
// explain your error handling choice if it's not obvious
}
... | **"A comment is a lie"**. Work on those variable names and the general logic so you can avoid it. And if you really need to lie, do it inside the catch block. | Commenting try catch statements | [
"",
"c#",
"error-handling",
"comments",
""
] |
How can I find out which FORM an HTML element is contained within, using a simple/small bit of JavaScript? In the example below, if I have already got hold of the SPAN called 'message', how can I easily get to the FORM element?
```
<form name="whatever">
<div>
<span id="message"></span>
</div>
</form>
... | **The form a form element belongs to can be accessed through `element.form`.**
When the element you are using as reference is not a form element, you'd still have to iterate through the `parentElement` or use some other kind of selector.
Using prototype, you could simplify this by using [Element.up()](http://www.prot... | Why not just use:
```
var nodesForm = node.form;
```
?
It works on FF3, FF4, google chrome, Opera, IE9 (I tested myself) | Finding the FORM that an element belongs to in JavaScript | [
"",
"javascript",
"html",
"webforms",
""
] |
We want to be able to create log files from our Java application which is suited for later processing by tools to help investigate bugs and gather performance statistics.
Currently we use the traditional "log stuff which may or may not be flattened into text form and appended to a log file", but this works the best fo... | It appears that the Lilith log viewer contains an XML-format which is well suited for dealing with the extra facilities available in logback and not only the log4j things.
It is - for now - the best bet so far :)
---
I adapted the log4j xmllayout class to logback, which works with chainsaw.
---
As I have not been ... | Unfortunately, I can't give you the answer you are looking for, but I would like to warn you of something to consider when logging to XML. For example:
```
<log>
<msg level="info">I'm a log message</msg>
<msg level="info">I'm another message</msg>
<!-- maybe you won't even get here -->
<msg level="fatal">My server... | Best XML format for log events in terms of tool support for data mining and visualization? | [
"",
"java",
"logging",
"visualization",
"data-mining",
"error-logging",
""
] |
It's been ages since I've written a COM dll. I've made a couple of classes now, that inherit from some COM interfaces, but I want to test it out. I know I have to put a GUID somewhere and then register it with regsvr32, but what are the steps involved?
Edit: Sorry, forgot to mention I'm using C++. | To create a new ATL COM project you can proceed as follow:
1. File/New Project
2. Visual C++/ATL/ATL Project
3. Customize it settings, and press finish when done
You have created a new dll, but it is empty, to add a COM object you can do this:
1. Project/Add Class
2. Visual C++/ATL/ATL simple object, press add
3. Gi... | You need to write a function called [DllGetClassObject](http://msdn.microsoft.com/en-us/library/ms680760(VS.85).aspx) and export it. That function is responsible for allocating a "class factory", which you also have to write, and which is in turn capable of allocating instances of your COM object. It has to implement [... | How do you create a COM DLL in Visual Studio 2008? | [
"",
"c++",
"visual-studio-2008",
"com",
"dll",
"guid",
""
] |
On Unix, I can either use `\r` (carriage return) or `\b` (backspace) to overwrite the current line (print over text already visible) in the shell.
Can I achieve the same effect in a Windows command line from a Python script?
I tried the curses module but it doesn't seem to be available on Windows. | yes:
```
import sys
import time
def restart_line():
sys.stdout.write('\r')
sys.stdout.flush()
sys.stdout.write('some data')
sys.stdout.flush()
time.sleep(2) # wait 2 seconds...
restart_line()
sys.stdout.write('other different data')
sys.stdout.flush()
``` | I know this is old, but i wanted to tell my version (it works on my PC in the cmd, but not in the idle) to override a line in Python 3:
```
>>> from time import sleep
>>> for i in range(400):
>>> print("\r" + str(i), end="")
>>> sleep(0.5)
```
**EDIT:**
It works on Windows and on Ubuntu | How can I overwrite/print over the current line in Windows command line? | [
"",
"python",
"windows",
"command-line",
"overwrite",
"carriage-return",
""
] |
I have this long and complex source code that uses a RNG with a **fix** seed.
This code is a simulator and the parameters of this simulator are the random values given by this RNG.
When I execute the code in the same machine, no matter how many attempts I do the output is the same. But when I execute this code on two ... | It is certainly possible, as the RNG may be combining machine specific data with the seed, such as the network card address, to generate the random number. It is basically implementation specific. | As they do give different results it is obviously possible that they give different results. Easy-to-answer question, next!
Seriously: without knowing the source code to the RNG itโs hard to know whether youโre observing a bug or a feature. But it sounds like the RNG in question is using a second seed from somewhere e... | C++. Is it possible that a RNG gives different random variable in two different machines using the same seed? | [
"",
"c++",
"gcc",
"random",
""
] |
How can i convert this to a decimal in SQL? Below is the equation and i get the answer as 78 (integer) but the real answer is 78.6 (with a decimal) so i need to show this as otherwise the report won't tally up to 100%
```
(100 * [TotalVisit1]/[TotalVisits]) AS Visit1percent
``` | ```
convert(decimal(5,2),(100 * convert(float,[TotalVisit1])/convert(float,[TotalVisits]))) AS Visit1percent
```
Ugly, but it works. | Try This:
```
(100.0 * [TotalVisit1]/[TotalVisits]) AS Visit1percent
``` | How do I calculate percentages with decimals in SQL? | [
"",
"sql",
"decimal",
"sum",
""
] |
I have a database that I used specifically for logging actions of users. The database has a few small tables that are aimed at specific types of actions. This data is rarely searched, but the rowcounts of the tables are starting to climb into multi-millions. I haven't noticed a large slow down, but I want to know if in... | This all depends on your empirical research. Take a copy of the database onto a different environment and run a profiler while running searches and inserts with and without indexes. Measure the performance and see what helps. :) | Rather than indexes, I think you should consider having no indexes on the table where you insert the rows into, and then replicate the table(s) (and possibly apply indexes) to use specifically for querying. | To Index or Not to Index | [
"",
"sql",
"indexing",
"sql-server-2000",
""
] |
I want to declare two beans and instantiate them using Spring dependency injection?
```
<bean id="sessionFactory" class="SessionFactoryImpl">
<property name="entityInterceptor" ref="entityInterceptor"/>
</bean>
<bean id="entityInterceptor" class="EntityInterceptorImpl">
<property name="sessionFactory" ref="sessionF... | Unfortunately the way container initialization works in Spring, a bean can only be injected in another bean once it is fully initialized. In your case you have a circular dependency that prevents either bean to be initialized because they depend on each other. To get around this you can implement BeanFactoryAware in on... | neesh is right, Spring doesn't do this out of the box.
Interdependent beans hint at a design problem. The "clean" way to do this is to redesign your services in such a way that there are no such odd dependencies, of course provided that you have control over the implementations. | How to wire Interdependent beans in Spring? | [
"",
"java",
"spring",
"dependency-injection",
""
] |
In PHP, we (at least the good programmers) always start general variable names with a lower-case letter, but class variables/objects with an upper-case letter to distinguish them. In the same way we start general file names with a lower case letter, but files containing Classes with an upper case letter.
E.g.:
```
<?... | Generally, all variables will start with lower case:
```
int count = 32;
double conversionFactor = 1.5d;
```
Some people like to put static constants in all case:
```
public static final double KILOGRAM_TO_POUND = 2.20462262;
```
Things get more annoying when you deal with acronyms, and there is no real standard on... | You can find the naming in the [Java Code Conventions](http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html#367).
A quick summary:
* For classes, use [upper camel case](https://en.wikipedia.org/wiki/Camel_case).
* For class members and local variables use [lower camel case](https://en.wikipedia.org/wiki/C... | Variable naming conventions in Java | [
"",
"java",
"naming-conventions",
"oop",
""
] |
I've just found [IPython](http://ipython.scipy.org/) and I can report that I'm in deep love. And the affection was immediate. I think this affair will turn into something lasting, like [the one I have with screen](https://stackoverflow.com/questions/431521/run-a-command-in-a-shell-and-keep-running-the-command-when-you-... | I use Linux, but I believe this tip can be used in OS X too. I use [GNU Screen](http://www.gnu.org/software/screen/) to send IPython commands from Vim as recommended by [this tip](http://vim.wikia.com/wiki/IPython_integration). This is how I do it:
First, you should open a terminal and start a screen session called 'i... | This questions is stale now, but just for reference - if you're using IPython 0.11 with ZeroMQ enabled, take a look at [vim-ipython](https://github.com/ivanov/vim-ipython) (an older version of which shipped with 0.11).
Using this plugin, you can send lines or whole files for IPython to execute, and also get back objec... | Advice regarding IPython + MacVim Workflow | [
"",
"python",
"vim",
"ipython",
""
] |
I often want to define new 'Exception' classes, but need to have an appropriate constructor defined because constructors aren't inherited.
```
class MyException : public Exception
{
public:
MyException (const UString Msg) : Exception(Msg)
{
};
}
```
Typedefs don't work for this, because they are simply aliase... | If you really want to have new classes derived from Exception, as opposed to having a template parameterized by a parameter, there is no way around writing your own constructor that just delegates the arguments without using a macro. C++0x will have the ability what you need by using something like
```
class MyExcepti... | ```
// You could put this in a different scope so it doesn't clutter your namespaces.
template<struct S> // Make S different for different exceptions.
class NewException :
public Exception
{
public:
NewException(const UString Msg) :
Exception(Msg)
{
}
};
// Create some n... | Can I use templates instead of macros for Exception class creation? | [
"",
"c++",
"templates",
"constructor",
""
] |
I am currently playing around with the Asp.Net mvc framework and loving it compared to the classic asp.net way. One thing I am mooting is whether or not it is acceptable for a View to cause (indirectly) access to the database?
For example, I am using the controller to populate a custom data class with all the informat... | Your view isn't really causing data access. The view is simply calling the GetDiscount() method in a model interface. It's the **model** which is causing data access. Indeed, you could create another implementation of IProduct which wouldn't cause data access, yet there would be no change to the view.
Model objects th... | > One thing I am mooting is whether or not it is acceptable for a View to cause (indirectly) access to the database?
I've often asked the same question. So many things we access on the Model in Stack Overflow Views can cause implicit database access. It's almost unavoidable. Would love to hear others' thoughts on this... | ASP.Net Mvc - Is it acceptable for the View to call functions which may cause data retrieval? | [
"",
"c#",
"asp.net-mvc",
"model-view-controller",
""
] |
I've looked at [this](https://stackoverflow.com/questions/316007/what-is-the-best-way-to-make-the-output-of-one-stream-the-input-to-another) and it wasn't much help.
I have a Ruby program that puts a question to the cmd line and I would like to write a Python program that can return an answer. Does anyone know of any ... | ```
p = subprocess.Popen(['ruby', 'ruby_program.rb'], stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
ruby_question = p.stdout.readline()
answer = calculate_answer(ruby_question)
p.stdin.write(answer)
print p.communicate()[0] # prints further info ruby may show.
```
The last ... | If you're on unix / linux you can use piping:
```
question.rb | answer.py
```
Then the output of question.rb becomes the input of answer.py
I've not tried it recently, but I have a feeling the same syntax might work on Windows as well. | How do I take the output of one program and use it as the input of another? | [
"",
"python",
"ruby",
"io",
""
] |
I have a table where one column has duplicate records but other columns are distinct. so something like this
Code SubCode version status
1234 D1 1 A
1234 D1 0 P
1234 DA 1 A
1234 DB 1 P
5678 BB 1 A
5678 BB 0 P
5678 BP 1 A
5678 BJ 1 A
0987 HH 1 A
So in the above table. subcode and Version are unique values whe... | ```
INSERT theTempTable (Code)
SELECT t.Code
FROM theTable t
LEFT OUTER JOIN theTable subT ON (t.Code = subT.Code AND subT.status <> 'A')
WHERE subT.Code IS NULL
GROUP BY t.Code
```
This should do the trick. The logic is a little tricky, but I'll do my best to explain how it is derived.
The outer join combi... | It's a little unclear as to whether or not the version column comes into play. For example, do you only want to consider rows with the largest version or if ANY subcde has an "A" should it count. Take 5678, BB for example, where version 1 has an "A" and version 0 has a "B". Is 5678 included because at least one of subc... | grouping records in one temp table | [
"",
"sql",
""
] |
Is there a pdf library attached/that can be attached to .NET 3.5 that allows creation of pdf files at runtime i.e opening a new pdf file, writing to it line by line, embedding images, etc and closing the pdf file all in C# code?
What I want is a set of tools and specifications which allow me to implement a customised ... | iTextSharp
<http://itextsharp.sourceforge.net/>
Complex but comprehensive.
[itext7](https://github.com/itext/itext7-dotnet) former iTextSharp | iTextSharp is no longer licensed under the MIT/LGPL license. Versions greater than 4.1.6 are licensed under the Affero GPL, meaning you can't even use it in a SaaS (Software as a Service) scenario without licensing your code under the GPL, or a GPL-compatible license.
Other opensource PDF implementations in native .NE... | Creating pdf files at runtime in c# | [
"",
"c#",
"pdf",
""
] |
I'm trying to build my own inversion of control container. Right now I store the objects with their types in a dictionary and resolve a reference when asked. But I want to make it possible to resolve a reference or a new instance. I can create a new instance with the Activator class. But, what if the constructor of the... | I decided to split it in to methods. A Resolve, that gives back the instance stored in the container. And a Create that instanciate a new instance.
something like:
```
public T Create<T>()
{
if (registeredTypes.ContainsKey(typeof(T)))
return (T)Activator.CreateInstance(register... | Checkout <http://funq.codeplex.com>. This is a very tiny Container that uses lambda expressions to define the function to resolve. Handles multiple parameters. | How to resolve instances with constructor parameters in custom IOC Container? | [
"",
"c#",
"dependency-injection",
"inversion-of-control",
"ioc-container",
""
] |
I'm using django and when users go to www.website.com/ I want to point them to the index view.
Right now I'm doing this:
```
(r'^$', 'ideas.idea.views.index'),
```
However, it's not working. I'm assuming my regular expression is wrong. Can anyone help me out? I've looked at python regular expressions but they didn't... | What you have should work (it does for me). Make sure it's in the top `urls.py`, and it should also be at the top of the list. | Just put an empty raw regular expression: r''
I tested here and it worked perfectly.
```
urlpatterns = patterns('',
url(r'', include('homepage.urls')),
)
```
Hope it help!
EDIT:
You can also put:
```
urlpatterns = patterns('',
url(r'\?', include('homepage.urls')),
)
```
The question mark makes the bar op... | What is the regular expression for the "root" of a website in django? | [
"",
"python",
"regex",
"django",
"django-urls",
""
] |
I've some questions .. and I really need your help.
1. I have an application.
First I display a splash screen, a form, and this splash would call another form.
**Problem**: When the splash form is displayed, if I then open another application on the top of the splash, and then minimize this newly opened applic... | 3) You have to set the "HelpButton" property of the form to true. However the "?" button is only visible if you deactivate the maximize and minimize buttons by setting "MinimizeBox" and "MaximizeBox" to false. | Here are a few...
1) you need to launch the window in another thread so that your app can do what it needs to do to start. When the startup finishes, signal to the splash screen that it can close itself.
2)
```
dropDownList.SelectedIndex = 0;
```
4) I would not recommend doing so. It is based on the system color sc... | Five Questions regarding the use of C# / VisualStudio 2005 | [
"",
"c#",
"visual-studio-2005",
""
] |
I am building a basic profiler for an open source project. One requirement is to measure execution time of a method. While this is easy enough, I have to do it without knowing the method or its containing class until runtime. The way to invoke the profiler will be when the user will invoke the profiler from the IDE in ... | Maybe you need
```
t.GetType().GetMethod(s)
``` | The error is caused because typeof expects a type name or parameter like typeof(int) or typeof(T) where T is a type parameter. It looks like t is an instance of System.Type so there is no need for the typeof.
Do you need a generic type for this? Will this not work?
```
public void DoSomething(object obj, string metho... | Using generics and methodinfo | [
"",
"c#",
".net",
"reflection",
""
] |
What is the best way to block certain input keys from being used in a TextBox with out blocking special keystrokes such as `Ctrl`-`V`/`Ctrl`-`C`?
For example, only allowing the user to enter a subset of characters or numerics such as A or B or C and nothing else. | I would use the keydown-event and use the e.cancel to stop the key if the key is not allowed. If I want to do it on multiple places then I would make a user control that inherits a textbox and then add a property AllowedChars or DisallowedChars that handle it for me. I have a couple of variants laying around that I use... | I used the [Masked Textbox](http://www.c-sharpcorner.com/UploadFile/jibinpan/MaskedTextBoxControl11302005051817AM/MaskedTextBoxControl.aspx) control for winforms. There's a longer explanation about it [here](http://en.csharp-online.net/MaskedTextBox). Essentially, it disallows input that doesn't match the criteria for ... | Input handling in WinForm | [
"",
"c#",
"winforms",
"keyboard",
"user-input",
""
] |
I am trying to resolve Euler Problem 18 -> <http://projecteuler.net/index.php?section=problems&id=18>
I am trying to do this with c++ (I am relearning it and euler problems make for good learning/searching material)
```
#include <iostream>
using namespace std;
long long unsigned countNums(short,short,short array[][... | Ok so first off, I'm a little unclear as to what you think the problem is. I can't parse that second-last sentence at all...
Secondly you might want to re-think your design here. Think about functions that perform a single discrete task and are not intertwined with the rest of the application (ie read up on "tightly c... | I've solved this problem. Given the nature of Project Euler is to solve the problem on your own ("photocopying a solved crossword puzzle doesn't mean you solved it") and that I don't want to ruin this for someone else, all I can really say is that your solution looks overly complex.
You can, however, solve this proble... | Triangle problem | [
"",
"c++",
"puzzle",
""
] |
I am asking about the best tool that you used before to convert a c# windows forms application into asp.net?
I already [googled](http://www.google.com/search?q=convert+windows+forms+into+asp.net&rls=com.microsoft:en-us&ie=UTF-8&oe=UTF-8&startIndex=&startPage=1) about this topic and found alot of tools but I want someon... | I really wouldn't recommend using a tool to do the conversion. Web applications and WinForms are fundamentally different, and should be *designed* differently. Even with the vast amount of Ajax kicking around these days, you still need to bear in mind the whole stateless HTTP model.
If you don't want to rethink the ap... | [@Jon Skeet](https://stackoverflow.com/questions/412763/convert-windows-forms-application-into-asp-net#412774) has the best advice. That said, let's examine the results of the Google link you provided. What would happen?
The majority of the on-topic (for the query) results are other programmers asking essentially the ... | Convert Windows Forms application into Asp.net | [
"",
"c#",
"asp.net",
"winforms",
""
] |
We wrote a small Windows class library that implements extension methods for some standard types (strings initially). I placed this in a library so that any of our projects would be able to make use of it by simply referencing it and adding using XXX.Extensions.
A problem came up when we wanted to use some of these me... | You cannot set a reference from a Silverlight assembly to a regular .NET assembly but you can do so the other way round.
So create a shared Silverlight assembly and add your code to that assembly. Now you can set a reference fro both your regular .NET and you other Silverlight assembly to the shared Silverlight assemb... | Since this question has been answered, there is a new solution from Microsoft, [Portable Class Libraries](http://msdn.microsoft.com/en-us/library/gg597391.aspx). [Here](http://blogs.msdn.com/b/bclteam/archive/2011/01/19/announcing-portable-library-tools-ctp-justin-van-patten.aspx) is the blog post where they announced ... | Sharing C# code between Windows and Silverlight class libraries | [
"",
"c#",
"windows",
"silverlight",
"sharing",
""
] |
I'd like to be able to replace things in a file with a regular expression using the following scheme:
I have an array:
```
$data = array(
'title' => 'My Cool Title',
'content' => ''
)
```
I also have a template (for clarity's sake, we'll assume the below is assigned to a variable *$template*)
```
<html>
<title>... | With a little work before hand you can do it with a single `preg_replace` call:
```
$replacements = array();
foreach ($data as $search => $replacement) {
$replacements["/<% $search %>/"] = $replacement;
}
$endMarkup = preg_replace(
array_keys($replacements),
array_values($replacements),
$template);... | You could try without regex if you wanted to. The function str\_replace was made for this. If you don't understand regex this will be the best option for you.
Test data:
```
$data = array(
'title' => 'My Cool Title',
'content' => ''
);
$file = <<< EOF
<html>
<title><% title %></title>
<body><% content %></body>
... | Super Basic Templating System | [
"",
"php",
"templates",
""
] |
I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:
```
for i in range(0, len(ints), 4):
# dummy op ... | As of Python 3.12, [the `itertools` module gains a `batched` function](https://docs.python.org/3.12/library/itertools.html#itertools.batched) that specifically covers iterating over batches of an input iterable, where the final batch may be incomplete (each batch is a `tuple`). Per the example code given in the docs:
... | ```
def chunker(seq, size):
return (seq[pos:pos + size] for pos in range(0, len(seq), size))
```
Works with any sequence:
```
text = "I am a very, very helpful text"
for group in chunker(text, 7):
print(repr(group),)
# 'I am a ' 'very, v' 'ery hel' 'pful te' 'xt'
print('|'.join(chunker(text, 10)))
# I am a v... | How to iterate over a list in chunks | [
"",
"python",
"list",
"loops",
"optimization",
"chunks",
""
] |
I want to get myself into programming some serious GUI based applications, but when I look at things like Swing/SWT from Java, I can't help but HATE programming a GUI interface by creating "widget" objects and populating them and calling methods on them.
I think GUI design should be done in a separate text-based file ... | You can try Mozilla's XUL. It supports Python via XPCOM.
See this project: [pyxpcomext](http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xulrunner_about.html)
XUL isn't compiled, it is packaged and loaded at runtime. Firefox and many other great applications use it, but most of them use Javascript fo... | You should look into Qt, which you can use from Python using the excellent PyQt interface (why they didn't name it QtPy --- cutiepie, get it ? --- I will never understand).
With Qt, you can have the choice of constructing your GUI's programmatically (which you don't want), or using XML markup. This XML file can either... | Markup-based GUI for python | [
"",
"python",
"user-interface",
"markup",
""
] |
I'm not quite sure when selecting only a certain number of rows would be better than simply making a more specific select statement. I have a feeling I'm missing something pretty straight forward but I can't figure it out. I have less than 6 months experience with any SQL and it's been cursory at that so I'm sorry if t... | I know of two common uses:
Paging : be sure to specify an ordering. If an ordering isn't specified, many db implementations use whatever is convenient for executing the query. This "optimal" ordering behavior could give very unpredictable results.
```
SELECT top 10 CustomerName
FROM Customer
WHERE CustomerID > 200 --... | Custom paging, typically. | When is the proper time to use the SQL statement "SELECT [results] FROM [tables] WHERE [conditions] FETCH FIRST [n] ROWS ONLY" | [
"",
"sql",
"select",
""
] |
I am in need of a popupwindow with the option of a radio button. I have tested with [Impromtu](http://en.wikipedia.org/wiki/Impromptu_%28programming_environment%29). Is any easy made Popupwindow plugin available?
My plugin should work in Internetย Explorer, Mozilla and Google Chrome. What would some sample code be? | [jqModal](http://dev.iceburg.net/jquery/jqModal/) is great and easy-to-use for building Modal Popups and the like.
If you want a tutorial on how to build one yourself without jQuery, check out [this tutorial](http://slayeroffice.com/code/custom_alert/). | Check out [Thickbox](http://jquery.com/demo/thickbox/)! You can use a div or so on your page as content (see inline content demo). | PopupWindow in jQuery | [
"",
"javascript",
"jquery",
"popupwindow",
""
] |
I'm having some problems getting my object to gracefully fail out if an invalid parameter is given during instantiation. I have a feeling it's a small syntax thing somewhere that I simply need fresh eyes on. Any help is more than appreciated.
```
class bib {
protected $bibid;
public function __construct($new_bib... | You can't return in a constructor in PHP - the object is still created as normal.
You could use a factory or something similar;
```
if(!$bib = Bib_Factory::loadValidBib('612e436')){
echo 'Error Message';
} else {
//do what I intend to do with the object
}
```
Or throw an exception in the constructor and use ... | I see several problems in this code.
* First of all, I think you want to do something like this:
$myBib=new bib();
if($myBib->validate\_bibid('612e436'))
{ ..do stuff.. }
(or something similar)
remember that \_\_construct is not a normal method. It's a constructor, and it shouldn't return anything. It alr... | Class Instantiation Fails | [
"",
"php",
"oop",
"class",
""
] |
I am inserting the HTML response from an AJAX call into my page, but then when I try to access those elements after they have been created, it fails..
This is how i retrieve and insert the HTML:
```
$.ajax({url: 'output.aspx',
data: 'id=5',
type: 'get',
datatype: 'html',
success: function(outData) {$('#... | How are you checking to see whether your AJAX call has completed? Because it's asynchronous, the elements will not, of course, be available to the code which executes immediately after your `$.ajax(โฆ)` call.
Try manipulating those elements from within the `success` function or in other code which is called from there ... | Are you sure your actual request is successful? If nothing is selected, the most probably reason is that nothing was actually inserted into #my\_container in the first place. | Access DOM elements after ajax.load | [
"",
"javascript",
"jquery",
"dom",
"client-side",
""
] |
I have a reference-type variable that is `readonly`, because the reference never change, only its properties. When I tried to add the `volatile` modifier to it the compiled warned me that it wouldn't let both modifiers apply to the same variable. But I think I need it to be volatile because I don't want to have caching... | Neither the `readonly` nor `volatile` modifiers are penetrative. They apply to the reference itself, not the object's properties.
The `readonly` keyword assertsโand enforcesโthat a *variable* cannot change after initialization. The variable is the small chunk of memory where the reference is stored.
The `volatile` ke... | A readonly field can only be written when the object is first constructed. Therefore there won't be any caching issue on the CPU because the field is immutable and can't possibly change. | Why readonly and volatile modifiers are mutually exclusive? | [
"",
"c#",
".net",
"multithreading",
"readonly",
"volatile",
""
] |
I am getting an undefined index on my config page and it reads:
> **Notice**: Undefined index: SERVER\_ADDR in **inc/config
> .inc.php** on line **3**
Any idea on how I can fix that? I know its warning, but would still like to get at it. I am using it to check for the address whether to use my local or remote config ... | If you haven't done so, make sure you're accessing SERVER\_ADDR using the $\_SERVER array to obtain the value of SERVER\_ADDR, which is an element of this array.
```
$_SERVER['SERVER_ADDR'];
```
If that doesn't work, it may mean that your server doesn't provide that information.
From [PHP.net](http://ca.php.net/manu... | The accepted answer is correct, but take note that on Windows IIS 7 (and above, to the best of my knowledge) you must use:
```
$_SERVER['LOCAL_ADDR']
```
instead of
```
$_SERVER['SERVER_ADDR']
``` | SERVER_ADDR undefined index | [
"",
"php",
""
] |
Is there a way to check if a ValidationSummary control has its IsValid property set to true using Javascript in the OnClientClick event of a button?
What I'm trying to do is to show a message that says "please wait while your file is uploading" on an upload page, but if I use javascript to show that message, it shows ... | In case others need something like this, here is my solution:
In the button's OnClientClick event, I'm calling a javascript function called showContent(). In this function, I use setTimeout to call a second function that checks the page's IsValid property:
```
function showContent()
{
setTimeout("delayedShow()",... | If you have several validation groups on single page then you should check only certain group:
```
var isValid = Page_ClientValidate('GroupName');
``` | Check if ValidationSummary is Valid using OnClientClick | [
"",
"asp.net",
"javascript",
"validation",
"upload",
""
] |
It's quite some time that I'm trying to figure out this problem and from googling around many people have similar problems.
I'm trying to model a User in a Social Network, using Hibernate, and what is more basic to a social network than to map a friendship relation?
Every user in the system should have a list of it's ... | The fact about Many to Many is that it needs a little more configuration, because its imperative that Hibernate generates a relation table.
Try this:
```
@Entity
@Table(name="users")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="userid")
protected Long id = null;
@M... | The `ManyToMany` annotation has a mappedBy parameter. I guess something like
```
@ManyToMany(mappedBy = "friends")
```
might work. In any case, see the [docs](http://www.hibernate.org/hib_docs/annotations/reference/en/html_single/#eentity-mapping-association-collection-manytomany).
Edit:
It seems as if a many to ma... | Hibernate: Mapping User-Friends relation in Social Networks | [
"",
"java",
"hibernate",
"annotations",
"hibernate-mapping",
""
] |
before posting the whole code, i wanted to make sure I am not missing a simple issue here.
```
var dv = $(myElement);
var pos = dv.offset();
var width = dv.width();
var height = dv.height();
alert(pos);
alert(width);
alert(height);
```
here, width alerts fine, height alerts fine but offset alerts [object Object] (i... | that's correct: the `offset()` function returns an object containing two properties, `left` and `top`. (See [the docs](http://docs.jquery.com/CSS/offset)). "[object Object]" is how most objects are converted to strings.
I'd suggest you install Firebug to help you with debugging Javascript like this as it would give yo... | Please also test with console.log() rather then alert() | jQuery offset doesn't produce value | [
"",
"javascript",
"jquery",
"css",
""
] |
In his The C++ Programming Language Stroustrup gives the following example for inc/dec overloading:
```
class Ptr_to_T {
T* p;
T* array ;
int size;
public:
Ptr_to_T(T* p, T* v, int s); // bind to array v of size s, initial value p
Ptr_to_T(T* p); // bind to single object, initial value p
Ptr_to... | To understand better, you have to imagine (or look at) how are these operators implemented. Typically, the prefix operator++ will be written more or less like this:
```
MyType& operator++()
{
// do the incrementation
return *this;
}
```
Since `this` has been modified "in-place", we can return a reference to t... | The postfix operator returns a copy of the value before it was incremented, so it pretty much has to return a temporary. The prefix operator does return the current value of the object, so it can return a reference to, well, its current value. | overloaded increment's return value | [
"",
"c++",
"operator-overloading",
""
] |
After peeking around the internet it looks like it is possible to interop between C# and Matlab. I am wondering if anyone has had success with it and what they did to do so. If possible somehow pulling it off without the use of COM. Thanks for your time. | Yes, quite possible. Though I ended up using the C interface and calling into that using a mixed-mode DLL (and getting C# to call into that... but that was because I was also interfacing with some other C code). It's quite straightforward. On computers where you want to run your program, you'll need to install Matlab R... | Beginning with the R2009a release of MATLAB, .NET objects can be accessed from MATLAB:
<http://www.mathworks.com/help/techdoc/matlab_external/brpb5k6.html>
In older versions of MATLAB, it is possible to access .NET objects from MATLAB using CCW:
<http://www.mathworks.com/support/solutions/data/1-5U8HND.html?solution... | Interoperating between Matlab and C# | [
"",
"c#",
".net",
"matlab",
"interop",
"matlab-deployment",
""
] |
SQLAlchemy's `DateTime` type allows for a `timezone=True` argument to save a non-naive datetime object to the database, and to return it as such. Is there any way to modify the timezone of the `tzinfo` that SQLAlchemy passes in so it could be, for instance, UTC? I realize that I could just use `default=datetime.datetim... | <http://www.postgresql.org/docs/8.3/interactive/datatype-datetime.html#DATATYPE-TIMEZONES>
> All timezone-aware dates and times are stored internally in UTC. They are converted to local time in the zone specified by the timezone configuration parameter before being displayed to the client.
The only way to store it wi... | One way to solve this issue is to always use timezone-aware fields in the database. But note that the same time can be expressed differently depending on the timezone, and even though this is not a problem for computers it is very inconvenient for us:
```
2003-04-12 23:05:06 +01:00
2003-04-13 00:05:06 +02:00 # This is... | SQLAlchemy DateTime timezone | [
"",
"python",
"postgresql",
"datetime",
"sqlalchemy",
"timezone",
""
] |
What JS/CSS trick can I use to prevent copy&paste of numbers in an ordered list?
```
<OL>
<LI>A
<LI>B
<LI>C
</OL>
```
1. A- B- C
If it's not doable, what alternative are available?
thanks | What about using a table like in
<http://bugzilla.gnome.org/attachment.cgi?id=127131> | The copying of the numbers of an OL is a browser behaviour. I believe some browsers don't but most do.
You could use JavaScript to rewrite the code once the page loads so that it looks the same but isn't underneath. This would fix your copying problem but cause other problems such as accessibility.
Essentially the wa... | Line numbering and copy/paste (HTML/CSS) | [
"",
"javascript",
"html",
"css",
""
] |
I'm looking for a python project to use as example to copy the design of the unit test parts.
The project should have these features:
1. its code is almost fully unit tested
2. the code is distributed in many packages, there are more that one level of packages
3. all the test can be run with a single command, for exa... | Maybe [Nose](http://code.google.com/p/python-nose/) itself? | [Django](http://www.djangoproject.com/) is a clean project that has a nice range of unit testing.
[Have a look](http://docs.djangoproject.com/en/dev/topics/testing/#topics-testing) at how they propose you test your own projects.
[Have a look](http://code.djangoproject.com/browser/django/trunk/tests) at the unit testi... | Where is a python real project to be used as example for the unit-test part? | [
"",
"python",
"unit-testing",
""
] |
I want to find all `if` statements and `for` statements which are not followed by curly brackets '`{`'. When you write a single line in an `if` statement you do not mostly enclose it in curly brackets, so I want to find all those `if` and `for` statements.
Please help!
Like I want to capture this statement
```
if (c... | Since the underlying mathematics disallow a perfect match, you could go for a good heuristic like "find all '`if`' followed by a semicolon without an intervening open brace:
```
/\<if\>[^{]*;/
```
where `\<` and `\>` are begin-of-word and end-of-word as applicable to your regex dialect. Also take care to ignore all n... | If you want a 100% working solution then a regex will not fit the bill. It's way too easy to trip up a regex with real code. Take for instance the following regex
```
"^\s*if\W[^{]*\n\s*[^{]"
```
This will match a good majority of "if" statements that are not surrounded by braces. However it can easily be broken. Tak... | i want to find all if statements in C# code which are not followed by brackets. Through regex | [
"",
"c#",
"regex",
"code-analysis",
""
] |
I want to know, how sockets are implemented in the Java Virtual Machine.
* Is there a native library included?
* And if, is it a C library?
Where can I find information about this topic?
The [offical Java tutorial on networking](http://java.sun.com/docs/books/tutorial/networking/TOC.html) does not help me there.
Som... | In the [network guide of Java 1.4.2](http://java.sun.com/j2se/1.4.2/docs/guide/net/socketOpt.html), an interesting piece of information is provided:
> **The implementation details...**
>
> ...that you don't need to know, unless you
> subclass
> SocketImpl/DatagramSocketImpl. **Every
> \*Socket object has an underlying... | Probably using the system-V socket calls exposed by the underlying platform, e.g. system-V under Unix, WinSock under Windows. The specification only dictates how a virtual machine must behave, so implementers are free to do as they wish. | How are sockets implemented in JVM? | [
"",
"java",
"sockets",
"network-programming",
"jvm",
""
] |
I was looking at the System.Net Namespace and it has an IPAddress instance you can use. This has a Parse method which you can use to parse a string into an IPInstance then use the Address property to give you the long value.
However...
The number returned is NOT the true conversion.
e.g. For IP 58.0.0.0 , the System... | This might work, will try it and see.
```
public double IPAddressToNumber(string IPaddress)
{
int i;
string [] arrDec;
double num = 0;
if (IPaddress == "")
{
return 0;
}
else
{
arrDec = IPaddress.Split('.');
for(i =... | Please see [How to convert an IPv4 address into a integer in C#?](https://stackoverflow.com/questions/461742/how-to-convert-an-ip-address-into-an-integer-in-c) | How do display the Integer value of an IPAddress | [
"",
"c#",
"vb.net",
"ip-address",
""
] |
What would be the easiest way to have a page where it will display a list of directories that the user can click on to open, where there will be more directories or eventually files to download and have it all happen on the same page? | For something basic you are probably better off just adding 'Options +Indexes' to an .htaccess for that folder. However if you want something more complicated and are running on PHP5 you can use the [Directory Iterator](https://www.php.net/manual/en/class.directoryiterator.php) to accomplish this. The most important th... | To remove index.php from the folder and allow directory browsing for that folder and subfolders in htacceess. | PHP list directories and files | [
"",
"php",
"directory",
""
] |
I have this struct:
```
struct Map
{
public int Size;
public Map ( int size )
{
this.Size = size;
}
public override string ToString ( )
{
return String.Format ( "Size: {0}", this.Size );
}
}
```
When using array, it works:
```
Map [ ] arr = new Map [ 4 ] {
new Map(10... | The C# compiler will give you the following error:
> Cannot modify the return value of 'System.Collections.Generic.List.this[int]' because it is not a variable
The reason is that structs are value types so when you access a list element you will in fact access an intermediate copy of the element which has been return... | Because it is a `struct`, when using the List<T>, you're are creating copies.
When using a struct, it is better to make them immutable. This will avoids effects like this.
When using an array, you have direct access to the memory structures. Using the List<T>.get\_Item you work on a return value, that is, a copy of t... | Directly modifying List<T> elements | [
"",
"c#",
".net",
""
] |
I have a chunk of code where it appears that a variable is changing at the end of a pre-processor block of code.
```
int initialKeyCount;
#if(DEBUG)
// int initialKeyCount = _root.CountAllKeys();
initialKeyCount = 20000;
#endif
currNode = currNode.EnsureDegreeKeysPresent(parent); //initialKeyCount... | Sounds like Visual Studio got confused. Try these steps in order
1. Use the Clean command
2. Restart Visual Studio
3. Delete every DLL and EXE that even remotely looks like your program
4. Double check every BIN and OBJ folder to see if you missed anything.
5. Search your whole hard drive for any DLL and EXE that even... | This sort of behaviour sounds very much like the debugger is running code that doesn't match the source code you are editing. Are you absolutely sure that your source changes are making it all the way to the code you're running?
The preprocessor blocks are unrelated to the language syntax. So, you're correct in saying... | Integer value changes when exiting preprocessor block | [
"",
"c#",
"c-preprocessor",
"variable-assignment",
""
] |
I've read on articles and books that the use of `String s = new String("...");` should be avoided pretty much all the time. I understand why that is, but is there any use for using the String(String) constructor whatsoever? I don't think there is, and don't see any evidence otherwise, but I'm wondering if anyone in the... | This is a good article: [String constructor considered useless turns out to be useful after all!](http://kjetilod.blogspot.com/2008/09/string-constructor-considered-useless.html)
> It turns out that this constructor can actually be useful in at least one circumstance. If you've ever peeked at the String source code, y... | If I remember correctly the only 'useful' case is where the original String is part of a much larger backing array. (e.g. created as a substring). If you only want to keep the small substring around and garbage collect the large buffer, it might make sense to create a new String. | Use of the String(String) constructor in Java | [
"",
"java",
"string",
"coding-style",
""
] |
I'm using **PHP 4.3.9, Apache/2.0.52**
I'm trying to get a login system working that registers DB values in a session where they're available once logged in. **I'm losing the session variables once I'm redirected**.
I'm using the following code to print the session ID/values on my login form page and the redirected p... | I don't see a `session_start()` in your login script. If you aren't starting the session I don't think php will save any data you place in the `$_SESSION` array. Also to be safe I'd explicitly place variables into the `$_SESSION` array instead of just overwriting the whole thing with `$_SESSION = mysql_fetch_array($res... | Try doing a
```
session_regenerate_id(true);
```
before the
```
session_write_close();
```
Also. The best way IMO to do a login script is this:
Let the login logic be handled within the mainpage the user is trying to access.
1. If the user is not authenticated, he is thrown back to the login page
2. If the user i... | PHP session variables not carrying over to my logged in page, but session ID is | [
"",
"php",
"session",
"redirect",
"variables",
""
] |
I've been doing a project at work recently focused on an almost entirely client-driven web site. Obviously Javascript is used heavily, and I've been using jQuery on top of it which has turned out to be an absolute pleasure to work with.
One of the things that has surprised me in this is how much I like the JSON object... | The canonical example is Lisp: in Lisp, the language isn't even defined in terms of text, it is defined in terms of data structures. There really is not difference between code and data: code is just a list whose first element is interpreted as an operation and the rest as operands.
Writing a program is just writing l... | Lua uses "tables" which are pretty much identical to javascript objects. | Language with similar object use to Javascript/JSON | [
"",
"javascript",
"json",
""
] |
I have this code below and the "if ((DateTime)DataReader[0] > DateTime.Now)" condition returns false even if the datetime in the database is greater than the datetimenow.
I used this code before and it use to work I never changed any thing.
So the question is why does the condition return false?
Thanks,
Simon
```
... | This is the actual answer:
You do not need/have/should to compare DateTime with >, <, == or != operators. Instead you can use the Compare and CompareTo methods of the DateTime class.
[Compare](http://msdn.microsoft.com/en-us/library/system.datetime.compare.aspx): Compares two instances of DateTime and returns an inte... | First of all it is a bad practice to work with DateTime that way. You should store value of DateTime.ToUniversalTime in the database and convert loaded DateTime to local time using DateTime.ToLocalTime method. Also it is not clear how much records will be returned from DB i.e. you can rewrite active several times. Just... | I have a condition comparing DateTime in C# using the < operator and it return's false even if it should not. Why? | [
"",
"c#",
""
] |
Having implemented CLogClass to make decent logging I also defined macro, but it works only with one parameter...
```
class CLogClass
{
public:
static void DoLog(LPCTSTR sMessage, ...);
};
#define DebugLog(sMessage, x) ClogClass::DoLog(__FILE__, __LINE__, sMessage, x)
```
Well, it fails when called with more ... | You could have a MYLOG macro returning a custom functor object which takes a variable number of arguments.
```
#include <string>
#include <cstdarg>
struct CLogObject {
void operator()( const char* pFormat, ... ) const {
printf( "[%s:%d] ", filename.c_str(), linenumber );
va_list args;
va_start( args, p... | Your questions actually appeals to two answers. You want to do the universal logging function, that works like printf but can be fully customise. So you need:
* macro taking a variable number of arguments
* function taking a variable number of arguments
Here is your code example adatapted:
```
#include <stdio.h>
#in... | Is this possible use ellipsis in macro? Can it be converted to template? | [
"",
"c++",
"visual-c++",
"logging",
"c-preprocessor",
""
] |
We are looking to implement Optimistic locking in our WCF/WPF application. So far the best way I've come up with doing this is to implement a generic Optimistic which will store a copy of the original and any changes (so it will store two copies: the original and modified) of any value object that can be modified. Is t... | If you are using SQL server you can use a timestamp column. The timestamp column is changed anytime a row is modified. Essentially when your updating the DB you can check if the timestamp column is the same as when the client first got the data, if so no one has modified the data.
# Edit
If you want to minimize the b... | One way of implementing optimistic locking logic is to base it on a last modified timestamp of a row. So the update will look as follows:
UPDATE .... WHERE id = x AND last\_updated = t
x: record id.
t: the last updated timestamp of the row when it was loaded from the database (i.e. before modifications).
Note that o... | Change Tracking Structure | [
"",
"c#",
".net",
"wpf",
"wcf",
"concurrency",
""
] |
I want to add a "Select One" option to a drop down list bound to a `List<T>`.
Once I query for the `List<T>`, how do I add my initial `Item`, not part of the data source, as the FIRST element in that `List<T>` ? I have:
```
// populate ti from data
List<MyTypeItem> ti = MyTypeItem.GetTypeItems();
/... | Use the [Insert](http://msdn.microsoft.com/en-us/library/sey5k5z4.aspx) method:
```
ti.Insert(0, initialItem);
``` | Since .NET 4.7.1, you can use the side-effect free [`Prepend()`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.prepend?view=netframework-4.8&viewFallbackFrom=netframework-4.7) and [`Append()`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.append?view=netframework-4.8). The ou... | How to add item to the beginning of List<T>? | [
"",
"c#",
"drop-down-menu",
"generic-list",
""
] |
In [this answer](https://stackoverflow.com/questions/452517/does-this-entity-repository-service-example-fit-into-domain-driven-design#452564) to a [recent question](https://stackoverflow.com/questions/452517), I was advised to
> "be wary of making every property in your domain model have public getters and setters. Tha... | I don't know if you can override the deserialization process with MVC, but note that `DataContractSerializer` supports non-public accessors, and there is a JSON version: [`DataContractJsonSerializer`](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx) - maybe wort... | You can always override the serialization or just write your own JSON deserialize method. I personally think it's not worth the effort. Just make the setter public and be done with it. What is the setter being private really buying you? | Conflict between avoiding anemic model and allowing serialization | [
"",
"c#",
"json",
"serialization",
""
] |
As far as I know, there's no way to use {% include %} within a dynamic JS file to include styles. But I don't want to have to make another call to the server to download styles.
Perhaps it would be possible by taking a stylesheet and injecting it into the head element of the document...has anyone does this before? | In your JS file:
```
var style = document.createElement('link');
style.setAttribute('rel', 'stylesheet');
style.setAttribute('type', 'text/css');
style.setAttribute('href', 'style.css');
document.getElementsByTagName('head')[0].appendChild(style);
```
Hope that helps. | With jquery...
```
$('head').append($('<link rel="stylesheet" type="text/css" href="style.css">'))
``` | Is it possible to use Django to include CSS (here's the tricky part) from a JS file? | [
"",
"javascript",
"css",
"django",
"dom",
""
] |
For part of a web application the user needs to import some data from a spreadsheet. Such as a list of names and email addresses. Currently we do this by asking the user to browse for and upload a CSV file.
Unfortunately, this isn't always possible as various corporate IT systems only allow users to access files from ... | This looks like a "delimited values" list to me, so basically the same as CSV with TAB as the field delimiter and line break as the row delimiter. You could try it with the [CSV Reader library from CodeProject](http://www.codeproject.com/KB/database/CsvReader.aspx), it should be handle to handle different delimiters, n... | try find something helpful in [System.Windows.Forms.Clipboard members](http://msdn.microsoft.com/en-us/library/system.windows.forms.clipboard_members.aspx) | How to parse a "cut n paste" from Excel | [
"",
"c#",
"asp.net",
"excel",
""
] |
I've got a form with a bunch of textboxes that are disabled by default, then enabled by use of a checkbox next to each one.
When enabled, the values in these textboxes are required to be a valid number, but when disabled they don't need a value (obviously). I'm using the jQuery Validation plugin to do this validation,... | Using the "ignore" option (<http://docs.jquery.com/Plugins/Validation/validate#toptions>) might be the easiest way for you to deal with this. Depends on what else you have on the form. For i.e. you wouldn't filter on disabled items if you had other controls that were disabled but you still needed to validate for some r... | Usually when doing this, I skip 'depends' and just use the `required` jQuery Validate rule and let it handle the checking based on the given selector, as opposed to splitting the logic between the validate rules and the checkbox click handler. I put together a [quick demo](http://www.command-tab.com/demos/checkbox_vali... | Using depends with the jQuery Validation plugin | [
"",
"javascript",
"jquery",
"jquery-validate",
""
] |
I have a class which has many small functions. By small functions, I mean functions that doesn't do any processing but just return a literal value. Something like:
```
string Foo::method() const{
return "A";
}
```
I have created a header file "Foo.h" and source file "Foo.cpp". But since the function is very small... | If the function is small (the chance you would change it often is low), and if the function can be put into the header without including myriads of other headers (because your function depends on them), it is perfectly valid to do so. If you declare them extern inline, then the compiler is required to give it the same ... | Depending on your compiler and it's settings it may do any of the following:
* It may ignore the inline keyword (it
is just a hint to the compiler, not a
command) and generate stand-alone
functions. It may do this if your
functions exceed a compiler-dependent
complexity threshold. e.g. too many
nested loop... | Writing function definition in header files in C++ | [
"",
"c++",
"performance",
"header-files",
""
] |
I am using an application in c++ that uses a special dprintf function to print information, this is an example:
```
dprintf(verbose, "The value is: %d", i);
```
What is doing is when I define verbose for test purposes then I print the information and when I am working in normal execution I do not define it and I do n... | I try to avoid using var-arg c-style functions for two main reasons:
* They are not type-safe, can't use operator<<
* They don't recognize when too few or many arguments were provided
I've made a way that works using `boost::fusion`, which is given arguments in a type-safe way. It iterates over those arguments, print... | ```
#ifdef DEBUG
#define dprintf(format, ...) real_dprintf(format, __VA_ARGS__)
#else
#define dprintf
#endif
```
Here real\_dprintf() is the "real" function that is invoked, and dprintf() is just a macro wrapping the call. | Print information in "test mode" but not in "normal execution" | [
"",
"c++",
"testing",
"printing",
""
] |
I am implementing a small queue to handle which process gets to run first. I am using a table in a database to do this. Here is the structure of the table (I'm mocking it up in SQLite):
```
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,
"identifier" VARCHAR NOT NULL ,
"priority_number" INTEGER DEFAULT 15,
"timest... | See if this works:
```
select * from queue_manager where priority_number =
(select min(priority_number) from queue_manager) and
timestamp = (select min(timestamp)
from queue_manager qm2
where qm2.priority_number = queue_manager.priority_number)
``` | ```
select * from queue_manager order by priority_number, timestamp LIMIT 1;
```
As for such called "database independency", it's a myth for most real world tasks. As a rule, you cannot even create schema in database-independent way. | Working out the SQL to query a priority queue table | [
"",
"sql",
"queue",
"priority-queue",
"queue-table",
""
] |
What garbage collectors are there available for C++? Are you using any of them? With what results? | The [Boost](http://www.boost.org/) library includes some shared\_ptr stuff that basically acts as a reference counting garbage collector. If you embrace the [RAII](http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization) principle of C++ design, that and auto\_ptr will fill your need for a "garbage collecto... | Several C++ GC are listed [on wikipedia](http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)#External_links).
However, I don't use any, RAII is also my friend. | What garbage collectors are there available for C++? | [
"",
"c++",
"garbage-collection",
""
] |
I have a script that did double inserts into the database with the same data. Is there a good way to do this (without scanning through, inserting every record into an array, and then deleting duplicate array entries)? | MySQL supports multi-table DELETE which is really cool and can help here. You can do a self-join on the equality of all columns except the `id`, and then delete the matching row with the greater `id`.
```
DELETE t2
FROM mytable t1 JOIN mytable t2
USING (column1, column2, column3) -- this is an equi-join
WHERE t1.id... | ```
DELETE
FROM t
WHERE ID IN (
SELECT MAX(ID)
FROM t
GROUP BY {Your Group Criteria Here}
HAVING COUNT(*) > 1
)
``` | How do I delete two rows that differ only by ID | [
"",
"sql",
"mysql",
""
] |
**EDIT**: This issue has been fixed by google in gtest 1.4.0; [see the original bug report](http://code.google.com/p/googletest/issues/detail?id=114) for more information.
I've recently switched to gtest for my C++ testing framework, and one great feature of it which I am presently unable to use is the ability to gene... | **Edit**: Google test has fixed this issue, which is included in the gtest 1.4.0 release. [See the original bug report](http://code.google.com/p/googletest/issues/detail?id=114) for more info.
Bah! I've finally found the cause of this problem -- it's because gtest produces one giant XML file for all test results, and ... | Here's how I do it:
```
<target name="junit" depends="compile-tests" description="run all unit tests">
<mkdir dir="${reports}"/>
<junit haltonfailure="false">
<jvmarg value="-Xms128m"/>
<jvmarg value="-Xmx128m"/>
<classpath>
<path refid="project.classpath"/>
... | Unable to get hudson to parse JUnit test output XML | [
"",
"c++",
"junit",
"hudson",
"googletest",
""
] |
Like every other web developer on the planet, I have an issue with users double clicking the submit button on my forms. My understanding is that the conventional way to handle this issue, is to disable the button immediately after the first click, however when I do this, **it doesn't post**.
I did do some research on ... | I think you're just missing this tag:
```
UseSubmitBehavior="false"
```
Try it like this:
```
<asp:Button ID="btnUpdate" runat="server" UseSubmitBehavior="false" OnClientClick="if(Page_ClientValidate()) { this.disabled = true; } else {return false;}" Text = "Update" CssClass="button" OnClick="btnUpdate_Click" Valida... | `UseSubmitBehavior="false"` converts submit button to normal button (`<input type="button">`). If you don't want this to happen, you can hide submit button and immediately insert disabled button on its place. Because this happens so quickly it will look as button becoming disabled to user. Details are at [the blog of J... | Why doesn't my form post when I disable the submit button to prevent double clicking? | [
"",
"asp.net",
"javascript",
"client-side",
"double-submit-prevention",
""
] |
I've created an ASP.Net user control that will get placed more than once inside of web page. In this control I've defined a javascript object such as:
```
function MyObject( options )
{
this.x = options.x;
}
MyObject.prototype.someFunction=function someFunctionF()
{
return this.x + 1;
}
```
In the code behind I'... | Your Javascript like this:-
```
function MyObject(options) { this.x = options.x; }
MyObject.prototype.someFunction = function() { return this.x + 1; }
MyObject.create(id, options) {
if (!this._instances) this._instances = {};
return this._instances[id] = new MyObject(options);
}
MyObject.getInstance(id) { retu... | Excellent solution Anthony. The other solutions offered were as good and I did consider them but I was looking for something a little more elegant like this solution.
Thanks! | Ideas on making a javascript object name unique in ASP.Net? | [
"",
"asp.net",
"javascript",
"function",
"prototype",
"unique",
""
] |
How to make this work in Opera? I found this piece of code for Opera, but it doesn't work for me:
```
function AddToFavorites(title, url) {
if (window.sidebar) { // Mozilla Firefox Bookmark
window.sidebar.addPanel(title, url,"");
return false;
}
else if( window.external ) { // IE Favorit... | *If* you insist on it, then do it without dynamically generated redundant links:
```
<a href="http://real.url.example.com" title="Bookmark me, pleaeease!"
rel="sidebar"
onclick="return !addToFav(this.href,this.title)">
```
but please, just don't do it.
As Opera user I will be grateful for not pushing that ... | ***Opera enforces the same user-event requirement*** to allow bookmarking, thus the code you have won't work, because the user never clicked on the link you just created.
You need something more like this:
```
function AddToFavorites(obj, title, url){
if(window.sidebar){
// Mozilla Firefox Bookmark
window.s... | "Add to favorites" with JavaScript in Opera | [
"",
"javascript",
"opera",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.