Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Does anyone know how to get the MS Office 2007 .NET C# Interop libraries to work with Vista?
I have a .NET C# application that I have setup to run as a Windows service. This program will open up a Word or Excel template depending on the situation and modify its contents and then save the document back out. All of this... | You should really avoiding running the Office clients as server side apps. Consider using xml as file format (xlsx for Office 2007, or using the Excel workbook xsd for (somewhat) older versions.) Then you would be freed from using the Excel API on the server. | On Vista and Windows Server 2008, services run in something called Session0. Before Vista, regular programs would run in Session0 alongside services.
This means that Session0 has become a desktop-less wasteland where your services can't even access explorer.exe. I'm pretty sure the problem is that Office applications ... | Vista, Office Interop not working | [
"",
"c#",
"interop",
"ms-office",
"office-2007",
""
] |
Is there a .dll version of the [inclued](http://t3.dotgnu.info/blog/php/messy-programmers-beware.html) extension for [PHP](https://www.php.net/manual/en/intro.inclued.php)?
The manual's link for [Inclued on PECL4WIN](http://pecl4win.php.net/ext.php/php_inclued.dll) doesn't help. I don't have a compiler to build my own ... | Which version of PHP are you running? I know someone that can compile you a version.
## update
Alright, got this compiled - I've tested on my 5.2.6 build and it seems to work fine.
I've been told there may be problems using it in a threaded environment (e.g. Windows) but that's only a maybe. Also:
```
[13:10] <g0pz... | As best as I can tell, the Windows version doesn't exist anymore. Maybe whoever was maintaining it before had to stop for some reason.
I wonder what it takes to compile a PECL extension under Windows.
---
**Edit**
Here's some info on compiling a different PECL extension [on Windows](http://groups.google.co.uk/group... | PHP Inclued for Windows? | [
"",
"php",
"windows",
"pecl",
""
] |
I have an application I am writing in PHP5, using the CodeIgniter framework.
I have it running on both Windows (using Xampp) and Ubuntu (using standard Apache, PHP, MySQL stack).
I have a form, that takes XML, parses it (using simpleXML) and posts the results into a database.
On Windows - no problem, works as intende... | It seems like you're running the [Suhosin](http://www.hardened-php.net/suhosin/) PHP extension.
Please have a look at the configuration documentation at: <http://www.hardened-php.net/suhosin/configuration.html>.
The relevant option seems to be (I've never used the Suhosin extension): [suhosin.post.max\_value\_length](... | Please check your PHP configuration on the Linux box and compare it to your Windows settings. Especially the following settings:
* memory\_limit
* post\_max\_size
* magic\_quotes\_gpc
* max\_input\_time
Perhaps you can do a dump of the data posted to the script
```
print_r($_POST);
```
to see what data is really co... | PHP SimpleXML, CodeIgniter and Apache with Suhosin | [
"",
"php",
"xml",
"apache",
"simplexml",
"suhosin",
""
] |
My style of coding includes the following idiom:
```
class Derived : public Base
{
public :
typedef Base super; // note that it could be hidden in
// protected/private section, instead
// Etc.
} ;
```
This enables me to use "super" as an alias to Base, for example, in c... | Bjarne Stroustrup mentions in *Design and Evolution of C++* that `super` as a keyword was considered by the ISO C++ Standards committee the first time C++ was standardized.
Dag Bruck proposed this extension, calling the base class "inherited." The proposal mentioned the multiple inheritance issue, and would have flagg... | I've always used "inherited" rather than super. (Probably due to a Delphi background), and I always make it **private**, to avoid the problem when the 'inherited' is erroneously omitted from a class but a subclass tries to use it.
```
class MyClass : public MyBase
{
private: // Prevents erroneous use by other classes... | Using "super" in C++ | [
"",
"c++",
"coding-style",
""
] |
I have to create the sin function from scratch in my Comp Sci class, and I am getting close to a solution. However, I am still having a few problems. If I put in a value of .5PI or less it works, but otherwise I get the incorrect result. Here is the code I have so far:
```
double i=1;
double sinSoFar = 0;
int term = 1... | Like Federico pointed, the problem probably is in your factorial() or pow(). I ran a test that worked fine replacing your functions with the pow() function provided in the Math class, and this factorial():
```
public static long factorial(long n) {
if (n < 0) throw new RuntimeException("Underflow error i... | Some advices:
* Start with term = 0. The canonical MacLaurin expansion also does
* compute the powers and the factorial *while you are cycling* (that is, updating them at each step). Maybe the problem is within pow() or factorial().
EDIT. Suggestion: once you have computed the k-th term, you can compute the (k+1)-th ... | Making a custom Sin() function in Java | [
"",
"java",
"trigonometry",
""
] |
I have to refactor a large C# application, and I found a lot of functions that are never used. How can I check for unused code, so I can remove all the unused functions? | Yes, ReSharper does this. Right click on your solution and selection "Find Code Issues". One of the results is "Unused Symbols". This will show you classes, methods, etc., that aren't used. | It's a great question, but be warned that you're treading in dangerous waters here. When you're deleting code you will have to make sure you're compiling and testing often.
One great tool come to mind:
NDepend - this tool is just amazing. It takes a little while to grok, and after the first 10 minutes I think most de... | Find unused code | [
"",
"c#",
".net",
"refactoring",
""
] |
I have a HQL query that can generate either an IList of results, or an IEnumerable of results.
However, I want it to return an array of the Entity that I'm selecting, what would be the best way of accomplishing that? I can either enumerate through it and build the array, or use CopyTo() a defined array.
Is there any ... | Which version of .NET are you using? If it's .NET 3.5, I'd just call `ToArray()` and be done with it.
If you only have a non-generic IEnumerable, do something like this:
```
IEnumerable query = ...;
MyEntityType[] array = query.Cast<MyEntityType>().ToArray();
```
If you don't know the type within that method but the... | Put the following in your .cs file:
```
using System.Linq;
```
You will then be able to use the following extension method from System.Linq.Enumerable:
```
public static TSource[] ToArray<TSource>(this System.Collections.Generic.IEnumerable<TSource> source)
```
I.e.
```
IEnumerable<object> query = ...;
object[] bo... | Best way to convert IList or IEnumerable to Array | [
"",
"c#",
"nhibernate",
""
] |
I'm having a small problem in Java. I have an interface called Modifiable. Objects implementing this interface are Modifiable.
I also have a ModifyCommand class (with the Command pattern) that receive two Modifiable objects (to swap them in a list further on - that's not my question, I designed that solution already).... | If you're using java 1.5 or higher, you can get the behavior you want and remove casting this way:
```
public interface Modifiable<T extends Modifiable<T>> extends Cloneable {
T clone();
}
public class Foo implements Modifiable<Foo> {
public Foo clone() { //this is required
return null; //todo: real w... | You don't need to redefine the clone method on the interface Modifiable.
Check the documentation: <http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Cloneable.html>
I understand that you are trying to force everyone to override clone method(), but you can't do it.
In another way, you cannot override a class on a int... | Mandatory cloneable interface in Java | [
"",
"java",
"interface",
"overriding",
"clone",
""
] |
I know about [`SortedSet`](https://docs.oracle.com/javase/9/docs/api/java/util/SortedSet.html), but in my case I need something that implements `List`, and not `Set`. So is there an implementation out there, in the API or elsewhere?
It shouldn't be hard to implement myself, but I figured why not ask people here first? | There's no Java collection in the standard library to do this. [`LinkedHashSet<E>`](https://docs.oracle.com/javase/9/docs/api/java/util/LinkedHashSet.html) preserves ordering similarly to a `List`, though, so if you wrap your set in a `List` when you want to use it as a `List` you'll get the semantics you want.
Altern... | Here is what I did and it works.
Assuming I have an `ArrayList` to work with the first thing I did was created a new `LinkedHashSet`.
```
LinkedHashSet<E> hashSet = new LinkedHashSet<E>()
```
Then I attempt to add my new element to the `LinkedHashSet`. The add method does not alter the `LinkedHasSet` and returns fal... | Is there a no-duplicate List implementation out there? | [
"",
"java",
"list",
"collections",
"duplicates",
""
] |
I have this ListBox which is bound to an ObservableCollection. Each object in the list implements an interface called ISelectable
```
public interface ISelectable : INotifyPropertyChanged
{
event EventHandler IsSelected;
bool Selected { get; set; }
string DisplayText { get; }
}
```
I want to keep track of... | You could also accomplish this by data binding ListBoxItem.IsSelected to your Selected property. The idea is to set the binding for each of the ListBoxItems as they are created. This can be done using a style that targets each of the ListBoxItems generated for the ListBox.
This way when an item in the ListBox is selec... | Have you looked at the list box's SelectedItemChanged and SelectedIndexChanged events?
These should be triggered whenever a selection is changed, no matter how it is selected. | How do I synchronize the SelectedItem of a ListBox? | [
"",
"c#",
"wpf",
"listbox",
""
] |
What I'd like to avoid:
```
ManagementClass m = new ManagementClass("Win32_LogicalDisk");
ManagementObjectCollection managementObjects = m.GetInstances();
List<ManagementObject> managementList = new List<ManagementObject>();
foreach(ManagementObject m in managementObjects){
managementList.Add(m);
}
```
Isn't... | What version of the framework? With 3.5 you could presumably use:
```
List<ManagementObject> managementList = managementObjects.Cast<ManagementObject>().ToList();
```
(edited to remove simpler version; I checked and `ManagementObjectCollection` only implements the non-generic `IEnumerable` form) | You could use
```
using System.Linq;
```
That will give you a ToList<> extension method for ICollection<> | Fastest Convert from Collection to List<T> | [
"",
"c#",
"collections",
""
] |
How do I detect if a process is already running under the Windows Task Manager? I'd like to get the memory and cpu usage as well. | Have you looked into the [System.Diagnostics.Process](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process) Class. | Simple example...
```
bool processIsRunning(string process)
{
return (System.Diagnostics.Process.GetProcessesByName(process).Length != 0);
}
```
Oops... forgot the mem usage, etc...
```
bool processIsRunning(string process)
{
System.Diagnostics.Process[] processes =
System.Diagnostics.Process.GetProcessesBy... | Detecting a Process is already running in windows using C# .net | [
"",
"c#",
".net",
"windows",
"winforms",
""
] |
Can you recommend a Java library for reading, parsing, validating and mapping rows in a comma separated value (CSV) file to Java value objects (JavaBeans)? | We have used
<http://opencsv.sourceforge.net/>
with good success
I also came across another question with good links:
[Java lib or app to convert CSV to XML file?](https://stackoverflow.com/questions/123/csv-file-to-xml) | [Super CSV](http://supercsv.sourceforge.net) is a great choice for reading/parsing, validating and mapping CSV files to POJOs!
We (the Super CSV team) have just released a new version (you can [download](http://supercsv.sourceforge.net/downloading.html) it from SourceForge or Maven).
# Reading a CSV file
The followi... | Can you recommend a Java library for reading (and possibly writing) CSV files? | [
"",
"java",
"parsing",
"csv",
""
] |
If I have a `Linq` to `SQL` expression like this:
```
from subscription in dbContext.Subscriptions
where subscription.Expires > DateTime.Now
select subscription
```
I want this to to use the SQL Servers `GETDATE()` function instead of the time of the machine running the `C#` program.
The next question would be ho... | Try [this](http://peteohanlon.wordpress.com/2008/01/11/sql-server-getdate-and-linq-to-sql/):
```
[Function(Name="GetDate", IsComposable=true)]
public DateTime GetSystemDate()
{
MethodInfo mi = MethodBase.GetCurrentMethod() as MethodInfo;
return (DateTime)this.ExecuteMethodCall(this, mi, new object[]{... | If you don't mind querying the database before every use, I would suggest the following workaround: Use ExecuteQuery in one place to get the date in the data context like this:
```
public partial class YourDataContext
{
public DateTime GetDate()
{
return ExecuteQuery<DateTime>("SELECT GETDATE()").First();
}
... | How do I use SQL's GETDATE() and DATEADD() in a Linq to SQL expression? | [
"",
"sql",
"linq-to-sql",
""
] |
What's the most efficient way of getting the value of the SERIAL column after the INSERT statement? I.e. I am looking for a way to replicate `@@IDENTITY` or `SCOPE_IDENTITY` functionality of MS SQL | The value of the last SERIAL insert is stored in the SQLCA record, as the second entry in the sqlerrd array. Brian's answer is correct for ESQL/C, but you haven't mentioned what language you're using.
If you're writing a stored procedure, the value can be found thus:
```
LET new_id = DBINFO('sqlca.sqlerrd1');
```
It... | I have seen this used.
```
if LOCAL_SQLCA^.sqlcode = 0 then
/* return serial */
Result := LOCAL_SQLCA^.sqlerrd[1]
else
/* return error code */
Result := -(Abs(LOCAL_SQLCA^.sqlcode));
``` | Informix: how to get an id of the last inserted record | [
"",
"sql",
"informix",
"identity",
""
] |
So, simple procedure, calculate a factorial number. Code is as follows.
```
int calcFactorial(int num)
{
int total = 1;
if (num == 0)
{
return 0;
}
for (num; num > 0; num--)
{
total *= num;
}
return total;
}
```
Now, this works fine and dandy (There are certainly qui... | 2^32 doesn't give you the limit for signed integers.
The signed integer limit is actually [2147483647](http://msdn.microsoft.com/en-us/library/296az74e(VS.80).aspx) (if you're developing on Windows using the MS tools, other toolsuites/platforms would have their own limits that are probably similar).
You'll need a C++... | In addition to the other comments, I'd like to point out two serious bugs in your code.
* You have no guard against negative numbers.
* The factorial of zero is one, not zero. | When I calculate a large factorial, why do I get a negative number? | [
"",
"c++",
"signed",
"factorial",
""
] |
I have an oc4j installation bereft of any release notes or version documentation. In the absence of such documents, how do I know for sure, which version of oc4j I am using? | Check Server header in HTTP headers. For example with wget or curl;
```
wget -S <url-to-server>
curl -I <url-to-server>
```
or with browser, which can show HTTP headers.
There should be a header something like
```
Server: Oracle-Application-Server-10g/10.1.3.1.0 Oracle-HTTP-Server
``` | If you have access to the OC4J JAR file, you can do:
```
java -jar oc4j.jar -version
``` | How to determine the version of oc4j being used? | [
"",
"java",
"oracle",
"oc4j",
""
] |
Why does the C++ STL not provide any "tree" containers, and what's the best thing to use instead?
I want to store a hierarchy of objects as a tree, rather than use a tree as a performance enhancement... | There are two reasons you could want to use a tree:
You want to mirror the problem using a tree-like structure:
For this we have [boost graph library](https://www.boost.org/doc/libs/1_70_0/libs/graph/doc/index.html)
Or you want a container that has tree like access characteristics
For this we have
* [`std::map`](h... | Probably for the same reason that there is no tree container in boost. There are many ways to implement such a container, and there is no good way to satisfy everyone who would use it.
Some issues to consider:
* Are the number of children for a node fixed or variable?
* How much overhead per node? - ie, do you need p... | Why does the C++ STL not provide any "tree" containers? | [
"",
"c++",
"data-structures",
"tree",
"stl",
""
] |
For a particular application, I need the screen saver to be disabled while it's running. The operator COULD manually turn it off, and then back on later, but the easiest thing to do would be to just keep the screen saver at bay while the application is running.
How do I do this? I've found code for actually turning of... | [theoldnewthing](https://devblogs.microsoft.com/oldnewthing/20090820-00/?p=17043 "Raymond Chen, The New Old Thing") has your answer: Use [`SetThreadExecutionState(ES_DISPLAY_REQUIRED)`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setthreadexecutionstate).
This is used by video players and Po... | **EDIT - I have an updated answer using the modern Power Availability Request API (supersedes `SetThreadExecutionState`) here: <https://stackoverflow.com/a/63632916/67824>**
```
[FlagsAttribute]
public enum EXECUTION_STATE : uint
{
ES_SYSTEM_REQUIRED = 0x00000001,
ES_DISPLAY_REQUIRED = 0x00000002,
// Legac... | Need to disable the screen saver / screen locking in Windows C#/.Net | [
"",
"c#",
"screensaver",
""
] |
If I want to construct a std::string with a line like:
```
std::string my_string("a\0b");
```
Where i want to have three characters in the resulting string (a, null, b), I only get one. What is the proper syntax? | ### Since C++14
we have been able to create [literal `std::string`](https://en.cppreference.com/w/cpp/string/basic_string/operator%22%22s)
```
#include <iostream>
#include <string>
int main()
{
using namespace std::string_literals;
std::string s = "pl-\0-op"s; // <- Notice the "s" at the end
... | If you are doing manipulation like you would with a c-style string (array of chars) consider using
```
std::vector<char>
```
You have more freedom to treat it like an array in the same manner you would treat a c-string. You can use copy() to copy into a string:
```
std::vector<char> vec(100)
strncpy(&vec[0], "blah b... | How do you construct a std::string with an embedded null? | [
"",
"c++",
"null",
"stdstring",
""
] |
Here's the information [according to the official documentation](http://www.php.net/manual/en/language.basic-syntax.php):
> There are four different pairs of
> opening and closing tags which can be
> used in PHP. Two of those, `<?php ?>`
> and `<script language="php"> </script>`,
> are always available. The other two
... | There must be a clear distinction between the PHP short tag (`<?`) and shorthand echo tag (`<?=`)
The former is prohibited by the [PHP Coding standard](https://www.php-fig.org/psr/psr-1/), mostly out of common sense because it's a PITA if you ever have to move your code to a server where it's not supported (and you ca... | I'm too fond of `<?=$whatever?>` to let it go. Never had a problem with it. I'll wait until it bites me in the ass. In all seriousness, 85% of (my) clients have access to php.ini in the **rare** occasion they are turned off. The other 15% use mainstream hosting providers, and virtually all of them have them enabled. I ... | Are PHP short tags acceptable to use? | [
"",
"php",
"php-shorttags",
""
] |
I've got a list in a Python program that contains a series of numbers, which are themselves ASCII values. How do I convert this into a "regular" string that I can echo to the screen? | You are probably looking for 'chr()':
```
>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(chr(i) for i in L)
'hello, world'
``` | Same basic solution as others, but I personally prefer to use map instead of the list comprehension:
```
>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(map(chr,L))
'hello, world'
``` | How do I convert a list of ascii values to a string in python? | [
"",
"python",
"string",
"ascii",
""
] |
How can I monitor the memory being used by a native C DLL that is being called from Java via JNI? Using standard Java monitoring tools and options I can see the Java memory space, but I cannot view any memory used by the C DLL. Java is using ~70MB, but the task in the Task Manager shows 200Mb+, and I'd like to see what... | You can monitor the native heap with counters in the performance montitor. (perfmon32) however it wont break it down for you on a per DLL basis, even jvm.dll will be included here.
Most profiling tools out there can attach to a process and capture and track memory allocations and deallocations. This allows them to spe... | Have you tried using [Process Viewer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) to dig deeper.
If you have the source to the DLL you could rebuild with debug libraries and possibly a mem allocation tracker - and debug using visual C++ debugger (you'll need to tell it to use the java application).
... | Monitoring memory usage for a C DLL called with Java via JNI? | [
"",
"java",
"c",
"memory",
"dll",
"java-native-interface",
""
] |
I'm trying to configure my WAR project build to fail if the line or branch coverage is below given thresholds. I've been using the configuration provided on page 455 of the excellent book [Java Power Tools](http://oreilly.com/catalog/9780596527938/), but with no success. Here's the relevant snippet of my project's Mave... | To my knowledge, *if the `<haltOnFailure>` element is set to true and any of the specified checks fails, then Cobertura will cause the build to fail* which is what you're asking for. But actually, this element defaults to `true` if you do not specify it so you **don't have to** add it to your [configuration checks](htt... | Add the following to the <check/> configuration.
```
<haltOnFailure>true</haltOnFailure>
``` | How to get Cobertura to fail M2 build for low code coverage | [
"",
"java",
"maven-2",
"build-automation",
"code-coverage",
"cobertura",
""
] |
Could someone supply some code that would get the xpath of a System.Xml.XmlNode instance?
Thanks! | Okay, I couldn't resist having a go at it. It'll only work for attributes and elements, but hey... what can you expect in 15 minutes :) Likewise there may very well be a cleaner way of doing it.
It is superfluous to include the index on every element (particularly the root one!) but it's easier than trying to work out... | Jon's correct that there are any number of XPath expressions that will yield the same node in an an instance document. The simplest way to build an expression that unambiguously yields a specific node is a chain of node tests that use the node position in the predicate, e.g.:
```
/node()[0]/node()[2]/node()[6]/node()[... | How to get xpath from an XmlNode instance | [
"",
"c#",
".net",
"xml",
".net-2.0",
""
] |
We've got a fairly large amount of code that just made the jump to Java 5. We've been using generics in those components targeted at being released in the Java 5 version, but the remaining code is, of course, full of raw types. I've set the compiler to generate an error for raw types and started manually clearing them,... | I would suggest ignoring the warnings. Otherwise, you'll be putting a lot of time into updating the legacy code without making any improvements to its functionality.
**Update:** Great comment from [Luke](https://stackoverflow.com/users/25920/luke) that I thought should get more visibility:
*"Generics are a way to catc... | As far as I know, you're going about it as efficiently as possible. It's
obviously not perfect, but you'll finish eventually.
I recommend that you do it in stages, however; there are likely parts of the
code that would benefit more from this than others, focus on those. Trying to
do it all in one sweep runs the risk o... | Generics in legacy code | [
"",
"java",
"generics",
"migration",
"legacy-code",
""
] |
I just noticed that you can not use standard math operators on an `enum` such as `++` or `+=`.
So what is the best way to iterate through all of the values in a C++ `enum`? | The typical way is as follows:
```
enum Foo {
One,
Two,
Three,
Last
};
for ( int fooInt = One; fooInt != Last; fooInt++ )
{
Foo foo = static_cast<Foo>(fooInt);
// ...
}
```
Please note, the enum `Last` is meant to be skipped by the iteration. Utilizing this "fake" `Last` enum, you don't have to update ... | ```
#include <iostream>
#include <algorithm>
namespace MyEnum
{
enum Type
{
a = 100,
b = 220,
c = -1
};
static const Type All[] = { a, b, c };
}
void fun( const MyEnum::Type e )
{
std::cout << e << std::endl;
}
int main()
{
// all
for ( const auto e : MyEnum::All )
fun( e );
// some... | How can I iterate over an enum? | [
"",
"c++",
"enums",
""
] |
Is there explicit support for Single Table Inheritance in Django? Last I heard, the feature was still under development and debate.
Are there libraries/hacks I can use in the meantime to capture the basic behavior? I have a hierarchy that mixes different objects. The canonical example of a corporation structure with a... | There are currently two forms of inheritance in Django - MTI (model table inheritance) and ABC (abstract base classes).
I wrote a [tutorial](http://web.archive.org/web/20090227074910/http://thisweekindjango.com/articles/2008/jun/17/abstract-base-classes-vs-model-tab/) on what's going on under the hood.
You can also r... | ## Summary
Django's [proxy models](https://docs.djangoproject.com/en/3.0/topics/db/models/#proxy-models) provide the basis for Single Table Inheritance.
However, some effort is required to make it work.
Skip to the end for a re-usable example.
## Background
[Martin Fowler](https://martinfowler.com/eaaCatalog/singl... | Single Table Inheritance in Django | [
"",
"python",
"django",
"django-models",
"single-table-inheritance",
""
] |
I am trying to detect which web in sharepoint that the user is looking at right now. One approach could be to read the URls from the browser and try to compare them to a reference URL to the sharepoint solution. I have not yet been able to locate any solution that works in both IE and Firefox.
The idea is to write a s... | It is possible to do this in a very hacky and prone to breakage way using the Win32 API function FindWindow.
The following C++ example that finds a running instance of the windows Calculator and gets the value of the edit field in it. You should be able to do something similar in C#. Disclaimer: I haven't actually che... | Its fairly easy in IE using the ActiveX shell application object in Javascript. Below is the sample code:
```
function GetURL()
{
var oShell = new ActiveXObject('shell.application');
var oColl = oShell.Windows();
for (var i = 0;i<oColl.count;i++)
{
try
{
var Title = oColl(i).document.title;
if (Title.ind... | How do I get the URLs from any tab in any open browser | [
"",
"c#",
"sharepoint",
"url",
""
] |
I'm working on a large, aging code base for an MFC app. The code has been worked on by many developers over time, and as a result, we have three different ways throughout the code of dealing with the possibility of an allocation failure with new.
The first way is to test for NULL on the result of new. We don't use not... | It will depend on the compile options for the static libraries to be linked to the application.
If the libraries are compiled with a configuration to use the **static** Standard C++ run-time then I would expect the `operator new` from the Standard C++ run-time to be called.
If libraries are compiled with a configurat... | Congratulations -- you seem to have stumped all of us. :-)
In theory, if MFC provides an overload for the global `new` function, then it should be used by *all* code in the program. But since the static libraries were compiled without knowing about that, I can't say for certain that it would.
The best I can suggest i... | Do c++ static libraries without mfc that are linked to an MFC project throw bad_alloc or CMemoryException*? | [
"",
"c++",
"exception",
"mfc",
""
] |
Would you guys think that a master page should be part of the company's framework or it should be part of each application? Or perhaps the company's framework should only have a interface to provide the least functionality to all master pages ?
Currenlty we face two problems: Firstly, the original idea was to have a c... | I would try to move UI elements like common controls into your framework libraries, and create a master page for each application *in* the application. This will give you the ability to maintain common UI elements across your applications through the use of common controls, and will provide the flexibility to create di... | Share some CSS and design library (templates, images, palette,) but a single shared master page is unlikely to be flexible enough. | Master Pages - Design question | [
"",
"c#",
"asp.net",
"master-pages",
""
] |
Hi I want to have two tables each have an INT "id" column which will auto-increment but I don't want either "id" columns to ever share the same number. What is this called and what's the best way to do it? Sequence? Iterator? Index? Incrementor?
Motivation: we're migrating from one schema to a another and have a web-p... | Just configure the identity increment to be >1 e.g. table one uses IDENTITY (1, 10) [1,11,21...] and table two uses IDENTITY (2, 10) [2,12,22...]. This will also give you some room for expansion if needed later. | I think using a [GUID](http://en.wikipedia.org/wiki/Guid) would be the most straightforward way, if I understand you correctly.
```
SELECT NEWID()
``` | Share auto-incremented primary key between two tables | [
"",
"sql",
"sql-server",
""
] |
I have the following JavaScript code to pop up a window in Internet Explorer. The code is executed from a page within a Microsoft CRM modal dialog box. (RequestID is a string that is always the same in the test system - at the moment it contains "abcdefg" - without the quotes).
```
var cancelUrl = "CancelRequest.aspx?... | Ah, I think I got it... missed it in the description...
You are **trying to open a non-modal** window **from a modal dialog** in **IE**.
This AFAIK, should not work.
Try opening another modal window instead.
Effectively you are saying...
on window A, open up modal window B, now open up non-modal window C, which is... | This code is simple. Use debugger and see what is going on.
Check that site with FireFox or Chrome, they have JS debuggers.
**Edit:**
Add try/catch block around `window.open()` and see if there is some exception there.
**Edit 2:**
I see now that you are sending characters as RequestId. You should check if that URL... | Strange behaviour opening pop-up window in Internet Explorer | [
"",
"javascript",
"internet-explorer",
"popup",
"microsoft-dynamics",
""
] |
I have code like this:
```
class RetInterface {...}
class Ret1: public RetInterface {...}
class AInterface
{
public:
virtual boost::shared_ptr<RetInterface> get_r() const = 0;
...
};
class A1: public AInterface
{
public:
boost::shared_ptr<Ret1> get_r() const {...}
...
};
```
**This code doe... | Firstly, this is indeed how it works in C++: the return type of a virtual function in a derived class must be the same as in the base class. There is the special exception that a function that returns a reference/pointer to some class X can be overridden by a function that returns a reference/pointer to a class that de... | There is a neat solution posted in [this blog post](https://www.fluentcpp.com/2017/09/12/how-to-return-a-smart-pointer-and-use-covariance/) (from Raoul Borges)
An excerpt of the bit prior to adding support for mulitple inheritance and abstract methods is:
```
template <typename Derived, typename Base>
class clone_inh... | How can I use covariant return types with smart pointers? | [
"",
"c++",
"covariance",
"smart-pointers",
""
] |
I am using VS 2008/C# and binding a local List of helper classes as the DataSource for a DataGridView control. Calling the Remove() method on my List of helper classes fires the CellFormatting event of the DataGridView, which makes sense (a bit).
When removing whatever happens to be the DataBoundItem of the last row i... | I've had this problem in the past, and if I remember correctly there's one of two things you can do. When you remove the record from the collection, set the datasource property on your datagridview to null, and then rebind it to your list. That should do the trick.
Alternatively, you can handle the DataError event on ... | First just disable the property of `Datagridview` as
```
dataGridView1.AllowUserToAddRows = false;
```
and then just remove the last rows as many rows as you want either with for loop by keeping -1.
```
dataGridView1.Rows.RemoveAt(dataGridView1.Rows.Count - 1);
dataGridView1.Rows.RemoveAt(dataGridView1.Rows.Count - ... | Remove Last Row Databound DataGridView C# | [
"",
"c#",
"datagridview",
""
] |
What is the best way to unit test a method that doesn't return anything? Specifically in c#.
What I am really trying to test is a method that takes a log file and parses it for specific strings. The strings are then inserted into a database. Nothing that hasn't been done before but being VERY new to TDD I am wondering... | If a method doesn't return anything, it's either one of the following
* **imperative** - You're either asking the object to do something to itself.. e.g change state (without expecting any confirmation.. its assumed that it will be done)
* **informational** - just notifying someone that something happened (without exp... | Test its side-effects. This includes:
* Does it throw any exceptions? (If it should, check that it does. If it shouldn't, try some corner cases which might if you're not careful - null arguments being the most obvious thing.)
* Does it play nicely with its parameters? (If they're mutable, does it mutate them when it s... | Unit testing void methods? | [
"",
"c#",
".net",
"unit-testing",
"tdd",
"void",
""
] |
Kinda long title, but anyways...
I've been looking at these examples, specifically on the parts on writing and reading the size of the message to the byte streams
<http://doc.trolltech.com/4.4/network-fortuneclient-client-cpp.html>
<http://doc.trolltech.com/4.4/network-fortuneserver-server-cpp.html>
But I can't s... | Generally you would send the length first. Both ends should agree on what a length looks like - for example, you might be happy to use fixed 4-byte length prefix as binary:
```
byte[] data = ...
int len = data.Length;
byte[] prefix = Bitconverter.GetBytes(len);
stream.Write(prefix, 0, prefix.Length); // fixed ... | Instead of `data.Length`, try:
```
writer.Write(chr(data.Length) + data);
```
This will prefix every data block with one byte indicating its length (up to 255 bytes long). As you requested, this is only a nudge. :)
Update: I just remembered that C# is all Unicode and stuff, so chr() probably gives you more than one ... | C# streaming sockets, how to separate messages? | [
"",
"c#",
"sockets",
""
] |
How can I fetch images from a server?
I've got this bit of code which allows me to draw some images on a canvas.
```
<html>
<head>
<script type="text/javascript">
function draw(){
var canvas = document.getElementById('canv');
var ctx = canvas.getContext('2d');
for (i=0;i<document.... | Use the built-in [JavaScript Image object](http://www.w3schools.com/htmldom/dom_obj_image.asp).
Here is a very simple example of using the Image object:
```
myimage = new Image();
myimage.src = 'http://myserver/nextimage.cgi';
```
Here is a more appropriate mechanism for your scenario from the comments on this answe... | If you want to draw an image to a canvas you also need to wait for the image to actually load, so the correct thing to do will be:
```
myimage = new Image();
myimage.onload = function() {
context.drawImage(myimage, ...);
}
myimage.src = 'http://myserver/nextimage.cgi';
``` | How to fetch a remote image to display in a canvas? | [
"",
"javascript",
"image",
"canvas",
""
] |
I have a class called EventConsumer which defines an event EventConsumed and a method OnEventConsumed as follows:
```
public event EventHandler EventConsumed;
public virtual void OnEventConsumed(object sender, EventArgs e)
{
if (EventConsumed != null)
EventConsumed(this, e);
}
```
I need to add attribute... | Here's the IL from a sample app:
```
.method public hidebysig virtual instance void OnEventConsumed(object sender, class [mscorlib]System.EventArgs e) cil managed
{
.maxstack 8
L_0000: nop
L_0001: ldarg.0
L_0002: ldarg.1
L_0003: ldarg.2
L_0004: call instance void... | I was actually really close - the problem was that I wasn't loading the 'this' argument, and that Callvirt calls the subclass method, where I actually wanted Call. So that section becomes:
```
// load 'this' and the first two args onto the stack
ilGenerator.Emit(OpCodes.Ldarg_0);
ilGenerator.Emit(OpCodes.Ldarg_1);
ilG... | What's the MSIL to call a base class's event handler? | [
"",
"c#",
"cil",
"reflection.emit",
""
] |
I'd like to invoke bash using a string as input. Something like:
```
sh -l -c "./foo"
```
I'd like to do this from Java. Unfortunately, when I try to invoke the command using `getRuntime().exec`, I get the following error:
```
foo": -c: line 0: unexpected EOF while looking for matching `"'
foo": -c: lin... | Use this:
```
Runtime.getRuntime().exec(new String[] {"sh", "-l", "-c", "./foo"});
```
Main point: don't put the double quotes in. That's only used when writing a command-line in the shell!
e.g., `echo "Hello, world!"` (as typed in the shell) gets translated to:
```
Runtime.getRuntime().exec(new String[] {"echo", "... | Windows command lines behave differently from UNIX, Mac OS X and GNU/Linux.
On Windows the process receives the input text verbatim after the executable name (and space). It's then up to the program to parse the command line (which is usually done implicitly, the programmer is often clueless about the process).
In GN... | Using Quotes within getRuntime().exec | [
"",
"java",
"exec",
"runtime.exec",
""
] |
Consider this:
```
public class TestClass {
private String a;
private String b;
public TestClass()
{
a = "initialized";
}
public void doSomething()
{
String c;
a.notify(); // This is fine
b.notify(); // This is fine - but will end in an exception
c.notify(); // "... | The rules for definite assignment are quite difficult (read chapter 16 of JLS 3rd Ed). It's not practical to enforce definite assignment on fields. As it stands, it's even possible to observe final fields before they are initialised. | The language defines it this way.
Instance variables of object type default to being initialized to null.
Local variables of object type are not initialized by default and it's a compile time error to access an undefined variable.
See section 4.12.5 for SE7 (same section still as of SE14)
<http://docs.oracle.com/java... | Uninitialized variables and members in Java | [
"",
"java",
"oop",
"variables",
""
] |
My database application is going to be deployed at multiple sites in different time zones.
I need a T-SQL function that will determine the UTC timestamp of midnight on January 1 of the current year for YTD calculations. All of the data is stored in UTC timestamps.
For example, Chicago is UTC-6 with Daylight Savings T... | Check out this previous question and answer for related information:
[Effectively Converting dates between UTC and Local (ie. PST) time in SQL 2005](https://stackoverflow.com/questions/24797/effectively-converting-dates-between-utc-and-local-ie-pst-time-in-sql-2005#25073)
(To summarize, you do need to build time zone... | Hmm, I guess I'm not understanding the problem. If the database app is already storing UTC timestamps for all of it's transactions, and you want to sum up some values since the first of the year "local time", your condition would have to be something like:
```
(timestamp + (getutcdate() - getdate())) > cast('01/01/200... | Determine Time Zone Offset in T-SQL | [
"",
"sql",
"sql-server",
"sql-server-2005",
"timezone",
""
] |
What are some strategies to achieve code separation in AJAX applications?
I am building a PHP application that I would like to have a nice AJAX front end on. I have long since learned to use some kind of templating in my PHP code to make sure I maintain good separation between my logic and display code, but I'm having... | * write your templates in the HTML page, probably within a hidden element.
* fetch data via AJAX calls, i find easier to use JSON, so you don't have to 'reformat' XML, it's only data.
* apply the template to the data to generate HTML and insert into the displayed page.
check some jQuery templating plugins: [jsRepeater... | I've been asking similar questions lately ([here](https://stackoverflow.com/questions/251814/jquery-and-organized-code) and [here](https://stackoverflow.com/questions/247209/javascript-how-do-you-organize-this-mess)) and I've found a couple things that can help. I understand the same issues that you're finding with UI ... | Code separation in AJAX applications | [
"",
"php",
"jquery",
"ajax",
""
] |
I've been working with the Joomla framework and I have noticed that they use a convention to designate private or protected methods (they put an underscore "`_`" in front of the method name), but they do not explicitly declare any methods `public`, `private`, or `protected`. Why is this? Does it have to do with portabi... | public, private and protected are PHP5 keywords. unfortunately, PHP4 still has a very high install base (especially amongst shared hosting services).
here's a [pretty pic](http://www.nexen.net/images/stories/phpversion/200807/evolution.milieu.png) showing july usage rates (text in french). **spoiler**: php4 still has ... | There's some good arguments for not using `private` methods and properties over here: <http://aperiplus.sourceforge.net/visibility.php>
Includes: makes coding and reading code harder. Makes re-using classes and debugging harder.
I'm not sold either way, but I would like to see an informed rebuttal of that article, if... | Why not use 'protected' or 'private' in PHP? | [
"",
"php",
"encapsulation",
""
] |
I need to be able to receive a fax in a java application. I was wondering what are some ways of doing this. Efax? Use a fax to email provider? | I suggest using fax to email. I've been using [RapidFax](http://www.rapidfax.com) for the past year or so, and it is fairly inexpensive and fast. I'm happy with it.
Alternatively, there are some Web Service based fax services, like [InterFax](http://www.interfax.net). | We use [Ringcentral.com](http://www.ringcentral.com) which sends the fax as a PDF to an email address. We then access the PDF by accessing the POP3 account programatically (sp?). | How can I programmatically receive faxes? Preferable in java | [
"",
"java",
"fax",
""
] |
I want to make a link call a Javascript function through the onclick event and not do anything else (follow the link). What is the best way to do that? I usually do this:
```
<a href="#" onclick="foo()">Click</a>
```
But I'm not sure that is the best way and in this case it is navigating to page.html# which isn't goo... | Usually, you should always have a fall back link to make sure that clients with JavaScript disabled still has some functionality. This concept is called unobtrusive JavaScript. Example... Let's say you have the following search link:
```
<a href="search.php" id="searchLink">Search</a>
```
You can always do the follow... | Just make sure to return `false` from your onclick handler. E.g. `foo()` should be defined as:
```
function foo() {
// ... do stuff
return false;
}
```
Someone pointed out in the comments that you may need to change your HTML slightly for that to work:
```
<a href="#" onclick="return foo()">Click</a>
```
Or jus... | What is the right way to change the behavior of an <a> tag? | [
"",
"javascript",
"ajax",
""
] |
I have a collection of Boost unit tests I want to run as a console application.
When I'm working on the project and I run the tests I would like to be able to debug the tests, and I would like to have the console stay open after the tests run.
I see that if I run in release mode the console window stays up after the ... | Boost test offers the following [usage recommendations for Visual Studio](http://www.boost.org/doc/libs/1_56_0/libs/test/doc/html/utf/usage-recommendations/dot-net-specific.html) that would enable you to run the unit tests automatically at the end of compilation and capture the output into the build window.
The nice s... | Try to run the application with the `Ctrl` + `F5` combination. | How do I make Visual Studio pause after executing a console application in debug mode? | [
"",
"c++",
"visual-studio",
"unit-testing",
"boost",
"console",
""
] |
I want to create an ini file to store some settings for my application. Is it a good idea to find where the jar file is located and create an ini file there? If yes, then how can I find the location of the jar file?
But if you know a better solution for something like this, I would like to hear some of them.
**EDIT**... | You can locate your application directory using the ClassLoader. See: [Java: finding the application directory](http://illegalargumentexception.blogspot.com/2008/04/java-finding-application-directory.html). Rather than an *.INI* file, use a *.properties* file - you can load and save this via the [Properties](http://jav... | If the settings are only written by your application (rather than edited manually), consider using the [Preferences API](http://docs.oracle.com/javase/8/docs/technotes/guides/preferences/index.html). | How to create an .INI file to store some settings in Java? | [
"",
"java",
"settings",
"configuration-files",
""
] |
To save some typing and clarify my code, is there a standard version of the following method?
```
public static boolean bothNullOrEqual(Object x, Object y) {
return ( x == null ? y == null : x.equals(y) );
}
``` | With Java 7 you can now directly do a null safe equals:
[Objects.equals(x, y)](http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html)
(The Jakarta Commons library ObjectUtils.equals() has become obsolete with Java 7) | if by some chance you are have access to the Jakarta Commons library there is [ObjectUtils.equals()](http://commons.apache.org/lang/apidocs/org/apache/commons/lang3/ObjectUtils.html#equals(java.lang.Object,%20java.lang.Object)) and lots of other useful functions.
EDIT: misread the question initially | Is there a Java standard "both null or equal" static method? | [
"",
"java",
"null",
"equals",
""
] |
I have a structure like this:
```
<ul>
<li>text1</li>
<li>text2</li>
<li>text3</li>
</ul>
```
How do I use javascript or jQuery to get the text as an array?
```
['text1', 'text2', 'text3']
```
My plan after this is to assemble it into a string, probably using `.join(', ')`, and get it in a format like this:
... | ```
var optionTexts = [];
$("ul li").each(function() { optionTexts.push($(this).text()) });
```
...should do the trick. To get the final output you're looking for, `join()` plus some concatenation will do nicely:
```
var quotedCSV = '"' + optionTexts.join('", "') + '"';
``` | Without redundant intermediate arrays:
```
var arr = $('li').map(function(i,el) {
return $(el).text();
}).get();
```
See jsfiddle [demo](http://jsfiddle.net/cC8fT/) | Get an array of list element contents in jQuery | [
"",
"javascript",
"jquery",
""
] |
I'm using a ListView in C# to make a grid. I would like to find out a way to be able to highlight a specific cell, programatically. I only need to highlight one cell.
I've experimented with Owner Drawn subitems, but using the below code, I get highlighted cells, but no text! Are there any ideas on how to get this work... | You can do this without owner-drawing the list:
```
// create a new list item with a subitem that has white text on a blue background
ListViewItem lvi = new ListViewItem( "item text" );
lvi.UseItemStyleForSubItems = false;
lvi.SubItems.Add( new ListViewItem.ListViewSubItem( lvi,
"subitem", Color.White, Color.Blue,... | Figured it out. Here's code to toggle the highlight of a specific subitem.
```
listView1.Items[1].UseItemStyleForSubItems = false;
if (listView1.Items[1].SubItems[10].BackColor == Color.DarkBlue)
{
listView1.Items[1].SubItems[10].BackColor = Color.White;
listView1.Items[1].SubItems[10].ForeColor = Color.Black;... | C# ListView Detail, Highlight a single cell | [
"",
"c#",
"listview",
"highlight",
"ownerdrawn",
""
] |
I'm using an Informix (Version 7.32) DB. On one operation I create a temp table with the ID of a regular table and a serial column (so I would have all the IDs from the regular table numbered continuously). But I want to insert the info from the regular table ordered by ID something like:
```
CREATE TEMP TABLE tempTab... | You might try it iterating a cursor over the SELECT ... ORDER BY and doing the INSERTs within the loop. | You can do this by breaking up the SQL into two temp tables:
```
CREATE TEMP TABLE tempTable1 (
id serial,
folio int);
SELECT folio FROM regularTable ORDER BY folio
INTO TEMP tempTable2;
INSERT INTO tempTable1(id,folio) SELECT 0,folio FROM tempTable2;
``` | Insert into temp values (select.... order by id) | [
"",
"sql",
"insert",
"informix",
""
] |
When using Maven to build an executable JAR, how do I specify the JVM arguments that are used when the JAR is executed?
I can specify the main class using `<mainClass>`. I suspect there's a similar attribute for JVM arguments. Specially I need to specify the maximum memory (example -Xmx500m).
Here's my assembly plugi... | I don't know of any such mechanism. The JVM configuration is specified by the calling java command.
Here's the jar file specification which conspicuously doesn't mention any attribute other than Main-Class for stand-alone execution:
<http://java.sun.com/javase/6/docs/technotes/guides/jar/jar.html> | First off, let me say that anything this tricky is probably hard for a reason.
This approach that may work for you if you really need it. As written, it assumes "java" is on the caller's path.
Overview:
1. Declare a Bootstrapper class as the main class in the jar's manifest.
2. The bootstrapper spawns another proces... | How to specify JVM argument for Maven built executable JAR | [
"",
"java",
"maven-2",
"jar",
"executable-jar",
""
] |
Can someone explain why there is the need to add an out or in parameter to indicate that a generic type is Co or Contra variant in C# 4.0?
I've been trying to understand why this is important and why the compiler can't just figure it out..
Thanks,
Josh | Eric Lippert, who works on the langauge, has a series of posts on msdn that should help clarify the issues involved:
<http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx>
When reading the articles shown at that link, start at the bottom and work up.
Eventually you'll get to [#7... | We don't actually *need* them, any more then we need `abstract` on classes or both `out` and `ref`. They exist just so that we, as programmers, can make our intention crystal clear, so that maintenance programmer know what we are doing, and the compiler can verify that we are doing it right. | Why do we need new keywords for Covariance and Contravariance in C#? | [
"",
"c#",
"c#-4.0",
"covariance",
"contravariance",
""
] |
I'm running into a common pattern in the code that I'm writing, where I need to wait for all threads in a group to complete, with a timeout. The timeout is supposed to be the time required for *all* threads to complete, so simply doing `Thread.Join(timeout)` for each thread won't work, since the possible timeout is the... | I still think using Join is simpler. Record the expected completion time (as Now+timeout), then, in a loop, do
```
if(!thread.Join(End-now))
throw new NotFinishedInTime();
``` | With .NET 4.0 I find [System.Threading.Tasks](http://msdn.microsoft.com/en-us/library/dd235608.aspx) a lot easier to work with. Here's spin-wait loop which works reliably for me. It blocks the main thread until all the tasks complete. There's also [Task.WaitAll](http://msdn.microsoft.com/en-us/library/dd270695.aspx), b... | Waiting for all threads to complete, with a timeout | [
"",
"c#",
"multithreading",
""
] |
What is the best way to refresh a `DataGridView` when you update an underlying data source?
I'm updating the datasource frequently and wanted to display the outcome to the user as it happens.
I've got something like this (and it works), but setting the `DataGridView.DataSource` to `null` doesn't seem like the right w... | Well, it doesn't get much better than that. Officially, you should use
```
dataGridView1.DataSource = typeof(List);
dataGridView1.DataSource = itemStates;
```
It's still a "clear/reset source" kind of solution, but I have yet to find anything else that would reliably refresh the DGV data source. | I ran into this myself. My recommendation: If you have ownership of the datasource, don't use a [List](https://msdn.microsoft.com/en-us/library/6sh2ey19.aspx). Use a [BindingList](https://msdn.microsoft.com/en-us/library/ms132679(v=vs.110).aspx). The [BindingList](https://msdn.microsoft.com/en-us/library/ms132679(v=vs.... | Refresh DataGridView when updating data source | [
"",
"c#",
".net",
"winforms",
"datagridview",
""
] |
What's the easiest way to get the UTC offset in PHP, relative to the current (system) timezone? | ```
date('Z');
```
returns the UTC offset in seconds. | ```
// will output something like +02:00 or -04:00
echo date('P');
``` | UTC Offset in PHP | [
"",
"php",
"timezone",
"utc",
""
] |
For example VK\_LEFT, VK\_DELETE, VK\_ESCAPE, VK\_RETURN, etc. How and where are they declared? Are they constants, #defines, or something else? Where do they come from?
If possible, please provide a file name/path where they are declared. Or some other info as specific as possible. | These are declared using `#define` in the file `winuser.h` in the Platform SDK. In my installation of Visual Studio 2008, the full path is
```
C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\WinUser.h
``` | There are also online copies of winuser.h , very handy sometimes :
<http://www.woodmann.com/fravia/sources/WINUSER.H>
<http://doc.ddart.net/msdn/header/include/winuser.h.html>
A bit of googling will get you more of those. | How are Windows VK_ constants declared? | [
"",
"c++",
"windows",
"winapi",
""
] |
This is just to satisfy my own curiosity.
Is there an implementation of this:
```
float InvSqrt (float x)
{
float xhalf = 0.5f*x;
int i = *(int*)&x;
i = 0x5f3759df - (i>>1);
x = *(float*)&i;
x = x*(1.5f - xhalf*x*x);
return x;
}
```
in C#? If it exists, post the code.
I guess I should have mention... | You should be able to use the StructLayout and FieldOffset attributes to fake a union for plain old data like floats and ints.
```
[StructLayout(LayoutKind.Explicit, Size=4)]
private struct IntFloat {
[FieldOffset(0)]
public float floatValue;
[FieldOffset(0)]
public int intValue;
// redundant ass... | Use [BitConverter](http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx) if you want to avoid unsafe code.
```
float InvSqrt(float x)
{
float xhalf = 0.5f * x;
int i = BitConverter.SingleToInt32Bits(x);
i = 0x5f3759df - (i >> 1);
x = BitConverter.Int32BitsToSingle(i);
x = x * (1.5f - xh... | Is it possible to write Quake's fast InvSqrt() function in C#? | [
"",
"c#",
""
] |
I'm making a program that fits the wizard concept ideally; the user is walked through the steps to create a character for a game.
However, I'm realizing that the limitations of the wizard are making it difficult to design "elegant" logic flow. For example, because all pages of the wizard are initalized at the same tim... | Here is a simple example. This way you can make your "wizard" work like a finite state machine where states are different pages that are initialized on demand. Also, the data is shared between pages.
```
import wx
import wx.lib.newevent
(PageChangeEvent, EVT_PAGE_CHANGE) = wx.lib.newevent.NewEvent()
class Data:
... | The wxPython demo has an example of a "dynamic" wizard. Pages override GetNext() and GetPrev() to show pages dynamically. This shows the basic technique; you can extend it to add and remove pages, change pages on the fly, and rearrange pages dynamically.
The wizard class is just a convenience, though. You can modify i... | Alternatives to a wizard | [
"",
"python",
"wxpython",
"wizard",
""
] |
Considering the criteria listed below, which of Python, Groovy or Ruby would you use?
* *Criteria (Importance out of 10, 10 being most important)*
* Richness of API/libraries available (eg. maths, plotting, networking) (9)
* Ability to embed in desktop (java/c++) applications (8)
* Ease of deployment (8)
* Ability to ... | I think it's going to be difficult to get an objective comparison. I personally prefer Python. To address one of your criteria, Python was designed from the start to be an embeddable language. It has a very rich C API, and the interpreter is modularized to make it easy to call from C. If Java is your host environment, ... | Having worked with all 3 of them, this is what I can say:
* **Python**
+ has very mature libraries
+ libraries are documented
+ documentation can be accessed from your debugger/shell at runtime through the docstrings
+ you can develop code without an IDE
* **Ruby**
+ has some great libraries ( even though ... | Python vs Groovy vs Ruby? (based on criteria listed in question) | [
"",
"python",
"ruby",
"scripting",
"groovy",
""
] |
At the moment I use PHP for almost everything I develop for the Web but its linguistic limitations are starting to annoy me. However, as I developed some practices and maintain some PHP libraries that help me a lot, I don't feel I'd be ready to just switch to LISP throwing away all my PHP output. It could even be impos... | It's not a mutually-exclusive choice, you can run both on one system, in the same way that perl and php (for example) are run side-by-side on many systems.
There's a [good post here](http://ubuntuforums.org/archive/index.php/t-277873.html) on a similar topic, which suggests using sockets to communicate between both la... | You would most likely not want to write code in PHP once you've started developing in Lisp. (New capitalization since circa 80s, by the way)
Hunchentoot is a popular server that gives you the basics in terms of connecting dispatchers to requests. There's a series of [screencasts on writing a reddit clone](http://lispc... | Combining Lisp and PHP code in the same application | [
"",
"php",
"web-applications",
"interop",
"lisp",
""
] |
I've been developing a GUI library for Windows (as a personal side project, no aspirations of usefulness). For my main window class, I've set up a hierarchy of option classes (using the [Named Parameter Idiom](http://www.parashift.com/c++-faq-lite/named-parameter-idiom.html)), because some options are shared and others... | Maybe not what you want to hear, but I for one think it's ok to have lots of ugly type-casts and template parameters in library-code that's (more or less) hidden from the client *as long as* it is safe *and* makes the life of the client a lot easier. The beauty in library code is not in the code itself, but in the code... | How about...?
```
template <class T>
class _sharedWindowOpts: public detail::_baseCreateWindowOpts {
protected: // (protected so the inheriting classes may also use it)
T & me() { return static_cast<T&>(*this); } // !
public:
// No required parameters in this case.
_sharedWindowOpts() { };... | Better Way To Use C++ Named Parameter Idiom? | [
"",
"c++",
"named-parameters",
""
] |
That's it. It's a dumb dumb (embarrassing!) question, but I've never used C# before, only C++ and I can't seem to figure out how to access a Label on my main form from a secondary form and change the text. If anybody can let me know real quick what to do I'd be so grateful!
BTW, I should really clarify. Sorry: I've go... | You'll need a reference to the instance of Form1 - for example, if it's Form1 which is constructing Form2, you might pass `this` in as a constructor parameter.
Then you'll need to either expose the label of Form1 via a property (or - ick! - a non-private field) or write a method/property which will set the text of the... | You have to have a reference to Form1 from Form2. Then you need either a method or a property on Form 1 visible to Form2 that changes the label text to "Hello". | How can I make a label on Form1 say "Hello" from form2? | [
"",
"c#",
""
] |
Usually, I need to retrieve data from a table in some range; for example, a separate page for each search result. In MySQL I use LIMIT keyword but in DB2 I don't know. Now I use this query for retrieve range of data.
```
SELECT *
FROM(
SELECT
SMALLINT(RANK() OVER(ORDER BY NAME DESC)) AS RUNNING_NO
, ... | My requirement have been added into DB2 9.7.2 already.
DB2 9.7.2 adds new syntax for limit query result as illustrate below:
```
SELECT * FROM TABLE LIMIT 5 OFFSET 20
```
the database will retrieve result from row no. 21 - 25 | It's very difficult, it is depends which database do you have.
for example:
```
SELECT * FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY ID_USER ASC) AS ROWNUM,
ID_EMPLOYEE, FIRSTNAME, LASTNAME
FROM EMPLOYEE
WHERE FIRSTNAME LIKE 'DEL%'
) AS A WHERE A.rownum
BETWEEN 1 AND 25
``` | How to query range of data in DB2 with highest performance? | [
"",
"sql",
"database",
"pagination",
"db2",
""
] |
There is another recent Project Euler question but I think this is a bit more specific (I'm only really interested in PHP based solutions) so I'm asking anyway.
[Question #5](http://projecteuler.net/index.php?section=problems&id=5) tasks you with: "What is the smallest number that is evenly divisible by all of the num... | in php it will look like this:
```
<?php
function gcd($a,$b) {
while($a>0 && $b>0) {
if($a>$b) $a=$a-$b; else $b=$b-$a;
}
if($a==0) return $b;
return $a;
}
function euler5($i=20) {
$euler=$x=1;
while($x++<$i) {
$euler*=$x/gcd($euler,$x);
}
return $euler;
}
?>
``... | Collect prime factors for all numbers between 1 and 20. Counting the maximal exponents of each prime factor, we have `16 = 2**4`, `9 = 3**2`, as well as 5, 7, 11, 13, 17, 19 (each appearing only once). Multiply the lot, and you have your answer. | A Project Euler Puzzler (specifically in PHP) | [
"",
"php",
"math",
"puzzle",
""
] |
I've got a little c# windows service that periodically pulls xml from a web service and stores the data in a database table.
Unfortunately it's failing because the web service has occasional bad data in it - strings instead of decimals. I don't have any control over the web service (unvalidated user input from softwar... | > Pre-process the XML provided by the
> web service before loading into the
> validating XML reader, removing any
> bad nodes entirely.
This is the option I would choose, it would allow you to grab the bad input before the exception and store it somewhere so it can be looked at later. Then you can find the offending u... | The question for me is: What do you want to do with the erroneus data?
Do you want to ignore it, sanitize it (remove the 'A' from 'A40'), or collect it to one day finally show it to the users (speaking of a large mallet;-) ?
If you just want to leave out any rows with incorrect data, the strip out the ones with errors... | right approach to handling bad xml data | [
"",
"c#",
"xml",
"xsd",
"xmlreader",
"xmlschemaset",
""
] |
I have this code
```
#include <iostream>
using namespace std;
int main(int argc,char **argv) {
unsigned long long num1 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999... | Your result is larger than the long long type - you need to look at a [BigInteger](http://mattmccutchen.net/bigint/) or arbitrary precision library, something like [gmp](http://gmplib.org/) | Those numbers won't fit into any C++ data types. If you just want to print them, store the numbers in a string. If you want to do math on it, find an arbitrary precision math library and use that. | How to print really big numbers in C++ | [
"",
"c++",
"biginteger",
"limits",
""
] |
Given a string of keywords, such as "Python best practices", I would like to obtain the first 10 Stack Overflow questions that contain that keywords, sorted by relevance (?), say from a Python script. My goal is to end up with a list of tuples (title, URL).
How can I accomplish this? Would you consider querying Google... | ```
>>> from urllib import urlencode
>>> params = urlencode({'q': 'python best practices', 'sort': 'relevance'})
>>> params
'q=python+best+practices&sort=relevance'
>>> from urllib2 import urlopen
>>> html = urlopen("http://stackoverflow.com/search?%s" % params).read()
>>> import re
>>> links = re.findall(r'<h3><a href... | Since Stackoverflow already has this feature you just need to get the contents of the search results page and scrape the information you need. Here is the URL for a search by relevance:
> <https://stackoverflow.com/search?q=python+best+practices&sort=relevance>
If you View Source, you'll see that the information you ... | How can I search through Stack Overflow questions from a script? | [
"",
"python",
"search",
"scripting",
"stackexchange-api",
""
] |
I'm looking to create a Visual Studio 2008 template that will create a basic project and based on remove certain files/folders based on options the user enters.
Right now, I have followed some tutorials online which have let me create the form to query the user and pass the data into an IWizard class, but I don't know... | In my experience, `ShouldAddProjectItem` only gets called for *folders* in the template project. As such, it's pretty much useless.
Instead, you would need to put code in your `ProjectFinishedGenerating` implementation that uses the VS API to remove ProjectItems.
In there, you can remove items like this:
```
Project... | You can selectively include parts of a file by using `$if$` with replacements. See, for example, this bit in the default C# Class Library template:
```
<ItemGroup>
<Reference Include="System"/>
$if$ ($targetframeworkversion$ >= 3.5)
<Reference Include="System.Core"/>
<Reference Include="System.Xml.Linq... | Creating Visual Studio Templates | [
"",
"c#",
"visual-studio",
"templates",
""
] |
I'm trying to read variables from a batch file for later use in the batch script, which is a Java launcher. I'd ideally like to have the same format for the settings file on all platforms (Unix, Windows), and also be a valid Java Properties file. That is, it should look like this:
```
setting1=Value1
setting2=Value2
.... | You can do this in a batch file as follows:
```
setlocal
FOR /F "tokens=*" %%i in ('type Settings.txt') do SET %%i
java -Dsetting1=%setting1% ...
endlocal
```
This reads a text file containing strings like "SETTING1=VALUE1" and calls SET to set them as environment variables.
setlocal/endlocal are used to limit the s... | This one-liner also unquotes value before assigning it to a variable:
```
for /F "delims== tokens=1,* eol=#" %%i in (%filename%) do set %%i=%%~j
```
* `delims==` split lines by `=` character
* `tokens=1,*` put first token (name) into `%%i` and the rest (value) into `%%j`
* `eol=#` skip lines starting with `#` (commen... | Read environment variables from file in Windows Batch (cmd.exe) | [
"",
"java",
"windows",
"command-line",
"cmd",
"environment-variables",
""
] |
I'm getting a whole bunch of linker errors in Visual studios for methods I'm not even calling directly. I'm a java developer by day, but I have a project I need to do in C++, intended to run on windows machines. Hence, I'm stuck messing about with Visual Studio.
Bascally, I have an os project that I added an accessor ... | The library `KeyCapture_Config.lib` is using MFC GUI classes (`CWnd`, `CWinApp`, etc), but the application you're linking it into is a console application (see the `/SUBSYSTEM:CONSOLE` option in your linker command line). This won't work. You should create a new MFC GUI application project and add the library to that p... | The link error seem to be complaining about the lack of a lot of MFC functions, and you link lines includes: /NODEFAULTLIB:"nafxcwd.lib" which would exclude MFC. Is the lib you are linking against built with MFC?
Other things to check are that you are compiling the app and the lib with the same character set (ie. both... | Linker Errors C++ Visual Studio 2005 | [
"",
"c++",
"visual-studio-2005",
"linker",
"visual-c++-2005",
""
] |
Basically I'm trying to change the `Canvas.Left` property of an Ellipse Silverlight control in C#. Here is how I'm accessing the control:
```
Ellipse c1 = this.FindName("Circle1") as Ellipse;
```
How would I then set the `Canvas.Left` property?
Thanks,
Jeff | The answer lies in Silverlights use of Dependancy Properties
c1.SetValue(Canvas.LeftProperty, value); | something like this...
```
double left=50;
c1.SetValue(Canvas.LeftProperty, left);
``` | How do you access an attached property of a Silverlight object in C#? | [
"",
"c#",
"silverlight",
""
] |
I have the following
```
var id='123';
newDiv.innerHTML = "<a href=\"#\" onclick=\" TestFunction('"+id+"', false);\"></a>";
```
Which renders `<a href="#" onclick="return Testfunction('123',false);"></a>` in my HTML.
The problem I have is that I wish to take the call to the method TestFunction, and use as a string ... | Try using " instead of \"
newDiv.innerHTML = "<a href="#"... | One of the biggest capital failures on the internet is creating html in javascript by gluing strings together.
```
var mya = document.createElement("a");
mya.href="#";
mya.onclick = function(){
StepTwo(function(){
TestFunction('123', false );
}, true );
};
newDiv.innerHTML = "";
newDiv.appendCh... | Escaping dilemma in Javascript | [
"",
"javascript",
"eval",
"escaping",
""
] |
The question is if a database connection should be passed in by reference or by value?
For me I'm specifically questioning a PHP to MySQL connection, but I think it applies to all databases.
I have heard that in PHP when you pass a variable to a function or object, that it is copied in memory and therefore uses twice... | A PHP resource is a special type that already is a reference in itself. Passing it by value or explicitly by reference won't make a difference (ie, it's still a reference). You can check this for yourself under PHP4:
```
function get_connection() {
$test = mysql_connect('localhost', 'user', 'password');
mysql_sele... | Call-time pass-by-reference is being depreciated,so I wouldn't use the method first described. Also, generally speaking, resources are passed by reference in PHP 5 by default. So having any references should not be required, and you should never open up more than one database connection unless you really need it.
Pers... | Passing database connection by reference in PHP | [
"",
"php",
"mysql",
"database",
""
] |
Is there a way to emulate mixins or traits in java? basically, I need a way to do multiple inheritance so I can add common business logic to several classes | I would encapsulate all of the business logic into a new class `BusinessLogic` and have each class that needs `BusinessLogic` make calls to the class. If you need a single rooted heirarchy for your classes that make calls to `BusinessLogic`, you'll have to create an interface as well (`BusinessLogicInterface`?)
In pse... | Not the way you want to do it. [Effective Java](https://rads.stackoverflow.com/amzn/click/com/0321356683) recommends that you "Favor composition over inheritance". Meaning you move the common logic to other classes and delegate. This is how you get around the lack of multiple inheritance in java. | java traits or mixins pattern? | [
"",
"java",
"mixins",
"traits",
""
] |
What's the best way to write a LINQ query that inserts a record and then returns the primary key of that newly inserted record using C# ? | The primary key value will be in that property after the SubmitChanges().
```
MyTable record = new MyTable();
record.Name = "James Curran";
db.MyTable.InsertOnSubmit(record);
db.SubmitChanges();
Console.WriteLine("record inserted as ID : {0}", record.Id);
``` | ```
// Create a new Order object.
Order ord = new Order
{
OrderID = 12000,
ShipCity = "Seattle",
OrderDate = DateTime.Now
// …
};
// Add the new object to the Orders collection.
db.Orders.InsertOnSubmit(ord);
// Submit the change to the database.
try
{
db.SubmitChanges();
}
catch (Exception e)
{
... | How to insert a record with LINQ and C# and return the Primary Key of that record | [
"",
"c#",
"linq",
""
] |
I need to present a wizard once, the first time my windows forms application is run after install. I could use a user setting like firstrun = false I suppose. But I also need handle the case where the program is uninstalled, then reinstalled. How will that user setting be reset? It's already present in the config file ... | It's probably best to have your installer create the FirstRun key in the registry and set it to true (or 1 or whatever), and make sure your uninstaller deletes this key entirely. Then just have your application read this key when it starts, and set it to false (or 0 or whatever).
If the user uninstalls and then reinst... | The Windows registry seems like the appropriate place for this type of setting. An installer step could reset the key when the user reinstalls, or you could just clear out the registry key on uninstall if you don't want to keep any settings between installations. | c# winforms: determine first run of program | [
"",
"c#",
".net",
"windows",
"winforms",
""
] |
I have always initialized my strings to NULL, with the thinking that NULL means the absence of a value and "" or String.Empty is a valid value. I have seen more examples lately of code where String.Empty is considered the default value or represents no value. This strikes me as odd, with the newly added nullable types ... | +1 for distinguishing between "empty" and NULL. I agree that "empty" should mean "valid, but blank" and "NULL" should mean "invalid."
So I'd answer your question like this:
**empty** when I want a valid default value that may or may not be changed, for example, a user's middle name.
**NULL** when it is an error if t... | According to [MSDN](http://msdn.microsoft.com/en-us/library/ms228362.aspx):
> By initializing strings with the `Empty` value instead of `null`, you can reduce the chances of a `NullReferenceException` occurring.
Always using `IsNullOrEmpty()` is good practice nevertheless. | Default string initialization: NULL or Empty? | [
"",
"c#",
""
] |
We are using LINQ very widely in our system. Particularly LINQ-to-objects. So in some places we end up having a LINQ query in memory build up from some huge expressions. The problem comes when there's some bug in the expressions. So we get NullReferenceException and the stack trace leads us nowhere (to [Lightweight Fun... | If you are building your own expressions and compiling them, or using AsQueryable, then yes; the LINQ-generated methods will be a royal pain to debug.
You can save some pain by using small fragements of *actual* methods - at least something useful will show in the stack trace...
Another consideration is: rather than ... | If you're using LINQ to Objects, I wouldn't expect to see dynamic methods being created. I'd expect them with LINQ to SQL etc. Could you give an example where you're seeing this?
I don't really have any good debugging tips when it comes to LINQ, but I'm pretty sure MS know about this as a pain point. Could I suggest y... | Debugging .NET dynamic methods | [
"",
"c#",
".net",
"linq",
"debugging",
"dynamic-method",
""
] |
I've got this python dictionary "mydict", containing arrays, here's what it looks like :
```
mydict = dict(
one=['foo', 'bar', 'foobar', 'barfoo', 'example'],
two=['bar', 'example', 'foobar'],
three=['foo', 'example'])
```
i'd like to replace all the occurrences of "example" by "someotherword".
While I... | ```
for arr in mydict.values():
for i, s in enumerate(arr):
if s == 'example':
arr[i] = 'someotherword'
``` | If you want to leave the original untouched, and just return a new dictionary with the modifications applied, you can use:
```
replacements = {'example' : 'someotherword'}
newdict = dict((k, [replacements.get(x,x) for x in v])
for (k,v) in mydict.iteritems())
```
This also has the advantage that its... | Replacing multiple occurrences in nested arrays | [
"",
"python",
"arrays",
"dictionary",
"replace",
""
] |
I have a few links that should all open in the same window or tab.
To accomplish this I've given the window a name like in this example code:
```
<a href="#" onClick='window.open("http://somesite.com", "mywindow", "");'>link 1</a>
<a href="#" onClick='window.open("http://someothersite.com", "mywindow", "");'>link 2</a... | The window.open() function in Javascript is specifically designed to open a new window, please see: [w3schools documentation](http://www.w3schools.com/HTMLDOM/met_win_open.asp). It actually sounds like IE is handling things in a non-standard way (which is hardly surprising).
If you want to relocate the existing locati... | Actually, the W3Schools documentation linked to by [gabriel1836](https://stackoverflow.com/questions/268902/javascript-windowopen-strange-behavior-in-firefox#268951) is only a very very brief summary of functions.
And Oddly, mozilla's own developer reference *CONTRADITCS* this logic.
[MDC / DOM / Window.open](https:/... | Javascript window.open strange behavior in Firefox | [
"",
"javascript",
"firefox",
""
] |
I'm looking for a library that can deal with RDF and OWL data.
So far I have found:
* [semweb](http://razor.occams.info/code/semweb/) (no owl support for all I know)
* [rowlex](http://rowlex.nc3a.nato.int/HowToUse.aspx) (more of a 'browser' application)
Your recommendations:
* [LinqToRdf](https://code.google.com/p/... | [ROWLEX](http://rowlex.nc3a.nato.int) is actually very cool (uses [SemWeb](http://razor.occams.info/code/semweb/) internally). It is not just a browser app but rather an SDK written in C#. If you use ROWLEX, you do not directly interact with the tripples of RDF anymore (though you can), but gives an object oriented loo... | BrightstarDB is a native, .NET NoSQL RDF triple store, with SPARQL support, a .NET entity framework with LINQ and OData support. It is free for developers and open source projects and has a small runtime cost for commercial use.
BrightstarDB provide three levels of API.
1. SPARQL query and simple transaction API.
2. ... | What is a good RDF library for .net? | [
"",
"c#",
".net",
"rdf",
"semantic-web",
"owl",
""
] |
From the MSDN documentation:
"Synchronized supports multiple writing threads, provided that no threads are reading the Hashtable. The synchronized wrapper does not provide thread-safe access in the case of one or more readers and one or more writers."
Source:
<http://msdn.microsoft.com/en-us/library/system.collection... | For the same reason there are different levels of DB transaction. You may care that writes are guaranteed, but not mind reading stale/possibly bad data.
---
**EDIT** I note that their specific example is an Enumerator. They can't handle this case in their wrapper, because if you break from the enumeration early, the ... | For the case where you can guarantee that no reader will access the data structure when writing to it (or when you don't care reading wrong data). For example, where the structure is not continually being modified, but a one time calculation that you'll later have to access, although huge enough to warrant many threads... | Why use Hashtable.Synchronized? | [
"",
"c#",
".net",
""
] |
I have stumbled into several methods of looping in JavaScript, what I like the most is:
```
for(var i = 0; i < a.length; i++){
var element = a[i];
}
```
But as tested here (<http://www.robertnyman.com/2008/04/11/javascript-loop-performance/>), it should probably be written so that the length is only calculated on... | I've started using iterators where relevant. Performance is reasonable, however more importantly it allows you to encapsulate the looping logic:
```
function createIterator(x) {
var i = 0;
return function(){
return x[i++];
};
}
```
Then to use:
```
var iterator=createIterator(['a','b','c','d','e... | Small improvement to the original, to only calculate the array size once:
```
for(var i = 0, len = a.length; i < len; i++){ var element = a[i]; }
```
Also, I see a lot of for..in loops. Though keep in mind that it's not technically kosher, and will cause problems with Prototype specifically:
```
for (i in a) { var e... | What is the best way to do loops in JavaScript | [
"",
"javascript",
"jquery",
"loops",
"macros",
""
] |
What do you usually use to connect to a Web Service when you are developing a Java project?
There are different API-s that can do the job.
From different books and tutorials I have read about: JAX-WS, JAXB, JAXM, JAXR, JAX-RPC, Axis ans so on.
I'm interested in what exactly are you using and how much? Take this as a ... | To answer your question, we first need to differentiate between the tools you listed.
JAX-WS, JAXB, JAXM, JAXR, JAX-RPC are XML and Web service related APIs while Axis 1 and 2 are implementations of zero, one, or more of these APIs depending on the version.
JAX-B 1 and 2 are XML to object binding APIs, JAX-WS is a WS... | <http://cxf.apache.org/> is nice. | Web Services in Java | [
"",
"java",
"xml",
"web-services",
"web-applications",
""
] |
I need to be able to send encrypted data between a Ruby client and a Python server (and vice versa) and have been having trouble with the [ruby-aes](http://rubyforge.org/projects/ruby-aes) gem/library. The library is very easy to use but we've been having trouble passing data between it and the pyCrypto AES library for... | Turns out what happened was that ruby-aes automatically pads data to fill up 16 chars and sticks a null character on the end of the final string as a delimiter. PyCrypto requires you to do multiples of 16 chars so that was how we figured out what ruby-aes was doing. | > (e.g., the lengths differ by one or there is extra garbage characters on the end of the decrypted string)
I missed that bit. There's nothing wrong with your encryption/decryption. It sounds like a padding problem. AES always encodes data in blocks of 128 bits. If the length of your data isn't a multiple of 128 bits ... | Which AES library to use in Ruby/Python? | [
"",
"python",
"ruby",
"encryption",
"aes",
""
] |
I have two Java classes: B, which extends another class A, as follows :
```
class A {
public void myMethod() { /* ... */ }
}
class B extends A {
public void myMethod() { /* Another code */ }
}
```
I would like to call the `A.myMethod()` from `B.myMethod()`. I am coming from the [C++ world](https://stackoverf... | The keyword you're looking for is `super`. See [this guide](http://java.sun.com/docs/books/tutorial/java/IandI/super.html), for instance. | Just call it using super.
```
public void myMethod()
{
// B stuff
super.myMethod();
// B stuff
}
``` | In Java, how do I call a base class's method from the overriding method in a derived class? | [
"",
"java",
"inheritance",
"methods",
"polymorphism",
""
] |
I'm on a project which is trying to write what amounts to a Mailing List app in Django, and we're running into a couple of problems/questions.
The code we have so far doesn't set various List headers, and re-sets the To header to be the person we're sending it to, instead of the list address.
Now, we can work our way... | [RFC 2919](http://www.apps.ietf.org/rfc/rfc2919.html) has some info and more references on this. | What about <http://labs.freehackers.org/projects/colibri/wiki>
It seems to do what you want: a mailing list manager with a django frontend. | How can you emulate a mailing list in Django? | [
"",
"python",
"django",
"mailing-list",
""
] |
I have been trying to learn how to add testing to existing code -- currently reading reading [Working Effectively With Legacy Code](https://rads.stackoverflow.com/amzn/click/com/0131177052). I have been trying to apply some of the principles in JavaScript, and now I'm trying to extract an interface.
In searching for c... | There's no definitive **right way**, because so many people are doing so many different things.. There are many useful patterns.
**Crockford** suggests that you "go with the grain", or write javascript in a way that corresponds to javascript's prototypal nature.
Of course, he goes on to show that the original model t... | There are no class in javascript, only objects.
But if you insist on emulating the class based object-oriented model you can use this:
```
function ChildClass() {
ParentClass.call(this);
// Write the rest of your constructor function after this point.
};
ChildClass.prototype = jQuery.extend({}, ParentClass.p... | Is there a "right" way to do inheritance in JavaScript? If so, what is it? | [
"",
"javascript",
"oop",
"refactoring",
"interface",
""
] |
Since I've started to use jQuery, I have been doing a lot more JavaScript development.
I have the need to parse different date formats and then to display them into another format.
Do you know of any good tool to do this?
Which one would you recommend? | 2014 update: [Moment.js](http://momentjs.com/) is an excellent date manipulation library, which includes parsing functions. It doesn't include automatic date format detection, but you can [specify multiple parsing patterns](http://momentjs.com/docs/#/parsing/string-formats/).
Do you know the format of the dates before... | If you already use jqueryUI on the page, than $.datepicker has parseDate() and formatDate() functions that enough in most cases. As for DateJS - profile yu code and you'll see how it baggy and how much time it spends in handling exception | Best JavaScript Date Parser & Formatter? | [
"",
"javascript",
"jquery",
"datetime",
"parsing",
"formatting",
""
] |
We've been using Trac for task/defect tracking and things were going well enough, but this morning it started serving up a 500 error. Looking in the Apache error\_log, I get a stack trace that culminates in:
```
PythonHandler trac.web.modpython_frontend:
ExtractionError: Can't extract file(s) to egg cache
The follo... | That should be fixed in 0.11 according to their [bug tracking system](http://trac.edgewall.org/ticket/7320).
If that's not the case you should try to pass the environment var to apache, since doing a SetEnv in the configuration file doesn't work. Adding something like
```
export PYTHON_EGG_CACHE=/tmp/python_eggs
```
... | I ran into the same problem when upgrading from Trac 10.4 to 0.11 earlier this year. Something must have changed for this problem to have just suddenly appeared -- an updated Python or Apache installation?
I don't remember all of the permutations I tried to solve this, but I ended up having to use `SetEnv PYTHON_EGG_C... | How do you fix a Trac installation that begins giving errors relating to PYTHON_EGG_CACHE? | [
"",
"python",
"configuration",
"trac",
"python-egg-cache",
""
] |
I installed Python 2.6 for one user on Windows Vista. Python works okay, but when I try: `import Tkinter`, it says the side-by-side configuration has errors. I've tried tinkering with the Visual Studio runtime, with no good results. Any ideas on how to resolve this? | Maybe you should downgrade to 2.5 version? | It seems this is a one of the many weird Vista problems and some random reinstalling, installing/upgrading of the visual studio runtime or some such seems sometimes to help, or disabling sxs in the system configuration or writing a manifest file etc.
Though I think you should downgrade to windows XP. | How do I use Tkinter with Python on Windows Vista? | [
"",
"python",
"windows",
"windows-vista",
"tkinter",
""
] |
I've got a **large** array of primitive types (double).
How do I sort the elements in **descending order**?
Unfortunately the Java API doesn't support sorting of **primitive** types with a Comparator.
The first approach that probably comes to mind is to convert it to a list of objects (boxing):
```
double[] array = ... | [Java Primitive](https://github.com/mintern-java/primitive#java-primitive) includes functionality for sorting primitive arrays based on a custom comparator. Using it, and Java 8, your sample could be written as:
```
double[] array = new double[1048576];
...
Primitive.sort(array, (d1, d2) -> Double.compare(d2, d1), fal... | I think it would be best not to re-invent the wheel and use Arrays.sort().
Yes, I saw the "descending" part. The sorting is the hard part, and you want to benefit from the simplicity and speed of Java's library code. Once that's done, you simply reverse the array, which is a relatively cheap O(n) operation. [Here's so... | Sort large arrays of primitive types in descending order | [
"",
"java",
"sorting",
""
] |
I have a co-worker that swears by
```
//in a singleton "Constants" class
public static final String EMPTY_STRING = "";
```
in a constants class available throughout the project. That way, we can write something like
```
if (Constants.EMPTY_STRING.equals(otherString)) {
...
}
```
instead of
```
if ("".equals(ot... | String literals are interned by default, so no matter how many times you refer to **""** in code, there will only be one empty String object. I don't see any benefit in declaring EMPTY\_STRING. Otherwise, you might as well declare ONE, TWO, THREE, FOUR, etc. for integer literals.
Of course, if you want to change the v... | Why on earth would you want a global variable in Java? James Gosling really tried to get rid of them; don't bring them back, please.
Either
```
0 == possiblyEmptyString.length()
```
or
```
possiblyEmptyString.isEmpty() // Java 6 only
```
are just as clear. | Is making an empty string constant worth it? | [
"",
"java",
"string",
""
] |
What would be the best way to check that a `std::vector` is sorted? Is there something faster than a loop checking that `v[i]<=v[i+1]`? Is it faster/cleaner with iterators? Or is it actually better to just call `sort` every time (though the "v is already sorted" case is quite common)?
We can safely assume the vector o... | **Consider Multiple Cpu Cores**
It depends on your platform and number of items in the vector. You'd have to benchmark to find what's best.
It's not possible to answer: Is there something faster than a loop checking that v[i]<=v[i+1] ?
With: No.
Because... computers now a days have multiple cpus/cores/hyperthreadi... | > Is there something faster than a loop
> checking that v[i]<=v[i+1] ?
No.
If this is something you wish to check often, you might want to make a wrapper class that keeps a "sorted" flag which starts out False, is set to False whenever an item is added, and add a member function sort() that sets the flag to True afte... | Best algorithm to check whether a vector is sorted | [
"",
"c++",
"algorithm",
"optimization",
"vector",
""
] |
I'm trying to run a particular JUnit test by hand on a Windows XP command line, which has an unusually high number of elements in the class path. I've tried several variations, such as:
```
set CLASS_PATH=C:\path\a\b\c;C:\path\e\f\g;....
set CLASS_PATH=%CLASS_PATH%;C:\path2\a\b\c;C:\path2\e\f\g;....
...
C:\apps\jdk1.6... | The Windows command line is very limiting in this regard. A workaround is to create a "pathing jar". This is a jar containing only a `Manifest.mf` file, whose `Class-Path` specifies the disk paths of your long list of jars, etc. Now just add this *pathing jar* to your command line classpath. This is usually more conven... | Since Java 6 you can use [classpath wildcards](https://docs.oracle.com/javase/6/docs/technotes/tools/windows/classpath.html#Understanding).
Example: `foo/*`, refers to all .jar files in the directory `foo`
* this will not match class files (only jar files). To match both use: `foo;foo/*` or `foo/*;foo`. The order det... | How to set a long Java classpath in Windows? | [
"",
"java",
"junit",
"classpath",
""
] |
Please help!
*Background info*
I have a WPF application which accesses a SQL Server 2005 database. The database is running locally on the machine the application is running on.
Everywhere I use the Linq DataContext I use a using { } statement, and pass in a result of a function which returns a SqlConnection object w... | From [MSDN](http://msdn.microsoft.com/en-us/library/bb292288.aspx) (`DataContext Constructor (IDbConnection)`):
> If you provide an open connection, the
> DataContext will not close it.
> Therefore, do not instantiate a
> DataContext with an open connection
> unless you have a good reason to do
> this.
So basically, ... | The `SqlProvider` used by the LINQ `DataContext` only closes the SQL connection (through `SqlConnectionManager.DisposeConnection`) if it was the one to open it. If you give an already-open `SqlConnection` object to the `DataContext` constructor, it will not close it for you. Thus, you should write:
```
using (SqlConne... | .net SqlConnection not being closed even when within a using { } | [
"",
"c#",
".net",
"linq-to-sql",
"sqlconnection",
""
] |
This is one of those ajax "alternate flow" questions. Normally I expect my ajax request to return a part of the page. But sometimes it may return a full page with html, head and body tag.
At the time I return from my ajax-request I can detect if this is a full page, but is it possible to trigger a full page reload (wi... | I don't think it's possible to do directly.
You'd be better off saving the HTML somewhere and sending back a URL where it can be retrieved, then using `location.href = ...`; | You can decide what to do with your [AJAX request](http://www.prototypejs.org/api/ajax/request) based on it's [HTTP status code](http://en.wikipedia.org/wiki/List_of_HTTP_status_codes).
If you get 301 ("moved permanently") you could do a redirect using `window.location`:
```
new Ajax.Request(url, {
method: 'get',
... | Can I trigger a complete web page reload with content from a javascript string? | [
"",
"javascript",
"ajax",
""
] |
**ASPX Code**
```
<asp:RadioButtonList ID="rbServer" runat="server" >
<asp:ListItem Value=<%=ServerDeveloper%>> Developer </asp:ListItemv
<asp:ListItem Value="dev.ahsvendor.com"> dev.test.com</asp:ListItem>
<asp:ListItem Value="staging.ahsvendor.com"> staging.test.com</asp:ListItem>
</asp:RadioButtonList>
```... | Would it be:
```
rbServer.Items.Add(ServerDeveloper)
```
Ok, so since you want to do it from presentation...It is possible, but horribly ugly:
```
<div>
<% rbServer.Items.Add(new ListItem("Dev", ServerDeveloper)); %>
<asp:RadioButtonList ID="rbServer" runat="server">
<asp:ListItem Value="Blah">Blah</asp:ListItem... | In retrospect, the better solution would be to add it from the codebehind using rbServer.Items.Add() | C# (ASP.Net) Linking selection values to constants in Codebehind | [
"",
"c#",
"asp.net",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.