Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm working on an ASP.Net application and working to add some Ajax to it to speed up certain areas. The first area that I am concentrating is the attendance area for the teachers to report attendance (and some other data) about the kids. This needs to be fast.
I've created a dual-control set up where the user clicks o... | If speed/performance is a major concern for you, I would strongly suggest against UpdatePanels, as they cause a full page postback that drags the ViewState in the header, among other crap, and forces the page to go through the whole life cycle every time (even though the user doesn't see this).
You should be able to (... | Its a known issue with IE only, see [KB 2000262](http://support.microsoft.com/kb/2000262). A workaround/fix can be found [here](http://blog.devlpr.net/2009/09/01/updatepanel-async-postsback-slow-in-ie-part-3/). I worked with them on the script and its a shame they cannot put out a real fix. | UpdatePanel Slowness in IE | [
"",
"c#",
"jquery",
"asp.net",
"performance",
"updatepanel",
""
] |
It seems like there is a lot of overhead involved in rapidly opening and closing sqlconnections. Should I persist a connection (one, per client, per database), or continue declaring a new sqlconnection object whenever I need one, and making sure I clean up after myself?
What have you done? What worked well and what wo... | In most cases, .NET connection pooling handles this for you. Even though you're opening and closing connections via code, that's not what's happening behind the scenes. When you instantiate and open a connection, .NET looks for an existing connection in the connection pool with the same connectionstring and gives you t... | There is not much overhead since, by default settings, pools are stored in the connection pool. Thus, when you open a connection, often you'll just get a ready connection from the pool. Creating SqlConnections has not given me any troubles. | Should I persist a sqlconnection in my data access layer? | [
"",
".net",
"sql",
"ado.net",
""
] |
How do I create, execute and control a winform from within a console application? | The easiest option is to start a windows forms project, then change the output-type to Console Application. Alternatively, just add a reference to System.Windows.Forms.dll, and start coding:
```
using System.Windows.Forms;
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.Run(new ... | I recently wanted to do this and found that I was not happy with any of the answers here.
If you follow Marc's advice and set the output-type to Console Application there are two problems:
1) If you launch the application from Explorer, you get an annoying console window behind your Form which doesn't go away until y... | how to run a winform from console application? | [
"",
"c#",
"winforms",
"console-application",
""
] |
One of the "best practice" is accessing data via stored procedures. I understand why is this scenario good.
My motivation is split database and application logic ( the tables can me changed, if the behaviour of stored procedures are same ), defence for SQL injection ( users can not execute "select \* from some\_tables"... | First: for your delete routine, your where clause should only include the primary key.
Second: for your update routine, do not try to optimize before you have working code. In fact, do not try to optimize until you can profile your application and see where the bottlenecks are. I can tell you for sure that updating on... | For reading data, you do not need a stored procedure for security or to separate out logic, you can use views.
Just grant only select on the view.
You can limit the records shown, change field names, join many tables into one logical "table", etc. | Accessing data with stored procedures | [
"",
"sql",
"sql-server-2005",
"stored-procedures",
"crud",
""
] |
I hear that tr1::result\_of gets used frequently inside of Boost... I'm wondering if there are any good (simple) use cases for tr1::result\_of I can use at home. | A description of result\_of is given at [open\_std.org](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1454.html). Microsoft has a quick example of a [unit test wrapper](http://msdn.microsoft.com/en-us/library/bb982028.aspx) that uses result\_of. | There are no simple cases. However, it's used in `BOOST_AUTO`, which can be used, e.g., in
```
BOOST_AUTO(x, make_pair(a, b));
``` | What is a good use case for tr1::result_of? | [
"",
"c++",
"stl",
"boost",
"tr1",
"use-case",
""
] |
I am designing a simple internal framework for handling time series data.
Given that LINQ is my current toy hammer, I want to hit everything with it.
I want to implement methods in class TimeSeries (Select(), Where() and so on) so that I can use LINQ syntax to handle time series data
Some things are straight forward,... | If I'm understanding the question correctly, you want to join multiple sequences based on their position within the sequence?
There isn't anything in the `System.Linq.Enumerable` class to do this as both the `Join` and `GroupJoin` methods are based on join keys. However, by coincidence I wrote a `PositionalJoin` metho... | `Union` sounds like the right way to go - no query expression support, but I think it expresses what you mean.
You might be interested in looking at the Range-based classes in [MiscUtil](http://pobox.com/~skeet/csharp/miscutil) which can be nicely used for times. Combined with a bit of extension method fun, you can do... | "Join" of time series | [
"",
"c#",
"linq",
"linq-to-objects",
"time-series",
""
] |
For example, I'm writing a multi-threaded time-critical application that processes and streams audio in real-time. Interruptions in the audio are totally unacceptable. Does this mean I cannot use the STL because of the potential slow down when an exception is thrown? | It's not clearly written in the previous answers, so:
## Exceptions happen in C++
Using the STL or not won't remove the RAII code that will free the objects's resources you allocated.
For example:
```
void doSomething()
{
MyString str ;
doSomethingElse() ;
}
```
In the code above, the compiler will generat... | Generally, the only exceptions that STL containers will throw by themselves is an std::bad\_alloc if new fails. The only other times are when user code (for example constructors, assignments, copy constructors) throws. If your user code never throws then you only have to guard against new throwing, which you would have... | Can I use the STL if I cannot afford the slow performance when exceptions are thrown? | [
"",
"c++",
"performance",
"exception",
""
] |
I'm using Java's [Transformer](http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/transform/Transformer.html) class to process an XML Document object.
This is the code that creates the Transformer:
```
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Tran... | Note that `<svg xmlns="SVGNS" />` is the same as `<svg:svg xmlns:svg="SVGNS" />`.
Did you check you called `setNamespaceAware(true)` on your `DocumentBuilderFactory` instance ? | The package description for [javax.xml.transform](http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/transform/package-summary.html#package_description) has a section *Qualified Name Representation* which seems to imply that it is possible to get the namespace represented in both input and output.
It isn't really clear... | Java XML: how to output the namespace of child elements? | [
"",
"java",
"xml",
""
] |
Anyone know of a good free winforms html editor for .NET. Ideally I would like html and preview modes along with the possibility of exporting to a pdf, word doc or similar.
Although the export I could probably create myself from the html output.
Another nice feature would be a paste from word that removes all the ext... | You can use the [WebBrowser](https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/webbrowser-control-windows-forms) control in design mode with a second `WebBrowser` control set in view mode.
In order to put the `WebBrowser` control in design mode, you can use the following code.
This code is a super ... | ```
//CODE in C#
webBrowser1.Navigate("about:blank");
Application.DoEvents();
webBrowser1.Document.OpenNew(false).Write("<html><body><div id=\"editable\">Edit this text</div></body></html>");
foreach (HtmlElement el in webBrowser1.Document.All)
{
el.SetAttribute("unselectable", "on");
el.SetAttribute("content... | winforms html editor | [
"",
"c#",
".net",
"html",
"winforms",
""
] |
## Scenario
I have two wrappers around Microsoft Office, one for 2003 and one for 2007. Since having two versions of Microsoft Office running side by side is "not officially possible" nor recommended by Microsoft, we have two boxes, one with Office 2003 and the other with Office 2007. We compile the wrappers separatel... | When the .NET assembly resolver is unable to find a referenced assembly at runtime (in this case, it cannot find the particular wrapper DLL version the application was linked against), its default behavior is to fail and essentially crash the application. However, this behavior can be overridden by hooking the AppDomai... | Just a thought - could you use TlbExp to create two interop assemblies (with different names and assemblies), and use an interface/factory to code against the two via your own interface? Once you have the interop dll, you don't need the COM dependency (except of course for testing etc).
TlbImp has a /asmversion for th... | Compile a version agnostic DLL in .NET | [
"",
"c#",
".net",
"visual-studio-2008",
"dll",
"version",
""
] |
Is it possible to get the originating port from an ActionExecutingContext object? If so, how? | Yes, look at `ActionExecutingContext.HttpContext.Request.Url.Port;` | use this:
context.HttpContext.Request.Path
OR
context.HttpContext.Request.PathBase | Get originating port from ActionExecutingContext? | [
"",
"c#",
"asp.net-mvc",
"logging",
""
] |
We're seeing `JTable` selection get cleared when we do a `fireTableDataChanged()` or `fireTableRowsUpdated()` from the `TableModel`.
Is this expected, or are we doing something wrong? I didn't see any property on the `JTable` (or other related classes) about clearing/preserving selection on model updates.
If this is ... | You need to preserve the selection and then re-apply it.
First of all you will need to get a list of all the selected cells.
Then when you re-load the JTable with the new data you need to programmatically re-apply those same selections.
The other point I want to make is, if the number or rows or columns in your tabl... | You can automatically preserve a table's selection if the STRUCTURE of that table hasn't changed (i.e. if you haven't add/removed any columns/rows) as follows.
If you've written your own implementation of TableModel, you can simply override the fireTableDataChanged() method:
```
@Override
public void fireTableDataCha... | Preserve JTable selection across TableModel change | [
"",
"java",
"swing",
"jtable",
"tablemodel",
""
] |
It seems like there should be a simpler way than:
```
import string
s = "string. With. Punctuation?" # Sample string
out = s.translate(string.maketrans("",""), string.punctuation)
```
Is there? | From an efficiency perspective, you're not going to beat
```
s.translate(None, string.punctuation)
```
For higher versions of Python use the following code:
```
s.translate(str.maketrans('', '', string.punctuation))
```
It's performing raw string operations in C with a lookup table - there's not much that will beat... | Regular expressions are simple enough, if you know them.
```
import re
s = "string. With. Punctuation?"
s = re.sub(r'[^\w\s]','',s)
``` | Best way to strip punctuation from a string | [
"",
"python",
"string",
"punctuation",
""
] |
I recently added JQuery's date-picker control to a project. In Internet Exploder, I get the following error message:
> Internet Explorer cannot open the
> Internet site
>
> <http://localhost/>
>
> Operation aborted
What is causing this problem? | **There was a related question earlier today**:
[**Operation Aborted Error in IE**](https://stackoverflow.com/questions/266585/operation-aborted-error-in-ie7)
This is a common problem.
It occurs in IE when a script tries to modify the DOM before the page is finished loading.
Take a look at what sort of scripts are ... | Just elaborating Keparo's answer.
You can put your script inside one of the following functions(as per the library you are using) and that will resolve the issue.
```
prototype.js:
document.observe(’dom:loaded’, function () { /* your script goes here */ }),
jquery:
jQuery(document).ready(function () { /* your script... | What is the "Operation Aborted" error in Internet Explorer? | [
"",
"javascript",
"internet-explorer",
""
] |
Is it possible to create an attribute that can be initialized with a variable number of arguments?
For example:
```
[MyCustomAttribute(new int[3,4,5])] // this doesn't work
public MyClass ...
``` | Attributes will take an array. Though if you control the attribute, you can also use `params` instead (which is nicer to consumers, IMO):
```
class MyCustomAttribute : Attribute {
public int[] Values { get; set; }
public MyCustomAttribute(params int[] values) {
this.Values = values;
}
}
[MyCustomA... | You can do it, but it isn't CLS compliant:
```
[assembly: CLSCompliant(true)]
class Foo : Attribute
{
public Foo(string[] vals) { }
}
[Foo(new string[] {"abc","def"})]
static void Bar() {}
```
Shows:
```
Warning 1 Arrays as attribute arguments is not CLS-compliant
```
For regular reflection usage, it may be ... | Can I initialize a C# attribute with an array or other variable number of arguments? | [
"",
"c#",
"attributes",
""
] |
**I have class A:**
```
public class ClassA<T>
```
**Class B derives from A:**
```
public class ClassB : ClassA<ClassB>
```
**Class C derives from class B:**
```
public class ClassC : ClassB
```
**Now I have a generic method with constraints**
```
public static T Method<T>() where T : ClassA<T>
```
OK, now I wa... | Well, you could change Method to:
```
public static T Method<T,U>() where T : ClassA<U> where U : T
```
Does that help at all? It's not much use if you can't change Method of course... | No. You must change or wrap this method.
Here is the reason.
ClassC inherits from ClassB which inherits from ClassA(ClassB)
ClassC does not inherit from ClassA(ClassC)
No child of ClassB will inherit from ClassA(child class), because they instead inherit from ClassB and ClassB does not inherit from ClassA(child cla... | Generic contraints on derived classes | [
"",
"c#",
"generics",
"subsonic",
"constraints",
""
] |
This code does not seem to compile, I just need to write something to a small log text file (a new row to end of file).
```
<%@ Import Namespace="System.IO" %>
void Page_Load( object sender, EventArgs e ){
FileSystem myFileSystem = new FileSystem();
myFileSystem.WriteAllText(logFile, hash, false);
``` | I can't see any class called FileSystem in [the `System.IO` namespace](http://msdn.microsoft.com/en-us/library/system.io.aspx). Is this something new in .NET 4.0 which you're trying to use?
Note that the [`File`](http://msdn.microsoft.com/en-us/library/system.io.file.aspx) class has a *static* method called [`WriteAll... | FileSystem is a class from the VisualBasic namespace:
<http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.filesystem.aspx>
Have a look at the FileStream class in C#:
<http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx> | How to write something to .txt log file from .aspx page (c#) | [
"",
"c#",
".net",
"logging",
"asp.net",
""
] |
I'm trying to create a table with two columns comprising the primary key in MySQL, but I can't figure out the syntax. I understand single-column PKs, but the syntax isn't the same to create a primary key with two columns. | ```
CREATE TABLE table_name
(
c1 INT NOT NULL,
c2 INT NOT NULL,
PRIMARY KEY (c1, c2)
)
``` | Try:
```
create table .....
primary key (`id1`, `id2`)
)
``` | How do I declare a multi-column PK in MySQL | [
"",
"mysql",
"sql",
"database",
"ddl",
""
] |
If I had a phone number like this
```
string phone = "6365555796";
```
Which I store with only numeric characters in my database **(as a string)**, is it possible to output the number like this:
```
"636-555-5796"
```
Similar to how I could if I were using a number:
```
long phone = 6365555796;
string output = pho... | Best I can think of without having to convert to a long/number and so it fits one line is:
```
string number = "1234567890";
string formattedNumber = string.Format("{0}-{1}-{2}", number.Substring(0,3), number.Substring(3,3), number.Substring(6));
``` | Be aware that not everyone uses the North American 3-3-4 format for phone numbers. European phone numbers can be up to 15 digits long, with significant punctuation, e.g. +44-XXXX-XXXX-XXXX is different from 44+XXXX-XXXX-XXXX. You are also not considering PBXs and extensions, which can require over 30 digits.
Military ... | Can I Format A String Like A Number in .NET? | [
"",
"c#",
".net",
"formatting",
""
] |
I have been asked to write a testing application that needs to test a new stored procedure on multiple rows in a database, in essence I want to do something like this:
```
[Test]
public void TestSelect()
{
foreach(id in ids)
{
DataTable old = Database.call("old_stored_proc",id);
DataTable new_ ... | 1) If the id's are constant and not looked up at test run time, create a separate unit test fixture for each id. That way you will know which id's are actually failing. See here for a write up on the problems with data driven tests:
<http://googletesting.blogspot.com/2008/09/tott-data-driven-traps.html>
2) If you ne... | Seems like you are just Asserting the wrong thing. If you want to check all the values and then assert that there are no errors (or show the number of errors) then try this:
```
[Test]
public void TestSelect()
{
int errors = 0;
foreach(id in ids)
{
DataTable old = Database.call("old_stored_proc",id... | NUnit: Running multiple assertions in a single test | [
"",
"c#",
"unit-testing",
"nunit",
""
] |
In Visual Studio, I can select the "Treat warnings as errors" option to prevent my code from compiling if there are any warnings. Our team uses this option, but there are two warnings we would like to keep as warnings.
There is an option to suppress warnings, but we DO want them to show up as warnings, so that won't w... | In Visual Studio 2022 we have a new Project Properties UI which includes an editor for this.
Under *Build | Errors and Warnings* if you set *Treat warnings as errors* to *All*, then another property appears which allows you to exempt specific warnings from being treated as errors:
[;
```
Then just set the control's Visible property to true/false. It doesn't seem to be working, I ... | The "Visible" property of an ASP.NET control determines whether or not it will be rendered on the client (i.e. sent to the client). If it is false when the page is rendered, it will never arrive at the client.
So, you cannot, technically, set that property of the control.
That said, if the control *is* rendered on th... | instead of using visible, set its css to display:none
```
//css:
.invisible { display:none; }
//C#
txtEditBox.CssClass = 'invisible';
txtEditBox.CssClass = ''; // visible again
//javascript
document.getElementById('txtEditBox').className = 'invisible'
document.getElementById('txtEditBox').className = ''
``` | How do you set the "Visible" property of a ASP.NET control from a Javascript function? | [
"",
"asp.net",
"javascript",
""
] |
Following techniques from 'Modern C++ Design', I am implementing a persistence library with various compile-time optimisations. I would like the ability to dispatch a function to a templated member variable if that variable derives from a given class:
```
template<class T, template <class> class Manager = DefaultManag... | Overloading can be useful to implement compile-time dispatching, as proposed by *Alexandrescu* in his book "Modern C++ Design".
You can use a class like this to transform at compile time a boolean or integer into a type:
```
template <bool n>
struct int2type
{ enum { value = n}; };
```
The following source code show... | You require a kind of compile-time `if`. This then calls a function depending on which case is `true`. This way, the compiler won't stumble upon code which it can't compile (because that is safely stored away in another function template that never gets instantiated).
There are several ways of realizing such a compile... | Compile-time type based dispatch | [
"",
"c++",
"templates",
""
] |
Similar question as [this one](https://stackoverflow.com/questions/56722/automated-processing-of-an-email-in-java) but for a Microsoft Environment.
Email --> Exchange Server -->[something]
For the [something] I was using Outlook 2003 & C# but it *feels* messy (A program is trying to access outlook, this could be a vi... | [This](http://www.codeproject.com/KB/IP/NetPopMimeClient.aspx) library provides you basic support for the POP3 protocol and MIME, you can use it to check specified mailboxes and retrieve emails and attachments, you can tweak it to your needs.
Here is [another library](http://www.codeproject.com/KB/IP/imaplibrary.aspx)... | I've been happy with the [Rebex components](http://www.rebex.net/mail.net/) which provide IMAP access. Of course you need to ensure your Exchange administrators will open an IMAP port on your Exchange servers. | Automated processing of an Email in C# | [
"",
"c#",
"outlook-2003",
""
] |
Should I be writing Doc Comments for all of my java methods? | @Claudiu
> When I write code that others will use - Yes. Every method that somebody else can use (any public method) should have a javadoc at least stating its obvious purpose.
@Daniel Spiewak
> I thoroughly document every public method in every API class. Classes which have public members but which are not intended... | If the method is, obviously self evident, I might skip a javadoc comment.
Comments like
```
/** Does Foo */
void doFoo();
```
Really aren't that useful. (Overly simplistic example, but you get the idea) | Do you use Javadoc for every method you write? | [
"",
"java",
"api",
"javadoc",
""
] |
I can't seem to get my application up and running on my dev server and I'm not sure why.
I have compiled my code in VS 2008 with a target framework of 3.5. I am using 3.5 mainly because I have implemented LINQ rather extensively. Compiling and runs local without any problems.
The hang up is that my server only has th... | You can just copy over the 3.5 dlls onto the server. You can absolutely run 3.5 code on a 2.0 server. | You are right in that 3.5 runs on the 2.0 CLR, but 3.5 contains libraries and if you have used any of those, you're out of luck unless you install 3.5 on that server.
There are plenty of options for a 3.5 program to not run correctly on only 2.0, so I'd consider downgrading the program, or upgrading the server.
---
... | Problems executing compiled 3.5 code on a server which only has the 2.0 framework | [
"",
"c#",
"asp.net",
".net-3.5",
""
] |
I'm just trying to get a general idea of what views are used for in RDBMSes. That is to say, I know what a view is and how to make one. I also know what I've used them for in the past.
But I want to make sure I have a thorough understanding of what a view is useful for and what a view shouldn't be useful for. More spe... | *1) What is a view useful for?*
> **IOPO** In One Place Only
>
> •Whether you consider the data itself or the queries that reference the joined tables, utilizing a view avoids unnecessary redundancy.
>
> •Views also provide an abstracting layer preventing direct access to the tables (and the resulting handc... | In a way, a view is like an interface. You can change the underlying table structure all you want, but the view gives a way for the code to not have to change.
Views are a nice way of providing something simple to report writers. If your business users want to access the data from something like Crystal Reports, you c... | What are views good for? | [
"",
"sql",
"view",
"rdbms-agnostic",
""
] |
We need to handle this event in the base form, regardless of which controls currently have focus. We have a couple of global key commands that need to work regardless of control focus.
This works by handling the PreviewKeyDown event in the form normally. When we add a user control to the form, the event no longer fire... | We ended up doing this:
I found a workaround for this by setting up a hidden menu item by setting:
```
ToolStripMenuItem.Visible = false
```
(Thanks to [this article)](http://blogs.msdn.com/jfoscoding/archive/2005/01/24/359334.aspx).
It appears that the Main Menu of a form always gets searched for your shortcut key... | The hidden menu you are using works fine for shortcuts that are valid menu item shortcuts, but if you want to use any key as a shortcut (such as Page Up/Page Down), you'll need a different trick.
Another way to do this that doesn't involve P/Invoke is to set the `Form.KeyPreview` property of your form to true. This wi... | Always handle the PreviewKeyDown event in a base form | [
"",
"c#",
"winforms",
""
] |
I've got a collection (List<Rectangle>) which I need to sort left-right. That part's easy. Then I want to iterate through the Rectangles in their *original* order, but easily find their index in the sorted collection. indexOf() won't work, since I may have a number of equal objects. I can't help feeling there should be... | I've found a solution - but perhaps there is a neater/more optimal one out there.
```
List<Rectangle> originalRects = ...;
/* record index of each rectangle object.
* Using a hash map makes lookups efficient,
* and using an IdentityHashMap means we lookup by object identity
* not value.
*/
IdentityHashMap<Rectang... | If you don't have tens of thousands of objects, you could just store them in two separate collections, one original, one sorted. Remember that collection classes in Java only store *references* to objects, so this doesn't take up as much memory as it might seem. | How to map sorted index back to original index for collection I'm sorting | [
"",
"java",
"sorting",
"collections",
""
] |
What's a good way to generate an icon in-memory in python? Right now I'm forced to use pygame to draw the icon, then I save it to disk as an .ico file, and then I load it from disk as an ICO resource...
Something like this:
```
if os.path.isfile(self.icon):
icon_flags = win32con.LR_LOADFROMFILE | win32con... | You can use [wxPython](http://wxpython.org/) for this.
```
from wx import EmptyIcon
icon = EmptyIcon()
icon.CopyFromBitmap(your_wxBitmap)
```
The [wxBitmap](http://docs.wxwidgets.org/stable/wx_wxbitmap.html#wxbitmap) can be generated in memory using [wxMemoryDC](http://docs.wxwidgets.org/stable/wx_wxmemorydc.html#wxm... | You can probably create a object that mimics the python file-object interface.
<http://docs.python.org/library/stdtypes.html#bltin-file-objects> | Create an icon in memory with win32 in python | [
"",
"python",
"windows",
"winapi",
"icons",
""
] |
I need to check the `RequestType` of an `HttpRequest` in ASP.NET (or `WebRequest.Method`). I know that I can just use the string values "`POST`" or "`GET`" for the request type, but I could have sworn there was a constant somewhere in some class in .NET that contained the values.
Out of curiosity I was wondering if an... | ```
System.Net.WebRequestMethods.Http
.Connect = "CONNECT"
.Get = "GET"
.Head = "HEAD"
.MkCol = "MKCOL"
.Post = "POST"
.Put = "PUT"
```
Ultimately, though; since `const` expressions are burned into the caller, this is identical to using "GET" etc, just without the risk of a typo. | Also exists [`System.Net.Http.HttpMethod`](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpmethod) which can serve instead of enum. You can compare them `aMethod == HttpMethod.Get`, etc. To get string method name call e.g. `HttpMethod.Get.Method`. | Where is the constant for "HttpRequest.RequestType" and "WebRequest.Method" values in .NET? | [
"",
"c#",
".net",
"asp.net",
""
] |
Let's imagine I got this:
index.php generates form with unpredictable number of inputs with certain IDs/Names and different values that can be edited by user and saved by script.php
```
<form action="script.php" method="post">
<input id="1" name="1" type="text" value="1"/>
<input id="24" name="24" type="text" value="... | i may be missing something in your question, but the `$_POST` variable will contain all the name => value pairs you're asking for. for example, in your above HTML snippet:
```
print_r($_POST);
// contains:
array
(
[1] => 1
[24] => 2233
[55] => 231321
)
// example access:
foreach($_POST as $name => $value) {
... | Use an array\_keys on the $\_POST variable in script.php to pull out the names you created and use those to get the values.
```
$keys = array_keys( $_POST );
foreach( $keys as $key ) {
echo "Name=" . $key . " Value=" . $_POST[$key];
}
``` | Is there some list of input's IDs or names of Form after the script was sent? | [
"",
"php",
"html",
"forms",
"numbers",
"input",
""
] |
I often have to convert a retreived value (usually as a string) - and then convert it to an int. But in C# (.Net) you have to choose either int16, int32 or int64 - how do you know which one to choose when you don't know how big your retrieved number will be? | Everyone here who has mentioned that declaring an Int16 saves ram should get a downvote.
The answer to your question is to use the keyword "int" (or if you feel like it, use "Int32").
That gives you a range of up to 2.4 billion numbers... Also, 32bit processors will handle those ints better... also (and **THE MOST IM... | Just wanted to add that... I remembered that in the days of .NET 1.1 the compiler was optimized so that **'int' operations are actually faster than byte or short operations.**
I believe it still holds today, but I'm running some tests now.
---
EDIT: I have got a surprise discovery: the add, subtract and multiply ope... | Converting to int16, int32, int64 - how do you know which one to choose? | [
"",
"c#",
"integer",
"typeconverter",
""
] |
[This article](http://blogs.msdn.com/larryosterman/archive/2004/09/10/228068.aspx) gives a good overview on why structured exception handling is bad. Is there a way to get the robustness of stopping your server from crashing, while getting past the problems mentioned in the article?
I have a server software that runs ... | Break your program up into worker processes and a single server process. The server process will handle initial requests and then hand them off the the worker processes. If a worker process crashes, only the users on that worker are affected. Don't use SEH for general exception handling - as you have found out, it can ... | Using SEH because your program crashes randomly is a bad idea. It's not magic pixie dust that you can sprinkle on your program to make it stop crashing. Tracking down and fixing the bugs that cause the crashes is the right solution.
Using SEH when you really need to handle a structured exception is fine. Larry Osterma... | Structured exception handling with a multi-threaded server | [
"",
"c++",
"exception",
"seh",
""
] |
I've never used [SOAP](http://en.wikipedia.org/wiki/SOAP) before and I'm sort of new to Python. I'm doing this to get myself acquainted with both technologies. I've installed [SOAPlib](http://trac.optio.webfactional.com/wiki/soaplib) and I've tried to read their [Client](http://trac.optio.webfactional.com/wiki/Client) ... | ***Update (2016):***
If you only need SOAP client, there is well maintained library called [zeep](https://pypi.org/project/zeep/). It supports both Python 2 and 3 :)
---
***Update:***
Additionally to what is mentioned above, I will refer to [Python WebServices](https://wiki.python.org/moin/WebServices#SOAP) page wh... | I followed the advice of other answers to this question and gave [SUDS](https://fedorahosted.org/suds "SUDS") a try. After using it "in anger" I must agree: SUDS is very nice! Highly recommended!
I did run into trouble calling HTTPS-based web services from behind a proxy. At the time of this writing, this affects **al... | What SOAP client libraries exist for Python, and where is the documentation for them? | [
"",
"python",
"soap",
"soap-client",
""
] |
I want to do something like:
```
exec sproc1 and sproc2 at the same time
when they are both finished exec sproc3
```
I can do this in dts.
Is there a way to do it in transact sql?
Or is there a way to do it with a batch script (eg vbs or powershell)? | sp \_ start \_ job
I'm doing a similar thing at the moment, and the only way I've found to avoid using SSIS or some external shell is to split my load routine into 'threads' manually, and then fire a single master sqlagent job which in turn executes as many sp \_ start \_ job's as I have threads. From that point, they... | You could create a CLR Stored Procedure that (using C#) would call the first two on their own threads, and then block until both are complete... then run the third one.
Are you able to use CLR sprocs in your situation? If so, I'll edit this answer to have more detail. | How can I run sql server stored procedures in parallel? | [
"",
"sql",
"sql-server",
"t-sql",
"parallel-processing",
"dts",
""
] |
I just noticed that java.beans.Introspector getBeanInfo does not pickup any superinterface's properties. Example:
```
public interface Person {
String getName();
}
public interface Employee extends Person {
int getSalary();
}
```
Introspecting on Employee only yields salary even though name is inherited from ... | This issue is covered in Sun bug
[java.beans.Introspector doesn't work for interfaces](https://bugs.java.com/bugdatabase/view_bug?bug_id=4275879) | The Java VM does not support this out of the box as [Phil](https://stackoverflow.com/questions/185004/java-beans-introspector-getbeaninfo-does-not-pickup-any-superinterfaces-properti/867423#867423) wrote. I also needed this and implemented a [helper class](http://kenai.com/projects/deut/sources/repo/content/trunk/src/d... | java.beans.Introspector getBeanInfo does not pickup any superinterface's properties | [
"",
"java",
"reflection",
"javabeans",
""
] |
I have a table with columns
> Index, Date
where an Index may have multiple Dates, and my goal is the following: select a list that looks like
> Index, MinDate, MaxDate
where each Index is listed only once, and MinDate (MaxDate) represents the earliest (latest) date present *in the entire table for that index*. That... | I would recommend a derived table approach. Like this:
```
SELECT
myTable.Index,
MIN(myTable.[Date]),
MAX(myTable.[Date])
FROM myTable
Inner Join (
SELECT Index
From myTable
WHERE [Date] BETWEEN '1/1/2000' AND '12/31/2000') As AliasName
On myTable.Index = AliasName.In... | I am not an SQL Server expert, but if you can do sub-selects like so, this is potentially faster.
```
SELECT Index,
(SELECT MIN([Date] FROM myTable WHERE Index = m.Index),
(SELECT MAX([Date] FROM myTable WHERE Index = m.Index)
From myTable m
WHERE [Date] BETWEEN '1/1/2000' AND '12/31/2000'
``` | Help with SQL query (Joining views?) | [
"",
"sql",
""
] |
Similar to [this](https://stackoverflow.com/questions/5415/convert-bytes-to-floating-point-numbers-in-python) question, I am trying to read in an ID3v2 tag header and am having trouble figuring out how to get individual bytes in python.
I first read all ten bytes into a string. I then want to parse out the individual ... | If you have a string, with 2 bytes that you wish to interpret as a 16 bit integer, you can do so by:
```
>>> s = '\0\x02'
>>> struct.unpack('>H', s)
(2,)
```
Note that the > is for big-endian (the largest part of the integer comes first). This is the format id3 tags use.
For other sizes of integer, you use different... | Why write your own? (Assuming you haven't checked out these other options.) There's a couple options out there for reading in ID3 tag info from MP3s in Python. Check out my [answer](https://stackoverflow.com/questions/8948/accessing-mp3-meta-data-with-python#102285) over at [this](https://stackoverflow.com/questions/89... | How Does One Read Bytes from File in Python | [
"",
"python",
"id3",
""
] |
How do you remove the jagged edges from a wide button in internet explorer? For example:
 | You can also eliminate Windows XP's styling of buttons (and every other version of Windows) by setting the `background-color` and/or `border-color` on your buttons.
Try the following styles:
```
background-color: black;
color: white;
border-color: red green blue yellow;
```
You can of course make this much more plea... | As a workaround, you can remove the blank spaces on each end of the button, which has the effect of decreasing the jagged edges. This is accomplished with the following css and a bit of jQuery:
```
input.button {
padding: 0 .25em;
width: 0; /* for IE only */
overflow: visible;
}
input.button[class] { /* IE i... | Jagged Button edges in Internet Explorer | [
"",
"javascript",
"css",
"internet-explorer",
""
] |
I have a class which implements UserControl. In .NET 2005, a Dispose method is automatically created in the MyClass.Designer.cs partial class file that looks like this:
```
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
... | In such a case I move the generated `Dispose` method to the main file and extend it. Visual Studio respects this.
An other approach would be using a partial method (C# 3.0). | All `Component` classes implement a `Disposed` event. You can add an event handler for that event and clean up things in there.
For example, in your `UserControl` you could add following method:
```
private void OnDispose(object sender, EventArgs e)
{
// do stuff on dispose
}
```
And in constructor (or in `Load`... | How do I add Dispose functionality to a C# UserControl? | [
"",
"c#",
"user-controls",
"dispose",
""
] |
I've got a PHPUnit mock object that returns `'return value'` no matter what its arguments:
```
// From inside a test...
$mock = $this->getMock('myObject', 'methodToMock');
$mock->expects($this->any))
->method('methodToMock')
->will($this->returnValue('return value'));
```
What I want to be able to do is ret... | Use a callback. e.g. (straight from PHPUnit documentation):
```
<?php
class StubTest extends PHPUnit_Framework_TestCase
{
public function testReturnCallbackStub()
{
$stub = $this->getMock(
'SomeClass', array('doSomething')
);
$stub->expects($this->any())
->method... | From the latest phpUnit docs: "Sometimes a stubbed method should return different values depending on a predefined list of arguments. You can use [returnValueMap()](https://phpunit.de/manual/current/en/test-doubles.html#test-doubles.stubs.examples.StubTest5.php) to create a map that associates arguments with correspond... | How can I get PHPUnit MockObjects to return different values based on a parameter? | [
"",
"php",
"unit-testing",
"mocking",
"phpunit",
""
] |
I have a table ("venues") that stores all the possible venues a volunteer can work, each volunteer is assigned to work one venue each.
I want to create a select drop down from the venues table.
Right now I can display the venue each volunteer is assigned, but I want it to display the drop down box, with the venue alr... | ```
$query = "SELECT volunteers_2009.id, volunteers_2009.comments, volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, venues.venue_name FROM volunteers_2009 AS volunteers_2009 LEFT OUTER JOIN venues ON (volunteers_2009.venue... | assuming you have an array of venues...personally i don't like to mix the sql with other wizardry.
```
function displayDropDown($items, $name, $label, $default='') {
if (count($items)) {
echo '<select name="' . $name . '">';
echo '<option value="">' . $label . '</option>';
echo '<option value="">--------... | Populate select drop down from a database table | [
"",
"php",
"mysql",
""
] |
How can I bind arguments to a Python function so that I can call it later without arguments (or with fewer additional arguments)?
For example:
```
def add(x, y):
return x + y
add_5 = magic_function(add, 5)
assert add_5(3) == 8
```
What is the `magic_function` I need here?
---
It often happens with frameworks ... | [`functools.partial`](http://docs.python.org/2/library/functools.html#functools.partial "Python 2 Documentation: functools module: partial function") returns a callable wrapping a function with some or all of the arguments frozen.
```
import sys
import functools
print_hello = functools.partial(sys.stdout.write, "Hell... | Using [`functools.partial`](https://docs.python.org/library/functools.html#functools.partial):
```
>>> from functools import partial
>>> def f(a, b):
... return a+b
...
>>> p = partial(f, 1, 2)
>>> p()
3
>>> p2 = partial(f, 1)
>>> p2(7)
8
``` | How can I bind arguments to a function in Python? | [
"",
"python",
"partial-application",
""
] |
What is the functional equivalent of [Windows Communication Foundation](http://msdn.microsoft.com/en-us/netframework/aa663324.aspx) in Java 6? | WCF offers several communication options. A nice presentation is [this white paper](http://www.davidchappell.com/articles/white_papers/WCF_Diversity_v1.0.docx) by David Chappel. There the following options are described:
* Interoperable Communication using SOAP and WS-\*
* Binary Communication Between WCF Applications... | I don't know what all WCF contains, but [JAX-WS](https://jax-ws.dev.java.net/) (and its reference implementation [Metro](https://metro.dev.java.net/)) might be a good starting point.
Some of the other [technologies in J2EE](http://java.sun.com/javaee/technologies/) may apply as well. | What is the functional equivalent of Windows Communication Foundation in Java 6? | [
"",
"java",
"wcf",
""
] |
Often times I need a collection of non-sequential objects with numeric identifiers. I like using the KeyedCollection for this, but I think there's a serious drawback. If you use an int for the key, you can no longer access members of the collection by their index (collection[index] is now really collection[key]). Is th... | Basically you need to decide if users of the class are likely to be confused by the fact that they can't, for example, do:
```
for(int i=0; i=< myCollection.Count; i++)
{
... myCollection[i] ...
}
```
though they can of course use foreach, or use a cast:
```
for(int i=0; i=< myCollection.Count; i++)
{
... ((... | An easy solution might be to wrap the `int` into another type to create a distinct type for overload resolution. If you use a `struct`, this wrapper doesn't have any additional overhead:
```
struct Id {
public int Value;
public Id(int value) { Value = value; }
override int GetHashCode() { return Value.Ge... | IS it OK to use an int for the key in a KeyedCollection | [
"",
"c#",
".net",
"generics",
"collections",
""
] |
I have to read a binary file in a legacy format with Java.
In a nutshell the file has a header consisting of several integers, bytes and fixed-length char arrays, followed by a list of records which also consist of integers and chars.
In any other language I would create `struct`s (C/C++) or `record`s (Pascal/Delphi)... | To my knowledge, Java forces you to read a file as bytes rather than being able to block read. If you were serializing Java objects, it'd be a different story.
The other examples shown use the [DataInputStream](http://java.sun.com/javase/6/docs/api/java/io/DataInputStream.html) class with a File, but you can also use ... | If you would be using [Preon](https://github.com/preon/preon), then all you would have to do is this:
```
public class Header {
@BoundNumber int version;
@BoundNumber byte type;
@BoundNumber int beginOfData;
@BoundString(size="15") String id;
}
```
Once you have this, you create Codec using a single l... | Best way to read structured binary files with Java | [
"",
"java",
"file",
"binaryfiles",
""
] |
I'm running Python 2.6 on Unix and when I run the interactive prompt ([SQLite](http://en.wikipedia.org/wiki/SQLite) is supposed to be preinstalled) I get:
```
[root@idev htdocs]# python
Python 2.6 (r26:66714, Oct 23 2008, 16:25:34)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
Type "help", "copyright", "credi... | The error:
```
ImportError: No module named _sqlite3
```
means that [SQLite](http://en.wikipedia.org/wiki/SQLite) 3 does not find the associated shared library. On Mac OS X it's \_sqlite3.so and it should be the same on other Unix systems.
To resolve the error you have to locate the \_sqlite3.so library on your comp... | ```
import sqlite3
```
[sqlite3](http://docs.python.org/library/sqlite3.html#module-sqlite3) - DB-API 2.0 interface for SQLite databases.
You are missing the `.so` (shared object) - probably an installation step. In my Linux python installation, `_sqlite3` is at:
```
${somewhere}/lib/python2.6/lib-dynload/_sqlite3.s... | Cannot import SQLite with Python 2.6 | [
"",
"python",
"sqlite",
""
] |
FindBugs has found a potential bug in my code. But it is not a bug.
Is it possible to mark this occurrence as 'not a bug' AND have it removed from the bug list?
I have documented quite clearly why for each case it is not a bug.
For example. A class implements the comparable interface. it has the compareTo method. I ... | Instead of using filters, you can also use the [SuppressWarnings](http://findbugs.sourceforge.net/api/edu/umd/cs/findbugs/annotations/SuppressWarnings.html "SuppressWarnings") annotation. You must use the annotation out of the findbugs package, meaning you either need an import or use the fully qualified name of it. Th... | Probably by adding a [filter](http://findbugs.sourceforge.net/manual/filter.html) as parameter of findbugs
> Match clauses can only match information that is actually contained in the bug instances
```
<Match>
<Class name="com.foobar.MyClass" />
<Method name="myMethod" />
<Bug pattern="EQ_COMPARETO_USE_OBJEC... | When using Eclipse with FindBugs can you mark a bug as not a bug and have it removed from the bug list? | [
"",
"java",
"eclipse",
"findbugs",
""
] |
I am writing a script at the moment that will grab certain information from HTML using dom4j.
Since Python/Jython does not have a native **switch** statement I decided to use a whole bunch of **if** statements that call the appropriate method, like below:
```
if type == 'extractTitle':
extractTitle(dom)
if type =... | To avoid specifying the tag and handler in the dict, you could just use a handler class with methods named to match the type. Eg
```
class MyHandler(object):
def handle_extractTitle(self, dom):
# do something
def handle_extractMetaTags(self, dom):
# do something
def handle(self, type, do... | With your code you're running your functions all get called.
```
handlers = {
'extractTitle': extractTitle,
'extractMetaTags': extractMetaTags
}
handlers[type](dom)
```
Would work like your original `if` code. | Dictionary or If statements, Jython | [
"",
"python",
"switch-statement",
"jython",
""
] |
C++ is mostly a superset of C, but not always. In particular, while enumeration values in both C and C++ implicitly convert into int, the reverse isn't true: only in C do ints convert back into enumeration values. Thus, bitflags defined via enumeration declarations don't work correctly. Hence, this is OK in C, but not ... | Why not just cast the result back to a Foo?
```
Foo x = Foo(Foo_First | Foo_Second);
```
EDIT: I didn't understand the scope of your problem when I first answered this question. The above will work for doing a few spot fixes. For what you want to do, you will need to define a | operator that takes 2 Foo arguments and... | It sounds like an ideal application for a cast - it's up to you to tell the compiler that yes, you DO mean to instantiate a Foo with a random integer.
Of course, technically speaking, Foo\_First | Foo\_Second isn't a valid value for a Foo. | How should C bitflag enumerations be translated into C++? | [
"",
"c++",
"c",
"enums",
"flags",
""
] |
I need an easy way to allow users to upload multiple files at once (ie I need to allow a user to upload a folder). I do not wish to put the burden of zipping on the user.
*I would prefer to avoid Flash or variants if possible.* I'm looking for a straight javascript / HTML solution if it is possible. Please note, this ... | You won't be able to do it with just HTML and Javascript. I'd recommend trying [Fancy Upload](http://digitarald.de/project/fancyupload/), a [MooTools](http://mootools.net/) plugin for multiple file uploads. It uses a mixture of JavaScript and Flash, but degrades gracefully. It works with all major browsers including IE... | With Firefox 42 and Edge having implemented the new [directory upload proposal](https://microsoftedge.github.io/directory-upload/proposal.html) we'll finally able to do cross-browser directory uploads. The APIs are nasty enough that you may want to check out my wrapper, [uppie](https://github.com/silverwind/uppie). | What is the best way to upload a folder to a website? | [
"",
"javascript",
"html",
"file-upload",
""
] |
I have some code that looks like:
```
template<unsigned int A, unsigned int B>
int foo() {
int v = 1;
const int x = A - B;
if (x > 0) {
v = v << x;
}
bar(v);
}
```
gcc will complain about x being negative for certain instantiations of A, B; however, I do perform a check to make sure it is non-negative. ... | Since A and B are known at compile time, not only can you get rid of your warning, but you can also get rid of a runtime `if`, without any casts, like this:
```
#include <iostream>
using namespace std;
template< unsigned int A, unsigned int B >
struct my
{
template< bool P >
static void shift_if( int & );
... | why not make x an unsigned char type and cast it? surely you don't need to shift more than 255 bits?
```
const unsigned char x = static_cast<unsigned char>(A - B);
```
or perhaps use masking to ensure that the shift is in bounds like this:
```
const unsigned int x = static_cast<unsigned int>(A - B) & 0x1f; // limit ... | Getting rid of gcc shift by negative warning | [
"",
"c++",
"gcc",
""
] |
How can I write a C++ function returning true if a real number is exactly representable with a double?
```
bool isRepresentable( const char* realNumber )
{
bool answer = false;
// what goes here?
return answer;
}
```
Simple tests:
```
assert( true==isRepresentable( "0.5" ) );
assert( false==isRepresentable(... | Parse the number into the form a + N / (10^k), where a and N are integers, and k is the number of decimal places you have.
Example: 12.0345 -> 12 + 345 / 10^4, a = 12, N = 345, k = 4
Now, 10^k = (2 \* 5) ^ k = 2^k \* 5^k
You can represent your number as exact binary fraction if and only if you get rid of the 5^k ter... | Holy homework, batman! :)
What makes this interesting is that you can't simply do an (atof|strtod|sscanf) -> sprintf loop and check whether you got the original string back. sprintf on many platforms detects the "as close as you can get to 0.1" double and prints it as 0.1, for example, even though 0.1 isn't precisely ... | How can I write a C++ function returning true if a real number is exactly representable with a double? | [
"",
"c++",
"floating-point",
""
] |
I have to use unsigned integers that could span to more than 4 bytes, what type should I use?
PS Sorry for the "noobism" but that's it :D
NB: I need integers because i have to do divisions and care only for the integer parts and this way int are useful | *long long*, 64 bit integer... [here](http://msdn.microsoft.com/en-us/library/s3f49ktz(VS.80).aspx) you can find some reference about the data types and ranges... | Simply include <stdint.h> and use int64\_t and uint64\_t (since you want unsigned, you want uint64\_t).
There are several other useful variants on that header, like the least variants (uint\_least64\_t is a type with at least 64 bits) and the fast variants (uint\_fast64\_t is the fastest integer type with at least 64 ... | What type for an integer of more than 4 bytes? | [
"",
"c++",
"integer",
""
] |
I want to print the full length of a C-string in GDB. By default it's being abbreviated, how do I force GDB to print the whole string? | ```
set print elements 0
```
[From the GDB manual](https://sourceware.org/gdb/onlinedocs/gdb/Print-Settings.html#index-number-of-array-elements-to-print):
> `set print elements` *`number-of-elements`*
> Set a limit on how many elements of an array GDB will print. If GDB is printing a large array, it stops printing a... | As long as your program's in a sane state, you can also `call (void)puts(your_string)` to print it to stdout. Same principle applies to all functions available to the debugger, actually. | How do I print the full value of a long string in gdb? | [
"",
"c++",
"c",
"string",
"debugging",
"gdb",
""
] |
Let's say we have defined a CSS class that is being applied to various elements on a page.
```
colourful
{
color: #DD00DD;
background-color: #330033;
}
```
People have complained about the colour, that they don't like pink/purple. So you want to give them the ability to change the style as they wish, and they... | I don't know about manipulating the class directly, but you can effectively do the same thing. Here's an example in jQuery.
```
$('.colourful').css('background-color', 'purple').css('color','red');
```
In plain javascript, you would have to do more work. | ```
var setStyleRule = function(selector, rule) {
var stylesheet = document.styleSheets[(document.styleSheets.length - 1)];
if(stylesheet.addRule) {
stylesheet.addRule(selector, rule)
} else if(stylesheet.insertRule) {
stylesheet.insertRule(selector + ' { ' + rule + ' }', stylesheet.cssRules... | How to redefine CSS classes with Javascript | [
"",
"javascript",
"css",
""
] |
We frequently have users that create multiple accounts and then end up storing the same lesson activity data more than once. Once they realize the error, then they contact us to merge the accounts into a single one that they can use.
I've been beating myself to death trying to figure out how to write a query in MySQL ... | One of my current clients is facing a similar problem, except that they have dozens of tables that have to be merged. This is one reason to use a real life primary key (natural key). Your best bet is to try to avoid this problem before it even happens.
Another thing to keep in mind, is that two people can share both t... | Attempting to merge this data via last/first is a horrible idea, the more users you have, the more likely you are to mesh up incorrect entries. You have IDs on your tables for a reason, use them.
I don't see any reason why you can't say "I want to merge user 7 into 12" and then do the following:
```
UPDATE lessonstat... | How to Write a Query to Merge Two Accounts and their Activity Logs into One? | [
"",
"mysql",
"sql",
""
] |
How can I move items from one list box control to another listbox control using JavaScript in ASP.NET? | This code assumes that you have an anchor or that will trigger to movement when it is clicked:
```
document.getElementById('moveTrigger').onclick = function() {
var listTwo = document.getElementById('secondList');
var options = document.getElementById('firstList').getElementsByTagName('option');
while(op... | If you're happy to use jQuery, it's very, very simple.
```
$('#firstSelect option:selected').appendTo('#secondSelect');
```
Where #firstSelect is the ID of the select box.
I've included a working example here:
<http://jsbin.com/aluzu> (to edit: <http://jsbin.com/aluzu/edit>) | Moving items in Dual Listboxes | [
"",
"asp.net",
"javascript",
"listbox",
"listbox-control",
""
] |
I recently built a program that parses a remote file from **\some\_server\c$\directory\file.xls** and it works fine on my local machine as just a normal aspx page.
> Then I put the program into web part
> form on my VM SharePoint server and I
> get this error: Access to the path
> '\some\_server\c$\directory\file.xls'... | Salamander is right, SharePoint doesn't run with trust to do this.
Changing the trust level for SharePoint in it's web.config from WSS\_Medium to Full is the quick solution, but there are security implications.. | Just a quick note, you could be running into the classic NTLM Double-Hop issue. You can authenticate to the front end, but because the front end does not have your password, it cannot then authenticate to a resource on another server.
Running with Elevated priviliges, and setting permissions based on the Application P... | Accessing a remote file with a SharePoint Web Part | [
"",
"c#",
"sharepoint",
"web-parts",
""
] |
This question is a follow up to:
[Why can’t I call a method outside of an anonymous class of the same name](https://stackoverflow.com/questions/252267/why-cant-i-call-a-method-outside-of-an-anonymous-class-of-the-same-name)
This previous question answer **why**, but now I want to know if javac **should** find run(int ... | This behavior of javac conforms to the spec. See [§15.12 Method Invocation Expressions](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#20448) in the Java Language Specification, specifically the paragraph under "Compile Time Step 1" explaining the meaning of an unqualified method invocation:
> ... | Sounds like a recipe for ambiguity and fragility to me - as soon as a new method is added in your base class (okay, not so likely for an interface...) the meaning of your code changes completely.
Anonymous classes are pretty ugly already - making this bit of explicit doesn't bother me at all. | Should javac find methods outside of an anonymous class of the same name? | [
"",
"java",
"methods",
"javac",
"anonymous-class",
""
] |
On an ASP.NET MVC (Beta) site that I am developing sometimes calls to ActionLink will return to me URLs containing querying strings. I have isolated the circumstances that produce this behavior, but I still do not understand why, instead of producing a clean URL, it decides to using a query string parameter. I know tha... | Not sure why different views are producing different URLs.
But you can get rid of that sortBy param by assigning a default value to the first route.
new { sortBy = "" }
During generation, if sortBy matches the default, the route engine will skip that parameter (if it's in the query string). | You're going to have to use named routes here, not action routes, because of the way routing works in ASP.NET, because it does "first match", not "best match". | Why the query strings in my ASP.NET MVC route? | [
"",
"c#",
"asp.net",
"asp.net-mvc",
"routes",
""
] |
I am using a Cursor in my stored procedure. It works on a database that has a huge number of data. for every item in the cursor i do a update operation. This is taking a huge amount of time to complete. Almost 25min. :( .. Is there anyway i can reduce the time consumed for this? | When you need to do a more complex operation to each row than what a simple update would allow you, you can try:
* Write a User Defined Function and use that in the update (probably still slow)
* Put data in a temporary table and use that in an UPDATE ... FROM:
Did you know about the UPDATE ... FROM syntax? It is qui... | The quick answer is not to use a cursor. The most efficient way to update lots of records is to use an update statement. There are not many cases where you have to use a cursor rather than an update statement, you just have to get clever about how you write the update statement.
If you posted a snapshot of your SQL yo... | Why is my SQL Server cursor very slow? | [
"",
"sql",
"sql-server-2005",
""
] |
I was just wondering how many experienced programers out there actually map out their process or algorithms in a program like MS Visio or Gnome Dia?
I am trying to code some complex PHP for my website and just seem to be missing something. Is a diagram program going to help or should I be looking in another area? | I use Visio only for quick graph that doesn't need to follow UML rules. Sometime useful for documentation that aren't about the detail of the code : if you need to show some high abstract view of your code, Visio do the job, Example, documentation that display how each big part communicate, or a simple activity diagram... | Everytime I've tried to make a truly usage diagram in Visio, it always ends up being more work than it's worth. Never underestimate the power of pencil & paper, or better yet, a white board.
But yes, explaining or writing out your problems will more quickly lead to a solution than merely sitting there and thinking abo... | Using Visio (Dia) to Map Out Algorithms | [
"",
"php",
"diagram",
"visio",
"dia",
""
] |
With a `TreeMap` it's trivial to provide a custom `Comparator`, thus overriding the semantics provided by `Comparable` objects added to the map. `HashMap`s however cannot be controlled in this manner; the functions providing hash values and equality checks cannot be 'side-loaded'.
I suspect it would be both easy and u... | [Trove4j](http://trove4j.sourceforge.net/html/overview.html) has the feature I'm after and they call it hashing strategies.
Their map has an implementation with different limitations and thus different prerequisites, so this does not implicitly mean that an implementation for Java's "native" HashMap would be feasible. | .NET has this via IEqualityComparer (for a type which can compare two objects) and IEquatable (for a type which can compare itself to another instance).
In fact, I believe it was a mistake to define equality and hashcodes in java.lang.Object or System.Object at all. Equality in particular is hard to define in a way wh... | Why not allow an external interface to provide hashCode/equals for a HashMap? | [
"",
"java",
"collections",
"hashmap",
"trove4j",
""
] |
`std::auto_ptr` is broken in VC++ 8 (which is what we use at work). My main gripe with it is that it allows `auto_ptr<T> x = new T();`, which of course leads to horrible crashes, while being simple to do by mistake.
From an [answer](https://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-u... | Move to boost smart pointers.
In the meantime, you may want to extract a working auto\_ptr implementation from an old / another STL, so you have working code.
I believe that auto\_ptr semantics are fundamentally broken - it saves typing, but the interface actually is not simpler: you still have to track which instanc... | Have you considered using [STLPort](http://www.stlport.org/)? | Replacing auto_ptr in VC++ 8 | [
"",
"c++",
"smart-pointers",
""
] |
How would I get the length of an `ArrayList` using a JSF EL expression?
```
#{MyBean.somelist.length}
```
does not work. | Yes, since some genius in the Java API creation committee decided that, even though certain classes have `size()` members or `length` attributes, they won't implement `getSize()` or `getLength()` which JSF and most other standards require, you can't do what you want.
There's a couple ways to do this.
One: add a funct... | You mean size() don't you?
```
#{MyBean.somelist.size()}
```
works for me (using JBoss Seam which has the Jboss EL extensions) | How do you get the length of a list in the JSF expression language? | [
"",
"java",
"jsp",
"jsf",
"jstl",
"el",
""
] |
The WPF control WindowsFormsHost inherits from IDisposable.
If I have a complex WPF visual tree containing some of the above controls what event or method can I use to call IDispose during shutdown? | Building from Todd's answer I came up with this generic solution for any WPF control that is hosted by a Window and want's to guarantee disposal when that window is closed.
(Obviously if you can avoid inheriting from IDisposable do, but sometimes you just can't)
Dispose is called when the the first parent window in t... | In the case of application shutdown there is nothing you need to do to properly dispose of the WindowsFormsHost. Since it derives from HwndHost disposing is handled when the Dispatcher is shutdown. If you use Reflector you will see that when HwndHost is initialized it creates a WeakEventDispatcherShutdown.
If you are ... | When can I dispose an IDisposable WPF control e.g. WindowsFormsHost? | [
"",
"c#",
".net",
"wpf",
"idisposable",
""
] |
At what point is it better to switch from java.net to java.nio? .net (not the Microsoft entity) is easier to understand and more familiar, while nio is scalable, and comes with some extra nifty features.
Specifically, I need to make a choice for this situation: We have one control center managing hardware at several r... | Scalability will probably drive your choice of package. java.net will require one thread per socket. Coding it will be significantly easier. java.nio is much more efficient, but can be hairy to code around.
I would ask yourself how many connections you expect to be handling. If it's relatively few (say, < 100), I'd go... | Avoid NIO unless you have a good reason to use it. [It's not much fun and may not be as beneficial as you would think](http://blog.uncommons.org/2008/09/03/avoid-nio-get-better-throughput/). You may get better scalability once you are dealing with tens of thousands of connections, but at lower numbers you'll probably g... | java.net versus java.nio | [
"",
"java",
"networking",
"io",
"nio",
""
] |
Why does this lambda expression not compile?
```
Action a = () => throw new InvalidOperationException();
```
Conjecture is fine, but I would really appreciate references to the C# language specification or other documentation.
And yes, I know that the following is valid and will compile:
```
Action a = () => { thro... | Hmm. I've got an answer, but it's not great.
I don't believe that there's a "throw" *expression*. There's a throw *statement*, but not just an expression. Compare this with "Console.WriteLine()" which is a method invocation expression with a void type.
As a parallel, you can't have a switch statement, or an if statem... | Here's my take:
`throw` is a statement, not an expression.
And the reference:
> 12.3.3.11 Throw statements
>
> For a statement stmt of the form
>
> `throw expr;`
>
> the definite assignment state of v
> at the beginning of expr is the same
> as the definite assignment state of v
> at the beginning of stmt.
To expla... | C# Action lambda limitation | [
"",
"c#",
"compiler-construction",
"lambda",
""
] |
First off, I know next to nothing about language theory, and I barely know any other languages except Java, but I had an idea that I think would be cool, but I need you guys to tell me:
a: why it sucks
b: how language x has had that for years
c: how my mind sucks
d: all of the above
The idea would give composi... | I think if you restricted it such that a class could only use this feature to compose a single class it would be somewhat useful and would avoid a lot of the headaches that are being discussed.
Personally I hate inheritance of concrete classes. I'm a big proponent of Item 14 from Bloch's *Effective Java*, [Favor compo... | It sounds cool but I think it makes for some horrible language constructs. Obviously there is a problem if you declare more than one 'composition' of the same class, but even if you forbid that what about the case where a call matches a method in more than one of the (different) composed classes? You would have to spec... | Would syntax for composition be a useful addition to Java? | [
"",
"java",
"inheritance",
"compiler-construction",
"programming-languages",
"composition",
""
] |
What is the difference between a Hash Map and dictionary ADT. And when to prefer one over another. For my programming assignment my instructor has asked to use one of them but I don't see any difference in between both. The program is supposed to work with a huge no. of strings. Any suggestions? | In terms of Java, both the class `HashMap` and the class `Dictionary` are *implementations* of the "Map" abstract data type. Abstract data types are not specific to any one programming language, and the Map ADT can also be known as a Hash, or a Dictionary, or an Associative Array (others at <http://en.wikipedia.org/wik... | This Stack Overflow post does a good job explaining the key differences:
[Java hashmap vs hashtable](https://stackoverflow.com/questions/40471/java-hashmap-vs-hashtable)
Note that Hashtable is simply an implementation of the Dictionary ADT. Also note that Java considers Dictionary ["obsolete"](http://java.sun.com/j2s... | Difference between a HashMap and a dictionary ADT | [
"",
"java",
"data-structures",
""
] |
is there a quick way to sort the items of a select element?
Or I have to resort to writing javascript?
Please any ideas.
```
<select size="4" name="lstALL" multiple="multiple" id="lstALL" tabindex="12" style="font-size:XX-Small;height:95%;width:100%;">
<option value="0"> XXX</option>
<option value="1203">ABC</option>... | This will do the trick. Just pass it your select element a la: `document.getElementById('lstALL')` when you need your list sorted.
```
function sortSelect(selElem) {
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i]... | This solution worked very nicely for me using jquery, thought I'd cross reference it here as I found this page before the other one. Someone else might do the same.
```
$("#id").html($("#id option").sort(function (a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}))
```
from [Sorting dropdown list u... | Javascript to sort contents of select element | [
"",
"javascript",
"select",
""
] |
I'm starting to develop a web application in PHP that I hope will become incredibly popular and make me famous and rich. :-)
If that time comes, my decision whether to parse the API's data as XML with SimpleXML or to use json\_decode could make a difference in the app's scalability.
Does anyone know which of these ap... | As the "lighter" format, I'd expect JSON to be slightly less stressful on the server, but I doubt it will be the biggest performance issue you find yourself dealing with as your site grows in popularity. Use whichever format you're more comfortable with.
Alternatively, if you know how you'll be structuring your data, ... | Not really an answer to the question, but you could just wait until you have lots of users hitting your system. You may be surprised where your bottlenecks actually lie:
<http://gettingreal.37signals.com/ch04_Scale_Later.php> | What puts less load on a PHP server: SimpleXML or json_decode? | [
"",
"php",
"performance",
"scalability",
"simplexml",
"json",
""
] |
What is the advantages/disadvantages of using inline functions in C++? I see that it only increases performance for the code that the compiler outputs, but with today's optimized compilers, fast CPUs, huge memory etc. (not like in the 1980< where memory was scarce and everything had to fit in 100KB of memory) what adva... | Inline functions are faster because you don't need to push and pop things on/off the stack like parameters and the return address; however, it does make your binary slightly larger.
Does it make a significant difference? Not noticeably enough on modern hardware for most. But it can make a difference, which is enough f... | ## Advantages
* By inlining your code where it is needed, your program will spend less time in the function call and return parts. It is supposed to make your code go faster, even as it goes larger (see below). Inlining trivial accessors could be an example of effective inlining.
* By marking it as inline, you can put... | What are the benefits of inline functions? | [
"",
"c++",
"inline",
"inline-functions",
""
] |
I'm trying to define a table to store student grades for a online report card. I can't decide how to do it, though.
The grades are given by subject, in a trimestral period. Every trimester has a average grade, the total missed classes and a "recovering grade" (I don't know the right term in English, but it's an extra ... | You could try structuring it like this with your tables. I didn't have all the information so I made some guesses at what you might need or do with it all.
TimePeriods:
* ID(INT)
* PeriodTimeStart(DateTime)
* PeriodTimeEnd(DateTime)
* Name(VARCHAR(50)
Students:
* ID(INT)
* FirstName(VARCHAR(60))
* LastName(VARCHAR(... | I think the best solution is to store one row per period. So you'd have a table like:
```
grades
------
studentID
periodNumber
averageGrade
missedClasses
recoveringGrade
```
So if it's 2 semesters, you'd have periods 1 and 2. I'd suggest using period 0 to mean "overall for the year". | Database table for grades | [
"",
"sql",
"database",
"data-modeling",
""
] |
All,
As part of an application I'm writing I need to have a HTTP PUT webservice which accepts incoming imagedata, which will by analyzed, validated, and added to a local file store.
My issue arises after the size validation as the
> `$_SERVER['CONTENT_LENGTH']`
has a > 0 value, and this value is identical to the te... | My best guess is that you need to alter httpd.conf to not deny PUT requests. Have you checked that? | Apache HTTPD denies PUT requests by default. You might check out mod\_put:
<http://perso.ec-lyon.fr/lyonel.vincent/apache/mod_put.html>
and add this to httpd.conf:
```
<Location /upload/dir>
EnablePut On
AuthType Basic
AuthName "Web publishing"
AuthUserFile /www/etc/passwd
AuthGroupFile /www/etc/group
<... | Unable to access HTTP PUT data in webservice code | [
"",
"php",
"web-services",
"rest",
""
] |
I have an array of integers:
```
int[] number = new int[] { 2,3,6,7 };
```
What is the easiest way of converting these into a single string where the numbers are separated by a character (like: `"2,3,6,7"`)?
I'm using C# and .NET 3.5. | ```
var ints = new int[] {1, 2, 3, 4, 5};
var result = string.Join(",", ints.Select(x => x.ToString()).ToArray());
Console.WriteLine(result); // prints "1,2,3,4,5"
```
As of (at least) .NET 4.5,
```
var result = string.Join(",", ints.Select(x => x.ToString()).ToArray());
```
is equivalent to:
```
var result = strin... | Although the OP specified .NET 3.5, people wanting to do this in .NET 2.0 with C# 2.0 can do this:
```
string.Join(",", Array.ConvertAll<int, String>(ints, Convert.ToString));
```
I find there are a number of other cases where the use of the Convert.xxx functions is a neater alternative to a lambda, although in C# 3.... | How can I join int[] to a character-separated string in .NET? | [
"",
"c#",
".net",
".net-3.5",
""
] |
I'm working through [Practical Web 2.0 Appications](https://rads.stackoverflow.com/amzn/click/com/1590599063) currently and have hit a bit of a roadblock. I'm trying to get PHP, MySQL, Apache, Smarty and the Zend Framework all working correctly so I can begin to build the application. I have gotten the bootstrap file f... | The problem isn't with the $name variable but rather with the $\_engine variable. It's currently empty. You need to verify that the path specification to Smarty.class.php is correct.
You might try this to begin your debugging:
```
$this->_engine = new Smarty();
print_r($this->_engine);
```
If it turns out that $\_en... | Zend has an example of creating a templating system which implements the Zend\_View\_Interface here: <http://framework.zend.com/manual/en/zend.view.scripts.html#zend.view.scripts.templates.interface>
That might save you some time from trying to debug a custom solution. | Call to a member function on a non-object | [
"",
"php",
"zend-framework",
"smarty",
""
] |
How do I remove the key 'bar' from an array foo so that 'bar' won't show up in
```
for(key in foo){alert(key);}
``` | Don't use **delete** as it won't remove an element from an array it will only set it as undefined, which will then not be reflected correctly in the length of the array.
If you know the key you should use **splice** i.e.
```
myArray.splice(key, 1);
```
For someone in Steven's position you can try something like this... | ```
delete foo[key];
```
:D | How do I unset an element in an array in javascript? | [
"",
"javascript",
"arrays",
""
] |
I need a way to determine the type of an HTML element in JavaScript. It has the ID, but the element itself could be a `<div>`, a `<form>` field, a `<fieldset>`, etc. How can I achieve this? | [`nodeName`](https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeName) is the attribute you are looking for. For example:
```
var elt = document.getElementById('foo');
console.log(elt.nodeName);
```
Note that `nodeName` returns the element name capitalized and without the angle brackets, which means that if you... | What about [`element.tagName`](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-104682815)?
See also [`tagName` docs on MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/tagName). | How can I determine the type of an HTML element in JavaScript? | [
"",
"javascript",
"dom",
""
] |
We're using Prototype for all of our Ajax request handling and to keep things simple we simple render HTML content which is then assigned to the appropriate div using the following function:
```
function ajaxModify(controller, parameters, div_id)
{
var div = $(div_id);
var request = new Ajax.Request
(
... | The parameter is:
```
evalScripts:true
```
Note that you should be using **Ajax.Updater**, not **Ajax.Request**
See: <http://www.prototypejs.org/api/ajax/updater>
Ajax.Request will only process JavaScript if the response headers are:
> application/ecmascript,
> application/javascript,
> application/x-ecmascript,
>... | Does setting `evalScripts: true` as an option help? | How to Force Javascript to Execute within HTML Response to Ajax Request | [
"",
"javascript",
"html",
"ajax",
"prototypejs",
""
] |
A colleague recently asked me how to deep-clone a Map and I realized that I probably have never used the clone() method- which worries me.
What are the most common scenarios you have found where you need to clone an object? | I assume you are referring to `Object.clone()` in Java. If yes, be advised that `Object.clone()` has some major problems, and its use is discouraged in most cases. Please see Item 11, from ["Effective Java"](http://java.sun.com/docs/books/effective/) by Joshua Bloch for a complete answer. I believe you can safely use `... | Most commonly, when I have to return a mutable object to a caller that I'm worried the caller might muck with, often in a thread-unfriendly way. Lists and Date are the ones that I do this to most. If the caller is likely to want to iterate over a List and I've got threads possibly updating it, it's safer to return a cl... | What have you used Object.clone() for? | [
"",
"java",
""
] |
This probably sounds really stupid but I have noo idea how to implement jquery's rounded corners (<http://www.methvin.com/jquery/jq-corner-demo.html>). My javascript-fu is complete fail and I can't seem to get it to work on my page. Can anyone show me a simple example of the HTML and JavaScript you would use to get the... | 1. This thing does not work in Safari & Google Chrome.
2. You need to include [jquery.js](http://jqueryjs.googlecode.com/files/jquery-1.2.6.js) in your page. Don't forget to have a separate closing tag.
`<script type="text/javascript" src="jquery.js"></script>`
3. You need to include the jQuery Corner Plugin JavaSc... | jquery corners by Methvin `http://www.methvin.com/jquery/jq-corner-demo.html` are ok and working fine, but... there is more beautiful alternative:
```
http://blue-anvil.com/jquerycurvycorners/test.html
```
you can use that lib to do rounded images even.
And what is very important:
- 18th July 2008 - Now works in IE6... | jquery round corners | [
"",
"javascript",
"jquery",
"rounded-corners",
""
] |
I need a way to determine whether the computer running my program is joined to any domain. It doesn't matter what specific domain it is part of, just whether it is connected to anything. I'm coding in vc++ against the Win32 API. | Straight from Microsoft:
[How To Determine If a Windows NT/Windows 2000 Computer Is a Domain Member](http://support.microsoft.com/kb/179891)
This approach uses the Windows API. From the article summary:
> This article describes how to
> determine if a computer that is
> running Windows NT 4.0 or Windows 2000
> is a ... | I think the [NetServerEnum](http://msdn.microsoft.com/en-us/library/aa370623%28VS.85%29.aspx) function will help you in what you want; I would ask for the primary domain controllers with the `SV_TYPE_DOMAIN_CTRL` constant for *servertype* parameter. If you don't get any, then you're not in a domain. | How do you programmatically determine whether a Windows computer is a member of a domain? | [
"",
"c++",
"windows",
"winapi",
"dns",
""
] |
I have this bit of script to widen a text box on mouseover and shorten it on mouseoff.
The problem I am having is that Internet Explorer doesn't seem to extend it's hover over the options of a select box.
This means in IE I can click the select, have the options drop down, but if I try to select one, they vanish and ... | Apparently IE doesn't consider the drop down bit part of the select element. It's doable, but it takes a bit of cheating with expando properties and blur/focus events to enable and disable the 'hide' effect to stop it kicking in when the mouse enters the drop-down part of the element.
Have a go with this:
```
$(funct... | Looks like this post has been up for a while, but hopefully there are still folks interested in a workaround. I experienced this issue while building out a new site that I'm working on. On it is a product slider, and for each product, mousing over the product pops up a large informational bubble with info about the pro... | JQuery/Javascript: IE hover doesn't cover select box options? | [
"",
"javascript",
"cross-browser",
""
] |
How do I write the SQL code to INSERT (or UPDATE) an array of values (with probably an attendant array of fieldnames, or with a matrix with them both) without simple iteration? | I construct the list as an xml string and pass it to the stored procs. In SQL 2005, it has enhanced xml functionalities to parse the xml and do a bulk insert.
check this post:
[Passing lists to SQL Server 2005 with XML Parameters](http://weblogs.asp.net/jgalloway/archive/2007/02/16/passing-lists-to-sql-server-2005-wit... | Simple way to concatenate the values into a list and pass it to the sp.
In the sp use dbo.Split udf to convert back to resultset (table).
Create this function:
```
CREATE FUNCTION dbo.Split(@String nvarchar(4000), @Delimiter char(1))
returns @Results TABLE (Items nvarchar(4000))
as
begin
declare @index int
declare @... | How to INSERT an array of values in SQL Server 2005? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"bulkinsert",
""
] |
I've been tasked with build an accessible RSS feed for my company's job listings. I already have an RSS feed from our recruiting partner; so I'm transforming their RSS XML to our own proxy RSS feed to add additional data as well limit the number of items in the feed so we list on the latest jobs.
The RSS validates via... | I haven't yet worked with WordML, but assuming that its elements are in a different namespace from RSS, it should be quite simple to do with XSLT.
Start with a basic identity transform (a stylesheet that add all nodes from the input doc "as is" to the output tree). You need these two templates:
```
<!-- Copy all el... | I would do something like this:
```
char[] charToRemove = { (char)8217, (char)8216, (char)8220, (char)8221, (char)8211 };
char[] charToAdd = { (char)39, (char)39, (char)34, (char)34, '-' };
string cleanedStr = "Your WordML filled Feed Text.";
for (int i = 0; i < charToRemove.Length; i++)
{
cleanedStr = cleanedStr... | Strip WordML from a string | [
"",
"c#",
"asp.net",
"xml",
"rss",
"xslt",
""
] |
Is there a way to test the type of an element in JavaScript?
The answer may or may not require the prototype library, however the following setup does make use of the library.
```
function(event) {
var element = event.element();
// if the element is an anchor
...
// if the element is a td
...
}
``` | You can use `typeof(N)` to get the actual object type, but what you want to do is check the tag, not the type of the DOM element.
In that case, use the `elem.tagName` or `elem.nodeName` property.
if you want to get really creative, you can use a dictionary of tagnames and anonymous closures instead if a switch or if/... | ```
if (element.nodeName == "A") {
...
} else if (element.nodeName == "TD") {
...
}
``` | Testing the type of a DOM element in JavaScript | [
"",
"javascript",
"prototypejs",
""
] |
Is it better in C++ to pass by value or pass by reference-to-const?
I am wondering which is better practice. I realize that pass by reference-to-const should provide for better performance in the program because you are not making a copy of the variable. | It used to be generally recommended best practice1 to **use pass by const ref for *all types*, except for builtin types (`char`, `int`, `double`, etc.), for iterators and for function objects** (lambdas, classes deriving from `std::*_function`).
This was especially true before the existence of *move semantics*. The re... | **Edit:** New article by Dave Abrahams on cpp-next:
## [Want speed? Pass by value.](http://web.archive.org/web/20140113221447/http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/)
---
Pass by value for structs where the copying is cheap has the additional advantage that the compiler may assume that the obje... | Is it better in C++ to pass by value or pass by reference-to-const? | [
"",
"c++",
"variables",
"pass-by-reference",
"constants",
"pass-by-value",
""
] |
I want to write a program that would print every combination of a set of variables to a text file, creating a word list. Each answer should be written on a separate line and write all of the results for 1 digit, 2 digits, and 3 digits to a single text file.
Is there a simple way I can write a python program that can a... | A naïve solution which solves the problem and is general enough for any application you might have is this:
```
def combinations(words, length):
if length == 0:
return []
result = [[word] for word in words]
while length > 1:
new_result = []
for combo in result:
new_resul... | ```
# Given two lists of strings, return a list of all ways to concatenate
# one from each.
def combos(xs, ys):
return [x + y for x in xs for y in ys]
digits = ['0', '1']
for c in combos(digits, combos(digits, digits)):
print c
#. 000
#. 001
#. 010
#. 011
#. 100
#. 101
#. 110
#. 111
``` | I want a program that writes every possible combination to a different line of a text file | [
"",
"python",
"recursion",
""
] |
Can I access a users microphone in Python?
Sorry I forgot not everyone is a mind reader:
Windows at minimum XP but Vista support would be VERY good. | Best way to go about it would be to use the ctypes library and use WinMM from that. mixerOpen will open a microphone device and you can read the data easily from there. Should be very straightforward. | I got the job done with [pyaudio](http://people.csail.mit.edu/hubert/pyaudio/)
It comes with a binary installer for windows and there's even an example on how to record through the microphone and save to a wave file. Nice! I used it on Windows XP, not sure how it will do on Vista though, sorry. | Microphone access in Python | [
"",
"python",
"windows",
"microphone",
""
] |
How can I change a file's extension using PHP?
Ex: photo.jpg to photo.exe | In modern operating systems, filenames very well might contain periods long before the file extension, for instance:
```
my.file.name.jpg
```
PHP provides a way to find the filename without the extension that takes this into account, then just add the new extension:
```
function replace_extension($filename, $new_ext... | ```
substr_replace($file , 'png', strrpos($file , '.') +1)
```
Will change any extension to what you want. Replace png with what ever your desired extension would be. | How can I change a file's extension using PHP? | [
"",
"php",
"file",
""
] |
I'm looking for a "quick and dirty" C++ testing framework I can use on my Windows/Visual Studio box. It's just me developing, so it doesn't have to be enterprise class software.
Staring at a list of testing frameworks, I am somewhat befuddled...
<http://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#C.2B.2B> | [Here's a great article about C++ TDD frameworks](http://www.gamesfromwithin.com/articles/0412/000061.html). For the record, my personal preference is CxxTest, which I have been happily using for about six months now. | I have used both [UnitTest++](http://unittest-cpp.sourceforge.net/) and [Boost.Test](http://www.boost.org/doc/libs/1_36_0/libs/test/doc/html/index.html). They are both easy to setup and use.
Although, I wouldn't use Boost.Test if you're not already using the Boost libraries. It's a bit much to install all of Boost just... | C++ testing framework: recommendation sought | [
"",
"c++",
"windows",
"unit-testing",
"frameworks",
""
] |
I have always found this to be a very useful feature in Visual Studio. For those who don't know about it, it allows you to edit code while you are debugging a running process, re-compile the code *while the binary is still running* and continue using the application seamlessly with the new code, without the need to res... | My understanding is that when the app is compiled with support for Edit and Continue enabled, the compiler leaves extra room around the functions in the binary image to allow for adding additional code. Then the debugger can compile a new version of the function, replace the existing version (using the padding space as... | My *guess* is that it recompiles the app (and for small changes this wouldn't mean very much would have to be recompiled). Then since Microsoft makes both the compiler and debugger they can make guarantees about how memory and the like are laid out. So, they can use the debugging API to re-write the code segments with ... | How does "Edit and continue" work in Visual Studio? | [
"",
"c++",
"visual-studio",
""
] |
in a web application I am building I need to upload photos without using a form, otherwise it will come up with form embedded in an outer from which is not permitted in XHTML.
I think uploading files is what jQuery.post should be able to do, but I currently can't figure out how to do this using jQuery. | take a look at [swfupload](http://swfupload.org/), it's a pretty nifty little app that should accomplish what you want. otherwise, you could separate out the forms, and just use css/javascript to reposition them if necessary. | With [jQuery.post](http://docs.jquery.com/Ajax/jQuery.post) you will be only able to send key/value pairs to the server in a POST Request, However you can use plugins like [jQuery Multiple File Upload Plugin](http://www.fyneworks.com/jquery/multiple-file-upload/). | How can I upload files without using an HTML <form>? | [
"",
"javascript",
"jquery",
"http",
"upload",
""
] |
In C# code can you catch a native exception thrown from deep in some unmanaged library? If so do you need to do anything differently to catch it or does a standard try...catch get it? | You can use [Win32Exception](http://msdn.microsoft.com/en-us/library/system.componentmodel.win32exception.aspx) and use its NativeErrorCode property to handle it appropriately.
```
// http://support.microsoft.com/kb/186550
const int ERROR_FILE_NOT_FOUND = 2;
const int ERROR_ACCESS_DENIED = 5;
const int ERROR_NO_APP_AS... | Catch without () will catch non-CLS compliant exceptions including native exceptions.
```
try
{
}
catch
{
}
```
See the following FxCop rule for more info
<http://msdn.microsoft.com/en-gb/bb264489.aspx> | Can you catch a native exception in C# code? | [
"",
"c#",
".net",
"exception",
""
] |
What is the best method of performing an scp transfer via the Java programming language? It seems I may be able to perform this via JSSE, JSch or the bouncy castle java libraries. None of these solutions seem to have an easy answer. | I ended up using [Jsch](http://www.jcraft.com/jsch/)- it was pretty straightforward, and seemed to scale up pretty well (I was grabbing a few thousand files every few minutes). | plug: sshj is the only sane choice! See these examples to get started: [download](https://github.com/hierynomus/sshj/blob/master/examples/src/main/java/net/schmizz/sshj/examples/SCPDownload.java), [upload](https://github.com/hierynomus/sshj/blob/master/examples/src/main/java/net/schmizz/sshj/examples/SCPUpload.java). | scp transfer via java | [
"",
"java",
"scp",
"bouncycastle",
"jsse",
"jsch",
""
] |
How would you go about converting a reasonably large (>300K), fairly mature C codebase to C++?
The kind of C I have in mind is split into files roughly corresponding to modules (i.e. less granular than a typical OO class-based decomposition), using internal linkage in lieu private functions and data, and external link... | Having just started on pretty much the same thing a few months ago (on a ten-year-old commercial project, originally written with the "C++ is nothing but C with smart `struct`s" philosophy), I would suggest using the same strategy you'd use to eat an elephant: take it one bite at a time. :-)
As much as possible, split... | What about:
1. Compiling everything in C++'s C subset and get that working, and
2. Implementing a set of [facades](http://en.wikipedia.org/wiki/Facade_pattern) leaving the C code unaltered?
Why is "translation into C++ mandatory"? You can wrap the C code without the pain of converting it into huge classes and so on. | Converting C source to C++ | [
"",
"c++",
"c",
"refactoring",
"legacy",
"program-transformation",
""
] |
In writing some test code I have found that Selector.select() can return without Selector.selectedKeys() containing any keys to process. This is happening in a tight loop when I register an accept()ed channel with
```
SelectionKey.OP_READ | SelectionKey.OP_CONNECT
```
as the operations of interest.
According to the ... | Short answer: remove `OP_CONNECT` from the list of operations you are interested in for the accepted connection -- an accepted connection is already connected.
I managed to reproduce the issue, which might be exactly what's happening to you:
```
import java.net.*;
import java.nio.channels.*;
public class MyNioServe... | The reason is that `OP_CONNECT` and `OP_WRITE` are the same thing under the hood, so you should never be registered for both simultaneously (ditto `OP_ACCEPT` and `OP_READ`), and you should never be registered for `OP_CONNECT` at all when the channel is already connected, as it is in this case, having been accepted.
A... | Java NIO select() returns without selected keys - why? | [
"",
"java",
"select",
"nio",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.