Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
i am trying to compile this very simple piece of code
```
class myList
{
public:
std::vector<std::string> vec;
class Items
{
public:
void Add(std::string str)
{
myList::vec.push_back(str);
};
}items;
};
int main()
{
myList newList;
newList.items.Add("A")... | Add a couple of constructors and a pointer to the parent class.
```
#include <string>
#include <vector>
class myList
{
public:
std::vector<std::string> vec;
myList(): items(this) {} // Added
class Items
{
public:
Items(myList *ml): self(ml) {} // Added
void Add(std::string str)
... | This way you aren't exposing your class members directly. Your example seems over-architected a bit. Why put a std::vector into a class and then expose it as public?
```
class myList
{
private:
std::vector<std::string> vec;
public:
void Add(std::string str)
{
vec.push_back(str);
};
};
int main... | C++ Nested classes driving me crazy | [
"",
"c++",
"class",
"nested",
""
] |
I've got a PHP script that needs to invoke a shell script but doesn't care at all about the output. The shell script makes a number of SOAP calls and is slow to complete, so I don't want to slow down the PHP request while it waits for a reply. In fact, the PHP request should be able to exit without terminating the shel... | If it "doesn't care about the output", couldn't the exec to the script be called with the `&` to background the process?
**EDIT** - incorporating what @[AdamTheHut](https://stackoverflow.com/users/1103/adamthehutt) commented to this post, you can add this to a call to `exec`:
```
" > /dev/null 2>/dev/null &"
```
Tha... | I used **at** for this, as it is really starting an independent process.
```
<?php
`echo "the command"|at now`;
?>
``` | Asynchronous shell exec in PHP | [
"",
"php",
"asynchronous",
"shell",
""
] |
I'm *considering* migrating my c# application from using custom GDI+ drawn controls to a WPF application with custom controls etc. I would like to know what's involved and what to expect.
Are there any resources people can recommend that might help? Or indeed any personal experiences that might be beneficial? | *(I apologize in advance for the long post ... there was just so much I wanted to convey ... I hope it helps you.)*
This is what we are doing now (migrating a Windows Forms application with heavy use of custom (GDI+) drawn controls to WPF). In fact, my role on the team was to build these GDI+ controls ... and now to b... | There is a paradigm shift in how you develop controls for WPF. Instead of defining all the behavior and look for a control, you only define the intended behavior.
This is the hardest aspect of migrating to WPF. Your control class defines a contract of behavior, and exposes properties that will be used to render, and a... | C# transition between GDI+ and WPF | [
"",
"c#",
"wpf",
"gdi+",
""
] |
I could write myself a helper class that does this when given a functor, but I was wondering if there's a better approach, or if there's something already in the standard library (seems like there should be).
Answers I've found on StackOverflow are all for C# which doesn't help me.
Thanks | No - there isn't. Apache `commons-collections` has predicates for this sort of thing but the resultant code (using anonymous inner classes) is usually ugly and a pain to debug.
Just use a basic **for-loop** until they bring [closures](http://javac.info) into the language | By using the [lambdaj](http://code.google.com/p/lambdaj/) library, for example you could find the top reputation users as it follows:
```
List<User> topUsers =
select(users, having(on(User.class).getReputation(), greaterThan(20000)));
```
It has some advantages respect the Quaere library because it doesn't use a... | Cleanest way to find objects matching certain criteria in a java.util.List? | [
"",
"java",
"list",
""
] |
I maintain a vb.net forms application that prints various labels to label printers. (Label printers are just like any printer, just smaller print area/lower resolution)
The system uses a legacy printing method that's supported in the printer hardware, but has been out of general use for over a decade. I'm adding logic... | Since what I need is fairly simple I went ahead and rolled my own simple desinger. Found at [a great little class](http://www.codeproject.com/KB/dotnet/Resize_Control_at_Runtime.aspx) that makes controls movable/resizable which saved a bunch of time. Thanks all for the ideas. | Have a look at this thread [Visual Print Design for .NET](https://stackoverflow.com/questions/182670/visual-print-design-for-net).
Also, you might consider a PDF template that you can inject with the values, then print the PDF, not perfect, but it could work depending on your needs. | Printing in VB.Net/C# Forms Application -- Layout Designer? | [
"",
"c#",
".net",
"vb.net",
"printing",
""
] |
I want to have a function that will return the reverse of a list that it is given -- using recursion. How can I do that? | Append the first element of the list to a reversed sublist:
```
mylist = [1, 2, 3, 4, 5]
backwards = lambda l: (backwards (l[1:]) + l[:1] if l else [])
print backwards (mylist)
``` | A bit more explicit:
```
def rev(l):
if len(l) == 0: return []
return [l[-1]] + rev(l[:-1])
```
---
This turns into:
```
def rev(l):
if not l: return []
return [l[-1]] + rev(l[:-1])
```
Which turns into:
```
def rev(l):
return [l[-1]] + rev(l[:-1]) if l else []
```
Which is the same as anothe... | How do I reverse a list using recursion in Python? | [
"",
"python",
"list",
"recursion",
""
] |
Here's the core problem: I have a .NET application that is using [COM interop](http://en.wikipedia.org/wiki/COM_Interop) in a separate AppDomain. The COM stuff seems to be loading assemblies back into the default domain, rather than the AppDomain from which the COM stuff is being called.
What I want to know is: is thi... | Unfortunately, A COM component is loaded within Process Space and not within the context of an AppDomain. Thus, you will need to manually tear-down (Release and Unload) your Native DLLs (applies to both COM and P/Invoke). Simply destroying an appdomain will do you no good, but respawning the whole process shouldn't be ... | Here's the proof that Shaun Wilson's answer is correct
 | Does COM interop respect .NET AppDomain boundaries for assembly loading? | [
"",
"c#",
"com",
"interop",
"com-interop",
"appdomain",
""
] |
I have the following classes
```
public interface InterfaceBase
{
}
public class ImplementA:InterfaceBase
{
}
public class ImplementB:InterfaceBase
{
}
public void TestImplementType<T>(T obj) where T: InterfaceBase
{
}
```
How to infer what the T is whether ImplementA or ImplementB? I tried to use
```
typeof(T) i... | `obj is ImplementA` | Strictly, you should avoid too much specialization within generics. It would be cleaner to put any specialized logic in a member on the interface, so that any implementation can do it differently. However, there are a number of ways:
You can test "obj" (assuming it is non-null)
```
bool testObj = obj is Implement... | Get the type of the generic parameter | [
"",
"c#",
"generics",
""
] |
Is there a way to get the count of rows in all tables in a MySQL database without running a `SELECT count()` on each table? | ```
SELECT SUM(TABLE_ROWS)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = '{your_db}';
```
[Note from the docs though:](https://dev.mysql.com/doc/refman/5.7/en/tables-table.html) For InnoDB tables, **the row count is only a rough estimate** used in SQL optimization. You'll need to use COUNT(\*) for ex... | You can probably put something together with [Tables table](http://dev.mysql.com/doc/refman/5.0/en/tables-table.html). I've never done it, but it looks like it has a column for *TABLE\_ROWS* and one for *TABLE NAME*.
To get rows per table, you can use a query like this:
```
SELECT table_name, table_rows
FROM INFORMAT... | Get record counts for all tables in MySQL database | [
"",
"mysql",
"sql",
"rowcount",
""
] |
Say I have a struct "s" with an int pointer member variable "i". I allocate memory on the heap for i in the default constructor of s. Later in some other part of the code I pass an instance of s by value to some function. Am I doing a shallow copy here? Assume I didn't implement any copy constructors or assignment oper... | To follow up on what @[don.neufeld.myopenid.com] said, it is not only a shallow copy, but it is either (take your pick) a memory leak or a dangling pointer.
```
// memory leak (note that the pointer is never deleted)
class A
{
B *_b;
public:
A()
: _b(new B)
{
}
};
// dangling ptr (who deletes the instance... | Yes, that's a shallow copy. You now have two copies of s (one in the caller, one on the stack as a parameter), each which contain a pointer to that same block of memory. | Question about shallow copy in C++ | [
"",
"c++",
"memory-management",
"constructor",
""
] |
I am currently working in C/C++ in a Unix environment and am new to Linux environments. I would like to learn about the Linux OS and learn C# as the next level of programming language for my career.
I decided to put Ubuntu Linux on my laptop. But I am not sure whether we can write, compile and run C# programs in Linux... | Learn [Mono](http://www.mono-project.com/Main_Page).
> The Mono Project is an open
> development initiative sponsored by
> Novell to develop an open source, UNIX
> version of the Microsoft .NET
> development platform. Its objective is
> to enable UNIX developers to build and
> deploy cross-platform .NET
> Applications... | [Mono](http://www.mono-project.com) is an open source .NET compiler, runtime and library.
[Monodevelop](http://monodevelop.com/) is an open source C# IDE, primarily intended for linux development. It includes a GUI designer. | C# in linux environment | [
"",
"c#",
"linux",
"installation",
""
] |
When working with my .Net 2.0 code base ReSharper continually recommends applying the latest c# 3.0 language features, most notably; convert simple properties into auto-implement properties or declaring local variables as var. Amongst others.
When a new language feature arrives do you go back and religiously apply it ... | If it ain't broke, don't fix it. Of course, if you have confidence in your unit tests, you can give it a whirl, but you shouldn't really go randomly changing code "just because".
Of course - in some cases, simplifying code is a valid reason to make a change - but even something as innocent as switching to an auto-impl... | I would simply maintain the code as I go. Eventually a large portion of the app will have been cleaned or tuned to the new features and improvements. Don't change something for the sake of changing it. If you don't get any performance or stability improvements there is no need to waste time updating code.
C# 3 buildin... | Retro fitting new language features C# (or any other language) | [
"",
"c#",
"resharper",
""
] |
When I try to create a new task in the task scheduler via the Java ProcessBuilder class I get an access denied error an Windows Vista. On XP it works just fine.
When I use the "Run as adminstrator" option it runs on Vista as well..
However this is a additional step requeried an the users might not know about this. Wh... | I'm not sure you can do it programmatically. If you have an installer for your app, you can add the registry key to force run as admin:
> Path:
> HKEY\_CURRENT\_USER\Software\Microsoft\Windows
> NT\Currentversion\Appcompatflags\layers
>
> Key: << Full path to exe >>
>
> Value: RUNASADMIN
>
> Type: REG\_SZ | Have you considered wrapping your Java application in an .exe using launch4j? By doing this you can embed a manifest file that allows you to specify the "execution level" for your executable. In other words, you control the privileges that should be granted to your running application, effectively telling the OS to "Ru... | Request admin privileges for Java app on Windows Vista | [
"",
"java",
"windows-vista",
"scheduler",
"access-denied",
""
] |
I'm looking for a Java library that is geared towards network math and already tested. Nothing particularly fancy, just something to hold ips and subnets, and do things like print a subnet mask or calculate whether an IP is within a given subnet.
Should I roll my own, or is there already a robust library for this? | We developed a Java IPv4 arithmetic library ourselves.
See it here: <http://tufar.com/ipcalculator/>
It is under BSD license. | [org.apache.lenya.ac.IPRange](http://lenya.apache.org/apidocs/2.0/org/apache/lenya/ac/IPRange.html) appears to have these features.
The Apache Lenya project is an open-source content management system. It uses the Apache License, so you may be able to reuse just the code you need. (But as always, read the [license](ht... | A good Java library for network math | [
"",
"java",
"math",
"networking",
""
] |
The point of this question is to create the shortest **not abusively slow** Sudoku solver. This is defined as: **don't recurse when there are spots on the board which can only possibly be one digit**.
Here is the shortest I have so far in python:
```
r=range(81)
s=range(1,10)
def R(A):
bzt={}
for i in r:
... | I haven't really made much of a change - the algorithm is identical, but here are a few further micro-optimisations you can make to your python code.
* No need for !=0, 0 is false in a boolean context.
* a if c else b is more expensive than using [a,b][c] if you don't need short-circuiting, hence you can use `h[ [0,A[... | ```
r=range(81)
def R(A):
if(0in A)-1:yield A;return
def H(i):h=set(A[j]for j in r if j/9==i/9or j%9==i%9or j/27==i/27and j%9/3==i%9/3);return len(h),h,i
l,h,i=max(H(i)for i in r if not A[i])
for j in r[1:10]:
if(j in h)-1:
A[i]=j
for S in R(A):yield S
A[i]=0
```
269 characters, and it finds all solution... | Smart Sudoku Golf | [
"",
"python",
"perl",
"code-golf",
"sudoku",
""
] |
I'm just concerned about Windows, so there's no need to go into esoterica about Mono compatibility or anything like that.
I should also add that the app that I'm writing is WPF, and I'd prefer to avoid taking a dependency on `System.Windows.Forms` if at all possible. | Give this a shot...
```
using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
namespace WMITestConsolApplication
{
class Program
{
static void Main(string[] args)
{
AddInsertUSBHandler();
AddRemoveUSBHandler();
while ... | There are much less cumbersome ways of doing this than using WMI polling - just capture WM\_DEVICECHANGE:
<http://msdn.microsoft.com/en-us/library/aa363215.aspx> | How do I detect when a removable disk is inserted using C#? | [
"",
"c#",
"wpf",
"windows",
""
] |
I'm trying to submit a form with javascript. Firefox works fine but IE complains that "Object doesn't support this property or method" on the submit line of this function:
```
function submitPGV(formName, action)
{
var gvString = "";
pgVisibilities.each(function(pair) {
gvString += pair.key + ":" + pa... | Try checking the type of the element IE is selecting:
```
// For getting element with id you must use #
alert( typeof( $( '#ProductGroupVisibility' )));
```
It is possible there is something else on the page with that ID that IE selects before the form. | What `name` does your `<input type="submit">` have?
If you called it "submit", you have overridden the `form.submit()` function, much the same way an input called "foo" would generate a `form.foo` property. That would explain the behavior. | Javascript form submit: Object doesn't support this property or method (IE7) | [
"",
"javascript",
"internet-explorer",
""
] |
Just wondering if anyone has any favourite SQL references they to use when creating new queries. Possibly something that shows syntax, or available functions? | If you're looking for one with just very basic functions you can try this to see if it fits your need.
<http://www.sql.su/>
You might have to paste the parts that you want into a better printing format as the top of the page has google ads =( | <http://blog.sqlauthority.com/2008/10/02/sql-server-2008-cheat-sheet-one-page-pdf-download/> | SQL Cheatsheet? | [
"",
"sql",
""
] |
How can I check if a string ends with a particular character in JavaScript?
Example: I have a string
```
var str = "mystring#";
```
I want to know if that string is ending with `#`. How can I check it?
1. Is there a `endsWith()` method in JavaScript?
2. One solution I have is take the length of the string and get t... | **UPDATE (Nov 24th, 2015):**
This answer is originally posted in the year 2010 (SIX years back.) so please take note of these insightful comments:
* [Shauna](https://stackoverflow.com/users/570040/shauna) -
> Update for Googlers - Looks like ECMA6 adds this function. The MDN article also shows a polyfill. <https://d... | ```
/#$/.test(str)
```
will work on all browsers, doesn't require monkey patching `String`, and doesn't require scanning the entire string as `lastIndexOf` does when there is no match.
If you want to match a constant string that might contain regular expression special characters, such as `'$'`, then you can use the ... | endsWith in JavaScript | [
"",
"javascript",
"string",
"ends-with",
""
] |
I have just noticed that a multidimensional array in C# does not implement `IEnumerable<T>`, while it does implement `IEnumerable`. For single-dimensional arrays, both `IEnumerable<T>` and `IEnumerable` are implemented.
Why this difference? If a multi-dimensional array is `IEnumerable`, surely it should also implement... | The CLR has two different kinds of arrays: *vectors* which are guaranteed to be one-dimensional with a lower bound of 0, and more general arrays which can have non-zero bounds and a rank other than 0.
From section 8.9.1 of the CLI spec:
> Additionally, a created vector with
> element type T, implements the
> interfac... | There is a workaround: you can convert any multidimensional array to an IEnumerable
```
public static class ArrayExtensions
{
public static IEnumerable<T> ToEnumerable<T>(this Array target)
{
foreach (var item in target)
yield return (T)item;
}
}
``` | Why do C# multidimensional arrays not implement IEnumerable<T>? | [
"",
"c#",
".net",
"arrays",
"multidimensional-array",
""
] |
What is the best way to get the application name (i.e MyApplication.exe) of the executing assembly from a referenced class library in C#?
I need to open the application's app.config to retrieve some appSettings variables for the referenced DLL. | If you want to get the current appdomain's config file, then all you need to do is:
`ConfigurationManager.AppSettings`....
(this requires a reference to System.Configuration of course).
To answer your question, you can do it as Ray said (or use `Assembly.GetExecutingAssembly().FullName`) but I think the problem is e... | To get the answer to the question title:
```
// Full-name, e.g. MyApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
string exeAssembly = Assembly.GetEntryAssembly().FullName;
// or just the "assembly name" part (e.g. "MyApplication")
string exeAssemblyName = Assembly.GetEntryAssembly().GetName().Name... | Get executing assembly name from referenced DLL in C# | [
"",
"c#",
".net",
""
] |
I have two lists that are of the same length, is it possible to loop through these two lists at once?
I am looking for the correct syntax to do the below
```
foreach itemA, itemB in ListA, ListB
{
Console.WriteLine(itemA.ToString()+","+itemB.ToString());
}
```
do you think this is possible in C#? And if it is, wha... | # Modern Answer
LINQ now has a [built-in Zip method](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.zip), so you don't need to create your own. The resulting sequence is as long as the shortest input. Zip currently (as of .NET Core 3.0) has 2 overloads. The simpler one returns a sequence of tuples... | [edit]: to clarify; this is useful in the generic LINQ / `IEnumerable<T>` context, where you **can't use** an indexer, because a: it doesn't exist on an enumerable, and b: you can't guarantee that you can read the data more than once. Since the OP mentions lambdas, it occurs that LINQ might not be too far away (and yes... | Looping through 2 lists at once | [
"",
"c#",
"list",
""
] |
I have this Array i wrote a function MostFreq that takes an array of integers and return 2 values : the more frequent number in the array and its frequency check this code i worte what do you think ? is there a better way to do it?
```
static void Main()
{
int [] M={4,5,6,4,4,3,5,3};
int x;
int f=MyMath.M... | LINQ it up. I know this is in VB but you should be able to convert it to C#:
```
Dim i = From Numbers In ints _
Group Numbers By Numbers Into Group _
Aggregate feq In Group Into Count() _
Select New With {.Number = Numbers, .Count = Count}
```
EDIT: Now in C# too:
```
var i = from... | Assuming you can't use LINQ, I'd probably approach the algorithm like this:
* Create Key/Value dictionary
* Iterate your array, add a key the dictionary for each unique elem, increment the value each time that element is repeated.
* Walk the dictionary keys, and return the elem with the highest value.
This isn't a gr... | The Most frequent Number in an array | [
"",
"c#",
"algorithm",
""
] |
If I have a key set of 1000, what is a suitable size for my Hash table, and how is that determined? | It depends on the load factor (the "percent full" point where the table will increase its size and re-distribute its elements). If you know you have exactly 1000 entries, and that number will never change, you can just set the load factor to 1.0 and the initial size to 1000 for maximum efficiency. If you weren't sure o... | You need to factor in the hash function as well.
one rule of thumb suggests make the table size about double, so that there is room to expand, and hopefully keep the number of collisions small.
Another rule of thumb is to assume that you are doing some sort of modulo related hashing, then round your table size up to ... | Chosing a suitable table size for a Hash | [
"",
"java",
"hash",
"hashtable",
""
] |
What is the best way to read and/or set Internet Explorer options from a web page in Javascript? I know that these are in registry settings.
For example, I'm using the [JavaScript Diagram Builder](http://www.lutanho.net/diagram/) to dynamically generate bar charts within a web page. This uses the background color in f... | Web pages have no business reading users' settings, therefore there is no interface for this. | You can style the bars using a whopping left border instead of using a background colour.
Like this:
```
<style>
div.bar
{
width:1px;
border-left:10px solid red;
}
</style>
<div class="bar" style="height:100px"></div>
```
Obviously depends on the versatility of the product you're using. But I... | Best way to read/set IE options? | [
"",
"javascript",
"internet-explorer",
"settings",
"registry",
""
] |
We have a JavaScript function named "move" which does just "windows.location.href = *any given anchor*".
This function works on IE, Opera and Safari, but somehow is ignored in Firefox. Researching on Google doesn't produce a satisfactory answer **why** it doesn't work.
Does any JavaScript guru knows about this be... | Have you tried just using
```
window.location = 'url';
```
In some browsers, `window.location.href` is a read-only property and is not the best way to set the location (even though technically it should allow you to). If you use the `location` property on its own, that should redirect for you in all browsers.
Mozill... | If you are trying to call this javascript code after an event that is followed by a callback then you must add another line to your function:
```
function JSNavSomewhere()
{
window.location.href = myUrl;
return false;
}
```
in your markup for the page, the control that calls this function on click must return... | windows.location.href not working on Firefox3 | [
"",
"javascript",
"firefox",
""
] |
What is the best way to set the time on a remote machine remotely? The machine is running Windows XP and is receiving the new time through a web service call. The goal is to keep the remote machines in synch with the server. The system is locked down so that our web service is the only access, so I cannot use a time se... | I would use Windows built-in internet time abilities. You can set up a [time server](http://en.wikipedia.org/wiki/Time_server) on your server, have it get time from a 2nd-tier timeserver, and have all your client machines get time from it.
I've been down the application-setting-system-time road before. | This is the Win32 API call for setting system time:
```
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEMTIME {
public short wYear;
public short wMonth;
public short wDayOfWeek;
public short wDay;
public short wHour;
public short wMinute;
public short wSecond;
public short wMilliseconds;
} ... | Set time programmatically using C# | [
"",
"c#",
"time",
""
] |
I have a Java maven project which includes XSLT transformations. I load the stylesheet as follows:
```
TransformerFactory tFactory = TransformerFactory.newInstance();
DocumentBuilderFactory dFactory = DocumentBuilderFactory
.newInstance();
dFactory.setNamespaceAware(true);
DocumentBuilder dBuilder =... | Solved my problem using a URIResolver.
```
class MyURIResolver implements URIResolver {
@Override
public Source resolve(String href, String base) throws TransformerException {
try {
ClassLoader cl = this.getClass().getClassLoader();
java.io.InputStream in = cl.getResourceAsStream("xsl/" + href);
InputSou... | URIResolver can also be used in a more straightforward way as below:
```
class XsltURIResolver implements URIResolver {
@Override
public Source resolve(String href, String base) throws TransformerException {
try{
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStr... | Transformation Failing due to xsl:include | [
"",
"java",
"xslt",
""
] |
On a recent project I have been working on in C#/ASP.NET I have some fairly complicated JavaScript files and some nifty Style Sheets. As these script resources grow in size it [is advisable to minify the resources](http://developer.yahoo.com/yui/compressor/) and keep your web pages as light as possible, of course. I kn... | The [MSBuildCommunityTasks Project](https://github.com/loresoft/msbuildtasks/) has a few MSBuild tasks that may do what you are looking for including Merge and JSCompress.
You could add these into your MSBuild project in the AfterBuild target to allow the project to perform this action every time the project is built ... | Another JS (and CSS!) compression library for MSBuild:
<http://www.codeplex.com/YUICompressor>
This is a .NET port of the java-based [Yahoo! compressor](http://developer.yahoo.com/yui/compressor/). | Script Minification and Continuous Integration with MSBuild | [
"",
"javascript",
"msbuild",
"continuous-integration",
"build-automation",
"minify",
""
] |
As the title says really.
I've had a look at inheriting from TextBox, but the only sensible override was "OnKeyDown", but that just gives me a key from the Key enum (with no way to use Char.IsNumeric()). | Take a look at NumericUpDown in the Toolkit <http://codeplex.com/Silverlight> and maybe you can use that or look at the source to implement your own numeric textbox. | I took Nidhal's suggested answer and edited it a bit to handle the shift case for the characters above the digits (ie. !@#$%^&\*()) since that solution will still allow those characters in the textbox.
```
private void NumClient_KeyDown(object sender, KeyEventArgs e)
{
// Handle Shift case
if (Keyboard.... | How to create a numeric textbox in Silverlight? | [
"",
"c#",
".net",
"silverlight",
"textbox",
"silverlight-2.0",
""
] |
Imagine I have a process that starts several child processes. The parent needs to know when a child exits.
I can use `waitpid`, but then if/when the parent needs to exit I have no way of telling the thread that is blocked in `waitpid` to exit gracefully and join it. It's nice to have things clean up themselves, but it... | The function can be interrupted with a signal, so you could set a timer before calling waitpid() and it will exit with an EINTR when the timer signal is raised. Edit: It should be as simple as calling alarm(5) before calling waitpid(). | Don't mix `alarm()` with `wait()`. You can lose error information that way.
Use the self-pipe trick. This turns any signal into a `select()`able event:
```
int selfpipe[2];
void selfpipe_sigh(int n)
{
int save_errno = errno;
(void)write(selfpipe[1], "",1);
errno = save_errno;
}
void selfpipe_setup(void)
{... | Waitpid equivalent with timeout? | [
"",
"c++",
"c",
"linux",
""
] |
I currently have 2 `BufferedReader`s initialized on the same text file. When I'm done reading the text file with the first `BufferedReader`, I use the second one to make another pass through the file from the top. Multiple passes through the same file are necessary.
I know about `reset()`, but it needs to be preceded ... | What's the disadvantage of just creating a new `BufferedReader` to read from the top? I'd expect the operating system to cache the file if it's small enough.
If you're concerned about performance, have you proved it to be a bottleneck? I'd just do the simplest thing and not worry about it until you have a specific rea... | The Buffered readers are meant to read a file sequentially. What you are looking for is the [java.io.RandomAccessFile](http://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html), and then you can use `seek()` to take you to where you want in the file.
The random access reader is implemented like so:
```
... | Java BufferedReader back to the top of a text file? | [
"",
"java",
"file",
"file-io",
"text-files",
"bufferedinputstream",
""
] |
I've got a bunch of properties which I am going to use read/write locks on. I can implement them either with a `try finally` or a `using` clause.
In the `try finally` I would acquire the lock before the `try`, and release in the `finally`. In the `using` clause, I would create a class which acquires the lock in its co... | From MSDN, [using Statement (C# Reference)](http://msdn.microsoft.com/en-us/library/yh598w02.aspx)
> The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Disp... | I definitely prefer the second method. It is more concise at the point of usage, and less error prone.
In the first case someone editing the code has to be careful not to insert anything between the Acquire(Read|Write)Lock call and the try.
(Using a read/write lock on individual properties like this is usually overki... | 'using' statement vs 'try finally' | [
"",
"c#",
".net",
"multithreading",
"using-statement",
""
] |
I seem to be losing a lot of precision with floats.
For example I need to solve a matrix:
```
4.0x -2.0y 1.0z =11.0
1.0x +5.0y -3.0z =-6.0
2.0x +2.0y +5.0z =7.0
```
This is the code I use to import the matrix from a text file:
```
f = open('gauss.dat')
lines = f.readlines()
f.close()
j=0
for line in lines:
bi... | I'm not familiar enough with the Decimal class to help you out, but your problem is due to the fact that decimal fractions can often not be accurate represented in binary, so what you're seeing is the closest possible approximation; there's no way to avoid this problem without using a special class (like Decimal, proba... | IEEE floating point is binary, not decimal. There is no fixed length binary fraction that is exactly 0.1, or any multiple thereof. It is a repeating fraction, like 1/3 in decimal.
Please read [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.sun.com/source/806-3568/ncg_goldberg.ht... | Decimal place issues with floats and decimal.Decimal | [
"",
"python",
"floating-point",
"decimal",
"floating-accuracy",
""
] |
We have an application that installs SQL Server Express from the command line and specifies the service account as the LocalSystem account via the parameter SQLACCOUNT="NT AUTHORITY\SYSTEM".
This doesn't work with different languages because the account name for LocalSystem is different. There's a table listing the di... | You can use .NET's built-in [System.Security.Principal.SecurityIdentifier](http://msdn.microsoft.com/en-us/library/system.security.principal.securityidentifier.aspx) class for this purpose: by translating it into an instance of [NtAccount](http://msdn.microsoft.com/en-us/library/system.security.principal.ntaccount.aspx... | Or you can use:
```
string localSystem = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null).Translate(typeof(NTAccount)).Value;
```
With `WellKnownSidType` you can look for other accounts, as `NetworkService` for example. | Determine the LocalSystem account name using C# | [
"",
"c#",
"sql-server",
"localsystem",
""
] |
In the .xsd file for a typed DataSet in .NET, there's a `<Connections>` section that contains a list of any data connections I've used to set up the DataTables and TableAdapters.
There are times when I'd prefer not to have those there. For instance, sometimes I prefer to pass in a connection string to a custom constru... | This has bugged me for a long time as well and I did some testing recently. Here is what I came up with. For the record, I'm using VS 2008 SP1.
* Datasets *will* store connection string information whether you want them to or not.
* You *can* make sure datasets won't store passwords in their connection strings.
* You ... | In a similar case I stored the connection string for the dataset in a settings file / app.config (default behaviour in Visual Studio when creating a dataset) with integrated security to a local development database. In order to be able to access this from external projects, I changed the settings file to be `public` in... | Typed DataSet connection - required to have one in the .xsd file? | [
"",
"c#",
".net",
"vb.net",
"dataset",
""
] |
I have a little pet web app project I'd like to show someone who doesn't have an application server themselves (and who has no clue about application servers).
What is the easiest and quickest way for them to get my WAR file running with zero configuration, preferably something I could send along with or bundle with t... | You can create the slimmed down version yourself easily.
<http://docs.codehaus.org/display/JETTY/Embedding+Jetty>
<http://jetty.mortbay.org/xref/org/mortbay/jetty/example/LikeJettyXml.html>
To run embedded Jetty you need only the following jars on the classpath:
```
* servlet-api-2.5-6.x.jar
* jetty-util-6.x.jar
* ... | If you don't know or do not want to mess with maven you could try Jetty-runner
<https://svn.codehaus.org/jetty-contrib/trunk/jetty-runner>
jetty-runner.jar is one jar file that you can run from command line like so:
java -jar jetty-runner.jar my.war | Slim application server for demonstrating a web app? | [
"",
"java",
"application-server",
""
] |
I am trying to compare two decimal values in Java script. I have two objects as one assogned value "3" and the other as "3.00". When i say if (obj1 == obj2) it does not pass the condition as it is does the string comparision.
I would instead want it to do a decimal comparision where 3 = 3.00. Please let me know how to... | [This page](http://www.javascripter.net/faq/convert2.htm) describes how to convert a string to a floating-point number; I believe that is what you want. This would let you compare the numbers as numbers, which I think is what you mean by "decimally". Beware that doing an exact comparison between two floating-point numb... | You can also do type casting:
```
var a = "3.00";
var b = "3";
Number(a) == Number(b) // This will be true
``` | Decimal comaprison in Java script | [
"",
"asp.net",
"javascript",
"scripting",
""
] |
I am working with a huge list of URL's. Just a quick question I have trying to slice a part of the URL out, see below:
```
http://www.domainname.com/page?CONTENT_ITEM_ID=1234¶m2¶m3
```
How could I slice out:
```
http://www.domainname.com/page?CONTENT_ITEM_ID=1234
```
Sometimes there is more than two paramet... | Use the [urlparse](http://docs.python.org/2/library/urlparse.html#urlparse.urlsplit) module. Check this function:
```
import urlparse
def process_url(url, keep_params=('CONTENT_ITEM_ID=',)):
parsed= urlparse.urlsplit(url)
filtered_query= '&'.join(
qry_item
for qry_item in parsed.query.split('&... | The quick and dirty solution is this:
```
>>> "http://something.com/page?CONTENT_ITEM_ID=1234¶m3".split("&")[0]
'http://something.com/page?CONTENT_ITEM_ID=1234'
``` | Slicing URL with Python | [
"",
"python",
"url",
"string",
""
] |
I want to allow users to paste `<embed>` and `<object>` HTML fragments (video players) via an HTML form. The server-side code is PHP. How can I protect against malicious pasted code, JavaScript, etc? I could parse the pasted code, but I'm not sure I could account for all variations. Is there a better way? | I'm not really sure what parameters `EMBED` and `OBJECT` take as I've never really dealt with putting media on a page (which is actually kind of shocking to think about) but I would take a BB Code approach to it and do something like `[embed url="http://www.whatever.com/myvideo.whatever" ...]` and then you can parse ou... | Your chances of detecting malicious code reliably by scanning inputted HTML are about nil. There are so many possible ways to inject script (including browser-specific malformed HTML), you won't be able to pick them all out. If big webmail providers are still after years finding new exploits there is no chance you'll b... | How to Safely Accept Pasted <embed> Code in PHP | [
"",
"php",
"validation",
"embed",
""
] |
What is the difference between `private` and `protected` members in C++ classes?
I understand from best practice conventions that variables and functions which are not called outside the class should be made `private`—but looking at my MFC project, MFC seems to favor `protected`.
What's the difference and which shoul... | Private members are only accessible within the class defining them.
Protected members are accessible in the class that defines them and in classes that inherit from that class.
Both are also accessible by friends of their class, and in the case of protected members, by friends of their derived classes.
Use whatever ... | **Public** members of a class A are accessible for all and everyone.
**Protected** members of a class A are not accessible outside of A's code, but is accessible from the code of any class derived from A.
**Private** members of a class A are not accessible outside of A's code, or from the code of any class derived fr... | What is the difference between private and protected members of C++ classes? | [
"",
"c++",
"class",
"oop",
"private",
"protected",
""
] |
This is a question I have wondered about for quite some time, yet I have never found a suitable solution. If I run a script and I come across, let's say an IndexError, python prints the line, location and quick description of the error and exits. Is it possible to automatically start pdb when an error is encountered? I... | You can use [traceback.print\_exc](http://docs.python.org/library/traceback.html#traceback.print_exc) to print the exceptions traceback. Then use [sys.exc\_info](http://docs.python.org/library/sys#sys.exc_info) to extract the traceback and finally call [pdb.post\_mortem](http://docs.python.org/library/pdb#pdb.post_mort... | ```
python -m pdb -c continue myscript.py
# or
python -m pdb -c continue -m myscript
```
If you don't provide the `-c continue` flag then you'll need to enter 'c' (for Continue) when execution begins. Then it will run to the error point and give you control there. As [mentioned by eqzx](https://stackoverflow.com/quest... | Starting python debugger automatically on error | [
"",
"python",
"debugging",
""
] |
I'm currently running into some issues resizing images using GD.
Everything works fine until i want to resize an animated gif, which delivers the first frame on a black background.
I've tried using `getimagesize` but that only gives me dimensions and nothing to distinguish between just any gif and an animated one.
A... | There is a brief snippet of code in the PHP manual page of the `imagecreatefromgif()` function that should be what you need:
[`imagecreatefromgif` comment #59787 by ZeBadger](https://php.net/manual/en/function.imagecreatefromgif.php#59787) | While searching for a solution to the same problem I noticed that the php.net site has a follow-up to the code Davide and Kris are referring to, but, according to the author, less memory-intensive, and possibly less disk-intensive.
I'll replicate it here, because it may be of interest.
source: <http://www.php.net/man... | Can I detect animated gifs using php and gd? | [
"",
"php",
"gd",
""
] |
I have several static factory patterns in my PHP library. However, memory footprint is getting out of hand and we want to reduce the number of files required during execution time. Here is an example of where we are today:
```
require_once('Car.php');
require_once('Truck.php');
abstract class Auto
{
// ... some s... | The Autoload facility is often seen as Evil, but it works at these task quite nicely.
If you can get a good filesystem <-> classname mapping so you can, when given a class to provide, find it, then it will save you overhead and only load classes when needed.
It works for static classes too, so once the static class i... | I would recommend using the [autoloader](http://php.net/autoload).
That is, don't use `require_once()` to require either subclass, but allows the autoloader to call a function which can load the referenced class when you call `new Truck()` or `new Car()`.
As for the memory leak question, no, `require_once` is not sco... | What is the best way to include PHP libraries when using static factory pattern? | [
"",
"php",
"include",
"polymorphism",
"require",
"require-once",
""
] |
Given a class, [org.eclipse.ui.views.navigator.ResourceNavigator](http://help.eclipse.org/stable/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/ui/views/navigator/ResourceNavigator.html) for example, how do I find out which jar file to use? I know it's in org.eclipse.ui.ide, but how would I fin... | You also have this eclipse plugin: [jarclassfinder](http://www.alphaworks.ibm.com/tech/jarclassfinder)
The user enters the name of the class not found (or the name of the class that the Java project needs to access). The plug-in will search the selected directory (and subdirectories) for JAR files containing that clas... | If you have the jar in your class path / project path hit CTRL-SHIFT-T and type the name ... the jar will be displayed at the bottom.
If you haven't the class in your build path
a) put together a dummy project containing all the jars
b) I think there is a plugin to find jars from IBM Alphaworks (but that might be kind... | Java: How do I know which jar file to use given a class name? | [
"",
"java",
"eclipse",
"jar",
""
] |
I'm inserting an img tag into my document with the new Element constructor like this (this works just fine):
```
$('placeholder').insert(new Element("img", {id:'something', src:myImage}))
```
I would like to trigger a function when this image loads, but I can't figure out the correct syntax. I'm guess it's something ... | In this case, the best solution is to not use Prototype or at least not exclusively. This works:
```
var img = new Element('img',{id:'logo',alt:'Hooray!'});
img.onload = function(){ alert(this.alt); };
img.src = 'logo.jpg';
```
The key is setting the onload directly instead of letting Prototype's wrapper do it for yo... | Try
```
$('placeholder').insert(new Element("img", {
id: 'something',
src:myImage
}).observe('load', function() {
// onload code here
}));
``` | How to add event handler with Prototype new Element() constructor? | [
"",
"javascript",
"html",
"prototypejs",
""
] |
How do I set the date/time of the computer in C#? | You can set the date using [Microsoft.VisualBasic.Today](http://msdn.microsoft.com/en-us/library/9z20y6ha(VS.80).aspx) and [Microsoft.VisualBasic.TimeOfDay](http://msdn.microsoft.com/en-us/library/8hhbhw4c(VS.80).aspx), although they're subject to security restrictions.
Yes, it's strange accessing the Microsoft,Visual... | You'll have to use a P/Invoke to the Windows API.
Here's some [example code](http://pinvoke.net/default.aspx/kernel32.SetLocalTime) in C# | How to set the date/time in C# | [
"",
"c#",
"datetime",
""
] |
Wanted to generate a UI diagram (with nice layout) depicting relationships amongst network components. Which is the best Java based API to do such layouts with minimum fuss and light codebase. | If you're logging for a Java API that can do layouts (e.g. arrange boxes in a hierarchical fashion without overlap), check out [JGraph](http://www.jgraph.com/). | yWorks. <http://www.yworks.com/en/index.html> | UI diagram layout | [
"",
"java",
"diagramming",
""
] |
I'd like to warn users when they **try to close a browser window** if they **didn't save** the changes they made in the web form.
I'm using ASP.NET 3.5 (with ASP.NET Ajax).
Is there a common solution which I could easily implement?
*EDIT: maybe my question wasn't clear:* I am specifically looking for a way which int... | Here is an ASP.NET extender control that will help you with this:
<http://www.codeproject.com/KB/ajax/ajaxdirtypanelextender.aspx>
Hope this helps. It may not perfectly fit your needs but it at least shows you how. | you'll want to leverage off the
```
window.onbeforeunload
```
event. Similar to Gmail if you attempt to close the window when you haven't saved a composed email.
Theres some sample JS here.
<http://forums.devarticles.com/javascript-development-22/how-to-stop-browser-from-closing-using-javascript-8458.html> | ASP.NET: Warning on changed data closing windows | [
"",
"asp.net",
"javascript",
"asp.net-ajax",
""
] |
I have been hearing a lot about Ruby and possibly even Javascript being "true" object oriented languages as opposed to C++ and C# which are class oriented (or template based) languages. What is meant by true OO and what are the advantages of this over the class/template approach? | It's a subjective term used to promote languages. I've seen it used to say C# and Java are true object oriented languages in comparison to C++ because everything must be in a class (no global functions or variables) and all objects inherit from one Object class.
For Ruby, it may refers to how Ruby treats everything as... | The C++ issue is the following. C++ classes exist only in the source syntax. There's no run-time class object with attributes and methods.
In Python, everything's an object. An object's class is another object, with it's own methods and attributes. This is true of the smalltalk environment, also, which is a kind of be... | What is meant by the term "true" object orientation | [
"",
"c#",
"ruby",
"oop",
""
] |
When developing JavaScript, I tend to separate JavaScript code out into different files and then run a script to concatenate the files and compress or pack the resulting file. In the end, I have one file that I need to include on my production site.
This approach has usually worked, but I've started to run into a prob... | > If the concatenation script I'm using is simply concatenating a directory full of files, the child class might occur in the code before the parent class.
Is it too simple a solution to prepend a sort order value to each filename, and sort by name before performing the operation?
eg:
```
01_parent.js
02_child.js
``... | When I've worked on large apps, I've use [requireJS](http://requirejs.org) to divide my code into modules, and make sure those modules are loaded in the correct order. Then I just mark my derived class as depending on the parent class.
RequireJS comes with a tool that will combine and minify all your modules for produ... | How do you take advantage of prototypal inheritance without needing to include files in a specific order? | [
"",
"javascript",
"prototypal-inheritance",
""
] |
Is there any way of doing parallel assignment in C++? Currently, the below compiles (with warnings)
```
#include <iostream>
int main() {
int a = 4;
int b = 5;
a, b = b, a;
std::cout << "a: " << a << endl
<< "b: " << b << endl;
return 0;
}
```
and prints:
```
a: 4
b: 5
```
What I'd like it ... | That's not possible. Your code example
```
a, b = b, a;
```
is interpreted in the following way:
```
a, (b = b), a
```
It does nothing. The comma operator makes it return the value of a (the right most operand). Because assignment binds tighter, b = b is in parens.
The proper way doing this is just
```
std::swap(... | Parallel assignment is not supported in C++. Languages that support this usually treat `a,b,c` as a list on either side of the assignment operator, this isn't the way the comma operator works in C++. In C++, `a, b` evaluates a and then b, so `a, b = b, a` is the same as `a; b = b; a;`. | Parallel assignment in C++ | [
"",
"c++",
""
] |
What's the best cross-platform way to get file creation and modification dates/times, that works on both Linux and Windows? | In Python 3.4 and above, you can use the object oriented [pathlib module](https://docs.python.org/3/library/pathlib.html) interface which includes wrappers for much of the os module. Here is an example of getting the file stats.
```
>>> import pathlib
>>> fname = pathlib.Path('test.py')
>>> assert fname.exists(), f'No... | Getting some sort of modification date in a cross-platform way is easy - just call [`os.path.getmtime(path)`](https://docs.python.org/library/os.path.html#os.path.getmtime) and you'll get the Unix timestamp of when the file at `path` was last modified.
Getting file *creation* dates, on the other hand, is fiddly and pl... | How do I get file creation and modification date/times? | [
"",
"python",
"file",
""
] |
How do I search the whole classpath for an annotated class?
I'm doing a library and I want to allow the users to annotate their classes, so when the Web application starts I need to scan the whole classpath for certain annotation.
I'm thinking about something like the new functionality for Java EE 5 Web Services or E... | Use [org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider](http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/context/annotation/ClassPathScanningCandidateComponentProvider.html)
API
> A component provider that scans the classpath from a base package. It then applie... | And another solution is [ronmamo's](https://github.com/ronmamo) [Reflections](https://github.com/ronmamo/reflections).
Quick review:
* Spring solution is the way to go if you're using Spring. Otherwise it's a big dependency.
* Using ASM directly is a bit cumbersome.
* Using Java Assist directly is clunky too.
* Annov... | Scanning Java annotations at runtime | [
"",
"java",
"annotations",
"classloader",
""
] |
I'm trying to code opposite action to this:
```
std::ostream outs; // properly initialized of course
std::set<int> my_set; // ditto
outs << my_set.size();
std::copy( my_set.begin(), my_set.end(), std::ostream_iterator<int>( outs ) );
```
it should be something like this:
```
std::istream ins;
std::set<int>::size_t... | You could derive from the istream\_iterator<T>.
Though using [Daemin generator method](https://stackoverflow.com/questions/250096/how-to-read-arbitrary-number-of-bytes-using-stdcopy#250380) is another option, though I would generate directly into the set rather than use an intermediate vector.
```
#include <set>
#in... | Use:
```
std::copy( std::istream_iterator<int>(ins),
std::istream_iterator<int>(),
std::inserter(my_set, my_set.end())
);
```
Note the empty parameter:
```
std::istream_iterator<int>();
``` | How to read arbitrary number of values using std::copy? | [
"",
"c++",
"iterator",
"stl-algorithm",
"istream-iterator",
""
] |
Is there any performance reason to declare method parameters final in Java?
As in:
```
public void foo(int bar) { ... }
```
Versus:
```
public void foo(final int bar) { ... }
```
Assuming that `bar` is only read and never modified in `foo()`. | The final keyword does not appear in the class file for local variables and parameters, thus it cannot impact the runtime performance. It's only use is to clarify the coders intent that the variable not be changed (which many consider dubious reason for its usage), and dealing with anonymous inner classes.
There is a ... | The only benefit to a final parameter is that it can be used in anonymous nested classes. If a parameter is never changed, the compiler will already detect that as part of it's normal operation even without the final modifier. It's pretty rare that bugs are caused by a parameter being unexpectedly assigned - if your me... | Is there any performance reason to declare method parameters final in Java? | [
"",
"java",
"performance",
"final",
""
] |
I would like to make my Java/Swing application compatible with the Services-menu available on Mac OS X. For example, so that the user could select some text in JTextArea and have it converted into speech by **Services -> Speech -> Start Speaking Text**.
Is there a simple way to achieve that?
(The application should sti... | This seems to work on Mac OS X Leopard, with no change to the original application. So I've lost interest in the answer (to how to make it work on Tiger). Thanks for your contribution, however. | Have a look at apple's [OSXAdapter package](https://developer.apple.com/samplecode/OSXAdapter/index.html) (link requires free apple developer login) for java development. The samples included in the package shows you how to integrate nicely to the OS X application menu in a way that is only activated when your applicat... | Using Mac OS X Services-menu from a Java/Swing application | [
"",
"java",
"macos",
"swing",
""
] |
How do you get the caret position in a `<textarea>` using JavaScript?
For example: `This is| a text`
This should return `7`.
How would you get it to return the strings surrounding the cursor / selection?
E.g.: `'This is', '', ' a text'`.
If the word “is” is highlighted, then it would return `'This ', 'is', ' a tex... | With Firefox, Safari (and other Gecko based browsers) you can easily use textarea.selectionStart, but for IE that doesn't work, so you will have to do something like this:
```
function getCaret(node) {
if (node.selectionStart) {
return node.selectionStart;
} else if (!document.selection) {
return 0;
}
... | **Updated 5 September 2010**
Seeing as everyone seems to get directed here for this issue, I'm adding my answer to a similar question, which contains the same code as this answer but with full background for those who are interested:
[IE's document.selection.createRange doesn't include leading or trailing blank lines... | How to get the caret column (not pixels) position in a textarea, in characters, from the start? | [
"",
"javascript",
"textarea",
"caret",
""
] |
I have a written a Visual C++ console application (i.e. subsystem:console) that prints useful diagnositic messages to the console.
However, I would like to keep the application minimized most of the time, and instead of minimizing to the taskbar, appear as a nice icon on the system tray. I would also like to restore t... | This is going to be an ugly hack.
First, you have to retrieve the `hWnd` / `hInstance` of you console application. Right now, I can only come up with one way:
* Create a Guid with `CoCreateGuid()`
* Convert it to a string
* Set the title of the console window to this guid with `SetConsoleTitle()`
* Find the `hWnd` of... | You might want to write a separate gui to function as a log reader. You will then find it much easier to make this minimize to the tray. It would also let you do some other stuff you might find useful, such as changing which level of logging messages are visible on the fly. | How do I write a console application in Windows that would minimize to the system tray? | [
"",
"c++",
"c",
"windows",
"visual-c++",
""
] |
I am not a fan of using SQL\*PLUS as an interface to Oracle. I usually use [yasql](http://sourceforge.net/projects/yasql/), but it hasn't been updated since 2005 and can do with some improvements. A quick [Google search](http://www.google.com/search?q=sql*plus+replacement) shows yasql and [SQLPal](http://www.sqlpal.com... | I presume that you want a low-overhead method of knocking out queries, but want more functions than SQL\*Plus provides? Why not use Oracle's [SQL Developer](http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html)? It's free.
Install, make a new connection to your database, then just start ... | Take a look at [gqlplus](http://gqlplus.sourceforge.net/). It wraps sql\*plus on linux and makes it more user-friendly by adding things like command history, table name completion and so on. | Is there a good alternative to SQL*PLUS for Oracle? | [
"",
"sql",
"database",
"oracle",
"sqlplus",
""
] |
I have a C library with numerous math routines for dealing with vectors, matrices, quaternions and so on. It needs to remain in C because I often use it for embedded work and as a Lua extension. In addition, I have C++ class wrappers to allow for more convenient object management and operator overloading for math opera... | Your wrapper itself will be inlined, however, your method calls to the C library typically will not. (This would require link-time-optimizations which are technically possible, but to AFAIK rudimentary at best in todays tools)
Generally, a function call as such is not very expensive. The cycle cost has decreased consi... | If you're just wrapping the C library calls in C++ class functions (in other words, the C++ functions do nothing but call C functions), then the compiler will optimize these calls so that it's not a performance penalty. | How to synchronize C & C++ libraries with minimal performance penalty? | [
"",
"c++",
"c",
"optimization",
"portability",
"maintainability",
""
] |
How can I test `Controller.ViewData.ModelState`? I would prefer to do it without any mock framework. | You don't have to use a Mock if you're using the Repository Pattern for your data, of course.
Some examples:
<http://www.singingeels.com/Articles/Test_Driven_Development_with_ASPNET_MVC.aspx>
```
// Test for required "FirstName".
controller.ViewData.ModelState.Clear();
newCustomer = new Customer
{
Fi... | ```
//[Required]
//public string Name { get; set; }
//[Required]
//public string Description { get; set; }
ProductModelEdit model = new ProductModelEdit() ;
//Init ModelState
var modelBinder = new ModelBindingContext()
{
ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(
() =>... | How can I test ModelState? | [
"",
"c#",
"asp.net-mvc",
""
] |
How do I remove all attributes which are `undefined` or `null` in a JavaScript object?
(Question is similar to [this one](https://stackoverflow.com/questions/208105/how-to-remove-a-property-from-a-javascript-object) for Arrays) | You can loop through the object:
```
var test = {
test1: null,
test2: 'somestring',
test3: 3,
}
function clean(obj) {
for (var propName in obj) {
if (obj[propName] === null || obj[propName] === undefined) {
delete obj[propName];
}
}
return obj
}
console.log(test);
console.log(clean(test));
... | ### ES10/ES2019 examples
A simple one-liner (returning a new object).
```
let o = Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));
```
Same as above but written as a function.
```
function removeEmpty(obj) {
return Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));
}
```
... | Remove blank attributes from an Object in Javascript | [
"",
"javascript",
""
] |
There has been a flurry of updates released to Microsoft's Silverlight over the past couple of months (Silverlight 2 beta 2 runtime + dev tools, RC0 + dev tools which broke beta 2 apps), and recently Microsoft has released the RTM.
I have been trying (unsuccessfully) to integrate Sharepoint 2007 and Silverlight. Many ... | I haven't tried this out but
it seems like a good start:
[Silverlight Blueprint for SharePoint](http://www.codeplex.com/SL4SP) | This isn't too difficult to do. There are a few steps you need to follow:
1. [Update IIS with the xap mime type](http://blogs.conchango.com/howardvanrooijen/archive/2008/03/10/configure-mime-type-for-silverlight-2-0-in-iis.aspx).
2. Put your files some that SharePoint can get them. In our case we developed a feature w... | How to host a Silverlight app in a Sharepoint 2007 Web Part | [
"",
"c#",
"silverlight",
"sharepoint",
""
] |
I'm looking for a good open source Windows FTP client library with a public domain or BSD-type license. Something that I have access to the source code and I can use it from C++ for Windows applications in a commercial app.
We have used Wininet for years and it's buggy and horrible. The last straw is the IE8 beta 2 co... | You need Ultimate TCP/IP which is now free!
<http://www.codeproject.com/KB/MFC/UltimateTCPIP.aspx>
You get FTP. HTTP, SMTP, POP and more.
You won't regret it. | I have used [libCurl](http://curl.haxx.se/) to very good effect. The only disadvantage is that, to my knowledge, there is no support for parsing directory information that comes back from FTP servers (apparently, there is no standard directory format). | Good free FTP Client Library (for Windows C++ commercial apps)? | [
"",
"c++",
"windows",
"ftp",
""
] |
Is it at all possible to do database-agnostic table dumps/hydrates? I don't have any complicated constraints. I would also settle for db-specific ways, but the more pure jdbc it is the better (I don't want to resort to impdp/expdp). | Have a look at [DBUnit](http://dbunit.sourceforge.net/). DBUnit support exporting to a xml file, and importing from a xml file. Their [faq](http://dbunit.sourceforge.net/faq.html#streaming) has some advice on how to make the export / imports fast, be sure to check that out. | DBUnit looks good, however you probably are not going to beat the vendor tools for import/export. If you are going to be importing or exporting 100,000+ rows it's probably best to use impdp/expdp.
I've also done strange things like building an insert statement from a sql query and then using sqlplus to process. [selec... | Database agnostic jdbc table import/export to files? | [
"",
"sql",
"mysql",
"oracle",
"jdbc",
"dump",
""
] |
1. **When an object is instantiated in Java, what is really going into memory?**
2. Are copies of parent constructors included?
3. Why do hidden data members behave differently than overridden methods when casting?
I understand the abstract explanations that are typically given to get you use this stuff correctly, but... | When an object is instantiated, only the non-static data is actually "Created", along with a reference to the type of object that created it.
None of the methods are ever copied.
The "Reference" to the class that created it is actually a pointer dispatch table. One pointer exists for each method that is available to ... | I think you'll find this to be a comprehensive example:
<http://www.onjava.com/pub/a/onjava/2005/01/26/classloading.html> | Java Instantiation | [
"",
"java",
"oop",
"jvm",
""
] |
I have the following legacy code:
```
public class MyLegacyClass
{
private static final String jndiName = "java:comp/env/jdbc/LegacyDataSource"
public static SomeLegacyClass doSomeLegacyStuff(SomeOtherLegacyClass legacyObj)
{
// do stuff using jndiName
}
}
```
This class is working in a J2EE-C... | Just to make @Robin's suggestion of a strategy pattern more concrete: (Notice that the public API of your original question remains unchanged.)
```
public class MyLegacyClass {
private static Strategy strategy = new JNDIStrategy();
public static SomeLegacyClass doSomeLegacyStuff(SomeOtherLegacyClass legacyObj) {... | Refactor the code to use dependency injection. Then use you preferred DI framework (Spring, Guice, ...) to inject your resources. That will make it easy to switch between resource objects and strategies at runtime.
In this case, you can inject your datasource.
EDIT: Based on your new restriction, you can accomplish t... | Refactoring static method / static field for Testing | [
"",
"java",
"testing",
"refactoring",
"static",
""
] |
```
private const int THE_ANSWER = 42;
```
or
```
private const int theAnswer = 42;
```
Personally I think with modern IDEs we should go with camelCase as ALL\_CAPS looks strange. What do you think? | The recommended naming and capitalization convention is to use [**P**ascal**C**asing](https://en.wikipedia.org/wiki/Camel_case) for constants (Microsoft has a tool named [StyleCop](https://github.com/StyleCop) that documents all the preferred conventions and can check your source for compliance - though it is a little ... | Visually, Upper Case is the way to go. It is so recognizable that way.
For the sake of uniqueness and leaving no chance for guessing, I vote for UPPER\_CASE!
```
const int THE_ANSWER = 42;
```
**Note**: The Upper Case will be useful when constants are to be used within the same file at the top of the page and for int... | C# naming convention for constants? | [
"",
"c#",
".net",
"visual-studio",
"constants",
"naming-conventions",
""
] |
I know that in the original C++0x standard there was a feature called `export`.
But I can't find a description or explanation of this feature. What is it supposed to do? Also: which compiler is supporting it? | Although Standard C++ has no such requirement, some compilers require that all function templates need to be made available in every translation unit that it is used in. In effect, for those compilers, the bodies of template functions must be made available in a header file. To repeat: that means those compilers won't ... | See [this](https://isocpp.org/wiki/faq/templates#separate-template-fn-defn-from-decl-export-keyword) explanation for its use
Quite a few compilers don't support it either because it's too new or in the case of gcc - because they disaprove.
This post describes standard support for many compilers.
[Visual Studio suppor... | What is the best explanation for the export keyword in the C++0x standard? | [
"",
"c++",
""
] |
I am trying to find out how much memory my application is consuming from within the program itself. The memory usage I am looking for is the number reported in the "Mem Usage" column on the Processes tab of Windows Task Manager. | A good starting point would be [GetProcessMemoryInfo](http://msdn.microsoft.com/en-us/library/ms683219.aspx), which reports various memory info about the specified process. You can pass `GetCurrentProcess()` as the process handle in order to get information about the calling process.
Probably the `WorkingSetSize` memb... | I think this is what you were looking for:
```
#include<windows.h>
#include<stdio.h>
#include<tchar.h>
// Use to convert bytes to MB
#define DIV 1048576
// Use to convert bytes to MB
//#define DIV 1024
// Specify the width of the field in which to print the numbers.
// The asterisk in the format specifier "%*I6... | How to get memory usage under Windows in C++ | [
"",
"c++",
"windows",
"memory-management",
""
] |
What is the best way to pass data between a C server to a Java applet? Currently it's done by using a buffer and copying bytes to it using memcpy, but if the object ever changes I have to hunt down every instance of where it's being sent to the applet and have it changed.
Is there a better way to pass object to java? ... | You might want to take a look at [Protocol Buffers](http://code.google.com/p/protobuf/)
They let you define structured data, then generate the code to read and write messages in any of the supported languages. The only catch is I think they only support C++ for now, though I know there was interest in straight C imple... | I would have opened a socket connection between the two applications. You could serialize the object to an array of bytes and have the Java servlet deserialize it into a Java object with the same value. This way if the class definition changes, you only have to change the code in two places. | Passing data from C to Java | [
"",
"java",
"c",
"serialization",
""
] |
I've tried reading a JPG file using the `StreamReader` class' `ReadToEnd()` method which returns a string.
For some reason though, when I write this string out to a file, it doesn't open.
Is something lost when reading data into a string? | Strings are for *text* data. They're not for binary data - if you use them this way you *will* lose data (there are encodings you can use which won't lose data if you're lucky, but there are subtle issues which still make it a really bad idea.)
If you're actually dealing with a file, the easiest way of reading the who... | String is designed for holding unicode characters; not binary. For binary, use a `byte[]` or `Stream`. Or an `Image` etc for more specialized image handling.
Despite the name, `StreamReader` is actually a specialized `TextReader` - i.e. it is a `TextReader` that reads from a `Stream`. Images are not text, so this isn'... | c# - Is data "lost" when using binary data in a string? | [
"",
"c#",
"string",
""
] |
I have a long URL with tons of parameters that I want to open in the default browser from Java on a Windows system using
```
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "+url)
```
For short URLs like "<http://www.google.com>" this works fine. But for long URLs (say, 2000 characters), this simply d... | You will be running up against [this (archived)](https://web.archive.org/web/20190902193246/https://boutell.com/newfaq/misc/urllength.html) operating system/browser specific maximum URL length problem:
For "rundll32 url.dll" (i.e. Microsoft IE) you will be limited to 2,083 characters (including http://).
From where I... | As an aside, I would suggest using the cross platform `Desktop.open()` or `Desktop.browse()` instead of Windows only `rundll32`. This will give you an IOException if it can't open the write application. | Limit for URL length for "rundll32 url.dll,FileProtocolHandler"? | [
"",
"java",
"windows",
"url",
""
] |
I have a dictionary where keys are strings, and values are integers.
```
stats = {'a': 1, 'b': 3000, 'c': 0}
```
How do I get the key with the maximum value? In this case, it is `'b'`.
---
Is there a nicer approach than using an intermediate list with reversed key-value tuples?
```
inverse = [(value, key) for key,... | You can use `operator.itemgetter` for that:
```
import operator
stats = {'a': 1000, 'b': 3000, 'c': 100}
max(stats.iteritems(), key=operator.itemgetter(1))[0]
```
And instead of building a new list in memory use `stats.iteritems()`. The `key` parameter to the `max()` function is a function that computes a key that is... | ```
max(stats, key=stats.get)
``` | Getting key with maximum value in dictionary? | [
"",
"python",
"dictionary",
"max",
""
] |
When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW".
Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl?
Lua seems... | Just because it is "marketed" (in some general sense) as a special-purpose language for embedded script engines, does not mean that it is limited to that. In fact, WoW could probably just as well have chosen Python as their embedded scripting language. | Lua is a cool language, light-weight and extremely fast!
But the point is: **Is performance so important for those
tasks you mentioned?**
* Renaming a bunch of files
* Download some files from the web
* Webscraping
You write those programs once, and run them once, too maybe.
Why do you care about performance so much... | Lua as a general-purpose scripting language? | [
"",
"python",
"scripting",
"lua",
""
] |
I have a [`draggable`](https://jqueryui.com/draggable/) with a custom [`helper`](http://api.jqueryui.com/draggable/#option-helper). Sometimes the helper is a clone and sometimes it is the original element.
The problem is that when the helper is the original element and is **not** dropped on a valid droppable it gets r... | Ok, I found a solution! It's ugly and it breaks the 'rules of encapsulation,' but at least it does the job.
Remember **this is just for special cases**! jQuery can handle its own helper removal just fine. In my case I had a helper that was sometimes the original element and sometimes a clone, so it wasn't always appro... | I might be missing something here, but is it not simply a case of adding
```
revert: "invalid"
```
to the options of the draggable if the draggable is of an original element, not a clone? | jQuery: How to stop a helper from being removed if it wasn't successfully dropped | [
"",
"javascript",
"jquery",
"jquery-ui",
"drag-and-drop",
"jquery-ui-draggable",
""
] |
Hi guys I wrote this code and i have two errors.
1. Invalid rank specifier: expected ',' or ']'
2. Cannot apply indexing with [] to an expression of type 'int'
Can you help please?
```
static void Main(string[] args)
{
ArrayList numbers = new ArrayList();
foreach (int number in new int[12] {... | ```
using System;
using System.Collections;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
ArrayList numbers = new ArrayList();
foreach (int number in new int[] { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 })
{
numbers.Ad... | 1 - You don't have to specify the length of the array just say new int[]
2 - number is just an integer, I think you're trying to access numbers[i] | Why this code is not working? | [
"",
"c#",
".net",
"arrays",
"arraylist",
""
] |
More specifically, if I have:
```
public class TempClass : TempInterface
{
int TempInterface.TempProperty
{
get;
set;
}
int TempInterface.TempProperty2
{
get;
set;
}
public int TempProperty
{
get;
set;
}
}
public interface TempInter... | I had to modify Jacob Carpenter's answer but it works nicely. nobugz's also works but Jacobs is more compact.
```
var explicitProperties =
from method in typeof(TempClass).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
where method.IsFinal && method.IsPrivate
select method;
``` | I think the class you are looking for is System.Reflection.InterfaceMapping.
```
Type ifaceType = typeof(TempInterface);
Type tempType = typeof(TempClass);
InterfaceMapping map = tempType.GetInterfaceMap(ifaceType);
for (int i = 0; i < map.InterfaceMethods.Length; i++)
{
MethodInfo ifaceMethod = map.InterfaceMetho... | How do I use reflection to get properties explicitly implementing an interface? | [
"",
"c#",
"reflection",
"explicit-interface",
""
] |
I'd like to format a duration in seconds using a pattern like H:MM:SS. The current utilities in java are designed to format a time but not a duration. | If you're using a version of Java prior to 8... you can use [Joda Time](http://joda-time.sourceforge.net/) and [`PeriodFormatter`](http://joda-time.sourceforge.net/api-release/org/joda/time/format/PeriodFormatter.html). If you've really got a duration (i.e. an elapsed amount of time, with no reference to a calendar sys... | If you don't want to drag in libraries, it's simple enough to do yourself using a Formatter, or related shortcut eg. given integer number of seconds s:
```
String.format("%d:%02d:%02d", s / 3600, (s % 3600) / 60, (s % 60));
``` | How to format a duration in java? (e.g format H:MM:SS) | [
"",
"java",
"date-formatting",
"duration",
""
] |
If I’m writing an applet that shows a video sequence (eg. streaming from a camera, or the applet itself is running the on the camera), do my clients need to download the Java Media Framework libraries inorder to see the sequence? | Did you consider to use [Java FX](http://javafx.com/)? This technology is dealing with this problem of downloading media libraries and so no. Of course. It is still in development. If to be first-adopter is option, it will be worth of considering this. | If the applet makes use of the JMF libraries they need to be downloaded to the client machine (where the applet executes). However, JMF gets very little development from Sun (read none) and is pretty much legacy now (*subjective*).
Depending on how modern the camera is and what codecs it can output it may also be wort... | Java Media Framework on client side? | [
"",
"java",
"applet",
"jmf",
""
] |
So - I have a checkbox
```
<asp:CheckBox ID="chkOrder" runat="server" Visible='<%#IsCheckBoxVisible() %>'
Checked="false"
OnCheckedChanged="chkOrder_CheckedChanged" AutoPostBack="true"
EnableViewState="false"></asp:CheckBox>
```
the one above. Now, the checkbox is in a gridview and on databound - for... | In some php coding I did recently, I noticed that FF3 was remembering what I checked, even after a F5 page refresh. Looking at the source showed the correct HTML that I wanted generated. To work around this was to go up to the Address Bar and force the request for the page again.
Why this work around was necessary I'm... | Firefox remembers the state of form fields by default. `Ctrl+F5` will force Firefox to clear this cache.
You can disable this for individual form and input elements:
```
<form autocomplete="off">
<input ... autocomplete="off" />
``` | Why does a checkbox remain checked in FF3 but not in IE, Chrome or | [
"",
"javascript",
"jquery",
"asp.net",
"checkbox",
""
] |
I have seen the following code:
```
[DefaultValue(100)]
[Description("Some descriptive field here")]
public int MyProperty{...}
```
The functionality from the above snippit seems clear enough, I have no idea as to how I can use it to do useful things. Im not even sure as to what name to give it!
Does anyone know whe... | People have already covered the UI aspect - attributes have other uses, though... for example, they are used extensively in most serialization frameworks.
Some attributes are given special treatment by the compiler - for example, `[PrincipalPermission(...)]` adds declarative security to a method, allowing you to (autom... | > The functionality from the above
> snippit seems clear enough,
Maybe not, as many people think that [DefaultValue()] *sets* the value of the property. Actually, all it does to tell some visual designer (e.g. Visual Studio), what the code is going to set the default value to. That way it knows to **bold** the value i... | C# property attributes | [
"",
"c#",
"properties",
"attributes",
""
] |
I've begun to the the built-in TraceSource and TraceListener classes and I would like to modify the output format of the events independently of the TraceSources and TraceListeners. It seems that the TraceListeners apply their own formatting. Is it possible to completely change the formatting without creating a new cla... | The Enterprise Library Logging Application Block (<http://msdn.microsoft.com/en-us/library/cc309506.aspx>) is built on the .Net TraceSource and TraceListener classes (so you can pretty much just drop it into your project and it'll work), and it supports a message formatter that you can configure in the web.config (or a... | This is way late, but for any latecomers who might be looking for a TraceSource/TraceListener solution that supports formatting similar to that available in log4net, NLog, and LAB, you might try [Ukadc.Diagnostics](http://ukadcdiagnostics.codeplex.com/). You can configure the Ukadc-provided TraceListeners with a format... | Does the .Net TraceSource/TraceListener framework have something similar to log4net's Formatters? | [
"",
"c#",
".net",
"trace",
""
] |
I have let's say two pc's.PC-a and PC-b which both have the same application installed with java db support.I want from time to time to copy the data from the database on PC-a to database to PC-b and vice-versa so the two PC's to have the same data all the time.
Is there an already implemented API in the database layer... | In short: You can't do this without some work on your side. SalesLogix fixed this problem by giving everything a site code, so here's how your table looked:
```
Customer:
SiteCode varchar,
CustomerID varchar,
....
primary key(siteCode, CustomerID)
```
So now you would take your databases, and match up ... | As you mention in the comments that you want to "merge" the databases, this sounds like you need to write custom code to do this, as presumably there could be conficts - the same key in both, but with different details against it, for example. | The best way to import(merge)-export java db database | [
"",
"java",
"database",
"import",
"export",
""
] |
```
$images = array();
$images[0][0] = "boxes/blue.jpg";
$images[0][1] = "blah.html";
$images[1][0] = "boxes/green.jpg";
$images[1][1] = "blah.html";
$images[2][0] = "boxes/orange.jpg";
$images[2][1] = "blah.html";
$images[3][0] = "boxes/pink.jpg";
$images[3][1] = "blah.html";
$images[4][0] = "boxes/purple.jpg";
$image... | Slightly off topic, but wouldn't it be easier in this case (picking 5 items from a list of 6) just to pick one element and discard it from the original array, and then use the original? This will also ensure you do not get duplicates in the resultant array.
I realise that you may have more than 6 items in the original... | This might be a nicer way of doing it:
```
foreach (array_rand($images, 5) as $key) {
$boxes[] = $images[$key];
}
``` | Random image picker PHP | [
"",
"php",
""
] |
I've been a PHP developer for many years now, with many tools under my belt; tools that I've either developed myself, or free-to-use solutions that I have learned to trust.
I looked into CodeIgniter recently, and discovered that they have many classes and helper routines to aid with development, yet saw nothing in the... | Frameworks have several advantages:
* You don't have to write everything. In your case, this is less of a help because you have your own framework which you have accumulated over the years.
* Frameworks provide standardized and tested ways of doing things. The more users there are of a given framework, the more edge c... | Here's another reason *not* to create your own framework. [Linus' Law](http://en.wikipedia.org/wiki/Linus%27s_Law) - "Given enough eyeballs, all bugs are shallow". In other words, the more people who use a given framework, the more solid and bug-free it is likely to be.
Have you seen how many web frameworks there are ... | Why do I need to use a popular framework? | [
"",
"php",
"frameworks",
""
] |
```
today1 = new Date();
today2 = Date.parse("2008-28-10");
```
To compare the time (millisecond) values of these I have to do the following, because today2 is just a number.
```
if (today1.getTime() == today2)
```
Why is this? | To answer the question in the title: Because they decided so when creating the JavaScript language. Probably because Java's `java.util.Date` parse function was doing the same thing, and they wanted to mimic its behavior to make the language feel more familiar.
To answer the question in the text... Use this construct t... | If I remember correctly, Date gives you a value down to the millisecond you created the Date object. So unless this code runs exactly on 2008-28-10 at 00:00:00:000, they won't be the same.
Just an addition: Date.parse() by definition returns a long value representing the millisecond value of the Date, and not the Date... | Why does Date.parse not return a Date object? | [
"",
"javascript",
""
] |
I basically have a page which shows a "processing" screen which has been flushed to the browser. Later on I need to redirect this page, currently we use meta refresh and this normally works fine.
With a new payment system, which includes 3D secure, we potentially end up within an iframe being directed back to our site... | So I added the following to my redirected pages. Luckily they have nothing posted at them so can be simply redirected. Also the use of javascript is ok as it is required to get to that point in the site.
```
<script type="text/javascript" language="javascript">
if (top.frames.length>0)
setTimeout("top.location... | I'm doing something similar to keep an old site inside it's frameset:
```
<SCRIPT TYPE="text/JavaScript">
if (window == top){top.location.replace("/foo.html");}
</SCRIPT>
```
So to break out of the iframe, just change == to !=
I see that you're using setTimeout in your example. Is waiting to break out of the ifr... | Busting out of an iframe using meta-refresh or javascript? | [
"",
"javascript",
"html",
"iframe",
"redirect",
""
] |
I have a class which has the following constructor
```
public DelayCompositeDesigner(DelayComposite CompositeObject)
{
InitializeComponent();
compositeObject = CompositeObject;
}
```
along with a default constructor with no parameters.
Next I'm trying to create an instance, but it only works without param... | I think you are dealing with a Type mismatch.
Likely the assembly is referenced in different places, or they are compiled against different versions.
I suggest you iterate through the ConstructorInfo's and do a `paramtype == typeof(DelayComposite)` on the appropriate parameter. | I would think that your call would need to be:
```
var designer = Activator.CreateInstance(designerAttribute.Designer, new object[] { new DelayComposite(4) });
```
Unless, of course, it *is* that, in which case the answer is not immediately obvious. | Activator.CreateInstance can't find the constructor (MissingMethodException) | [
"",
"c#",
".net",
"activator",
"missingmethodexception",
""
] |
example:
I want to see if `array[5]` holds a value or is empty. | Elements in primitive arrays can't be empty. They'll always get initialized to something (usually `0` for `int` arrays, but depends on how you declare the array).
If you declare the array like so (for example):
```
int [] myArray ;
myArray = new int[7] ;
```
then all of the elements will default to `0`.
An alternat... | There is no such thing as an "empty" element in a Java array. If the array's length is at least six, then element 5 exists and it has a value. If you have not assigned anything else to that location, then it will have the value zero, just like an object's uninitialized field would have.
If it is an array of `Object` d... | How can I see if an element in an int array is empty? | [
"",
"java",
"arrays",
""
] |
Can someone please let me know how to get the different segments of the three rows that are intersecting in different ways using SQL? The three rows in #t2 represent sets A,B, C - I am looking for A I B, A I C, B I C, A I B I C, A' , B', C' etc., (7 possible segments with 3 rows as in a Venn diagram) where I is the Int... | If I have understood the problem correctly, I think you may have to resort to using a loop to cope with 'n' number of rows
```
DECLARE @Key2 INT
DECLARE @Subset VARCHAR(1000)
DECLARE @tblResults TABLE
(
Key2 INT,
Subset VARCHAR(1000)
)
SET @Subset = ''
SELECT @Key2 = MIN(Key2) FROM #t1
WHILE @Key2 IS NOT NUL... | How about this?
```
SELECT key2,
CASE
WHEN InA = 1 and InB = 1 and InC = 1 THEN 'ABC'
WHEN InA = 0 and InB = 1 and InC = 1 THEN 'BC'
WHEN InA = 1 and InB = 0 and InC = 1 THEN 'AC'
WHEN InA = 1 and InB = 1 and InC = 0 THEN 'AB'
WHEN InA = 1 and InB = 0 and InC = 0 THEN 'A'
WHEN InA = 0 and InB = 1 and InC... | Splitting rows in SQL | [
"",
"sql",
"rows",
"split",
""
] |
I want to capture the HTTP request header fields, primarily the Referer and User-Agent, within my client-side JavaScript. How may I access them?
---
Google Analytics manages to get the data via JavaScript that they have you embed in you pages, so it is definitely possible.
> **Related:**
> [Accessing the web page'... | If you want to access referrer and user-agent, those are available to client-side Javascript, but not by accessing the headers directly.
To retrieve the referrer, use [`document.referrer`](https://developer.mozilla.org/en-US/docs/DOM/document.referrer).
To access the user-agent, use [`navigator.userAgent`](https://d... | Almost by definition, the client-side JavaScript is not at the receiving end of a http request, so it has no headers to read. Most commonly, your JavaScript is the result of an http response. If you are trying to get the values of the http request that generated your response, you'll have to write server side code to e... | How do I access the HTTP request header fields via JavaScript? | [
"",
"javascript",
"http",
"http-headers",
""
] |
If you want to associate some constant value with a class, here are two ways to accomplish the same goal:
```
class Foo
{
public:
static const size_t Life = 42;
};
class Bar
{
public:
enum {Life = 42};
};
```
Syntactically and semantically they appear to be identical from the client's point of view:
```
siz... | The `enum` hack used to be necessary because many compilers didn't support in-place initialization of the value. Since this is no longer an issue, go for the other option. Modern compilers are also capable of optimizing this constant so that no storage space is required for it.
The only reason for not using the `stati... | They're not identical:
```
size_t *pLife1 = &Foo::Life;
size_t *pLife2 = &Bar::Life;
``` | static const Member Value vs. Member enum : Which Method is Better & Why? | [
"",
"c++",
"class-design",
""
] |
I am having trouble understanding how the System Registry can help me convert a DateTime object into the a corresponding TimeZone. I have an example that I've been trying to reverse engineer but I just can't follow the one critical step in which the UTCtime is offset depending on Daylight Savings Time.
I am using .NET... | Here is a code snippet in C# that I'm using in my WPF application. This will give you the current time (adjusted for Daylight Savings Time) for the time zone id you provide.
```
// _timeZoneId is the String value found in the System Registry.
// You can look up the list of TimeZones on your system using this:
// ReadO... | You can use DateTimeOffset to get the UTC offset so you shouldn't need to dig into the registry for that information.
TimeZone.CurrentTimeZone returns additional time zone data, and TimeZoneInfo.Local has meta data about the time zone (such as whether it supports daylight savings, the names for its various states, etc... | Displaying Time Zones in WPF/C#. Discover Daylight Savings Time Offset | [
"",
"c#",
"wpf",
"datetime",
"timezone",
""
] |
I'm working on a time sheet application, where I'd like the user to be able to enter times in TextBoxes, e.g.: 8 a or 8:00 a or the like, just like you can in Excel.
Now if you enter a *date* in a TextBox and then use DateTime.TryParse, you can enter it in several formats (Jan 31, 2007; 1/31/2007; 31/1/2007; January 3... | Come to think of it, never mind. I just noticed that if I use "am" and "pm" instead of "a" and "p", it works fine. It assumes today's date, instead of the default 1/1/0001, but that's not a problem for my purposes.
(Still, any reasonably easy solution to get the "a" and "p" to work is welcome.) | You can always cheat the system (quite easily):
```
DateTime blah = DateTime.Parse("1/1/0001 " + myTimeString);
```
I've done something similar myself. | Parsing time without date in a TextBox | [
"",
"c#",
"wpf",
"vb.net",
"datetime",
".net-3.5",
""
] |
We want to throw an exception, if a user calls DataContext.SubmitChanges() and the DataContext is not tracking anything.
That is... it is OK to call SubmitChanges if there are no inserts, updates or deletes. But we want to ensure that the developer didn't forget to attach the entity to the DataContext.
Even better...... | I don't think there are any public/protected methods that would let you get at this directly. You'd probably have to use reflection, like I did about 3 messages down [here](http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/1ad473b24976235e/345083e2f19884b1), looking at the `... | Look at the ObjectTracker or something that hangs off DataContext. It has the change list stored in there.
Also, I believe SubmitChanges is virtual, so you can intercept the SubmitChanges call and do some checking there. | Can I check wheter Linq 2 SQL's DataContext is tracking entities? | [
"",
"c#",
"linq-to-sql",
""
] |
I would like to remove two files from a folder at the conclusion of my script. Do I need to create a function responsible for removing these two specific files? I would like to know in some detail how to use os.remove (if that is what I should use) properly. These two files will always be discarded at the conclusion of... | Just call `os.remove("path/to/file")`. For example, to remove the file `.emacs`, call
```
os.remove(".emacs")
```
The path should be a `str` that's the pathname of the file. It may be relative or absolute. | It sounds like what you really want is a temp file:
<http://docs.python.org/library/tempfile.html> | How do I remove a specific number of files using python (version 2.5)? | [
"",
"python",
"file",
""
] |
I have an application that I'm trying to wrap into a jar for easier deployment. The application compiles and runs fine (in a Windows cmd window) when run as a set of classes reachable from the CLASSPATH. But when I jar up my classes and try to run it with java 1.6 in the same cmd window, I start getting exceptions:
``... | The -jar option is mutually exclusive of -classpath. See an old description [here](http://download.java.net/jdk8u20/docs/technotes/tools/windows/java.html)
> -jar
>
> Execute a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name. In order for this option to ... | You can omit the `-jar` option and start the jar file like this:
`java -cp MyJar.jar;C:\externalJars\* mainpackage.MyMainClass` | NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong? | [
"",
"java",
"jar",
"classpath",
"executable-jar",
""
] |
Once I have all the files I require in a particular folder, I would like my python script to zip the folder contents.
Is this possible?
And how could I go about doing it? | Adapted version of [the script](http://mail.python.org/pipermail/python-list/2006-May/384142.html) is:
```
#!/usr/bin/env python
from __future__ import with_statement
from contextlib import closing
from zipfile import ZipFile, ZIP_DEFLATED
import os
def zipdir(basedir, archivename):
assert os.path.isdir(basedir)
... | On python 2.7 you might use: [shutil.make\_archive(base\_name, format[, root\_dir[, base\_dir[, verbose[, dry\_run[, owner[, group[, logger]]]]]]])](http://docs.python.org/library/shutil#shutil.make_archive).
**base\_name** archive name minus extension
**format** format of the archive
**root\_dir** directory to comp... | How do I zip the contents of a folder using python (version 2.5)? | [
"",
"python",
"file",
"zip",
"python-2.5",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.