Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
What's the proper way for a Java command line application to do background work without hogging resources? Should it use sleep() in the loop or is there a more elegant/efficient way? | Some heuristics:
* Don't attempt to make scheduling decisions in your application. The operating system's scheduler is way better than yours will be. Let it do its job.
* Don't poll if you don't have to. For instance, instead of sleeping *n* seconds, then waking up to check a non-blocked socket, block on the socket. T... | I'd only use sleep() if there's no work to be done. For example, if you're doing something like polling a task queue periodically and there's nothing there, sleep for a while then check again, etc.
If you're just trying to make sure you don't hog the CPU but you're still doing real work, you could call Thread.yield() ... | What's the proper background process behaviour for a non-GUI Java app? | [
"",
"java",
"background",
""
] |
For an ASP.NET C# application, we will need to restrict access based on IP address. What is the best way to accomplish this? | In IIS 7 best way to restrict IP is by using the config file.
Full article:
<http://boseca.blogspot.com/2010/12/programmatically-addremove-ip-security.html> | One way is using a [HttpModule](http://www.codeproject.com/KB/aspnet/http-module-ip-security.aspx).
From the link (in case it ever goes away):
```
/// <summary>
/// HTTP module to restrict access by IP address
/// </summary>
public class SecurityHttpModule : IHttpModule
{
public SecurityHttpModule() { }
public... | Best way to restrict access by IP address? | [
"",
"c#",
".net",
"asp.net",
"security",
""
] |
I am having a couple of issues deciding how best to describe a certain data structure in C# (.NET 3.5).
I have to create a class library that creates some text files for the input of a command line program. There are dozens of file types, but most of them have a similar header, footer and a couple of other properties.... | This looks like something a Template Method would solve... (Finally a place to use a pattern :)
```
public abstract class DocumentGenerator
{
abstract protected void AddHeader();
abstract protected void AddBody();
abstract protected void AddFooter();
// Template Method http://en.wikipedia.org/wiki/Template_me... | As you say, constructors are not inherited.
Forcing the derived class to supply the details in the constructor would be the ideal case if you need to know the values during construction. If you don't, consider an abstract property that the derived class must provide:
```
// base-class
public abstract FileType FileTyp... | How best to structure class heirachy in C# to enable access to parent class members? | [
"",
"c#",
""
] |
How do I find out if a class is immutable in C#? | There is `ImmutableObjectAttribute`, but this is rarely used and poorly supported - and of course not enforced (you could mark a mutable object with `[ImmutableObject(true)]`. AFAIK, the only thing this this affects is the way the IDE handles attributes (i.e. to show / not-show the named properties options).
In realit... | Part of the problem is that "immutable" can have multiple meanings. Take, for example, ReadOnlyCollection<T>.
We tend to consider it to be immutable. But what if it's a ReadOnlyCollection<SomethingChangeable>? Also, since it's really just a wrapper around an IList I pass in to the constructor, what if I change the ori... | How do I find out if a class is immutable in C#? | [
"",
"c#",
"immutability",
""
] |
Since I can't use Microsoft as an example for best practice since their exception messages are stored in resource files out of necessity, I am forced to ask where should exception messages be stored.
I figure it's probably one of common locations I thought of
* Default resource file
* Local constant
* Class constant
... | I may get shot (well, downvoted) for this, but why not "where you create the exception"?
```
throw new InvalidDataException("A wurble can't follow a flurble");
```
Unless you're going to internationalize the exception messages ([which I suggest you don't](https://stackoverflow.com/questions/474450/should-exception-me... | If your exceptions are strongly typed, you don't need to worry about messages. Messages are for presenting errors to users, and exceptions are for controlling flow in exceptional cases.
```
throw new InvalidOperationException("The Nacho Ordering system is not responding.");
```
could become
```
throw new SystemNotRe... | Where Should Exception Messages be Stored | [
"",
"c#",
"exception",
"resources",
""
] |
I have a database which is in Access (you can get it [link text](http://cid-84dd6ce2da273835.skydrive.live.com/self.aspx/.Public/Unisa.accdb)). If I run
```
SELECT DISTINCT Spl.Spl_No, Spl.Spl_Name
FROM Spl INNER JOIN Del
ON Spl.Spl_No = Del.Spl_No
WHERE Del.Item_Name <> 'Compass'
```
It provides the names of the... | Do you mean something like this?
```
SELECT SPL.SPL_Name
FROM SPL
WHERE NOT SPL.SPL_no IN
(SELECT SPL_no FROM DEL WHERE DEL.Item_Name = "Compass")
``` | I think I would go for:
```
SELECT SELECT Spl_No, Spl_Name
FROM Spl
WHERE Spl_No NOT IN
(SELECT Spl_No FROM Del
WHERE Item_Name = 'Compass')
``` | SQL Sub-Query vs Join Confusion | [
"",
"sql",
"ms-access",
"join",
""
] |
I have an array of filenames and need to sort that array by the extensions of the filename. Is there an easy way to do this? | ```
Arrays.sort(filenames, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
// the +1 is to avoid including the '.' in the extension and to avoid exceptions
// EDIT:
// We first need to make sure that either both files or neither file
// has an exte... | If I remember correctly, the Arrays.sort(...) takes a Comparator<> that it will use to do the sorting. You can provide an implementation of it that looks at the extension part of the string. | Java sort String array of file names by their extension | [
"",
"java",
"arrays",
"file",
"sorting",
"filenames",
""
] |
* Implemented the **Sink** Class - to receive event notifications from COM Server
* Event Interface derives from **IDispatch**
I have an issue whereby an **IConnectionPoint::Advise** call returns **E\_NOTIMPL**. This could be because the **connection point** only allows one connection - [MSDN](http://msdn.microsoft.co... | ## Solved:
* Using **pure C++**
* No ATL
With the following **implementation** of **QI**:
```
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject)
{
if (iid == __uuidof(IUnknown) || iid == __uuidof(IS8SimulationEvents))
{
*ppvObject = (IS8SimulationEvents*)this;
} else {
... | Please read the MSDN article again.
```
A connection point that allows only one interface
can return E_NOTIMPL FROM the IConnectionPoint::EnumConnections method
EnumConnections : E_NOTIMPL
The connection point does not support enumeration.
```
IConnectionPoint::Advise is required to reply
CONNECT\_E\_ADVISELIMIT
... | How to check if a container supports multiple connections? | [
"",
"c++",
"visual-studio-2008",
"com",
"connection-points",
""
] |
I am developing a small business application which uses Sqlserver 2005 database.
Platform: .Net framework 3.5;
Application type: windows application;
Language: C#
Question:
I need to take and restore the backup from my application. I have the required script generated from SSME.
How do I run that particular script ... | You can run these scripts the same way you run a query, only you don't connect to the database you want to restore, you connect to master instead. | For the backup you probably want to use xp\_sqlmaint. It has the handy ability to remove old backups, and it creates a nice log file. You can call it via something like:
EXECUTE master.dbo.xp\_sqlmaint N''-S "[ServerName]" [ServerLogonDetails] -D [DatabaseName] -Rpt "[BackupArchive]\BackupLog.txt" [RptExpirationSchedul... | How do I run that database backup and restore scripts from my winform application? | [
"",
"c#",
"sql-server",
"database",
"backup",
"database-restore",
""
] |
Does creating an object using reflection rather than calling the class constructor result in any significant performance differences? | **Yes - absolutely.** Looking up a class via reflection is, *by magnitude*, more expensive.
Quoting [Java's documentation on reflection](http://java.sun.com/docs/books/tutorial/reflect/index.html):
> Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be... | Yes, it's slower.
But remember the damn #1 rule--PREMATURE OPTIMIZATION IS THE ROOT OF ALL EVIL
(Well, may be tied with #1 for DRY)
I swear, if someone came up to me at work and asked me this I'd be very watchful over their code for the next few months.
You must never optimize until you are sure you need it, until ... | Java Reflection Performance | [
"",
"java",
"performance",
"optimization",
"reflection",
""
] |
I am designing a psychology experiment with java applets. I have to make my java applets full screen. What is the best way of doing this and how can I do this.
Since I haven't been using java applets for 3 years(The last time I've used it was for a course homework :) ) I have forgotten most of the concepts. I googled ... | I think you want to use WebStart. You can deploy from a browser but it is otherwise a full blown application. There are a few browserish security restrictions, but, as you're using an Applet currently, I think I can assume they're not a problem. | The obvious answer is don't use applets. Write an application that uses a JFrame or JWindow as its top-level container. It's not a huge amount of work to convert an applet into an application. Applets are designed to be embedded in something else, usually a web page.
If you already have an applet and want to make it f... | How to make full screen java applets? | [
"",
"java",
"applet",
"fullscreen",
""
] |
I have a program that uses [JAMA](http://math.nist.gov/javanumerics/jama/) and need to test is a matrix can be inverted. I know that I can just try it and catch an exception but that seems like a bad idea (having a catch block as part of the "normal" code path seems to be bad form).
A test that also returns the invers... | In general, if you can't solve the matrix, it's singluar (non-invertable). I believe the way that JAMA does this is to try to solve the matrix using LU factorization, and if it fails, it returns "true" for isSingular().
There isn't really a general way to just look at the elements of a matrix and determine if it is si... | sounds like you would like to estimate the reciprocal of the condition number.
[This site](http://www.alglib.net/matrixops/general/rcond.php) looks somewhat promising...
See also [Golub and Van Loan, p. 128-130](http://books.google.com/books?id=mlOa7wPX6OYC&pg=PA128). (If you don't have a copy of it, get one.)
...or... | Test for invertability using Jama.Matrix | [
"",
"java",
"linear-algebra",
"jama",
"matrix-inverse",
""
] |
I want to be able to close an alert box automatically using Javascript after a certain amount of time or on a specific event (i.e. `onkeypress`). From my research, it doesn't look like that's possible with the built-in `alert()` function. Is there a way to override it and have control over the dialog box that it opens?... | As mentioned previously you really can't do this. You can do a modal dialog inside the window using a UI framework, or you can have a popup window, with a script that auto-closes after a timeout... each has a negative aspect. The modal window inside the browser won't create any notification if the window is minimized, ... | Appears you can somewhat accomplish something similar with the [Notification](https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API) API. You can't control how long it stays visible (probably an OS preference of some kind--unless you specify requireInteraction true, then it stay... | Javascript close alert box | [
"",
"javascript",
"dialog",
"alert",
"dom-events",
""
] |
I have been playing with javascript arrays and I have run into, what I feel, are some inconsistencies, I hope someone can explain them for me.
Lets start with this:
```
var myArray = [1, 2, 3, 4, 5];
document.write("Length: " + myArray.length + "<br />");
for( var i in myArray){
document.write( "myArray[" + i + "]... | The keys of a JavaScript array are actually strings. For details and an implementation of a map type for arbitrary keys, check [this answer](https://stackoverflow.com/questions/368280/javascript-hashmap-equivalent#383540).
---
To clarify and add to what Jason posted: JavaScript arrays are objects. Objects have proper... | (edit: the following is not quite right)
The keys of a JavaScript *Object* are actually strings. A Javascript *Array* by itself has numeric indices. If you store something with an index that can be interpreted as a nonnegative integer, it will try to do so. If you store something with an index that is not a nonnegativ... | Arrays keys number and "number" are unexpectedly considered the same | [
"",
"javascript",
"arrays",
"type-conversion",
""
] |
I'm wondering how others handle this situation... and how to apply the Don't Repeat Yourself (DRY) principle to this situation.
I find myself constantly PIVOTing or writing CASE statements in T-SQL to present Months as columns. I generally have some fields that will include (1) a date field and (2) a value field. When... | This isn't exactly what you're looking for, but I've done a lot of repetitive `UNPIVOT`, and typically, I would code-gen this, with some kind of standardized naming and use CTEs heavily:
```
WITH P AS (
SELECT Some Data
,[234] -- These are stats
,[235]
FROM Whatever
)
,FINAL_UNPIVO... | ```
/* I leave year and month separate so you can use "real" Months or Fiscal Months */
CREATE FUNCTION [dbo].[fn_MonthValueColumns]
(
@year int,
@month int,
@measure int
)
RETURNS TABLE
AS
RETURN
(
SELECT @year as [Year],
CASE WHEN @month = 1 THEN @measure ELSE 0 END AS [Jan],
... | How to apply the DRY principle to SQL Statements that Pivot Months | [
"",
"sql",
"sql-server",
"t-sql",
"dry",
"pivot",
""
] |
I am using python-ldap to try to authenticate against an existing Active Directory, and when I use the following code:
```
import ldap
l = ldap.initialize('LDAP://example.com')
m = l.simple_bind_s(username@example.com,password)
```
I get the following back:
```
print m
(97, [])
```
What does the 97 and empty list s... | According to the [documentation](http://support.microsoft.com/kb/218185), this is:
```
LDAP_REFERRAL_LIMIT_EXCEEDED 0x61 The referral limit was exceeded.
```
Probably
```
ldap.set_option(ldap.OPT_REFERRALS, 0)
```
could help. | The first item is a status code (97=success) followed by a list of messages from the server.
See [here](http://www.packtpub.com/article/installing-and-configuring-the-python-ldap-library-and-binding-to-an-ldap-directory) in the section **Binding**. | What does the LDAP response tuple (97, []) mean? | [
"",
"python",
"active-directory",
"ldap",
""
] |
I have a MySQL query like this:
```
SELECT *, SUM(...some SQL removed for brevety) AS Occurrences FROM some_table AS q
WHERE criterion="value" GROUP BY q.P_id ORDER BY Occurrences DESC LIMIT 10;
```
I want to restrict the results to rows where Occurrences>0. This seems very simple to me, but I can't seem to make it w... | I am not as familiar with MySQL as I am with SQL Server, but in T-SQL, you can't use aliases in GROUP BY clauses (I originally thought ORDER BY clauses as well, but that has since been shown to be incorrect). In this case, you want to filter based on the results of a GROUP BY, so I would use a HAVING clause as follows:... | This query works for me...
```
select order_id, sum(qty_ordered) as total_qty
from sales_flat_order_item
group by order_id
having total_qty > 10
order by total_qty desc
``` | How to use an aliased column in a MySQL WHERE clause? | [
"",
"sql",
"mysql",
"where-clause",
"having",
""
] |
I'm looking for a way to display a VNC viewer in a thick/rich java client (specifically, I'm using SWT, but if I can get it into AWT/Swing, I can integrate that specifically.) This is not an applet, but a real, live, thick java client.
[TightVNC](http://www.tightvnc.com/download.html) is probably sufficient; however, ... | A quick survey of the options thus far (I haven't found a satisfactory answer as of this writing):
* **[vncjlgpl](http://sourceforge.net/projects/vncjlgpl)** - Server only. Perhaps I could use the knowledge captured here to roll my own, which would make it a derivative work, which could be LGPL'd.
* **[TightVNC](http:... | I don't know if you still need something for this, but I've found the MetaVNC (on sourceforge) java viewer is pretty simple to work with. Last mods were in 2007 so it doesn't look like it's being maintained, but it might give you basic functionality. | How can I display a VNC Viewer in a Java rich client (LGPL, Apache, MIT license)? | [
"",
"java",
"open-source",
""
] |
Is there a way to do the following preprocessor directives in Python?
```
#if DEBUG
< do some code >
#else
< do some other code >
#endif
``` | There's `__debug__`, which is a special value that the compiler does preprocess.
```
if __debug__:
print "If this prints, you're not running python -O."
else:
print "If this prints, you are running python -O!"
```
`__debug__` will be replaced with a constant 0 or 1 by the compiler, and the optimizer will remove a... | I wrote a python preprocessor called pypreprocessor that does exactly what you're describing.
[The source and documentation is available on GitHub](https://github.com/interpreters/pypreprocessor).
[The package can also be downloaded/installed through the PyPI](http://pypi.python.org/pypi/pypreprocessor/).
Here's an ... | How would you do the equivalent of preprocessor directives in Python? | [
"",
"python",
"preprocessor",
"equivalent",
"directive",
""
] |
I have a temp table I am creating a query off of in the following format. That contains a record for every CustomerID, Year, and Month for several years.
## #T
Customer | CustomerID | Year | Month
ex.
```
Foo | 12345 | 2008 | 12
Foo | 12345 | 2008 | 11
Bar | 11224 | 2007 | 7
```
When I join this temp table to ... | You're specifying the date on the event table but not on the join -- so it's joining all records from the temp table with a matching customerid.
Try this:
```
SELECT COUNT(e.EventID), T.Customer, T.Year, T.Month
FROM [Event] e
INNER JOIN #T T ON (
T.CustomerID = e.CustomerID and
T.Year = year(e.DateOpened) and
... | Perhaps what you mean is:
```
SELECT COUNT(EventID)
,Customer
,Year
,Month
FROM [Event]
INNER JOIN #T
ON [Event].CustomerID = #T.CustomerID
AND YEAR([Event].DateOpened) = #T.YEAR
AND MONTH([Event].DateOpened) = #T.MONTH
WHERE [Event].DateOpened >= '2008-12-01'
AND [Event].DateOpened < '200... | SQL Join Not Returning What I Expect | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
In the past, when one made a `JPopupMenu` visible it's first item would get selected by default: <http://weblogs.java.net/blog/alexfromsun/archive/2008/02/jtrayicon_updat.html>
Nowadays the default behavior is to pop up the menu without any item selected. I would like create a `JPopupMenu` with a single item that will... | > Nowadays the default behavior is to pop up the menu without any item selected.
Actually, I would argue that this is the correct behavior, at least in Windows. Other non-Java applications do this too. I don't think it's worth breaking this convention even if there is only one item in the menu. If you feel otherwise, ... | Secret turns out to be `MenuSelectionManager.defaultManager().setSelectedPath(new MenuElement[]{menu, ...});`
```
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.MenuElement;
import javax.sw... | How to select first item in JPopupMenu? | [
"",
"java",
"swing",
"jmenupopup",
""
] |
I am having a few issues when people are trying to access a MySQL database and they are trying to update tables with the same information.
I have a webpage written using PHP. In this webpage is a query to check if certain data has been entered into the database. If the data hasn't, then i proceed to insert it. The tro... | You're looking for `LOCK`.
<http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html>
This can be run as a simple `mysql_query` (or `MySQLi::query/prepare`).
I'd say it's better to lock specific tables (although you can probably try `LOCK TABLES *`) that need to be locked rather than the whole database - as nothing w... | Read up on [database transactions](http://en.wikipedia.org/wiki/Database_transaction). That's probably a better way to handle what you need than running LOCK TABLES. | Locking a MySQL database so only one person at once can run a query? | [
"",
"php",
"mysql",
"concurrency",
""
] |
I work at a small LAMP Development Studio where the idea has been to just get the code done and go on to the next item on the list.
The team works in Zend Studio 5.5 connected to the Live server via FTP or SFTP. What they love about this is the speed of their deployment of code (since its just modifying live code).
B... | Questions:
1. Have you (they) never had a disaster where you (they) needed to revert to a previous version of the web site but couldn't because they'd broken it?
2. Do they use a staging web server to test changes?
3. Surely they don't modify the code in the production server without some testing somewhere?
I suspect... | Here's one trick that everyone will love:
I include this 'plugin' in most of my production sites:
Ofcourse, you need to create a limited-rights robot svn account for this first and svn must be installed on the server.
```
echo(' updating from svn<br>' );
$username = Settings::Load()->Get('svn','username');
... | Converting a development team from FTP to a Versioning System | [
"",
"php",
"version-control",
"development-environment",
""
] |
I have a form with 3 panels, the panels are created because at certain times I need certain groups of controls hidden/shown. Until now, it worked fine - that is until I was asked to have a specific way to navigate the form with TAB key.
First of all, I noticed that there is no TabIndex property in the Panel object and... | Pressing the TAB key will move the focus to the next control in the ControlCollection. Since the focus is always in a control within the Panel and not in the panel itself, how could you expect that a Panel supports tab index?
I suggest that you think again what you are trying to do. When a specific panel is visible, T... | I had the same issue. My solution was to put all controls in subpanels on the form. The tabbing of .net algorithm is to tab within the 'current' container using the TabIndex. If any of the TabIndexes within a container are the same, the first one in z-order will be first, etc.
Once in a container (a form is a containe... | Setting TabIndex in CF .net framework | [
"",
"c#",
".net",
"compact-framework",
"tabindex",
""
] |
Some people don't like sequences on Oracle. Why? I think they are very easy to use and so nice. You can use them in select, inserts, update,... | I don't. I should point out that sometimes people hate what they don't understand.
Sequences are incredibly important for generating unique IDs. Conceptually, it's useful to have a method of generating an ID that does not depend on the contents of a table. You don't need to lock a table in order to generate a unique n... | To sum it up, I like sequences, but I'd like an autoincrement keyword for columns even more. | Why do you hate sequences on Oracle? | [
"",
"sql",
"oracle",
"sequences",
""
] |
Suppose we have the following class hierarchy:
```
class Base {
...
};
class Derived1 : public Base {
...
};
class Derived2 : public Base {
...
};
```
Given a `Base*` which could point to either a `Derived1` or `Derived2` object how can I make a copy of the actual object given that it's concrete type is... | Unfortunately a virtual clone/copy pattern is your only real choice.
There are variations of this, but essentially they all come down to writing functions for each type that can return a new copy. | You need to implement the virtual clone method on every object in the hierarchy. How else would your object of undefined type know how to copy itself?
In order to make this more obvious to people writing derived classes, you might think about making the clone method abstract in your base class as well, to force people... | Make a copy of an unknown concrete type in c++ | [
"",
"c++",
"inheritance",
"polymorphism",
""
] |
When I'm debugging, I often have to deal with methods that does not use an intermediate variable to store the return value :
```
private int myMethod_1()
{
return 12;
}
private int myMethod_2()
{
return someCall( someValue );
}
```
Well, in order to recreate a bug, I often have to chang... | **For those who are looking for a solution to this in VB.NET:**
It was so simple, I can't believe I did not see it : To look at the value a function will return : just place the pointer over the function's name. The value will be shown in a tool tip.
The change the value : just click on this tool tip, change the valu... | Return values from functions are usually returned in the EAX register.
If you set a breakpoint just at the end of the function then there's a chance that changing EAX would change the return value. You can change and view any register in visual studio simply by writing its name in the watch window.
This is likely to... | Visual Studio - How to change the return value of a method in the debugger? | [
"",
"c#",
".net",
"vb.net",
"visual-studio",
"debugging",
""
] |
I'm new to python, and have a list of longs which I want to join together into a comma separated string.
In PHP I'd do something like this:
```
$output = implode(",", $array)
```
In Python, I'm not sure how to do this. I've tried using join, but this doesn't work since the elements are the wrong type (i.e., not stri... | You have to convert the ints to strings and then you can join them:
```
','.join([str(i) for i in list_of_ints])
``` | You can use map to transform a list, then join them up.
```
",".join( map( str, list_of_things ) )
```
BTW, this works for any objects (not just longs). | How to convert a list of longs into a comma separated string in python | [
"",
"python",
""
] |
Using POSIX threads & C++, I have an "Insert operation" which can only be done safely one at a time.
If I have multiple threads waiting to insert using pthread\_join then spawning a new thread
when it finishes. Will they all receive the "thread complete" signal at once and spawn multiple inserts or is it safe to assum... | From [opengroup.org on pthread\_join](http://opengroup.org/onlinepubs/007908799/xsh/pthread_join.html):
> The results of multiple simultaneous calls to pthread\_join() specifying the same target thread are undefined.
So, you really should not have several threads joining your previous insertThread.
First, as you use... | According to the Single Unix Specifcation: "The results of multiple simultaneous calls to pthread\_join() specifying the same target thread are undefined."
The "normal way" of achieving a single thread to get the task would be to set up a condition variable (don't forget the related mutex): idle threads wait in pthrea... | pthread_join - multiple threads waiting | [
"",
"c++",
"multithreading",
"posix",
""
] |
When I try this code:
```
class MyStuff:
def average(a, b, c): # Get the average of three numbers
result = a + b + c
result = result / 3
return result
# Now use the function `average` from the `MyStuff` class
print(MyStuff.average(9, 18, 27))
```
I get an error that says:
```
File "class... | You can instantiate the class by declaring a variable and calling the class as if it were a function:
```
x = mystuff()
print x.average(9,18,27)
```
However, this won't work with the code you gave us. When you call a class method on a given object (x), it always passes a pointer to the object as the first parameter w... | From your example, it seems to me you want to use a static method.
```
class mystuff:
@staticmethod
def average(a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
return result
print mystuff.average(9,18,27)
```
Please note that an heavy usage of static methods in python is usuall... | Why do I get a TypeError if I try to call a method directly from the class, supplying all arguments? | [
"",
"python",
"python-3.x",
"class",
"methods",
""
] |
Let's say I have a couple composite shapes (`<g>`). I want to be able to click and drag them, but I want the one I happen to be dragging at the moment to be on TOP of the other one in the Z order, so that if I drag it over the OTHER one, the other one should be eclipsed. | Z index in SVG is defined by the order the elements appear in the document (subsequent elements are painted on top of previous elements).
You will have to change the element order if you want to bring a specific shape to the top. | An alternative to moving elements in the tree is to use `<use>` elements where you change the `xlink:href` attribute so that it gives you the z ordering you want.
Here's an [old thread](http://tech.groups.yahoo.com/group/svg-developers/message/59312) on svg-developers mailinglist discussing this topic in context of wa... | With JavaScript, can I change the Z index/layer of an SVG <g> element? | [
"",
"javascript",
"svg",
""
] |
So, I have a method that performs a parametrised LIKE query. The method takes in the search parameter/value in and then it is added to the command ready for the query.
It is not working. It should work, and when I code the value to search for directly into the SQL string, sans parametrisation, it does work! When I hav... | Try this:
```
command.CommandText = "SELECT * FROM TableOfAwesomeness WHERE BestTVShow LIKE @tvShow + '%'"
``` | Try appending the '%' to the end of the parameter string rather than embedding it in the sql. | Parameterised query breaks when doing LIKE condition. Why? | [
"",
"sql",
".net",
"parameters",
"sql-like",
""
] |
While looking for an SFTP client in C# SSH File Transfer Protocol (SFTP), I've come across these two suitable projects - [one](http://sourceforge.net/projects/sharpssh) and [two](http://granados.sourceforge.net/).
While trying to understand the basics, I came across this confusing [Wikipedia article](http://en.wikiped... | Here is the difference:
* [SFTP](http://en.wikipedia.org/wiki/SSH_File_Transfer_Protocol) (SSH file transfer protocol) is a protocol that provides file transfer and manipulation capabilities. It can work over any reliable data stream, but is typically used with SSH
* "FTP over SSH" uses the regular old FTP protocol, b... | Basically, there are the following file transfer protocols around:
* FTP – the plain old FTP protocol that has been around since 1970s. The acronym stands for "File Transfer Protocol". It usually runs over TCP port 21.
* SFTP – another, completely different file transfer protocol that has nothing to do with FTP. SFTP ... | Differences between SFTP and "FTP over SSH" | [
"",
"c#",
"ftp",
"ssh",
"sftp",
""
] |
> **Possible Duplicate:**
> [JavaScript data formatting/pretty printer](https://stackoverflow.com/questions/130404/javascript-data-formatting-pretty-printer)
I am getting a bit tired of looking at unformatted json blobs in FireBug.
Does anyone know an equivalent to PHP's print\_r() for jQuery?
Something that would... | [`console.log`](http://getfirebug.com/wiki/index.php/Console_API#console.log.28object.5B.2C_object.2C_....5D.29) is what I most often use when debugging.
I was able to find this [`jQuery extension`](http://plugins.jquery.com/taxonomy/term/471) though. | You could use very easily [reflection](http://pietschsoft.com/post/2008/02/Simple-JavaScript-Object-Reflection-API-(NET-Style).aspx) to list all properties, methods and values.
For Gecko based browsers you can use the .toSource() method:
```
var data = new Object();
data["firstname"] = "John";
data["lastname"] = "Smi... | jQuery: print_r() display equivalent? | [
"",
"php",
"jquery",
"debugging",
""
] |
Actually what i am trying to build is like a kind of firewall. It should be able to get to know all the requests going from my machine. It should be able to stop selected ones. I am not sure how to even start about with this. I am having VS 2008/2005 with framework 2.0. Please let me know if there is any particular cla... | Firewalls really should be implemented fairly low in the networking stack; I'd strongly suggest NDIS. [This article](http://www.codeproject.com/KB/IP/drvfltip.aspx) may be of interest. | Something like this may help you get started: <http://www.mentalis.org/soft/projects/pmon/>
> This C# project allows Windows NT administrators to intercept IP packets sent through one of the network interfaces on the computer. This can be very handy to debug network software or to monitor the network activity of untru... | How to build a kind of firewall | [
"",
"c#",
"visual-studio",
"firewall",
""
] |
I attempted to open a Java bug last Halloween. I immediately got a response that my submission was accepted, and have heard nothing since. Looking at Sun's web pages, I can't found any contact information where I can inquire. Almost two weeks ago I made a post in the [Sun forums](http://forums.sun.com/thread.jspa?threa... | I've had mixed results when submitting bug reports. I've submitted quite a few bug reports/RFE's related to the `java.util.regex` package; they always appeared in the public database within a few weeks, and were usually resolved to my satisfaction fairly quickly. But that's probably because the regex package is small a... | Did you get an email telling you that your bug report will appear in the [Bug Database](http://bugs.sun.com/) soon? I filed a report once and it took about a week before appearing in the public database. There are also some caveats regarding bugs that will not be on the public database because of "[security reasons](ht... | How does one successfully open a Java bug if Sun doesn't respond? | [
"",
"java",
"bug-tracking",
"no-response",
""
] |
I have a script that loops through a series of four (or less) characters strings. For example:
```
aaaa
aaab
aaac
aaad
```
If have been able to implement it with nested for loops like so:
```
chars = string.digits + string.uppercase + string.lowercase
for a in chars:
print '%s' % a
for b in chars:
... | ```
import string
import itertools
chars = string.digits + string.letters
MAX_CHARS = 4
for nletters in range(MAX_CHARS):
for word in itertools.product(chars, repeat=nletters + 1):
print (''.join(word))
```
That'll print all **`15018570`** words you're looking for. If you want more/less words just change ... | I'm going to submit my answer as the most readable and least scalable :)
```
import string
chars = [''] + list(string.lowercase)
strings = (a+b+c+d for a in chars
for b in chars
for c in chars
for d in chars)
for string in strings:
print string
```
EDIT: ... | Replace Nested For Loops... or not | [
"",
"python",
"loops",
"for-loop",
"nested-loops",
""
] |
I have a template I made that sets variables that rarely change, call my headers, calls my banner and sidebar, loads a variable which shows the individual pages, then calls the footer. In one of my headers, I want the URL of the page in the user's address bar. Is there a way to do this?
Currently:
```
<?php
$title = ... | The main variables you'll be intersted in is:
`$_SERVER['REQUEST_URI']` Holds the path visited, e.g. `/foo/bar`
`$_SERVER['PHP_SELF']` is the path to the main PHP file (*NOT* the file you are in as that could be an include but the actual base file)
There are a ton of other useful variables worth remembering in $\_SER... | the Web address of the Page being called, can be obtained from the following function ::
```
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SER... | PHP - Find URL of script that included current document | [
"",
"php",
"url",
"include",
""
] |
What's the best way in PHP to sort an array of arrays based on array length?
e.g.
```
$parent[0] = array(0, 0, 0);
$parent[2] = array("foo", "bar", "b", "a", "z");
$parent[1] = array(4, 2);
$sorted = sort_by_length($parent)
$sorted[0] = array(4, 2);
$sorted[1] = array(0, 0, 0);
$sorted[2] = array("foo", "bar", "b",... | This will work:
```
function sort_by_length($arrays) {
$lengths = array_map('count', $arrays);
asort($lengths);
$return = array();
foreach(array_keys($lengths) as $k)
$return[$k] = $arrays[$k];
return $return;
}
```
Note that this function will preserve the numerical keys. If you want to r... | I'm upvoting Peter's but here's another way, I think:
```
function cmp($a1, $a2) {
if (count($a1) == count($a2)) {
return 0;
}
return (count($a1) < count($a2)) ? -1 : 1;
}
usort($array, "cmp");
``` | Sorting an array of arrays by the child array's length? | [
"",
"php",
"arrays",
"sorting",
""
] |
Ran across this line of code:
```
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
```
What do the two question marks mean, is it some kind of ternary operator?
It's hard to look up in Google. | It's the null coalescing operator, and quite like the ternary (immediate-if) operator. See also [?? Operator - MSDN](https://learn.microsoft.com/en-in/dotnet/csharp/language-reference/operators/null-coalescing-operator).
```
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
```
expands to:
```
FormsAuth = f... | Just because no-one else has said the magic words yet: it's the **null coalescing operator**. It's defined in section 7.12 of the [C# 3.0 language specification](http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc).
It's very handy, particularly becau... | What do two question marks together mean in C#? | [
"",
"c#",
"null-coalescing-operator",
""
] |
I have my resource and they typical overridden method to handle POST requests.
```
public void acceptRepresentation(Representation rep) {
if (MediaType.APPLICATION_XML.equals(rep.getMediaType())) {
//Do stuff here
}
else {
//complain!
}
}
```
What I want to know is the best practice to handle my ... | This is more of the kind of response I was looking for. Thanks to [Thierry Boileau](http://restlet.tigris.org/ds/viewMessage.do?dsForumId=4447&dsMessageId=1024110) for the answer:
> You can use two kinds of "XML
> representations": DomRepresentation
> and SaxRepresentation. You can
> instantiate both of them with the
... | We currently do this using RESTeasy, which is an alternative JAX-RS implementation. We use JAXB bindings (annotations) to map between the XML and our model POJOs, and specify a *JAXB provider* to JAX-RS so it knows how. This is described in our [RESTful web services in Java EE with RESTEasy (JAX-RS) article](http://www... | REST web service accepting a POST using Restlet - Best Practice | [
"",
"java",
"web-services",
"rest",
"post",
"restlet",
""
] |
Looking at the [unicode standard](http://www.unicode.org/versions/Unicode5.0.0/ch05.pdf#G23927), they recommend to use plain `char`s for storing UTF-8 encoded strings. Does this work as expected with C++ and the basic `std::string`, or do cases exist in which the UTF-8 encoding can create problems?
For example, when c... | There's a library called "[UTF8-CPP](http://utfcpp.sourceforge.net/)", which lets you store your UTF-8 strings in standard std::string objects, and provides additional functions to enumerate and manipulate utf-8 characters.
I haven't tested it yet, so I don't know what it's worth, but I am considering using it myself. | An example with [ICU library](http://icu-project.org/) (C, C++, Java):
```
#include <iostream>
#include <unicode/unistr.h> // using ICU library
int main(int argc, char *argv[]) {
// constructing a Unicode string
UnicodeString ustr1("Привет"); // using platform's default codepage
// calculating the length ... | What is the best way to store UTF-8 strings in memory in C/C++? | [
"",
"c++",
"unicode",
""
] |
Does anyone know how to maintain text formatting when using XPath to extract data?
I am currently extracting all blocks
`<div class="info">
<h5>title</h5>
text <a href="somelink">anchor</a>
</div>`
from a page. The problem is when I access the nodeValue, I can only get plain text. How can I capture the contents incl... | If you have it as a DomElement $element as part of a DomDocument $dom then you will want to do something like:
```
$string = $dom->saveXml($element);
```
The NodeValue of an element is really the textual value, not the structured XML. | I would like to add to Ciaran McNulty answer
You can do the same in SimpleXml like:
```
$simplexml->node->asXml(); // saveXml() is now an alias
```
And to expand on the quote
> The NodeValue of an element is really the textual value, not the structured XML.
You can think of your node as follows:
```
<div class="i... | Screen Scraping with PHP and XPath | [
"",
"php",
"xpath",
"screen-scraping",
""
] |
Is it possible to use the `__call` magic method when calling functions statically? | Not yet, there is a proposed (now available) [`__callStatic`*Docs*](http://php.net/language.oop5.overloading#object.callstatic) method in the pipeline last I knew. Otherwise `__call` and the other `__` magic methods are not available for use by anything but the instance of a object. | You have to use the *other* magic method, [`__callStatic`](https://www.php.net/language.oop5.overloading) - this is only available in PHP >= 5.3, which hasn't actually been released yet. | Using __call with static classes? | [
"",
"php",
"oop",
"static",
"magic-methods",
""
] |
< backgound>
I'm at a point where I really need to optimize C++ code. I'm writing a library for molecular simulations and I need to add a new feature. I already tried to add this feature in the past, but I then used virtual functions called in nested loops. I had bad feelings about that and the first implementation pr... | If you want to force *any* compiler to not discard a result, have it write the result to a volatile object. That operation cannot be optimized out, by definition.
```
template<typename T> void sink(T const& t) {
volatile T sinkhole = t;
}
```
No iostream overhead, just a copy that has to remain in the generated co... | **edit**: the easiest thing you can do is simply use the data in some spurious way after the function has run and outside your benchmarks. Like,
```
StartBenchmarking(); // ie, read a performance counter
for (int i=0; i<500; ++i)
{
coords[i][0] = 3.23;
coords[i][1] = 1.345;
coords[i][2] = 123.998;
}
StopBen... | How to correctly benchmark a [templated] C++ program | [
"",
"c++",
"optimization",
"benchmarking",
""
] |
I've been thinking about playing with [Java3D](https://java3d.dev.java.net/). But first I would like to know if anyone has done much with it? What types of projects have you done and what tutorials/examples/guides did you use to learn it? What are your general thoughts about the API? Is it well developed? Can you progr... | I have tried to develop in it about 4-5 years ago, and my impression is that while it was initially a great idea and had some good design going for it, Sun eventually stopped working on it and moved it to the purgatory of a "community project" where it has slowly been dying.
I was working at the time on a 3D conferenc... | If you want to experiment with 3D, it's far easier to get up and running than to try to do anything with DirectX (although the DirectX API more closely matches what game developers actually do, of course).
The fact that it's community-supported does mean you won't get a lot of richness today, but for a lot of tools, i... | Java3D: Tutorials, Projects, General 3D Programming | [
"",
"java",
"java-3d",
""
] |
I'm using the [jQuery Validation plugin](http://docs.jquery.com/Plugins/Validation) and I've got a textbox with the class `digits` to force it to be digits only, but not required. When I call validate on the form it works fine, but if I call `valid()` on the textbox when it's empty, it returns 0, despite no error messa... | Check this, from the [documentation](http://docs.jquery.com/Plugins/Validation/Methods/digits):
> Makes "field" required and digits
> only.
You could do something like this:
```
var isValid = jQuery('#kiloMetresTravelled').valid() || jQuery('#kiloMetresTravelled').val() == "";
``` | I think this works:
```
var e="#whatever";
var isValid = $(e).valid() || $(e).val()== "" && !$(e).hasClass('required');
``` | The jQuery Validation `valid()` method returns 0 when required is not true | [
"",
"javascript",
"jquery",
"validation",
"jquery-validate",
""
] |
I consider myself quite fluent in PHP and am rather familiar with nearly all of the important aspects and uses, as well as its pratfalls. This in mind, I think the major problem in taking on Perl is going to be with the syntax. Aside from this (a minor hindrance, really, as I'm rather sold on the fact that Perl's is fa... | some different things worth a read about:
* packages
* lexical scopes
* regular expression syntax
* hashes, arrays and lists (all the same in PHP, all different in Perl)
* CPAN | After you learn the basics of Perl, I highly recommend the book "[Perl Best Practices](http://oreilly.com/catalog/9780596001735/)" by Damian Conway.
It really changes your writing style, and the way you think about programming, and in particular, makes your Perl programs much more readable, and maintainable. | As a PHP developer thinking of making Perl a secondary strong suit, what do I need to know? | [
"",
"php",
"perl",
""
] |
Given a string with replacement keys in it, how can I most efficiently replace these keys with runtime values, using **Java**? I need to do this often, fast, and on reasonably long strings (say, on average, 1-2kb). The form of the keys is my choice, since I'm providing the templates here too.
Here's an example (please... | The appendReplacement method in [Matcher](http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html) looks like it might be useful, although I can't vouch for its speed.
Here's the sample code from the Javadoc:
```
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in the yard");
Str... | It's premature to leap to writing your own. I would start with the naive replace solution, and actually benchmark that. Then I would try a third-party templating solution. THEN I would take a stab at the custom stream version.
Until you get some hard numbers, how can you be sure it's worth the effort to optimize it? | I need a fast key substitution algorithm for java | [
"",
"java",
"algorithm",
"optimization",
"string",
""
] |
I have written some code that works pretty well, but I have a strange bug
Here is an example...
---
## **[PLEASE WATCH MY COMBOBOX BUG VIDEO](http://vimeo.com/3112710)**
---
Like I said, this works well every time datachanged fires - the right index is selected and the displayField is displayed but, everytime after... | It's probably because when you type random data into combo, it may not locate correct fieldValue every time. Then it *stucks* at the last non-existing value.
Try to set ComboBox to any *existing* value (in combo's datastore) before doing new setValue() in your datachanged event handler. Or you can try to use clearValu... | ```
function formatComboBox(value, metaData, record, rowIndex, colIndex, store) {
myStore = Ext.getCmp('myComboBox');
myStore.clearFilter();
var idx = myStore.find('value',value);
return (idx != '-1') ? myStore.getAt(idx).data.label : value;
}
``` | EXTJS Combobox not selecting by valueField after expand | [
"",
"javascript",
"combobox",
"extjs",
""
] |
The Java [`Collections.max`](https://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#max(java.util.Collection)) method takes only a collection of a sortable ([`Comparable`](https://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html)) object. However since the collection is not necessarily sorted, ... | `Collections.max` was introduced in 1.2. `Iterable` was introduced in 1.5.
It's rare to have an `Iterable` that is not a `Collection`. If you do then it's straightforward to implement (be careful to read the spec). If you think it is really important you can submit an RFE in the [Java Bug Database](https://bugs.java.c... | While Guava is not Java's standard library, it's close enough...
[`E com.google.common.collect.Ordering#max(Iterable<E> iterable)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Ordering.html#max%28java.lang.Iterable%29)
e.g. `T max = Ordering.natural().max(myIterable);`
As to why ... | Collections.max function for Iterable<Integer> in Java | [
"",
"java",
"collections",
"max",
"standard-library",
""
] |
As someone new to GUI development in Python (with pyGTK), I've just started learning about threading. To test out my skills, I've written a simple little GTK interface with a start/stop button. The goal is that when it is clicked, a thread starts that quickly increments a number in the text box, while keeping the GUI r... | Threading with PyGTK is bit tricky if you want to do it right. Basically, you should not update GUI from within any other thread than main thread (common limitation in GUI libs). Usually this is done in PyGTK using mechanism of queued messages (for communication between workers and GUI) which are read periodically usin... | Generally it's better to avoid threads when you can. It's very difficult to write a threaded application correctly, and even more difficult to know you got it right. Since you're writing a GUI application, it's easier for you to visualize how to do so, since you already have to write your application within an asynchro... | Beginner-level Python threading problems | [
"",
"python",
"multithreading",
"pygtk",
""
] |
I have a long sequence of hex digits in a string, such as
> 000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44
only much longer, several kilobytes. Is there a builtin way to convert this to a bytes object in python 2.6/3? | ```
result = bytes.fromhex(some_hex_string)
``` | Works in Python 2.7 and higher including python3:
```
result = bytearray.fromhex('deadbeef')
```
**Note:** There seems to be a bug with the `bytearray.fromhex()` function in Python 2.6. The python.org documentation states that the function accepts a string as an argument, but when applied, the following error is thro... | How to create python bytes object from long hex string? | [
"",
"python",
"hex",
"byte",
""
] |
Can I pass "this" to a function as a pointer, from within the class constructor, and use it to point at the object's members before the constructor returns?
Is it safe to do this, so long as the accessed members are properly initialized before the function call?
As an example:
```
#include <iostream>
class Stuff
{
... | When you instantiate an object in C++, the code in the constructor is the last thing executed. All other initialization, including superclass initialization, superclass constructor execution, and memory allocation happens beforehand. The code in the constructor is really just to perform additional initialization once t... | You can find a good answer to this [here](https://isocpp.org/wiki/faq/ctors#using-this-in-ctors) (C++ FAQ).
All inherited members and members of the calling class are guaranteed to have been constructed at the start of the constructor's code execution and so can be referenced safely within it.
The main gotcha is that... | Passing "this" to a function from within a constructor? | [
"",
"c++",
"constructor",
"this",
""
] |
I am trying to use the axis-java2wsdl ant task to create a wsdl from one of my java classes, but I cannot get the classpath correct.
I am using Ubuntu's libaxis-java package which installs axis-ant.jar in $ANT\_HOME/lib and axis.jar in /usr/share/java. The interesting parts of my build.xml look like this:
```
<proper... | In general, this works. But you need to check very carefully which classes are where.
**If your task class can be loaded in a classloader higher up in the classloader hierarchy (like CLASSPATH or ANT\_HOME/lib) then your classpathref will simply get ignored**.
Read the [FAQ entry](http://ant.apache.org/faq.html#deleg... | Ant [mechanism](http://ant.apache.org/manual/using.html#external-tasks) for adding libraries is:
* via command line argument -lib
* adding to ${user.home}/.ant/lib
* adding to ${ant.home}/lib
Only. The [manual](http://ant.apache.org/manual) doesn't mention anything about using the *system.library.dir* property. Proba... | Ant cannot find a class needed by an externally defined taskdef | [
"",
"java",
"ant",
"classpath",
"axis",
""
] |
I would like to change the contents of the list of a `JComboBox` (like adding another list in place of and older one). Is there any way I might be able to do that?
Thanks in advance! | If you want to be able to add and remove items from an existing combo box at runtime, the underlying data model for the combo box needs to be a MutableComboBoxModel
Google for that class for interface information and for examples of how to use it.
Note that if you want the user to type in new values, you also need to... | I found this thread and came up with a quick (and probably dirty) solution:
```
oldComboBox.setModel(new JComboBox<>(new_items).getModel());
``` | Changing the Contents of the JComboBox | [
"",
"java",
"swing",
"jcombobox",
""
] |
It's possible to declare variables with the below structure in C++
```
private:
public:
protected:
float bla1;
float bla2;
float bla3;
```
Is there an equivalent in C#? It seems rather tedious having to repeat yourself;
```
protected float bla1;
protected float bla2;
protected float bla3;
``` | No there isn't such a thing. In fact, it's designed to be like that to make code more readable. This applies to both C# and Java. | No. The access is specified on each declaration.
The benefit of this is that a method's location within the source file has no effect on the behaviour. That means you can move methods and properties around (e.g. to cluster related methods together) with impunity. The same isn't *quite* true of fields - it's possible t... | Is there a C# equivalent to access-modifier regions in C++ | [
"",
"c#",
"access-modifiers",
""
] |
I am trying to compare the performance of boost::multi\_array to native dynamically allocated arrays, with the following test program:
```
#include <windows.h>
#define _SCL_SECURE_NO_WARNINGS
#define BOOST_DISABLE_ASSERTS
#include <boost/multi_array.hpp>
int main(int argc, char* argv[])
{
const int X_SIZE = 200;... | Are you building release or debug?
If running in debug mode, the boost array might be really slow because their template magic isn't inlined properly giving lots of overhead in function calls. I'm not sure how multi array is implemented though so this might be totally off :)
Perhaps there is some difference in storag... | On my machine using
```
g++ -O3 -march=native -mtune=native --fast-math -DNDEBUG test.cpp -o test && ./test
```
I get
```
[Boost] Elapsed time: 0.020 seconds
[Native]Elapsed time: 0.020 seconds
```
However changing `const int ITERATIONS` to `5000` I get
```
[Boost] Elapsed time: 0.240 seconds
[Native]Elapsed ti... | Boost::multi_array performance question | [
"",
"c++",
"performance",
"boost",
"boost-multi-array",
""
] |
My current code to the effect of:
```
if( objectPointer != NULL){
delete objectPointer;
}
```
doesn't work because the pointers are getting set to invalid hex numbers by the compiler such as:
* 0xbaadf00d
* 0xdeadbeef
etc....
So what's the best way to check for an invalid pointer before trying to delete the ob... | Always initialize your pointers to NULL (that is, 0). From <http://www.lysator.liu.se/c/c-faq/c-1.html>:
> A null pointer is conceptually different from an uninitialized pointer. A null pointer is known not to point to any object; an uninitialized pointer might point anywhere. | You don't need to check for not-NULL when calling delete. It is explicitly defined to do nothing.
```
delete NULL; // this is allowed
```
Any correct code you are writing would not be affected by these weird values the compiler is putting into your uninitialised or already freed memory. It puts those values there in ... | How do you check for an invalid pointer? | [
"",
"c++",
"pointers",
""
] |
I am taking a beginning C++ class, and would like to convert letters between hex representations and binary. I can manage to print out the hex numbers using:
```
for(char c = 'a'; c <= 'z'; c++){
cout << hex << (int)c;
}
```
But I can't do the same for binary. There is no `std::bin` that I can use to convert the ... | Like so:
```
for(char c = 'a'; c <= 'z'; c++){
std::bitset<sizeof(char) * CHAR_BIT> binary(c); //sizeof() returns bytes, not bits!
std::cout << "Letter: " << c << "\t";
std::cout << "Hex: " << std::hex << (int)c << "\t";
std::cout << "Binary: " << binary << std::endl;
}
``` | There isn't a binary io manipulator in C++. You need to perform the coversion by hand, probably by using bitshift operators. The actual conversion isn't a difficult task so should be within the capabilities of a beginner at C++ (whereas the fact that it's not included in the standard library may not be :))
Edit: A lot... | How can I convert hexadecimal numbers to binary in C++? | [
"",
"c++",
"binary",
"hex",
""
] |
Why can't enum's constructor access static fields and methods? This is perfectly valid with a class, but is not allowed with an enum.
What I'm trying to do is store my enum instances in a static Map. Consider this example code which allows lookup by abbreivation:
```
public enum Day {
Sunday("Sun"), Monday("Mon")... | The constructor is called before the static fields have all been initialized, because the static fields (including those representing the enum values) are initialized in textual order, and the enum values always come before the other fields. Note that in your class example you haven't shown where ABBREV\_MAP is initial... | Quote from [JLS, section "Enum Body Declarations"](https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9.2):
> Without this rule, apparently reasonable code would fail at run time
> due to the initialization circularity inherent in enum types. (A
> circularity exists in any class with a "self-typed" sta... | Why can't enum's constructor access static fields? | [
"",
"java",
"enums",
""
] |
Ok so I have this regex that I created and it works fine in RegexBuddy but not when I load it into php. Below is an example of it.
Using RegexBuddy I can get it to works with this:
```
\[code\](.*)\[/code\]
```
And checking the dot matches newline, I added the case insensitive, but it works that way as well.
Here i... | You're including the forward slash in the middle of your pattern (/code). Either escape it or delimit your pattern with something else (I prefer !). | When transferring your regular expression from RegexBuddy to PHP, either generate a source code snippet on the Use tab, or click the Copy button on the toolbar at the top, and select to copy as a PHP preg string. Then RegexBuddy will automatically add the delimiters and flags that PHP needs, without leaving anything un... | preg_match works in regexbuddy, not in php | [
"",
"php",
"regex",
"pcre",
"regexbuddy",
""
] |
I have threaded code where each thread needs to write to the same file. To prevent concurrency issues, I am using a Lock object.
My question is whether I am using the Lock correctly. If I set the lock from within each thread, is that lock global or only specific to that specific thread?
Basically, should I create a L... | Create the lock outside the method.
```
class Agent(Thread):
mylock = Lock()
def write_result(self):
self.mylock.acquire()
try:
...
finally:
self.mylock.release()
```
or if using python >= 2.5:
```
class Agent(Thread):
mylock = Lock()
def write_result(s... | For your use case one approach could be to write a `file` subclass that locks:
```
class LockedWrite(file):
""" Wrapper class to a file object that locks writes """
def __init__(self, *args, **kwds):
super(LockedWrite, self).__init__(*args, **kwds)
self._lock = Lock()
def write(self, *args... | Multithreaded Resource Access - Where Do I Put My Locks? | [
"",
"python",
"multithreading",
"locking",
""
] |
I'm looking for the equivalent of a [urlencode](http://docs.python.org/library/urllib.html#urllib.quote_plus) for terminal output -- I need to make sure that garbage characters I (may) print from an external source don't end up doing funky things to my terminal, so a prepackaged function to escape special character seq... | ```
$ ./command | cat -v
$ cat --help | grep nonprinting
-v, --show-nonprinting use ^ and M- notation, except for LFD and TAB
```
Here's the same in py3k based on [android/cat.c](http://www.google.com/codesearch/p?hl=en#2wSbThBwwIw/toolbox/cat.c&q=file:%5Cbcat.c&l=-1):
```
#!/usr/bin/env python3
"""Emulate `cat -v... | Unfortunately "terminal output" is a very poorly defined criterion for filtering (see [question 418176](https://stackoverflow.com/questions/418176/why-does-pythons-string-printable-contains-unprintable-characters)). I would suggest simply whitelisting the characters that you want to allow (which would be most of string... | Safe escape function for terminal output | [
"",
"python",
"terminal",
"escaping",
""
] |
I need to get the path to the native (rather than the WOW) program files directory from a 32bit WOW process.
When I pass CSIDL\_PROGRAM\_FILES (or CSIDL\_PROGRAM\_FILESX86) into SHGetSpecialFolderPath it returns the WOW (Program Files (x86)) folder path.
I'd prefer to avoid using an environment variable if possible.
... | I appreciate all the help and, especially, the warnings in this thread. However, I really do need this path and this is how I got it in the end:
(error checking removed for clarity, use at your own risk, etc)
```
WCHAR szNativeProgramFilesFolder[MAX_PATH];
ExpandEnvironmentStrings(L"%ProgramW6432%",
... | Let me quote **Raymond Chen**'s [excellent blogpost](http://blogs.msdn.com/oldnewthing/archive/2008/12/22/9244582.aspx) on the issue:
> On 64-bit Windows, 32-bit programs run
> in an emulation layer. This emulation
> layer simulates the x86 architecture,
> virtualizing the CPU, the file system,
> the registry, the env... | How to get Program Files folder path (not Program Files (x86)) from 32bit WOW process? | [
"",
"c++",
"windows",
"64-bit",
""
] |
I'm looking to implement user login onto my site for the first time. I'm happy to either build my own solution, or implement something open source, however no package has been an obvious choice in my search so far. Equally, I'm fully aware that as an intermediate php programmer at best, I am highly likely to miss somet... | A few good security gotcha's are
* **never** store the an un-encrypted users password in the database
* **never** store the users password or even a hash of the password in session or cookie data.
* If you need to have ensure that the login is secure you have to use https.
I found these article very helpful in buildi... | "You'll put your eye out kid."
Security is hard. I hate to say this, but the odds of you making a simple authorization scheme that is secure are quite slim. There is no easy mode here. So you might want to start by reading through a bunch of authentication code in the various frameworks/cmses, and other places where y... | simple authorisation / login capability in php | [
"",
"php",
"security",
"authentication",
""
] |
If I have a certain week number (eg 51) and a given year (eg 2008), how do I find the date of the first Monday of that same week?
Many thanks | ```
>>> import time
>>> time.asctime(time.strptime('2008 50 1', '%Y %W %w'))
'Mon Dec 15 00:00:00 2008'
```
Assuming the first day of your week is Monday, use `%U` instead of `%W` if the first day of your week is Sunday. See the documentation for [strptime](http://docs.python.org/library/time.html#time.strptime) for d... | PEZ's and Gerald Kaszuba's solutions work under assumption that January 1st will always be in the first week of a given year. This assumption is not correct for ISO calendar, see [Python's docs](http://docs.python.org/library/datetime.html#datetime.date.isocalendar) for reference. For example, in ISO calendar, week 1 o... | In Python, how do I find the date of the first Monday of a given week? | [
"",
"python",
"datetime",
""
] |
When i give wrong number of parameters in a function , i get errors.
How do I handle it?
I gave
```
def fun_name(...):
try:
...
except TypeError:
print 'Wrong no of arg'
```
It is not working.
Help please. | The caller triggers this exception, not the receiver.
If you want the receiving function to explicitly check argument count you'll need to use varargs:
```
def fun_name(*args):
if len(args) != 2:
raise TypeError('Two arguments required')
``` | You need to handle it where you call the function.
```
try:
fun_name(...)
except TypeError:
print "error!"
``` | How to handle the error that occurs on giving wrong number of parameters in a function call in Python? | [
"",
"python",
"function-call",
""
] |
OSGi has a problem with split packages, i.e. same package but hosted in multiple bundles.
Are there any edge cases that split packages might pose problems in plain java (without OSGi) ?
Just curious. | For OSGi packages in different bundles are different, regardless of their name, because each bundle uses its own class loader. It is not a problem but a feature, to ensure encapsulation of bundles.
So in plain Java this is normally not a problem, until you start using some framework that uses class loaders. That is ty... | ## Where split packages come from
*Split packages* (in OSGi) occur when the manifest header `Require-Bundle` is used (as it is, I believe, in Eclipse's manifests). `Require-Bundle` names other bundles which are used to search for classes (if the package isn't `Import`ed). The search happens before the bundles own clas... | Split packages in plain java | [
"",
"java",
"osgi",
"package",
""
] |
I am implementing an HTML form with some checkbox input elements, and I want to have a Select All or DeSelect All button. However, *I do not want to rely on the name* of the input element (like [this example](http://www.plus2net.com/javascript_tutorial/checkbox-checkall.php)) but rather the **type** because I have mult... | This should do it:
```
<script>
function checkUncheck(form, setTo) {
var c = document.getElementById(form).getElementsByTagName('input');
for (var i = 0; i < c.length; i++) {
if (c[i].type == 'checkbox') {
c[i].checked = setTo;
}
}
}
</script>
<form id='myForm'>
<input type='ch... | iterate through the form.elements collection and check .type == "checkbox".
```
var button = getSelectAllButtonInFormSomeHow();
/*all formelements have a reference to the form. And the form has an elements-collection.*/
var elements = button.form.elements;
for(var i = 0; i < elements.length;i++) {
var input = ele... | Using JavaScript to manipulate HTML input (checkbox) elements via type instead of name | [
"",
"javascript",
"html",
""
] |
I wrote an Oracle SQL expression like this:
```
SELECT
...
FROM mc_current_view a
JOIN account_master am USING (account_no)
JOIN account_master am_loan ON (am.account_no = am_loan.parent_account_no)
JOIN ml_client_account mca USING (account_no)
```
When I try to run it, Oracle throws an error in the line with "ON" se... | The error message is actually (surprise!) telling you exactly what the problem is. Once you use the USING clause for a particular column, you cannot use a column qualifier/table alias for that column name in any other part of your query. The only way to resolve this is to not use the USING clause anywhere in your query... | My preference is never to use **USING**; always use **ON**. I like to my SQL to be very explicit and the **USING** clause feels one step removed in my opinion.
In this case, the error is coming about because you have `account_no` in `mc_current_view`, `account_master`, and `ml_client_account` so the actual join can't ... | Mixing "USING" and "ON" in Oracle ANSI join | [
"",
"sql",
"oracle",
"ora-00918",
""
] |
Wouldn't it be nice to just do a keystroke and have eclipse organize all imports in all java classes instead of just the one you are looking at? Is this possible? Is there a keystroke for it? | Select the project in the package explorer and press `Ctrl` + `Shift` + `O` (same keystroke as the single class version). Should work for packages, etc. | You can edit the clean up options on save to make it organize imports. That way all of your imports will always be organized.
In eclipse 3.4 just go into Window - Preferences. In the tree view look under Java -- Editor -- Save Actions.
This is how I keep my imports organized all of the time. | Can you organize imports for an entire project in eclipse with a keystroke? | [
"",
"java",
"eclipse",
"keyboard-shortcuts",
""
] |
Why do PHP regexes have the surrounding delimiters? It seems like it would be more clear if any pattern modifiers were passed in as a parameter to whatever function was being used. | There is no technical reason why it has to be like this.
As noted in a comment, the underlying library does not require that flags be passed as part of the regexp - in fact, the extension has to strip these off and pass them as a separate argument.
It appears as though the original implementer was trying to make it l... | The reason for the delimiter is to put flags after the pattern. Arguably flags could be passed as a separate parameter (Java can do it this way) but that's the way Perl did it originally (and sed/awk/vi before it) so that's how it's done now.
Don't use forward slashes: they're too common. Personally I nearly always us... | PHP regex delimiter, what's the point? | [
"",
"php",
"regex",
""
] |
Maybe there are VB.net and other language that related with .Net framework.
When I install the Visual C++ 2008 ,I have to install the .Net framework 3.5.
However,why people think .Net gets mainly related with C# language? | The easiest way of putting this is to compare it to the C languages. The C language is known as the "scripting language of the Von Neuman machine". It is this most expressive of what happens in the underlying machine code.
C# is basically the scripting language of the .Net framework. The .Net framework was designed wit... | Because people love {curly braces}!
As the [top three most popular programming languages](http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html) are all curly-braced, it is easy for most programmers to understand and code C# quickly.
C# was also built from the ground up to be .NET language. While VB.NET, i... | Why C# get so related with .NET framework? | [
"",
"c#",
".net",
""
] |
I plan on installing Multiple Instances of MS SQL EXPRESS on my Development Server.
I am hoping this will let me get around the [limitations](http://msdn.microsoft.com/en-us/library/cc645993.aspx) of SQL EXPRESS:
* 1 GB of RAM,
* 1 CPU
* Database size max 4 GB
[I understand and wish that I could afford a full licenc... | If you have an MSDN subscription then you can install the Development version and I don't believe that has any restrictions...of course it's for development purposes only.
You can purchase SQL Server Developer Edition from Microsoft at this link...it's $50
<http://store.microsoft.com/microsoft/SQL-Server-2008-Develop... | The answer to your question is yes.
All instances will have their own independent limitations.
Problems that you will face are:
* Obvious performance issue.
* OS will decide which processor they will use, and there is a good chance
that they will all use the same one. You need to try that.
* Servers need to listen... | Limitations of Running Multiple Instances of MS SQL EXPRESS | [
"",
"sql",
"sql-server-express",
""
] |
I will be building a set of applications. One of these apps is unattended application (written in VB6) which will write data it receives from various sources to a local database. All the other applications (will be written in VS 2008/c# 3.0) will read this data for mostly reporting reasons.
I don't want SQL Server/MyS... | [SQLite](http://www.sqlite.org/) might just fit the bill. Make sure you [check out all the available wrappers](http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers) as well. | Have you thought of [FireBird SQL](http://firebirdsql.org/dotnetfirebird/blog/2005/02/embedded-firebird-and-microsoft-sql.html)? | Which local database fits my situation? | [
"",
"c#",
"database",
"vb6",
"embedded-database",
""
] |
When implementing a singleton in C++, is it better for GetInstance() to return a pointer to the singleton object, or a reference? Does it really matter? | I prefer a reference. I use reference instead of a pointer whenever I want to document that:
* It can't be null
* It won't be changed (to point to something else)
* It mustn't be deleted | I think it would be safer to return a reference, but don't forget about "copy protection" of your singleton object. | C++ singleton GetInstance() return | [
"",
"c++",
"reference",
"singleton",
"pointers",
""
] |
I have a C# Application I am creating that stores all data in SQL Server.
Sometimes it's easier for me to make data changes programmatically and sometimes it's easier to have stored procedures and functions in the SQL Server database and call them.
I am rather new to programming and I don't know what the subtle advan... | Well, Stored Procs can be an additional level of abstraction or a set of functions/methods if you look at the database like an object or service. This can be beneficial, since you can hide underlying implementation details and change it when need be without breaking the app (as long as you leave the interface, e.g. the... | Two points that haven't been covered yet:
SProcs can be placed in a schema, and impersonate a different schema. This means that you can lock down the database access and give users permissions ONLY to execute your SProcs, not to select update etc, which is a very nice security bonus.
Secondly, the sproc can be SIGNIF... | C# Application - Should I Use Stored Procedures or ADO.NET with C# Programming Techniques? | [
"",
"c#",
".net",
"sql-server",
"ado.net",
""
] |
I did some timing tests and also read some articles like [this one](http://www.cincomsmalltalk.com/userblogs/buck/blogView?showComments=true&title=Smalltalk+performance+vs.+C%23&entry=3354595110#3354595110) (last comment), and it looks like in Release build, float and double values take the same amount of processing ti... | On x86 processors, at least, `float` and `double` will each be converted to a 10-byte real by the FPU for processing. The FPU doesn't have separate processing units for the different floating-point types it supports.
The age-old advice that `float` is faster than `double` applied 100 years ago when most CPUs didn't ha... | It depends on **32-bit** or **64-bit** system. If you compile to 64-bit, double will be faster. Compiled to 32-bit on 64-bit (machine and OS) made float around 30% faster:
```
public static void doubleTest(int loop)
{
Console.Write("double: ");
for (int i = 0; i < loop; i++)
{
... | Float vs Double Performance | [
"",
"c#",
".net",
"clr",
"performance",
""
] |
We have started using Spring framework in my project. After becoming acquainted with the basic features (IoC) we have started using spring aop and spring security as well.
The problem is that we now have more than 8 different context files and I feel we didn't give enough thought for the organization of those files an... | If you're still reasonably early in the project I'd advice you strongly to look at annotation-driven configuration. After converting to annotations we only have 1 xml file with definitions and it's really quite small, and this is a large project. Annotation driven configuration puts focus on your implementation instead... | Start with applicationContext.xml and separate when there's a lot of beans which have something in common.
To give you some idea of a possible setup, in the application I'm currently working on, here's what I have in server:
* applicationContext.xml
* securityContext.xml
* schedulingContext.xml
* dataSourcecontext.xm... | Spring context files organization and best practices | [
"",
"java",
"spring",
"jakarta-ee",
""
] |
Per the example array at the very bottom, i want to be able to append the depth of each embedded array inside of the array. for example:
```
array (
53 =>
array (
'title' => 'Home',
'path' => '',
'type' => '118',
'pid' => 52,
'hasChildren' => 0,
),
```
Ha... | I assume there is another array( at the top not included in your example code.
Something like this?
```
function array_set_depth($array, $depth = -1)
{
$subdepth = $depth + 1;
if ($depth < 0) {
foreach ($array as $key => $subarray) {
$temp[$key] = array_set_depth(($subarray), $subdepth);
}
}
if (... | A recursive function like this should do it?
```
function setDepth(&$a, $depth)
{
$a['depth']=$depth;
foreach($a as $key=>$value)
{
if (is_array($value))
setDepth($a[$key], $depth+1);
}
}
```
The thing to note is that the array is passed by reference, so that we can modify it. Note... | PHP Arrays, appending depth of array item recursively to an array with the key of 'depth' | [
"",
"php",
"arrays",
"recursion",
"associative-array",
""
] |
I heard lots of reviews on the book Linq in Action, but it does not cover Linq to Entities.
Please provide your feedback on the books you may have read. | Check this, it may help till a good book appear: <http://weblogs.asp.net/zeeshanhirani/archive/2008/12/05/my-christmas-present-to-the-entity-framework-community.aspx> | [LINQ in Action](http://www.manning.com/marguerie/) is a good book for understanding the principles of LINQ, and LINQ-to-SQL in particular.
[C# in Depth](http://manning.com/skeet/) is good for understand how LINQ works at the language level, including query syntax, extension methods and expression trees.
EF... tricki... | Which is the best book out there to learn Linq, including Linq to Entities? | [
"",
"c#",
"linq",
"entity-framework",
"linq-to-entities",
".net-3.5",
""
] |
I have a table with arbitrary columns and rows. This fact is irrelevant though really, all I want to do is develop a function that will turn a row (or multiple rows) into a series of text inputs containing the data in the table (or empty if no data in cell).
I can't find any examples of people explicitly doing this, s... | Iterate over the table cells in the rows, and replace the contents with text inputs:
```
function editRow(row) {
$('td',row).each(function() {
$(this).html('<input type="text" value="' + $(this).html() + '" />');
});
}
```
You need to pass the relevant row/rows into the function obviously. | use <http://code.google.com/p/jquery-inline-editor/>, it does exactly what you need | jQuery - Edit a table row inline | [
"",
"javascript",
"jquery",
"html-table",
"rows",
"inline-editing",
""
] |
I have a page where some event listeners are attached to input boxes and select boxes. Is there a way to find out which event listeners are observing a particular DOM node and for what event?
Events are attached using:
1. [Prototype's](http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework) `Event.observe`;
2. D... | If you just need to inspect what's happening on a page, you might try the [Visual Event](http://www.sprymedia.co.uk/article/Visual+Event) bookmarklet.
**Update**: [Visual Event 2](http://www.sprymedia.co.uk/article/Visual+Event+2) available. | Chrome, Vivaldi and Safari support `getEventListeners(domElement)` in their Developer Tools console.
For majority of the debugging purposes, this could be used.
Below is a very good reference to use it:
[getEventListeners function](https://developer.chrome.com/docs/devtools/console/utilities/#getEventListeners-func... | How to find event listeners on a DOM node in JavaScript or in debugging? | [
"",
"javascript",
"events",
"dom",
""
] |
I would like to use RNGCryptoServiceProvider as my source of random numbers. As it only can output them as an array of byte values how can I convert them to 0 to 1 double value while preserving uniformity of results? | ```
byte[] result = new byte[8];
rng.GetBytes(result);
return (double)BitConverter.ToUInt64(result,0) / ulong.MaxValue;
``` | This is how I would do this.
```
private static readonly System.Security.Cryptography.RNGCryptoServiceProvider _secureRng;
public static double NextSecureDouble()
{
var bytes = new byte[8];
_secureRng.GetBytes(bytes);
var v = BitConverter.ToUInt64(bytes, 0);
// We only use the 53-bits of integer precision avai... | How to get random double value out of random byte array values? | [
"",
"c#",
".net",
"random",
""
] |
Youll need a 64bit machine if you want to see the actuall exception. I've created some dummy classes that repro's the problem.
```
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class InnerType
{
char make;
char model;
UInt16 series;
}
[StructLayout(LayoutKind.Explicit)]
... | The part about overlapping types is misleading here. The problem is that in .Net reference types must always be aligned on pointer size boundaries. Your union works in x86 since the field offset is 4 bytes which is the pointer size for a 32 bit system but fails on x64 since there it must be offset a multiple of 8. The ... | I have also noticed that you are packing your char data type into 1 byte. Char types in .NET are 2 bytes in size. I cannot verify if this is the actual issue, but I would double-check that. | TypeLoadException on x64 but is fine on x86 with structlayouts | [
"",
"c#",
".net",
"x86",
"64-bit",
""
] |
I know how package level protection in java works. I *read* a lot of code (including lots of open source stuff) and no-one seem to be using it. The whole protection level seems slightly faulty to me (I'd have c#'s internal any day of the week).
Are there any legit real-world use-cases that are in common use ?
Edit: A... | There are two good uses for package level visibility (in my experience):
1) Defining "internal" classes in a public API. Commonly you would define your interfaces and core factories as public and the "internal" implementations as package level. Then the public factories can construct the package level implementation c... | Are you talking about package-private protection in Java? That's the protection that is in effect by default for class members. It's useful occasionally if you got classes that interact intimately in a way that requires additional information or methods to be visible.
Say you have a Sink class, and several classes can... | What is the use of package level protection in java? | [
"",
"java",
""
] |
I'm trying to call a stored procedure (on a SQL 2005 server) from C#, .NET 2.0 using `DateTime` as a value to a `SqlParameter`. The SQL type in the stored procedure is 'datetime'.
Executing the sproc from SQL Management Studio works fine. But everytime I call it from C# I get an error about the date format.
When I ru... | How are you setting up the [`SqlParameter`](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter.aspx)? You should set the [`SqlDbType` property](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter.sqldbtype.aspx) to [`SqlDbType.DateTime`](http://msdn.microsoft.com/en-us/lib... | Here is how I add parameters:
```
sprocCommand.Parameters.Add(New SqlParameter("@Date_Of_Birth",Data.SqlDbType.DateTime))
sprocCommand.Parameters("@Date_Of_Birth").Value = DOB
```
I am assuming when you write out DOB there are no quotes.
Are you using a third-party control to get the date? I have had problems with t... | Using DateTime in a SqlParameter for Stored Procedure, format error | [
"",
"c#",
"sql-server",
"datetime",
"stored-procedures",
".net-2.0",
""
] |
Consider [System.Windows.Forms.StatusStrip](https://msdn.microsoft.com/en-us/library/system.windows.forms.statusstrip%28v=vs.110%29.aspx). I have added a StatusStrip to my Windows Forms application, but I am having a few problems.
I would like to have a label anchored at the left and a progressbar anchored on the righ... | Just set the `Spring` property on the label control to `True` and you should be good to go. | What you have to do is set the alignment property of your progressbar to right. Then set the LayoutStyle of the StatusStrip to HorizontalStackWithOverflow.
```
private void InitializeComponent()
{
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabel1 = new Syste... | Using StatusStrip in C# | [
"",
"c#",
"winforms",
"anchor",
"statusstrip",
""
] |
I need some mind reading here, since I am trying to do what I do not completely understand.
There is a 32-bit application (electronic trading application called CQG) which provides a COM API for external access. I have sample programs and scripts which access this API from Excel, .NET (C++, VB and C#) and shell VBScri... | There are a number of things you have to remember with a 64 bit machine. These are some things that have caught me out in the past.
1. Building for Any CPU in [.NET](http://en.wikipedia.org/wiki/.NET_Framework) means
it will run as 64 bit on a 64 bit
machine.
2. Lots of COM components
seem to be 32 bit only (... | The problem is probably DEP.
I had the exact same problem as you, and got some help from tech support at CQG. Data Execution Prevention is turned on by Windows Vista & Windows 7 by default. You can turn it off with in command prompt with admin rights using
```
bcdedit.exe /set {current} nx AlwaysOff
```
Later, if yo... | Using 32-bit COM object from C# or VBS on Vista 64-bit and getting error 80004005 | [
"",
"c#",
".net",
"com",
"64-bit",
"wsh",
""
] |
I'm trying to use protobuf in a C# project, using protobuf-net, and am wondering what is the best way to organise this into a Visual Studio project structure.
When manually using the protogen tool to generate code into C#, life seems easy but it doesn't feel right.
I'd like the .proto file to be considered to be the ... | As an extension of Shaun's code, I am pleased to announce that protobuf-net now has Visual Studio integration by way of a Custom Tool. The msi installer is available from the [project page](http://code.google.com/p/protobuf-net/). More complete information here: [protobuf-net; now with added Orcas](http://marcgravell.b... | Calling a pre-build step but using project variables (e.g. `$(ProjectPath)`) to create absolute filenames without having them actually in your solution would seem a reasonable bet to me.
One thing you might want to consider, based on my past experience of code generators: you might want to write a wrapper for protogen... | Protocol buffers in C# projects using protobuf-net - best practices for code generation | [
"",
"c#",
"visual-studio",
"protocol-buffers",
"protobuf-net",
""
] |
How do we combine [How to request a random row in SQL?](https://stackoverflow.com/questions/19412/how-to-request-a-random-row-in-sql) and [Multiple random values in SQL Server 2005](https://stackoverflow.com/questions/183124/multiple-random-values-in-sql-server-2005) to select N random rows using a single pure-SQL quer... | I don't know about pure ANSI, and it's not simple, but you can check out my answer to a similar question here:
[[Simple Random Samples from a Sql database](https://stackoverflow.com/questions/249301/simple-random-samples-from-a-mysql-database)](https://stackoverflow.com/questions/249301/simple-random-samples-from-a-mys... | The answer to your question is in the second link there:
```
SELECT * FROM table ORDER BY RAND() LIMIT 1
```
Just change the limit, and/or rewrite for SQL Server:
```
SELECT TOP 1 * FROM table ORDER BY newid()
```
Now, this *strictly* answers your question, but you really shouldn't be using this solution. Just try ... | How to select N random rows using pure SQL? | [
"",
"sql",
"random",
""
] |
Just wondering: When I add restrict to a pointer, I tell the compiler that the pointer is not an alias for another pointer. Let's assume I have a function like:
```
// Constructed example
void foo (float* result, const float* a, const float* b, const size_t size)
{
for (size_t i = 0; i < size; ++i)
{
... | Your pointer is const, telling anyone calling your function that you won't touch the data which is pointed at through that variable. Unfortunately, the compiler still won't know if result is an alias of the const pointers. You can always use a non-const pointer as a const-pointer. For example, a lot of functions take a... | Yes, you need restrict. **Pointer-to-const doesn't mean that nothing can change the data, only that you can't change it through that pointer**.
`const` is mostly just a mechanism to ask the compiler to help you keep track of which stuff you want functions to be allowed to modify. **`const` is not a promise to the comp... | Does restrict help in C if a pointer is already marked const? | [
"",
"c++",
"c",
"optimization",
"restrict-qualifier",
""
] |
I am parsing a XML file in Java using the W3C DOM.
I am stuck at a specific problem, I can't figure out how to get the whole inner XML of a node.
The node looks like that:
```
<td><b>this</b> is a <b>test</b></td>
```
What function do I have to use to get that:
```
"<b>this</b> is a <b>test</b>"
``` | You have to use the transform/xslt API using your <b> node as the node to be transformed and put the result into a new StreamResult(new StringWriter());
. See [how-to-pretty-print-xml-from-java](https://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java) | I know this was asked long ago but for the next person searching (was me today), this works with JDOM:
```
JDOMXPath xpath = new JDOMXPath("/td");
String innerXml = (new XMLOutputter()).outputString(xpath.selectNodes(document));
```
This passes a list of all child nodes into outputString, which will serialize them ou... | Java/DOM: Get the XML content of a node | [
"",
"java",
"xml",
"dom",
""
] |
My attempts to query MySQL from PHP with a create statement of a store procedure (SP) have all failed. Is this not possible ?
If indeed possible, please give an example. | The MySQL manual has a clear overview about [how to create stored procedures (*13.1.15. `CREATE PROCEDURE` and `CREATE FUNCTION` Syntax*)](http://dev.mysql.com/doc/refman/5.1/en/create-procedure.html).
The next question is: does the account you use to access the MySQL database the propper rights to actually create a p... | Besides of the privileges, what quite probably might cause your problem is, that actually mysql\_query($query) can only work one command per call !
So what you have to do is to split up the commands into sevaral mysql\_query($query) -calls.
What i mean is something like this:
```
$query = "DROP FUNCTION IF EXISTS fn... | How to create a MySQL stored procedure from PHP? | [
"",
"php",
"mysql",
"stored-procedures",
""
] |
I have a file listing in my application and I would like to allow people to right-click on an item and show the Windows Explorer context menu. I'm assuming I would need to use the IContextMenu interface, but I'm not really sure where to start. | There's a very good tutorial (albeit in C++) about hosting an IContextMenu on Raymond Chen's blog in 11 parts (in order):
1. [Initial foray](https://devblogs.microsoft.com/oldnewthing/20040920-00/?p=37823)
2. [Displaying the context menu](https://devblogs.microsoft.com/oldnewthing/20040922-00/?p=37793)
3. [Invocation ... | I have written a library that might be able to help you. You could use the controls provided by the library, or if you don't want to do that, looking through the code may give you an answer.
You can find the library at: <http://gong-shell.sourceforge.net/>
Please let me know if this helped! | How do you show the Windows Explorer context menu from a C# application? | [
"",
"c#",
"contextmenu",
"explorer",
""
] |
So in Ruby there is a trick to specify infinity:
```
1.0/0
=> Infinity
```
I believe in Python you can do something like this
```
float('inf')
```
These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it ... | Dijkstra's Algorithm typically assigns infinity as the initial edge weights in a graph. This doesn't *have* to be "infinity", just some arbitrarily constant but in java I typically use Double.Infinity. I assume ruby could be used similarly. | Off the top of the head, it can be useful as an initial value when searching for a minimum value.
For example:
```
min = float('inf')
for x in somelist:
if x<min:
min=x
```
Which I prefer to setting `min` initially to the first value of `somelist`
Of course, in Python, you should just use the min() built-in... | In what contexts do programming languages make real use of an Infinity value? | [
"",
"python",
"ruby",
"language-agnostic",
"idioms",
"infinity",
""
] |
We've been having an problem recently where other sites are running our e-commerce site inside a frameset where our site (with the offenders affiliate id tacked on) is the only content in a single full width frame. So essentially it looks and feels like our site with their URL at the top. We can cut off their affiliate... | I believe the proper modern method to achieve this is with [The X-Frame-Options response header](https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options).
From the MDN:
> The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a frame or if... | I've heard of solutions to this problem being referred to as a "frame popper script". A quick google comes up with [this thread](http://www.webmasterworld.com/google/3226698.htm). Looks like this is one of the simplest:
```
if (window != top) top.location.href = location.href;
``` | Possible to prevent our website from running inside another domain's frameset or IFrame? | [
"",
"javascript",
"dns",
"frame",
"frameset-iframe",
""
] |
I have an app that, while running, needs to poll its own memory usage. It would be ideal if it could list out the memory usage for each object instantiated. I know this can be achieved by WMI, but I was hoping for something that doesn't rely on WMI. | Two functions you might find useful are:
```
GC.GetTotalMemory();
Process.PagedMemorySize64();
```
My experience has been that GC.GetTotalMemory() is not terribly reliable. It often reports memory usage that is much smaller than the actual memory usage. I've seen it report that I'm using only 8 gigabytes when my ... | ```
Process proc = Process.GetCurrentProcess();
Logger.Info(proc.PeakWorkingSet64/1024 + "kb");
``` | Poll C# app's memory usage at runtime? | [
"",
"c#",
"runtime",
"memory-management",
""
] |
For C++, there are lots of good unit test frameworks out there, but I couldn't find a good one for [functional testing](http://en.wikipedia.org/wiki/Functional_testing). With functional testing, I mean stuff which touches the disk, requires the whole application to be in place etc.
Point in case: What framework helps ... | I wrote one from scratch three times already - twice for testing C++ apps that talked to exchanges using FIX protocol, once for a GUI app.
The problem is, you need to emulate the outside world to do proper system testing. I don't mean "outside of your code" - outside of your application. This involves emulating end us... | Below I list a couple of tools and larger testing applications of which I am aware. If you provide more information on your platform (OS, etc.) we can probably provide better answers.
For part of what you require, Microsoft provides the [Application Verifier](http://technet.microsoft.com/en-us/library/bb457063.aspx):
... | Testing framework for functional/system testing for C/C++? | [
"",
"c++",
"c",
"testing",
"system-testing",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.