Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I develop web applications and in my job so far, I have been waging battles with various browsers whenever some JS or CSS quirks happen. I believe using GWT will help me tremendously from what I understand from [this](http://code.google.com/webtoolkit/) description:
> Writing web apps today is a tedious
> and error-pr... | You don't say if you've got any background with Java. If you don't, then, well, I can't speak to what your learning curve may be.
However...as someone who's been working with Java for ~9 years, and much of that time spent with Swing, I've found GWT very easy to learn.
The widgets are different from Swing, so that tak... | If you're coming from Java background or are used to something like Swing I think it makes sense to use GWT as it keeps you coding in a familiar environment with familiar concepts. The other good reason to use GWT is if your team consists of mostly Java developers and very few web developers. In these cases it should b... | How useful is learning GWT? | [
"",
"java",
"gwt",
""
] |
I have a table of data sorted by date, from which a user can select a set of data by supplying a start and end date. The data itself is non-continuous, in that I don't have data for weekends and public holidays.
I would like to be able to list all the days that I don't have data for in the extracted dataset. Is there ... | You could create a temp list and x it as needed.
(Not actual Java. Sorry, my memory of it is horrible.)
```
dates = [...]; // list you have now;
// build list
unused = [];
for (Date i = startdate; i < enddate; i += day) {
unused.push(i);
}
// remove used dates
for (int j = 0; j < dates.length; j += 1) {
if ... | You should be able to create a filtered iterator that provides this. Perhaps have the method for the iterator accept the start and stop date of your sub-collection. As for the actual implementation of the iterator, I can't think of anything much more elegant than a brute-force run at the whole collection once the start... | How can I list the missing dates from an array of non-continuous dates in Java? | [
"",
"java",
"datetime",
""
] |
I have a Java method which returns an array of doubles. I would then like to store these values in individual variables in the calling function. Is there an elegant way of doing this in Java.
I could write it as this:
```
double[] returnValues = calculateSomeDoubles();
double firstVar = returnValues[0];
double secon... | Basically no, this isn't possible.
You'll have to return an object that contains the values.
```
MyObject myObject = calculateMyObject();
``` | The only way would be using reflection, granted you know upfront how many items method "calculateSomeDouble" will return.
A variation of ***[this](https://stackoverflow.com/questions/271109/iterate-static-int-values-in-java#271127)*** would be needed. But as you see there's more to code.
So the question that raises i... | Set Variable from an Array directly into a List of Variables in Java | [
"",
"java",
"function",
"return",
""
] |
Is there any way to split a long string of HTML after N words? Obviously I could use:
```
' '.join(foo.split(' ')[:n])
```
to get the first n words of a plain text string, but that might split in the middle of an html tag, and won't produce valid html because it won't close the tags that have been opened.
I need to ... | Take a look at the [truncate\_html\_words](http://code.djangoproject.com/browser/django/trunk/django/utils/text.py) function in django.utils.text. Even if you aren't using Django, the code there does exactly what you want. | I've heard that [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) is very good at parsing html. It will probably be able to help you get correct html out. | Split HTML after N words in python | [
"",
"python",
"html",
"plone",
"zope",
""
] |
How can I get the current system status (current CPU, RAM, free disk space, etc.) in Python? Ideally, it would work for both Unix and Windows platforms.
There seems to be a few possible ways of extracting that from my search:
1. Using a library such as [PSI](http://www.psychofx.com/psi/trac/wiki/) (that currently see... | [The psutil library](https://pypi.python.org/pypi/psutil) gives you information about CPU, RAM, etc., on a variety of platforms:
> psutil is a module providing an interface for retrieving information on running processes and system utilization (CPU, memory) in a portable way by using Python, implementing many function... | Use the [psutil library](https://pypi.org/project/psutil/). On Ubuntu 18.04, pip installed 5.5.0 (latest version) as of 1-30-2019. Older versions may behave somewhat differently.
You can check your version of psutil by doing this in Python:
```
from __future__ import print_function # for Python2
import psutil
print(p... | How to get current CPU and RAM usage in Python? | [
"",
"python",
"system",
"cpu",
"status",
"ram",
""
] |
I have a class like this:
```
public class myClass
{
public List<myOtherClass> anewlist = new List<myOtherClass>;
public void addToList(myOtherClass tmp)
{
anewList.Add(tmp);
}
}
```
So I call "addToList" a hundred times, each adding a unique item to the list. I've tested my items to show that before I ... | Given the signature of your addToList method:
```
public void addToList(myOtherClass tmp)
{
anewList.Add(tmp);
}
```
Is is possible that in the consumer of that method, you aren't actually creating a new instance?
You said that you are calling addToList 100 times. Presumably, that is in a loop. At each loop ... | In this case, it would likely be helpful to see how you are validating each item to be sure that the items are unique. If you could show the ToString() method of your class it might help: you might be basing it on something that is actually the same between each of your objects. This might help decide whether you reall... | List.Add seems to be duplicating entries. What's wrong? | [
"",
"c#",
"list",
""
] |
So I've got some scripts I've written which set up a Google map on my page. These scripts are in included in the `<head>` of my page, and use jQuery to build the map with markers generated from a list of addresses on the page.
However, I have some exact co-ordinate data for each address which the javascript requires t... | I would not reccomend using style to hide something, it will show up in browsers without (or with disabled) css suppor and look strange.
You could store it in a javascript variable or add a form with hidden values like this
(inside an unused form to be sure it validates):
```
<form action="#" method="get" id="myHidde... | My first thought was a hidden input with a CSV or similar of the data. Since the data is not really secret, just not for display.
```
<input id="coordinates" type="hidden" value="123.2123.123:123,123,321;....." />
```
Then access it with jquery
```
var myCoordsCSV = $("#coordinates").val();
```
Edit: A below answ... | Best way to include unobtrusive information on a web page | [
"",
"javascript",
"html",
"json",
"google-maps",
""
] |
I have the following code for a UDF but it errors with the message:
> Msg 156, Level 15, State 1, Procedure
> CalendarTable, Line 39 Incorrect
> syntax near the keyword 'OPTION'.
is it because of my WITH statement as I can run the same code fine in a stored procedure?
```
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER O... | No, you can't use the OPTION keyword.
From the documentation: "MAXRECURSION can be used to prevent a poorly formed recursive CTE from entering into an infinite loop. The following example intentionally creates an infinite loop and uses the MAXRECURSION hint to limit the number of recursion levels to two."
If you expl... | From what I can tell, OPTION MAXRECURSION is not allowed in a UDF. There is an item at [connect.microsoft.com](http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=124653) with the issue. | Can you have a WITH statement in a tabular user defined function | [
"",
"sql",
"sql-server-2005",
"t-sql",
""
] |
I have an array of different type objects and I use a BinaryWriter to convert each item to its binary equivalent so I can send the structure over the network.
I currently do something like
```
for ( i=0;i<tmpArrayList.Count;i++)
{
object x=tmpArrayList[i];
if (x.GetType() == typeof(byte))
{
wrt.Write(... | Here is a solution for BinaryWriter that uses reflection.
This basically scans BinaryWriter for methods named Write that takes exactly one parameter, then builds a dictionary of which method handles which type, then for each object to write, finds the right method and calls it on the writer.
Dirty, and you should pro... | No. The cast has to be known at compile-time, but the actual type is only known at execution time.
Note, however, that there's a better way of testing the type calling GetType. Instead of:
```
if (x.GetType() == typeof(byte))
```
Use:
```
if (x is byte)
```
EDIT: To answer the extra questions:
"What are all the t... | Is there a way cast an object back to it original type without specifing every case? | [
"",
"c#",
"casting",
"syslog",
"udpclient",
""
] |
I have a J2EE project in Eclipse 3.2 and at the end of every build I want to automatically create and deploy a WAR file. At the moment I have to do this by hand which is 5 or 6 mouse-cliks and it would be nice to automate it.
I know I can do this with a custom build script using ANT but I am hoping for an Eclipse nati... | If you can implement it as an Ant script, then you can have Eclipse invoke that Ant script on each build automatically (and inside the Eclipse environment). Use Project->Properties->Builders->Add->Ant Builder.
Give that builder you custom Ant script and it will automatically be executed after the "normal" builders of y... | There are only two options:
* Or you right click on project: Run -> Run on server. (Your project needs to be a web project.)
* Or you write that ant script and use eclipse to store you ant run configuration and reuse that config. | How do I automatically export a WAR after Java build in Eclipse? | [
"",
"java",
"eclipse",
"deployment",
"war",
""
] |
I'm using Hibernate 3.1 and Oracle 10 DB. The blob is defined as @Lob @Basic @Column in the Hibernate entity which corresponds to the relevant DB table.
The error -java.sql.SQLException: Closed Connection- seem to appear once in while, not in every attempt to get the blob from the DB.
This seems like a hibernate fetchi... | I've recently implemented a hibernate system on top of a Oracle 11g db that uses blobs. There isn't any real magic to it.
The standard cause of 'Session closed' hibernate errors is (not to point out the obvious) that the session that your entity is attached to really is closed.
Make a point of working out exactly whe... | Is this against an Oracle database?
I've had to resort to user data types in Hibernate to get this to work, but that was using Hibernate 3.0 against an Oracle 9 db.
See <http://www.hibernate.org/56.html> for a long discussion about this topic (including user data types). | "Session closed" error when trying to get a blob from DB using getBinaryStream() | [
"",
"java",
"oracle",
"hibernate",
""
] |
I noticed that the generic `IEnumerator<T>` inherits from IDisposable, but the non-generic interface IEnumerator does not. Why is it designed in this way?
Usually, we use foreach statement to go through a `IEnumerator<T>` instance. The generated code of foreach actually has try-finally block that invokes Dispose() in ... | Basically it was an oversight. In C# 1.0, `foreach` *never* called `Dispose` 1. With C# 1.2 (introduced in VS2003 - there's no 1.1, bizarrely) `foreach` began to check in the `finally` block whether or not the iterator implemented `IDisposable` - they had to do it that way, because retrospectively making `IEnumerator` ... | IEnumerable<T> doesn't inherit IDisposable. IEnumerator<T> does inherit IDisposable however, whereas the non-generic IEnumerator doesn't. Even when you use *foreach* for a non-generic IEnumerable (which returns IEnumerator), the compiler will still generate a check for IDisposable and call Dispose() if the enumerator i... | Why does IEnumerator<T> inherit from IDisposable while the non-generic IEnumerator does not? | [
"",
"c#",
"generics",
"ienumerator",
""
] |
I have an array in PHP which holds a bunch of unix timestamps.
As a simplified example, here is an array of 10 values.
```
$array = [
1510790277,
1586522582,
1572272336,
1650049585,
1591332330,
1698088238,
1646561226,
1639050043,
1652067570,
1548161804,
];
```
I need to produce an array containin... | You could use [asort](https://www.php.net/manual/en/function.asort.php) to sort the array and maintain index and then use [slice](https://www.php.net/manual/en/function.array-slice.php) along with the 4th parameter, again to maintain the index, to grap the top x number of elements you are after, and finally use [array\... | Simon posted the simple and probably good-enough performing method.
The other option, only if you have a really large array, is to scan through the array and keep track of the indexes of the three highest values you see. This is O(n), but (especially since its in interpreted PHP code, not a compiled built-in function)... | Get indexes of 3 largest values in a flat array | [
"",
"php",
"arrays",
"sorting",
"key",
"slice",
""
] |
I'm looking at starting a project in C++ using the Qt 4 framework (a cross-platform GUI is required). I've heard great things about the Boost libraries from friends and online. I've started reading up on both and wanted to ask a cursory question before I got too deep: Are these two development "systems" mutually exclus... | Yes it makes perfect sense. I would generally prefer using the boost/stdlib functions where possible rather than their Qt alternatives.
It makes the code easier to port to the next framework.
It makes is easier for new non-Qt programmers to get upto speed.
Boost has some great functionality and is getting more all... | [This paper](http://www.elpauer.org/stuff/a_deeper_look_at_signals_and_slots.pdf) compares [signal slots](http://doc.qt.io/qt-4.8/signalsandslots.html) mechanism in QT and [Boost::Signal](http://www.boost.org/doc/html/signals.html) very decently. It is a must read for those who are a bit curious of this mix. | Mixing Qt and Boost | [
"",
"c++",
"qt",
"boost",
""
] |
I need some help calculating Pi. I am trying to write a python program that will calculate Pi to X digits. I have tried several from the python mailing list, and it is to slow for my use.
I have read about the [Gauss-Legendre Algorithm](http://en.wikipedia.org/wiki/Gauss-Legendre_algorithm), and I have tried porting it... | 1. You forgot parentheses around `4*t`:
```
pi = (a+b)**2 / (4*t)
```
2. You can use `decimal` to perform calculation with higher precision.
```
#!/usr/bin/env python
from __future__ import with_statement
import decimal
def pi_gauss_legendre():
D = decimal.Decimal
with decimal.l... | ```
pi = (square((a+b)))/4*t
```
should be
```
pi = (square((a+b)))/(4*t)
``` | Gauss-Legendre Algorithm in python | [
"",
"python",
"algorithm",
"pi",
""
] |
Why don't we get compile errors on inline code errors in asp.net mvc views f.eks
```
<h1><%= ViewData.Model.Title.Tostrig() %></h1>
```
The code above will build just fine. Wrong spelling in webform controls will give you an error so I can't see why this isn't supported in asp.net mvc
EDIT:
Luckily there seem to be ... | The ASPX files in both ASP.NET and ASP.NET MVC are not compiled from the Visual Studio IDE. This is often the cause for "false positives" as you have pointed out.
I often add the [aspnet\_compiler](http://msdn.microsoft.com/en-us/library/ms229863(VS.80).aspx) as a post build action to find those errors. You will add s... | Following from Jason's answer, this line should work on most projects:
```
C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_compiler -v / -p "$(ProjectDir)\"
```
Or for .NET 4 projects:
```
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_compiler -v / -p "$(ProjectDir)\"
```
Source - [Compiling aspx temp... | Build does not catch errors in the View in asp.net mvc | [
"",
"c#",
"asp.net",
"asp.net-mvc",
"debugging",
""
] |
I was wondering if it is possible to declare an array (size not known at this time), as a private member of a class and later set the size in the constructor of the class. For example:
```
class Test {
int a[];
public:
Test(int size);
};
Test::Test(int size) {
a[size]; // this is wrong, but what can i do here?
}
``... | No this is not possible. Array declarations in headers must have constant sized value. Otherwise it's impossible for constructs like "sizeof" to function properly. You'll need to declare the array as a pointer type and use new[] in the constructor. Example.
```
class Test {
int *a;
public:
Test(int size) {
... | Short Answer: No (The size of an array is defined at compile time only)
Long Answer:
You can use a vector to achieve the same result:
```
class Test
{
std::vector<int> a;
public:
Test(std::size_t size):
a(size)
{}
};
``` | c++ array declaration in a header | [
"",
"c++",
"arrays",
"dynamic",
"header",
""
] |
I need an OpenSource API in Java, which can encode \*.wav and \*.au formats to MP3 and vice-versa.
I have evaluated Java Sound API and [LameOnJ](http://openinnowhere.sourceforge.net/lameonj), but they do not meet my requirements and are not stable, respectively. Please suggest one that is free and platform independent... | There may not be an adequate answer for you, yet, as the MP3 format requires the authors of decoder/encoders to obtain a license from the Fraunhofer Institute.
I think the the LAME library is distributed from a country that does not respect these IP issues, but it took a considerably amount of legal hackery to get thi... | Is has been some time, but Oracle/Sun has released MP3 support for JMF. This can be downloaded from the following url:
<http://www.oracle.com/technetwork/java/javase/tech/index-jsp-140239.html>
Adding it to the classpath will enable playback via the AudioSystem api. | MP3 Encoding in Java | [
"",
"java",
"api",
"encoding",
"mp3",
""
] |
On my Centos server Python's mimetypes.guess\_type("mobile.3gp") returns (None, None), instead of ('video/3gpp', None).
Where does Python get the list of mimetypes from, and is it possible to add a missing type to the list? | On my system (Debian lenny) its in /usr/lib/python2.5/mimetypes.py
in the list `knownfiles` you can supply your own files for the `init()` function. | The mimetypes module uses mime.types files as they are common on Linux/Unix systems. If you look in mimetypes.knownfiles you will find a list of files that Python tries to access to load the data. You can also specify your own file to add new types by adding it to that list. | Adding a mimetype in python | [
"",
"python",
"mime-types",
""
] |
I have written a game that uses GLUT, OpenGL and FMOD. The problem is that the binary won't run, unless Visual Studio 2008 is installed on the computer.
Why is this? | Most likely you're linking with DLL versions of the C/C++ runtime. Go to project properties -> C++ -> Code Generation, and set Runtime Library to *not* be one of "DLL" kinds.
Alternatively, you can link to DLL runtimes, but then you have to redistribute the runtime with your application.
MSDN has more information on ... | You mean why is [Microsoft Visual C++ 2008 Redistributable Package (x86)](http://www.microsoft.com/downloads/details.aspx?FamilyID=9b2da534-3e03-4391-8a4d-074b9f2bc1bf&displaylang=en) needed?
> This package installs runtime
> components of C Runtime (CRT),
> Standard C++, ATL, MFC, OpenMP and
> MSDIA libraries. For li... | Why won't my program run unless Visual Studio 2008 is installed? | [
"",
"c++",
"visual-studio-2008",
"redistributable",
""
] |
I have an interface that defines some methods I would like certain classes to implement.
```
public interface IMyInterface
{
MethodA;
MethodB;
}
```
Additionally I would like all classes implementing this interface to be serializable. If I change the interface definition to implement ISerializable as below...... | Thanks for the replies. It would be nice to be able to force classes derived from an interface to implement serialization without this then forcing them to custom serialize but it doesn't seem to be possible. | **There does not seem to be a way to do this**, but I wish there were.
Note two things though:
* The **Serializable attribute can not be inherited from a base class**,
even if the base class is marked as
abstract.
* You **don't technically need the
Serializable attribute, IF** you are
**using an XmlSerializer... | Enforcing serializable from an interface without forcing classes to custom serialize in C# | [
"",
"c#",
"interface",
"serialization",
""
] |
I have a c# struct where I need to forbid calling the no args constructor on it.
```
MyStruct a;
/// init a by members // OK
MyStruct b = MyStruct.Fact(args); // OK, inits by memebers
MyStruct s = new MyStruct(); // can't have that
```
I'm doing this mostly to force explicet values for all members as there are no ... | You can't. All structs have a public parameterless constructor by definition in C#. (In the CLR almost none of them do, but they can always act as if they have.) See [this question](https://stackoverflow.com/questions/333829) for why you can't define your own parameterless constructors on structs (in C#, anyway).
In f... | You can't.
All values in a struct must be initialized at construction time, and there's no way to do that outside the constructor.
What exactly are you trying to accomplish by doing that? Structs are value types, so you'll get a "new" struct for most operations. It will be very difficult to enforce the sorts of const... | How do I enforce using a factory on a struct in C# | [
"",
"c#",
"struct",
"factory",
""
] |
My company needs a PDF viewer with Java API with the additional requirement on being able to use FDF form data.
The only one i found was [JPedal](http://www.jpedal.org/index.php) which promises to feature everything we need, but it costs a bunch. So what are my options? Is there another tool to do it?
edit:
I found ... | Have a look at the Foxit SDK. <http://www.foxitsoftware.com/> The cost seems at bit less and i'm sure you'll get much more.
Maybe Open Office has something in its belt for you?
I also just found those:
<http://www.crionics.com/>
<http://www.qoppa.com/>
<http://multivalent.sourceforge.net/> | Try the Big Faceless' Java Viewer: <http://big.faceless.org/products/pdfviewer/> | Java PDF viewer with FDF | [
"",
"java",
"pdf",
""
] |
If I have an mssql varchar[1024] that is always empty in a table, how much actual bytes will be wasted in the db file on disk per row?
Please let me know the size for both:
1. NULLs allowed storing ''
* NULLs not allowed storing ''
* NULLs allowed storing NULL
Since the max varchar size is > 2^1 and < 2^3 I wo... | I believe that a varchar uses only the minimum storage required to hold the string.
MSDN and books online seem to confirm this.
However, the sum of stored data (including other fields) cannot exceed a certain length (which I think is 8K). I don't think you've got this problem, as I think it is flagged at creation time.... | In each row that allows nulls, there is a null bitmap object that controls whether a particular column's value is null or not. The size in bytes of this bitmap will be NumberOfNullableColumns/8, rounded up to the next whole byte Additionally, the overhead for the length of a varchar is 2 bytes.
With that in mind:
1. ... | If I have an mssql varchar[1024] that is always empty in a table, how much actual bytes will be wasted? | [
"",
"sql",
"sql-server",
""
] |
I am coding a feature in a program where users can edit documents stored in a database, it saves the document to a temporary folder then uses Process.Start to launch the document into the editing application, let's say Microsoft Word for example.
Then my app needs to wait until they've closed the called process and re... | After further research and coming across a number of posts mentioning the unreliability of WaitForExit and the process' Exited event, I've come up with a completely different solution: I start the process and don't bother waiting for it, just pop up a modal dialog in which the user can click on update to update the tem... | Personally I'm not sure I agree with this approach at all. Displaying a modal form might get you out of this situation, but in most cases when a solution seems hard to find, it's helpful to change the problem you're trying to solve.
**Option 1:**
In this case, I'd recommend a checkout/checkin model. This would allow ... | C# Process.Start, how to prevent re-use of existing application? | [
"",
"c#",
"winforms",
""
] |
Can anyone recommend a decent SFTP library for use with Windows C++ apps? If a cross-platform one is available then all the better, but it's not essential. It's for use with a commercial application, so paying for something isn't an issue.
I am using the superb [Ultimate TCP/IP](http://www.codeproject.com/KB/MFC/Ultim... | Check out [libcurl](http://curl.haxx.se/libcurl/).
> libcurl is a free and easy-to-use client-side URL transfer library, supporting FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS and FILE. libcurl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookie... | [OpenSSH](http://www.openssh.com/) would be a good option. It's cross-platform and comes with a BSD license, so you can use it in your commercial application without having to disclose your source code. | SFTP C++ library? | [
"",
"c++",
"sftp",
""
] |
<http://leepoint.net/notes-java/data/expressions/22compareobjects.html>
> It turns out that defining equals()
> isn't trivial; in fact it's moderately
> hard to get it right, especially in
> the case of subclasses. The best
> treatment of the issues is in
> Horstmann's Core Java Vol 1.
If equals() must always be over... | > If equals() must always be overridden,
> then what is a good approach for not
> being cornered into having to do
> object comparison?
You are mistaken. You should override equals as seldom as possible.
---
All this info comes from [Effective Java, Second Edition](http://java.sun.com/docs/books/effective/) ([Josh B... | I don't think it's true that equals should always be overridden. The rule as I understand it is that overriding equals is only meaningful in cases where you're clear on how to define semantically equivalent objects. In that case, you override hashCode() as well so that you don't have objects that you've defined as equi... | What are the alternatives to comparing the equality of two objects? | [
"",
"java",
"equals",
""
] |
3 fields: FirstName, MiddleName, LastName
Any field can be null, but I don't want extra spaces. Format should be "First Middle Last", "First Last", "Last", etc. | use a UDF:
```
`Select udfConcatName(First, Middle, Last) from foo`
```
That way all your logic for concatenating names is in one place and once you've gotten it written it's short to call. | ```
LTRIM(RTRIM(
LTRIM(RTRIM(ISNULL(FirstName, ''))) + ' ' +
LTRIM(RTRIM(ISNULL(MiddleName, ''))) + ' ' +
LTRIM(ISNULL(LastName, ''))
))
```
NOTE: This won't leave trailing or leading spaces. That's why it's a little bit uglier than other solutions. | What's the shortest TSQL to concatenate a person's name which may contain nulls | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
What do I gain by adding a timestamp column called recordversion to a table in ms-sql? | You can use that column to make sure your users don't overwrite data from another user.
Lets say user A pulls up record 1 and at the same time user B pulls up record 1. User A edits the record and saves it. 5 minutes later, User B edits the record - but doesn't know about user A's changes. When he saves his changes, y... | Nothing that I'm aware of, or that Google seems to find quickly.
You con't get anything inherent by using that name for a column. Sure, you can create a column and do the record versioning as described in the next response, but there's nothing special about the column name. You could call the column anything you want ... | What do I gain by adding a timestamp column called recordversion to a table in ms-sql? | [
"",
"sql",
"sql-server",
"t-sql",
"timestamp",
""
] |
How can I extend a builtin class in python?
I would like to add a method to the str class.
I've done some searching but all I'm finding is older posts, I'm hoping someone knows of something newer. | Just subclass the type
```
>>> class X(str):
... def my_method(self):
... return int(self)
...
>>> s = X("Hi Mom")
>>> s.lower()
'hi mom'
>>> s.my_method()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in my_method
ValueError: invalid literal for int() w... | One way could be to use the "class reopening" concept (natively existing in Ruby) that can be implemented in Python using a class decorator.
An exemple is given in this page:
<http://www.ianbicking.org/blog/2007/08/opening-python-classes.html>
I quote:
I think with class decorators you could do this:
```
@extend(Som... | Extending builtin classes in python | [
"",
"python",
"string",
"monkeypatching",
""
] |
Has anyone attempted this? Is it possible, and if so, what kind of problems will I run into if I try to accomplish it? | Sure, you can easily subclass controllers in Cake.. and then you'd typically utilize their hook function such as 'beforeFilter', 'afterFilter', etc. to add runtime logic to your controllers.. I typically put at least 1 abstract controller between cakes controller and the final controller that you configure in the route... | If you goal is to share logic between controllers:
* add the logic to the AppController to share it with all the controllers in your app.
* make a component and add that to $this->components for the controllers you want to share it.
Adding additional inheritance between controllers should only be concidered as a last... | Controller inheritance in Cake PHP? | [
"",
"php",
"cakephp",
"inheritance",
""
] |
I have a version resource in my resources in a C++ project which contains version number, copyright and build details. Is there an easy way to access this at run-time to populate my *help/about* dialog as I am currently maintaining seperate const values of this information. Ideally, the solution should work for Windows... | This is an edited version of my original answer.
```
bool GetProductAndVersion(CStringA & strProductName, CStringA & strProductVersion)
{
// get the filename of the executable containing the version resource
TCHAR szFilename[MAX_PATH + 1] = {0};
if (GetModuleFileName(NULL, szFilename, MAX_PATH) == 0)
{... | To get a language independent result to Mark's answer change :
```
// replace "040904e4" with the language ID of your resources
!VerQueryValue(&data[0], _T("\\StringFileInfo\\040904e4\\ProductVersion"), &pvProductVersion, &iProductVersionLen))
{
TRACE("Can't obtain ProductName and ProductVersion from resour... | How do I read from a version resource in Visual C++ | [
"",
"c++",
"visual-c++",
"resources",
"version",
""
] |
```
public Int64 ReturnDifferenceA()
{
User[] arrayList;
Int64 firstTicks;
IList<User> userList;
Int64 secondTicks;
System.Diagnostics.Stopwatch watch;
userList = Enumerable
.Range(0, 1000)
.Select(currentItem => new User()).ToList();
arrayList = userList.ToArray();
watch ... | by the way, using IEnumerable.Count() on an Array is hundreds of times slower than Array.Length... Although this doesn't answer the question at all. | You are running in a high level language with a runtime environment that does a lot of caching and performance optimizations, this is common. Sometimes it is called warming up the virtual machine, or warming up the server (when it is a production application).
If something is going to be done repeatedly, then you will... | C#, For Loops, and speed test... Exact same loop faster second time around? | [
"",
"c#",
"arrays",
"foreach",
"for-loop",
"loops",
""
] |
There must be an easy way to do this, but somehow I can wrap my head around it. The best way I can describe what I want is a lambda function for a class. I have a library that expects as an argument an uninstantiated version of a class to work with. It then instantiates the class itself to work on. The problem is that ... | There's no need for lambda at all. lambda is just syntatic sugar to define a function and use it at the same time. Just like any lambda call can be replaced with an explicit def, we can solve your problem by creating a real class that meets your needs and returning it.
```
class Double:
def run(self,x):
re... | Does the library really specify that it wants an "uninitialized version" (i.e. a class reference)?
It looks to me as if the library actually wants an object factory. In that case, it's acceptable to type:
```
lib3 = Library(lambda: Multiply(5))
```
To understand how the lambda works, consider the following:
```
Mul... | Lambda function for classes in python? | [
"",
"python",
"lambda",
""
] |
I'd like to create an XPS document for storing and printing.
What is the easiest way to create an XPS document (for example with a simple grid with some data inside) in my program, and to pass it around? | Nothing easy about it. But it can be done. I've got some (sadly, still buggy) sample code and information on my blog for creating the document in memory.
Here's some code I whipped up for testing that encapsulates everything (it writes a collection of FixedPages to an XPS document in memory). It includes code for seri... | If you are working in .NET (v2 or later), you can very easily generate a valid XPS document from a WPF visual.
For an example, take a look at this blog post of mine:
[<http://nixps.blogspot.com/2008/12/wpf-to-pdf.html>](http://nixps.blogspot.com/2008/12/wpf-to-pdf.html)
In the example I create a WPF visual and conve... | How to create an XPS document? | [
"",
"c#",
".net",
"xps",
"xpsdocument",
""
] |
How do I add a certain number of days to the current date in PHP?
I already got the current date with:
```
$today = date('y:m:d');
```
Just need to add x number of days to it | `php` supports c style date functions. You can add or substract date-periods with English-language style phrases via the `strtotime` function. examples...
```
$Today=date('y:m:d');
// add 3 days to date
$NewDate=Date('y:m:d', strtotime('+3 days'));
// subtract 3 days from date
$NewDate=Date('y:m:d', strtotime('-3 da... | a day is 86400 seconds.
```
$tomorrow = date('y:m:d', time() + 86400);
``` | Increase days to php current Date() | [
"",
"php",
"date",
"days",
""
] |
Say we have normal distribution n(x): mean=0 and \int\_{-a}^{a} n(x) = P.
What is the easiest way to compute standard deviation of such distribution? May be there are standard libraries for python or C, that are suitable for that task? | The standard deviation of a mean-zero gaussian distribution with Pr(-a < X < a) = P is
```
a/(sqrt(2)*inverseErf(P))
```
which is the expression you're looking for, where inverseErf is the inverse of the error function (commonly known as erf).
For C, the Gnu Scientific Library (GSL) is a good resource. However it on... | If X is normal with mean 0 and standard deviation sigma, it must hold
```
P = Prob[ -a <= X <= a ] = Prob[ -a/sigma <= N <= a/sigma ]
= 2 Prob[ 0 <= N <= a/sigma ]
= 2 ( Prob[ N <= a/sigma ] - 1/2 )
```
where N is normal with mean 0 and standard deviation 1. Hence
```
P/2 + 1/2 = Prob[ N <= a/sigma ] = Phi(a/sig... | Standard C or Python libraries to compute standard deviation of normal distribution | [
"",
"python",
"c",
"algorithm",
"math",
"probability",
""
] |
We are scheduling a task programatically. However, the executable to be scheduled could be installed in a path that has spaces. ie c:\program Files\folder\folder\folder program\program.exe
When we provide this path as a parameter to the Tasjk Scheduler it fails to start because it cannot find the executable. It obviou... | It appears that you're using schtasks.exe - it took me longer to figure that out than to find an answer! More details please! :) I found an answer with [a quick google search](http://tinyurl.com/6z6m8j)
Try this code:
```
string args = "/CREATE /RU SYSTEM /SC " + taskSchedule + " /MO " + taskModifier + " /SD " + task... | you could replace program files with progra~1
and folder program to folder~1 (1st 6 letters and ~1) to get it to work till someone posts the right answer | Schedule Task with spaces in the path | [
"",
"c#",
".net",
".net-2.0",
"c#-2.0",
""
] |
```
<document.write("<SCR"+"IPT TYPE='text/javascript' SRC='"+"http"+(window.location.protocol.indexOf('https:')==0?'s':'')+"://"+gDomain+"/"+gDcsId+"/wtid.js"+"'><\/SCR"+"IPT>");
```
I need to escape the string above in order to add the whole thing to a StringBuilder but so far I must be missing something because str... | ```
string x = @"<document.write(""<SCR""+""IPT TYPE=""'text/javascript' SRC='""+""http""+(window.location.protocol.indexOf('https:')==0?'s':'')+""://""+gDomain+""/""+gDcsId+""/wtid.js""+""'><\/SCR""+""IPT>"");";
```
The @ prefix makes escaping simpler. You just have to turn each " into "".
You will find your program... | You should try something like this :
```
@"<document.write(""<SCR""+""IPT TYPE='text/javascript' SRC='""+""http""+(window.location.protocol.indexOf('https:')==0?'s':'')+""://""+gDomain+""/""+gDcsId+""/wtid.js""+""'><\/SCR""+""IPT>"");"
```
When prefixing a string literal with @, the only escaping needed is to double ... | C# StringBuilder - how to escape this string: | [
"",
"c#",
"stringbuilder",
""
] |
I'm trying to change assembly binding (from one version to another) dynamically.
I've tried this code but it doesn't work:
```
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSection assemblyBindingSection = config.Sections["assemblyBinding"];
... | The best way I've found to dynamically bind to a different version of an assembly is to hook the `AppDomain.AssemblyResolve` event. This event is fired whenever the runtime is unable to locate the exact assembly that the application was linked against, and it allows you to provide another assembly, that you load yourse... | I love Eric's answer. It's a lifesaver when trying to use the new buggy NuGet PackageReference model with a Web app. The problem is that you can have msbuild automatically generate the bindings, however, they generate the bindings to Assembly.dll.config, and not to web.config. So this workaround is great.
I've modifie... | how to update assemblyBinding section in config file at runtime? | [
"",
"c#",
".net",
"configuration",
""
] |
What is this "Execute Around" idiom (or similar) I've been hearing about?
Why might I use it, and why might I not want to use it? | Basically it's the pattern where you write a method to do things which are always required, e.g. resource allocation and clean-up, and make the caller pass in "what we want to do with the resource". For example:
```
public interface InputStreamAction
{
void useStream(InputStream stream) throws IOException;
}
// S... | The Execute Around idiom is used when you find yourself having to do something like this:
```
//... chunk of init/preparation code ...
task A
//... chunk of cleanup/finishing code ...
//... chunk of identical init/preparation code ...
task B
//... chunk of identical cleanup/finishing code ...
//... chunk of identica... | What is the "Execute Around" idiom? | [
"",
"java",
"language-agnostic",
"design-patterns",
"idioms",
""
] |
When an item is clicked in the checkedlistbox, it gets highlighted. How can I prevent this highlighting effect?
I can hook into the SelectedIndexChanged event and clear the selection, but the highlighting still happens and you see a blip. In fact, if you hold down the mouse click, never releasing it after you clicked ... | this will do it apart from you still get the dotted line bit.
```
this.checkedListBox1.SelectionMode = System.Windows.Forms.SelectionMode.None;
```
although now you can't click the check boxes... so you'll have to do something like so:
```
private void checkedListBox1_Click(object sender, EventArgs e)
{
... | Use the following:
```
private void checkedListBox1__SelectedIndexChanged(object sender, EventArgs e)
{
checkedListBox1.ClearSelected();
}
``` | How to get rid of checkedlistbox selection highlighting effect? | [
"",
"c#",
"winforms",
"checkedlistbox",
""
] |
I'm trying to open a folder in explorer with a file selected.
The following code produces a file not found exception:
```
System.Diagnostics.Process.Start(
"explorer.exe /select,"
+ listView1.SelectedItems[0].SubItems[1].Text + "\\"
+ listView1.SelectedItems[0].Text);
```
How can I get this command to ... | Use [this method](http://msdn.microsoft.com/en-us/library/h6ak8zt5.aspx):
```
Process.Start(String, String)
```
First argument is an application (explorer.exe), second method argument are arguments of the application you run.
For example:
in CMD:
```
explorer.exe -p
```
in C#:
```
Process.Start("explorer.exe", "... | ```
// suppose that we have a test.txt at E:\
string filePath = @"E:\test.txt";
if (!File.Exists(filePath))
{
return;
}
// combine the arguments together
// it doesn't matter if there is a space after ','
string argument = "/select, \"" + filePath +"\"";
System.Diagnostics.Process.Start("explorer.exe", argument);... | Opening a folder in explorer and selecting a file | [
"",
"c#",
"explorer",
""
] |
I'm adding avatars to a forum engine I'm designing, and I'm debating whether to do something simple (forum image is named .png) and use PHP to check if the file exists before displaying it, or to do something a bit more complicated (but not much) and use a database field to contain the name of the image to show.
I'd m... | As well as what the other posters have said, the result of file\_exists() is automatically cached by PHP to improve performance.
However, if you're already reading user info from the database, you may as well store the information in there. If the user is only allowed one avatar, you could just store a single bit in a... | Since your web server will already be doing a lot of (the equivalent of) file\_exists() operations in the process of showing your web page, one more run by your script probably won't have a measurable impact. The web server will probably do at least:
* one for each subdirectory of the web root (to check existence and ... | Is file_exist() in PHP a very expensive operation? | [
"",
"php",
"performance",
""
] |
Is a string literal in C++ created in static memory and destroyed only when the program exits? | Where it's created is an implementation decision by the compiler writer, really. Most likely, string literals will be stored in read-only segments of memory since they never change.
In the old compiler days, you used to have static data like these literals, and global but changeable data. These were stored in the TEXT... | Yes, string literals are valid for the entire duration of the program, even during the destruction of static objects.
2.13.4/1 in the Standard says
> An ordinary string literal has type "array of n const char" and static storage duration.
The Standard says of 'static storage duration' in 3.7.1/1:
> The storage for ... | Is a string literal in С++ created in static memory? | [
"",
"c++",
"string",
"char",
""
] |
I'm trying to use reflection to get a property from a class. Here is some sample code of what I'm seeing:
```
using System.Reflection;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
PropertyInfo[] tmp2 = typeof(TestClass).GetProperties();
... | Add `BindingFlags.Instance` to the `GetProperty` call.
EDIT: In response to comment...
The following code returns the property.
Note: It's a good idea to actually make your property do something before you try to retrieve it (VS2005) :)
```
using System.Reflection;
namespace ConsoleApplication
{
class Program
... | Try to add the following tag:
```
System.Reflection.BindingFlags.Instance
```
**EDIT:** This works (at least to me)
```
PropertyInfo test = typeof(TestClass).GetProperty("TestProp", BindingFlags.Public | BindingFlags.Instance);
Console.WriteLine(test.Name);
``` | Why does GetProperty fail to find it? | [
"",
"c#",
"reflection",
"properties",
""
] |
I need to change an element's ID using jQuery.
Apparently these don't work:
```
jQuery(this).prev("li").attr("id")="newid"
jQuery(this).prev("li")="newid"
```
I found out that I can make it happen with the following code:
```
jQuery(this).prev("li")show(function() {
this.id="newid";
});
```
But that doesn't se... | Your syntax is incorrect, you should pass the value as the second parameter:
```
jQuery(this).prev("li").attr("id","newId");
``` | A PREFERRED OPTION over `.attr` is to use `.prop` like so:
```
$(this).prev('li').prop('id', 'newId');
```
`.attr` retrieves the element's attribute whereas `.prop` retrieves the property that the attribute references (i.e. what you're *actually* intending to modify) | Changing an element's ID with jQuery | [
"",
"javascript",
"jquery",
""
] |
A few years ago, it was proven that [PRIMES is in P](http://www.cse.iitk.ac.in/~manindra/algebra/primality_v6.pdf). Are there any algorithms implementing [their primality test](http://en.wikipedia.org/wiki/AKS_primality_test) in Python? I wanted to run some benchmarks with a naive generator and see for myself how fast ... | Quick answer: no, the AKS test is not the fastest way to test primality. There are much *much* faster primality tests that either assume the (generalized) Riemann hypothesis and/or are randomized. (E.g. [Miller-Rabin](http://en.wikipedia.org/wiki/Miller-Rabin_primality_test) is fast and simple to implement.) The real b... | I simplified using Binomial Expansion,
```
from math import comb
def AKS(n):
if (n ^ 1 == n + 1): # check if it's even
if n == 2:
return True
return False
for i in range(3,n//2):
if comb(n,i)%n != 0: # check if any coeffici... | AKS Primes algorithm in Python | [
"",
"python",
"algorithm",
"primes",
""
] |
Is there a way to be **sure** that a page is coming from cache on a production server and on the development server as well?
The solution **shouldn't** involve caching middleware because not every project uses them. Though the solution itself might **be** a middleware.
Just checking if the data is stale is not a very... | We do a lot of component caching and not all of them are updated at the same time. So we set host and timestamp values in a universally included context processor. At the top of each template fragment we stick in:
```
<!-- component_name {{host}} {{timestamp}} -->
```
The component\_name just makes it easy to do a Vi... | Peter Rowells suggestion works well, but you don't need a custom template context processor
for timestamps. You can simply use the template tag:
```
<!-- {% now "jS F Y H:i" %} -->
``` | How to test django caching? | [
"",
"python",
"django",
"caching",
"django-cache",
""
] |
It is my understanding that I can test that a method call will occur if I call a higher level method, i.e.:
```
public abstract class SomeClass()
{
public void SomeMehod()
{
SomeOtherMethod();
}
internal abstract void SomeOtherMethod();
}
```
I want to test that if I call `SomeMethod()` t... | You can see if a method in something you have mocked has been called by using Verify, e.g.:
```
static void Main(string[] args)
{
Mock<ITest> mock = new Mock<ITest>();
ClassBeingTested testedClass = new ClassBeingTested();
testedClass.WorkMethod(mock.Object);
mock.Verify(m => m.Method... | No, mock testing assumes you are using certain testable design patterns, one of which is injection. In your case you would be testing `SomeClass.SomeMethod` and `SomeOtherMethod` must be implemented in another entity which needs to be interfaced.
Your `Someclass` constructor would look like `New(ISomeOtherClass)`. The... | Using Moq to determine if a method is called | [
"",
"c#",
".net",
"unit-testing",
"mocking",
"moq",
""
] |
My table has a large number of columns. I have a command to copy some data - think of it as cloning a product - but as the columns may change in the future, I would like to only select everything from the table and only change the value of one column without having to refer to the rest.
Eg instead of:
```
INSERT INTO... | You could do this:
```
create table mytable_copy as select * from mytable;
update mytable_copy set id=new_id;
insert into mytable select * from mytable_copy;
drop table mytable_copy;
``` | I don't think this is doable entirely within SQL without going to the trouble of creating a temp table. Doing it in memory should be much faster. Beware if you go the temporary table route that you must choose a unique name for your table for each function invocation to avoid the race condition where your code runs twi... | How can I copy a record, changing only the id? | [
"",
"sql",
"db2",
""
] |
I'm playing with an embedded Linux device and looking for a way to get my application code to communicate with a web interface. I need to show some status information from the application on the devices web interface and also would like to have a way to inform the application of any user actions like uploaded files etc... | I recently did something very similar using sockets, and it worked really well. I had a Java application that communicates with the device, which listened on a server socket, and the PHP application was the client.
So in your case, the PHP client would initialize the connection, and then the server can reply with the ... | What kind of device is it?
If you work with something like a shared file, how will the device be updated?
How will named pipes run into concurrency problems that sockets will avoid?
In terms of communication from the device to PHP, a file seems perfect. PHP can use something basic like file\_get\_contents(), the dev... | Communication between PHP and application | [
"",
"php",
"linux",
"embedded",
""
] |
A few years ago client Java was unsuitable for web development because a remarkable part of web users did not have Java installed. ( I don't remember exact numbers, more than 10%).
Now I see the Google Analytics stats for a big site and it tells that >98% of users have Java installed.
Is these stats very biased by Ja... | When I wrote my diploma project, I had to choose between Flash and Java Applets. Here are some pros and cons:
Java Applets:
* [plus] you program in Java, which is mature and stable
* [plus] you can use the Java GUI frameworks that pack a lot of punch
* [minus] the first time the user hits the page with the applet, th... | Mmm, Java seems to be better supported than I though, I searched some stats and found between 92 and 96% of browsers support Java (ie. it is enabled enough to detect it! although I guess lot of Java detection algorithms use JavaScript to detect & report - as you point out - but JS support is very good too anyway, even ... | Client Java vs (Adobe) Flash for web applications, what to choose and when | [
"",
"java",
"apache-flex",
"flash",
"client-side",
""
] |
I recently wrote a class for an assignment in which I had to store names in an ArrayList (in java). I initialized the ArrayList as an instance variable `private ArrayList<String> names`. Later when I checked my work against the solution, I noticed that they had initialized their ArrayList in the `run()` method instead.... | In the words of the great Knuth "Premature optimization is the root of all evil".
Just worry that your program functions correctly and that it does not have bugs. This is far more important than an obscure optimization that will be hard to debug later on.
But to answer your question - if you initialize in the class m... | ## Initialization
As a rule of thumb, try to initialize variables when they are declared.
If the value of a variable is intended never to change, make that explicit with use of the `final` keyword. This helps you reason about the correctness of your code, and while I'm not aware of compiler or JVM optimizations that ... | Choosing when to instantiate classes | [
"",
"java",
"variables",
"performance",
""
] |
Here is the scenario. 2 web servers in two separate locations having two mysql databases with identical tables. The data within the tables is also expected to be identical in real time.
Here is the problem. if a user in either location simultaneously enters a new record into identical tables, as illustrated in the two... | There isn't much performance to be gained from replicating your database on two masters. However, there is a nifty bit of failover if you code your application correct.
Master-Master setup is essentially the same as the Slave-Master setup but has both Slaves started and an important change to your config files on each... | MySQL does not support synchronous replication, however, even if it did, you would probably not want to use it (can't take the performance hit of waiting for the other server to sync on every transaction commit).
You will have to consider more appropriate architectural solutions to it - there are third party products ... | Which is the best way to bi-directionally synchronize dynamic data in real time using mysql | [
"",
"php",
"mysql",
"database",
"synchronization",
"data-synchronization",
""
] |
I have created a form to add a user to a database and make user available for login.
Now I have two password fields (the second is for validation of the first). How can I add a validator for this kind of validation to zend\_form?
This is my code for the two password fields:
```
$password = new Zend_Form_Element_... | When I was looking for the same, I found this very well working generic Validator for Identical Fields. I don't find it now so I just post the code...
```
<?php
class Zend_Validate_IdenticalField extends Zend_Validate_Abstract {
const NOT_MATCH = 'notMatch';
const MISSING_FIELD_NAME = 'missingFieldName';
const ... | The current version of Zend\_Validate has this built in - while there are plenty of other answers, it seems that all require passing a value to `Zend_Validate_Identical`. While that may have been needed at one point, you can now pass the name of another element.
From the [`Zend_Validate` section of the reference guide... | Zend_Form: how to check 2 fields are identical | [
"",
"php",
"validation",
"zend-framework",
"zend-form",
""
] |
For the umpteenth time my laptop just shut down in the middle of my game because my power cable had disconnected without me noticing it.
Now I want to write a little C# program that detects when my power cable disconnects and then emits a nice long System beep. What API could I use for that? | This should be trivial to implement using the [SystemInformation.PowerStatus](http://msdn.microsoft.com/en-us/library/system.windows.forms.systeminformation.powerstatus.aspx) property. And even though that lives in Windows.Forms, it should be perfectly usable from a system service.
For a solution that also works on th... | [SystemEvents.PowerModeChanged](http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.powermodechanged.aspx). You will need to use either GetSystemPowerStatus (see link in one of the answers) or SystemInformation.PowerStatus (link is in another answer) in the handler to check what happened. | How to detect when laptop power cable has been disconnected? | [
"",
"c#",
".net",
""
] |
In javascript, is there an equivalent of `String.indexOf(...)` that takes a regular expression instead of a string for the first parameter, while still allowing a second parameter ?
I need to do something like
```
str.indexOf(/[abc]/ , i);
```
and
```
str.lastIndexOf(/[abc]/ , i);
```
While String.search() takes a... | Combining a few of the approaches already mentioned (the indexOf is obviously rather simple), I think these are the functions that will do the trick:
```
function regexIndexOf(string, regex, startpos) {
var indexOf = string.substring(startpos || 0).search(regex);
return (indexOf >= 0) ? (indexOf + (startpos ||... | Instances of the `String` constructor have a [`.search()` method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search) which accepts a RegExp and returns the index of the first match.
To start the search from a particular position (faking the second parameter of `.indexOf()`)... | JavaScript: String.indexOf(...) allowing regular-expressions? | [
"",
"javascript",
"regex",
"indexof",
""
] |
I have a list of data that looks like the following:
```
// timestep,x_position,y_position
0,4,7
0,2,7
0,9,5
0,6,7
1,2,5
1,4,7
1,9,0
1,6,8
```
... and I want to make this look like:
```
0, (4,7), (2,7), (9,5), (6,7)
1, (2,5), (4,7), (9,0), (6.8)
```
My plan was to use a dictionary, where the value of t is the key f... | Let's look at
```
d[t].append(c)
```
What is the value of `d[t]`? Try it.
```
d = {}
t = 0
d[t]
```
What do you get? Oh. There's nothing in `d` that has a key of `t`.
Now try this.
```
d[t] = []
d[t]
```
Ahh. Now there's something in `d` with a key of `t`.
There are several things you can do.
1. Use example 2.... | I think you want to use setdefault. It's a bit weird to use but does exactly what you need.
```
d.setdefault(t, []).append(c)
```
The `.setdefault` method will return the element (in our case, a list) that's bound to the dict's key `t` if that key exists. If it doesn't, it will bind an empty list to the key `t` and r... | Storing and updating lists in Python dictionaries: why does this happen? | [
"",
"python",
"dictionary",
"list",
""
] |
We're having a bit of fun here at work. It all started with one of the guys setting up a Hackintosh and we were wondering whether it was faster than a Windows Box of (nearly) same specs that we have. So we decided to write a little test for it. Just a simple Prime number calculator. It's written in Java and tells us th... | Well I see a couple of quick optimizations that can be done.
First you don't have to try each number up to half of the current number.
Instead you only have try up to the square root of the current number.
And the other optimization was what BP said with a twist:
Instead of
```
int count = 0;
...
for (int i = 2; i <... | That's a bit worse than my sieve did on a 8 Mhz 8088 in turbo pascal in 1986 or so. But that was after optimisations :) | Prime number calculation fun | [
"",
"java",
"primes",
""
] |
Let's say I have a source file with many preprocessor directives. Is it possible to see how it looks after the preprocessor is done with it? | `cl.exe`, the command line interface to Microsoft Visual C++, has three different options for outputting the preprocessed file (hence the inconsistency in the previous responses about Visual C++):
* `/E`: [preprocess to stdout](http://msdn.microsoft.com/en-us/library/3xkfswhy.aspx) (similar to GCC's -E option)
* `/P`:... | Most compilers have an option to just run the preprocessor. *e.g.*, gcc provides -E:
```
-E Stop after the preprocessing stage; do not run the compiler proper.
The output is in the form of preprocessed source code, which is sent
to the standard output.
```
So you can just run:
```
gcc -E foo.c
``... | How do I see a C/C++ source file after preprocessing in Visual Studio? | [
"",
"c++",
"c",
"debugging",
"visual-studio-2005",
"c-preprocessor",
""
] |
I know how they are different syntactically, and that C++ uses new, and C uses malloc. But how do they work, in a high-level explanation?
See [What is the difference between new/delete and malloc/free?](https://stackoverflow.com/questions/240212/what-is-the-difference-between-newdelete-and-mallocfree#240308) | I'm just going to direct you to this answer: [What is the difference between new/delete and malloc/free?](https://stackoverflow.com/questions/240212/what-is-the-difference-between-newdelete-and-mallocfree#240308) . Martin provided an excellent overview. Quick overview on how they *work* (without diving into how you cou... | What `new` does differently form `malloc` is the following:
* It constructs a value in the allocated memory, by calling `operator new`. This behaviour can be adapted by overloading this operator, either for all types, or just for your class.
* It calls handler functions if no memory can be allocated. This gives you th... | How do 'malloc' and 'new' work? How are they different (implementation wise)? | [
"",
"c++",
"c",
""
] |
I'm writing a simple templating layer in PHP but I've got myself a little stuck. Here's how it works at the moment:
Firstly I use `fetch_template` to load the template contents from the database - this works (and I collect all the templates at startup if you're interested).
I use PHP variables in my template code and... | Rather than run through your loop you can use `include($template_name)`.
Or, if you want the content of the output from the template, you can do something like this:
```
$template_name = 'template.php';
// import the contents into this template
ob_start();
include($template_name);
$content = ob_get_clean();
// do s... | I'd pass an associative array with variables to replace, then extract() them.
Then you could also pass $\_GLOBALS to achieve the same result.
```
function output_template($template, $vars) {
extract($vars);
eval('return "' . $template . '";');
}
```
Edit: you might also want to consider string subtitution in... | PHP Templating | [
"",
"php",
"templates",
"variables",
"global-variables",
""
] |
I need to use `FtpWebRequest` to put a file in a FTP directory. Before the upload, I would first like to know if this file exists.
What method or property should I use to check if this file exists? | ```
var request = (FtpWebRequest)WebRequest.Create
("ftp://ftp.domain.com/doesntexist.txt");
request.Credentials = new NetworkCredential("user", "pass");
request.Method = WebRequestMethods.Ftp.GetFileSize;
try
{
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
Ft... | Because
```
request.Method = WebRequestMethods.Ftp.GetFileSize
```
may fails in some case (550: SIZE not allowed in ASCII mode), you can just check Timestamp instead.
```
reqFTP.Credentials = new NetworkCredential(inf.LogOn, inf.Password);
reqFTP.UseBinary = true;
reqFTP.Method = WebRequestMethods.Ftp.GetDateTimesta... | How to check if file exists on FTP before FtpWebRequest | [
"",
"c#",
".net",
"ftp",
"ftpwebrequest",
""
] |
I am working on a small team of web application developers. We edit JSPs in Eclipse on our own machines and then move them over to a shared application server to test the changes. I have an Ant script that will take ALL the JSPs on my machine and move them over to the application server, but will only overwrite JSPs if... | Add a target to your [ant](http://ant.apache.org) build file to copy a single jsp using a command line property definition as @matt b described.
Create a new external tool launch profile and use the "String Substitution Preferences" to pass in the reference to the active file in the editor (`resource_name`).
See Ecli... | How would Ant know what file was "current"? It has no way of knowing.
You *could* pass the name of the file into your Ant script (by taking advantage of the fact that any arguments you pass into Ant with `-D` are automatically parameters in your script)...
> ant -Dfile=myfile.jsp update
and have your script look som... | How to move only the current file with Eclipse and/or Ant? | [
"",
"java",
"eclipse",
"ant",
""
] |
I'm starting to use CUDA at the moment and have to admit that I'm a bit disappointed with the C API. I understand the reasons for choosing C but had the language been based on C++ instead, several aspects would have been a lot simpler, e.g. device memory allocation (via `cudaMalloc`).
My plan was to do this myself, us... | I would go with the placement new approach. Then I would define a class that conforms to the std::allocator<> interface. In theory, you could pass this class as a template parameter into std::vector<> and std::map<> and so forth.
Beware, I have heard that doing such things is fraught with difficulty, but at least you ... | In the meantime there were some further developments (not so much in terms of the CUDA API, but at least in terms of projects attempting an STL-like approach to CUDA data management).
Most notably there is a project from NVIDIA research: [thrust](http://code.google.com/p/thrust) | CUDA: Wrapping device memory allocation in C++ | [
"",
"c++",
"cuda",
"raii",
"placement-new",
""
] |
I would like to generate some JavaScript on the server side in ASP.Net MVC. Is there a view engine that supports this? Ideally I would like to be able to get JavaScript from an url like:
```
http://myapp/controller/action.js
```
I've looked at the MonoRail project, and they seem to have this feature, but it's very la... | I wanted to extend this idea to not only allow Javascript views, but more or less any type of document. To use it, you just put the views for \*.js urls in a subfolder of your controller's view folder:
```
\Views
+-\MyController
+-\js
| +-Index.aspx <- This view will get rendered if you request /MyController/Index... | Based on your edit I'll try with a new answer asumming you need json data for ExtJS. I've just tested it in the app I'm building and it works fine. First you need two routes
```
{controller}/{action}.{format}
{controller}/{action}
```
Now the Controller class has a Json method to serialize whatever object you want a... | Is there an ASP.Net MVC view engine that supports JavaScript views? | [
"",
"javascript",
"asp.net-mvc",
"viewengine",
""
] |
I've got this small question - given a bitmask of weekdays (e.g., `Sunday = 0x01, Monday = 0x02, Tuesday = 0x04`, etc...) and today's day (in a form of `Sunday = 1, Monday = 2, Tuesday = 3`, etc...) - what's the most elegant way to find out the next day from today, that's set in the bitmask? By elegant I mean, is there... | ```
int getNextDay(int days_mask, int today) {
if (!days_mask) return -1; // no days set
days_mask |= days_mask << 7; // duplicate days into next week
mask = 1 << (today % 7); // keep track of the day
while (!(mask & days_mask)) {
mask <<= 1;
++today;
}
return today % 7;
}
```
So that's j... | You don't need any extra variables at all. The simplest idea -- start with "tomorrow", look at successive days until you find a day in the mask -- is also the most elegant to implement. The trick to doing it nicely is to think of the days as Sunday=0, Monday=1 and so on (only inside this function). Then, "today" is act... | An algorithm to get the next weekday set in a bitmask | [
"",
"c++",
"algorithm",
""
] |
I'm messing around with some C code using floats, and I'm getting 1.#INF00, -1.#IND00 and -1.#IND when I try to print floats in the screen. What does those values mean?
I believe that 1.#INF00 means positive infinity, but what about -1.#IND00 and -1.#IND? I also saw sometimes this value: 1.$NaN which is Not a Number, ... | From [IEEE floating-point exceptions in C++](http://www.johndcook.com/IEEE_exceptions_in_cpp.html) :
> This page will answer the following questions.
>
> * My program just printed out 1.#IND or 1.#INF (on Windows) or nan or inf (on Linux). What happened?
> * How can I tell if a number is really a number and not a NaN ... | For anyone wondering about the difference between `-1.#IND00` and `-1.#IND` (which the question specifically asked, and none of the answers address):
**`-1.#IND00`**
This specifically means a non-zero number divided by zero, e.g. `3.14 / 0` ([source](https://stackoverflow.com/a/33057379))
**`-1.#IND`** (a synonym fo... | What do 1.#INF00, -1.#IND00 and -1.#IND mean? | [
"",
"c++",
"c",
""
] |
How can I convert an `std::string` to a `char*` or a `const char*`? | If you just want to pass a [`std::string`](http://en.cppreference.com/w/cpp/string/basic_string) to a function that needs `const char *`, you can use [`.c_str()`](https://en.cppreference.com/w/cpp/string/basic_string/c_str):
```
std::string str;
const char * c = str.c_str();
```
And if you need a non-const `char *`, ... | Given say...
```
std::string x = "hello";
```
## Getting a `char \*` or `const char\*` from a `string`
**How to get a character pointer that's valid while `x` remains in scope and isn't modified further**
**C++11** simplifies things; the following all give access to the same internal string buffer:
```
const char*... | How to convert a std::string to const char* or char* | [
"",
"c++",
"string",
"char",
"stdstring",
""
] |
I have two running processes in Windows, and each process has a pipe to the other.
I want to serialize a complicated class and transmit it from one process to the other. I already have the serialization procedure worked out, and I understand that the pipes are sending binary streams. How should I go about sending my s... | Here is the tutorial for `boost::serialization`. I could imagine it would work fine sending the data over the pipe and deserializing on the other side: <http://www.boost.org/doc/libs/1_37_0/libs/serialization/doc/tutorial.html> | You might want to check out [protocol buffer](http://code.google.com/p/protobuf/). | Simple anonymous pipes - what wrapper model you use? (WinAPI, C++) | [
"",
"c++",
"winapi",
"oop",
"ipc",
"pipe",
""
] |
My question is whether or not Flex's fcsh can be called from within a PHP script. Here is the background:
I have been created a simple process that creates a simple quiz/tutorial by converting a text file into a .mxml file and compiling to a .swf file using the mxmlc compiler. This works well from the command line, bu... | The problem with calling fcsh from within scripts is that it works as an *interactive shell* instead of taking command-line arguments, compiling, and returning an exit status. There are different ways to get around this, which I've listed in [this blog post of mine](http://hasseg.org/blog/?p=194), where I mainly talk a... | There are a few other ways in php to execute an external script. They are exec(), passthru(), system(), and backticks i.e. the key to the left of the 1 key. Each one has a different purpose and return mechanism.
You may have to put the command that executes your executable into a script and call that script via one of... | Calling fcsh from PHP script | [
"",
"php",
"apache-flex",
"fcsh",
""
] |
Is there some way to catch exceptions which are otherwise unhandled (including those thrown outside the catch block)?
I'm not really concerned about all the normal cleanup stuff done with exceptions, just that I can catch it, write it to log/notify the user and exit the program, since the exceptions in these casese ar... | This can be used to catch unexpected exceptions.
```
catch (...)
{
std::cout << "OMG! an unexpected exception has been caught" << std::endl;
}
```
Without a try catch block, I don't think you can catch exceptions, so structure your program so the exception thowing code is under the control of a try/catch. | Check out [`std::set_terminate()`](http://en.cppreference.com/w/cpp/error/set_terminate)
Edit: Here's a full-fledged example with exception matching:
```
#include <iostream>
#include <exception>
#include <stdexcept>
struct FooException: std::runtime_error {
FooException(const std::string& what): std::runtime_err... | Catching all unhandled C++ exceptions? | [
"",
"c++",
"exception",
""
] |
Ok, this is working on windows. My Java app is running and functioning normally
```
javac -classpath .;ojdbc14.jar -g foo.java
java -classpath .;ojdbc14.jar foo
```
However, when I do the same thing on Unix I get this error:
ojdbc14.jar: not found
What am I doing wrong? I know the ";" is telling my shell that ojdb... | Use a colon (":") instead of a semicolon (";").
See [Setting the class path (Solaris and Linux)](http://java.sun.com/javase/6/docs/technotes/tools/solaris/classpath.html) vs [Setting the class path (Windows)](http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html) | The final solution was:
```
javac -classpath .:ojdbc14.jar -g foo.java
java -classpath .:ojdbc14.jar foo
```
Note: Using '.;ojdbc14.jar' removed the initial error message I was getting, but resulted in the following errro:
```
Exception in thread "main" java.lang.NoClassDefFoundError: foo
``` | Compiling and Running java in Unix ( coming from Windows ) | [
"",
"java",
"bash",
"unix",
"sh",
""
] |
When running FindBugs on my project, I got a few instances of the error described above.
Namely, my overriding versions of equals cast the RHS object into the same type as the object in which the overriding version is defined.
However, I'm not sure whether a better design is possible, since AFAIK Java does not allow ... | Typically, when implementing equals you can check to see whether the class of the argument is equal (or compatible) to the implementing class before casting it. Something like this:
```
if (getClass() != obj.getClass())
return false;
MyObj myObj = (MyObj) obj;
```
Doing it this way will prevent the FindBugs warni... | You're probably doing something like this:
```
public class Foo {
// some code
public void equals(Object o) {
Foo other = (Foo) o;
// the real equals code
}
}
```
In this example you are assuming something about the argument of equals(): You are assuming it's of type Foo. This needs not be the case! Yo... | Findbugs warning: Equals method should not assume anything about the type of its argument | [
"",
"java",
"equals",
"findbugs",
""
] |
You may have seen JavaScript sliders before:
<http://dev.jquery.com/view/tags/ui/1.5b2/demos/ui.slider.html>
What I'm envisioning is a circular slider. It would consist of a draggable button at one point on the circle -- and that button can be dragged anywhere along the ring. The value depends on what position the bu... | define a center point c
current mouse point at m
in your mouse drag event handler, you'd have
```
var dx = m.x-c.x;
var dy = m.y-c.y;
var scale = radius/Math.sqrt(dx*dx+dy*dy);
slider.x = dx*scale + c.x;
slider.y = dy*scale + c.y;
```
radius would be some preset value of the slider, | How about this: <http://www.thewebmasterservice.com/dev-blog/curved-rounded-or-circular-sliders-javascript-jquery-ui>
Some explanations and a demo. | jQuery: Creating a circular slider | [
"",
"javascript",
"jquery",
"jquery-ui",
"slider",
"draggable",
""
] |
I'm working on a java program, and I have several vectors defined and filled (from a file) inside a method. I need to return the contents of all the vectors from the method. I have heard you can put them all in one object to return them. Is that possible, and if so, how? If not, do you have any possible solutions for m... | Personnally, I'd scrap that approach completely. It seems like you need a Product class:
```
public class Product {
private String itemName;
private int itemID;
// etc etc
public Product(String itemName, int itemID) {
this.itemName = itemName;
this.itemID = itemID;
// etc etc
... | First of all, use ArrayList instead of Vector. Then use a Map as your return object, with each value of the entry is one of your Lists.
Second of all, a much better approach is to create an object that actually holds each of your fields and return a java.util.List of these objects.
```
public class Item
{
String ... | Vectors in Java, how to return multiple vectors in an object | [
"",
"java",
"object",
"vector",
""
] |
I'm having a difficult time figuring out how to add a .jar/library to a Netbeans project in such a way that I can get it committed to the repository.
The typical way to add a library (per the Netbeans documents I've already gone through) ends up with it just being local to me. Anyone who checks out my project ends up ... | OK, the working solution that I've now moved to is to extract the class files out of the jars and dump them into the Source Packages area. Then it all gets committed to the repository and also avoids having to deal with handling a separate "lib" directory in the deployment phase.
This solution does everything I'm look... | There are a couple ways to fix this.
A. When you define your Library, use a path to a common location. A location that's identical on everyone's machine--such as the location of a JAR installed with a third-party app into Program Files or /usr/local/ works well or a network drive.
Then, when they check-out the code, ... | Getting Netbeans and Subversion to play together nicely with libraries? | [
"",
"java",
"svn",
"netbeans",
""
] |
I'm looking to learn some fundamentals on cartesian geometry or coordinates based game programming. Platform is irrelevant, although I'm most proficient in JavaScript, C, Objective-C. Ultimately being able to create something such as dots or checkers would be ideal. The idea is for me to learn how sprites work and how ... | I think there's a few more steps to accomplishing your objective, which is understanding the basics of game programming. You mentioned understanding sprites and pathing, which are imperative to game programming, but I think that initially you should spend a little time understanding the programming and methodology behi... | O'Reilly has a great tutorial on simple game development using Objective-C and Cocoa on the Mac. [Lines of Action.](http://www.oreillynet.com/pub/a/mac/2006/12/19/building-a-game-engine-with-cocoa.html) | Programming coordinates-based game, like dots or checkers | [
"",
"javascript",
"c",
"geometry",
"gridworld",
""
] |
I'm looking at some open source Java projects to get into Java and notice a lot of them have some sort of 'constants' interface.
For instance, [processing.org](http://www.processing.org) has an interface called [PConstants.java](http://dev.processing.org/source/index.cgi/tags/processing-1.0/core/src/processing/core/PC... | It's generally considered bad practice. The problem is that the constants are part of the public "interface" (for want of a better word) of the implementing class. This means that the implementing class is publishing all of these values to external classes even when they are only required internally. The constants prol... | Instead of implementing a "constants interface", in Java 1.5+, you can use static imports to import the constants/static methods from another class/interface:
```
import static com.kittens.kittenpolisher.KittenConstants.*;
```
This avoids the ugliness of making your classes implement interfaces that have no functiona... | Interfaces with static fields in java for sharing 'constants' | [
"",
"java",
""
] |
Can the alignment of a structure type be found if the alignments of the structure members are known?
Eg. for:
```
struct S
{
a_t a;
b_t b;
c_t c[];
};
```
is the alignment of S = max(alignment\_of(a), alignment\_of(b), alignment\_of(c))?
Searching the internet I found that "for structured types the largest align... | There are two closely related concepts to here:
1. The alignment required by the processor to access a particular object
2. The alignment that the compiler actually uses to place objects in memory
To ensure alignment requirements for structure members, the alignment of a structure must be at least as strict as the al... | I wrote this type trait code to determine the alignment of any type(based on the compiler rules already discussed). You may find it useful:
```
template <class T>
class Traits
{
public:
struct AlignmentFinder
{
char a;
T b;
};
enum {AlignmentOf = sizeof(AlignmentFinder) - sizeof(T)};
... | Determining the alignment of C/C++ structures in relation to its members | [
"",
"c++",
"c",
"alignment",
""
] |
There has been a lot of sentiment to include a `nameof` operator in C#. As an example of how this operator would work, `nameof(Customer.Name)` would return the string `"Name"`.
I have a domain object. And I have to bind it. And I need names of properties as strings then. And I want them to be type-safe.
I remember co... | This code basically does that:
```
class Program
{
static void Main()
{
var propName = Nameof<SampleClass>.Property(e => e.Name);
Console.WriteLine(propName);
}
}
public class Nameof<T>
{
public static string Property<TProp>(Expression<Func<T, TProp>> expression)
{
var bod... | While reshefm and Jon Skeet show the proper way to do this using expressions, it should be worth noting there's a cheaper way to do this for method names:
Wrap a delegate around your method, get the MethodInfo, and you're good to go. Here's an example:
```
private void FuncPoo()
{
}
...
// Get the name of the funct... | Workaround for lack of 'nameof' operator in C# for type-safe databinding? | [
"",
"c#",
".net",
"data-binding",
".net-3.5",
".net-2.0",
""
] |
I am working on a C++ app which internally has some controller objects that are created and destroyed regularly (using new). It is necessary that these controllers register themselves with another object (let's call it controllerSupervisor), and unregister themselves when they are destructed.
The problem I am now faci... | You could use the Observer pattern. A Controller communicates to it's supervisor that it's being destroyed. And the Supervisor communicates the same to it's child upon destruction.
Take a look at <http://en.wikipedia.org/wiki/Observer_pattern> | The order of destruction of automatic variables (that include "normal" local variables that you use in functions) is in the reverse order of their creation. So place the controllerSupervisor at the top.
Order of destruction of globals is also in the reverse of their creation, which in turn depends on the order in whic... | Forcing something to be destructed last in C++ | [
"",
"c++",
"destructor",
""
] |
I have a deceptively simple scenario, and I want a simple solution, but it's not obvious which is "most correct" or "most Java".
Let's say I have a small authenticate(Client client) method in some class. The authentication could fail for a number of reasons, and I want to return a simple boolean for control flow, but ... | Returning a small object with both the boolean flag and the String inside is probably the most OO-like way of doing it, although I agree that it seems overkill for a simple case like this.
Another alternative is to always return a String, and have null (or an empty String - you choose which) indicate success. As long ... | You could use exceptions....
```
try {
AuthenticateMethod();
} catch (AuthenticateError ae) {
// Display ae.getMessage() to user..
System.out.println(ae.getMessage());
//ae.printStackTrace();
}
```
and then if an error occurs in your AuthenticateMethod you send a new AuthenticateError (ex... | Best way to return status flag and message from a method in Java | [
"",
"java",
"exception",
"return-value",
""
] |
At work we recently upgraded from Microsoft SQL Server 7 to SQL 2005. The database engine is a lot more advanced, but the management studio is pretty awful in a number of ways. Most of our developers decided they preferred to stick with the old Query Analyzer tool, even though it had a lot of limitations.
In my spare ... | While I would love something better, it would have to be significantly better and free. SMS is definetly a hog but I've gotten used to it. What I miss the most is Query Analyzer. I don't mind using SSMS to manage the server but having a fast lightweight, editor for SQL queries would be awsome...
Did I mention free? No... | Ha, I came from exactly the same standpoint, so I made a tool, code completion and all, plus there's a free edition available. It's at <http://www.atlantis-interactive.co.uk> - it's basically for people who miss QA. Your tool looks nice, good job. | Would you consider using an alternative to MS SQL Server Management Studio? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"query-analyzer",
""
] |
MySQL ResultSets are by default retrieved completely from the server before any work can be done. In cases of huge result sets this becomes unusable. I would like instead to actually retrieve the rows one by one from the server.
In Java, following the instructions [here](http://dev.mysql.com/doc/refman/5.1/en/connecto... | I think you have to connect passing `cursorclass = MySQLdb.cursors.SSCursor`:
```
MySQLdb.connect(user="user",
passwd="password",
db="mydb",
cursorclass = MySQLdb.cursors.SSCursor
)
```
The default cursor fetches all the data at once, even if you do... | The limit/offset solution runs in quadratic time because mysql has to rescan the rows to find the offset. As you suspected, the default cursor stores the entire result set on the client, which may consume a lot of memory.
Instead you can use a server side cursor, which keeps the query running and fetches results as ne... | How to get a row-by-row MySQL ResultSet in python | [
"",
"python",
"mysql",
""
] |
Similar to [this question](https://stackoverflow.com/questions/85978/query-a-tables-foreign-key-relationships) but for MySQL....
How can I programmatically determine foreign key references in MySQL (assuming InnoDB)? I can almost get them with:
```
SHOW TABLE STATUS WHERE Name = 'MyTableName';
```
...but alas, the c... | There are two tables you can query to get this information: [`INFORMATION_SCHEMA.TABLE_CONSTRAINTS`](http://dev.mysql.com/doc/refman/5.1/en/table-constraints-table.html) and [`INFORMATION_SCHEMA.KEY_COLUMN_USAGE`](http://dev.mysql.com/doc/refman/5.1/en/key-column-usage-table.html).
Here's a query from the comments on ... | Here you have a little improvement over the @bill solution:
```
SELECT CONSTRAINT_SCHEMA AS db,
CONCAT (
TABLE_NAME,
'.',
COLUMN_NAME,
' -> ',
REFERENCED_TABLE_NAME,
'.',
REFERENCED_COLUMN_NAME
) AS relationship
FROM INFORMATIO... | MySQL: How to determine foreign key relationships programmatically? | [
"",
"sql",
"mysql",
"c",
"foreign-keys",
""
] |
How do I append an object (such as a string or number) to an array in JavaScript? | Use the [`Array.prototype.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) method to append values to the end of an array:
```
// initialize array
var arr = [
"Hi",
"Hello",
"Bonjour"
];
// append new value to the array
arr.push("Hola");
console.log(arr);
```
... | If you're only appending a single variable, then `push()` works just fine. If you need to append another array, use `concat()`:
```
var ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];
var ar3 = ar1.concat(ar2);
alert(ar1);
alert(ar2);
alert(ar3);
```
The concat does not affect `ar1` and `ar2` unless reassigned, for example:
... | How to append something to an array? | [
"",
"javascript",
"arrays",
"append",
""
] |
I wrote a `while loop` in a function, but don't know how to stop it. When it doesn't meet its final condition, the loop just go for ever. How can I stop it?
```
def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
... | just indent your code correctly:
```
def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
return period
if period>12: #i w... | ```
def determine_period(universe_array):
period=0
tmp=universe_array
while period<12:
tmp=apply_rules(tmp)#aplly_rules is a another function
if numpy.array_equal(tmp,universe_array) is True:
break
period+=1
return period
``` | How can I stop a While loop? | [
"",
"python",
"while-loop",
""
] |
I think I've declared a Vector with an object correctly. But, I don't know how to access it's members when looping with Iterator.
In my code, the line --->> cout << " " << \*Iter;
How do I print the contents of the members? Like \*Iter.m\_PackLine ???
Not sure if I used the correct terminology, but appreciate the he... | ```
cout << " " << *Iter;
```
will only work if `CFileInfo` has an overloaded `operator<<` that can output your struct. You can output individual members of the struct instead like this:
```
cout << " " << Iter->m_PackLine;
```
Alternatively, the following is equivalent to that:
```
cout << " " << (*Iter).m_PackLin... | Use (\*iter).member or iter->member.
You can also use temporaries:
```
CFileInfo &fileInfo = *iter;
cout << " " << fileInfo.myMember;
```
Also, for what you're doing, you'd probably want a const\_iterator instead of an (mutable) iterator.
In addition, std::vector is a template accepting a typename and an allocator,... | C++ STL Vector Iterator accessing members of an Object | [
"",
"c++",
""
] |
There's an existing function that ends in the following, where `d` is a dictionary:
```
return d.iteritems()
```
that returns an unsorted iterator for a given dictionary. I would like to return an iterator that goes through the items sorted *by key*. How do I do that? | Haven't tested this very extensively, but works in Python 2.5.2.
```
>>> d = {"x":2, "h":15, "a":2222}
>>> it = iter(sorted(d.iteritems()))
>>> it.next()
('a', 2222)
>>> it.next()
('h', 15)
>>> it.next()
('x', 2)
>>>
```
If you are used to doing `for key, value in d.iteritems(): ...` instead of iterators, this will s... | Use the [`sorted()`](http://pydoc.org/2.5.1/__builtin__.html#-sorted) function:
```
return sorted(dict.iteritems())
```
If you want an actual iterator over the sorted results, since `sorted()` returns a list, use:
```
return iter(sorted(dict.iteritems()))
``` | In Python, how do I iterate over a dictionary in sorted key order? | [
"",
"python",
"sorting",
"dictionary",
""
] |
I'm currently working with a specialized, interpreted, programming language implemented in Java. As a very small part of the language, I'd like to add the ability to make calls into Java. Before I dive into all of the nitty-gritty of reflection, I was wondering if anyone knew of a general library for doing the "back-en... | Just a comment to your own answer; actually beanutils has support for getting "a close match" given a set of parameters. See [getMatchingAccessibleMethod()](http://commons.apache.org/beanutils/v1.8.0/apidocs/org/apache/commons/beanutils/MethodUtils.html#getMatchingAccessibleMethod(java.lang.Class,%20java.lang.String,%2... | Try the [FEST Reflection](https://github.com/alexruiz/fest-reflect) module. It's a fluent way to do Java reflection. For example:
```
String name = method("get").withReturnType(String.class)
.withParameterTypes(int.class)
.in(names)
.invoke(8)... | Is there a general "back-end" library for Java reflection | [
"",
"java",
"reflection",
"dynamic",
"invoke",
""
] |
I have four tables containing exactly the same columns, and want to create a view over all four so I can query them together.
Is this possible?
(for tedious reasons I cannot/am not permitted to combine them, which would make this irrelevant!) | Assuming that in addition to having the same column names, columns of the same contain the same data, you want to create a view that is the union of all those tables.
Something like the following should work, but my SQL is rusty:
```
(CREATE VIEW view_name AS
(SELECT * FROM table1
UNION
SELECT * FROM table2
UNION
SEL... | It may be worth noting that you might need to use "union all" to preserve unique rows which may exist in more than one of the tables. A standard union will remove duplicates. | View over multiple tables containing same columns | [
"",
"sql",
"database",
"union",
""
] |
I don't think that this is specific to a language or framework, but I am using xUnit.net and C#.
I have a function that returns a random date in a certain range. I pass in a date, and the returning date is always in range of 1 to 40 years before the given date.
Now I just wonder if there is a good way to unit test th... | In addition to testing that the function returns a date in the desired range, you want to ensure that the result is well-distributed. The test you describe would pass a function that simply returned the date you sent in!
So in addition to calling the function multiple times and testing that the result stays in the des... | Mock or fake out the random number generator
Do something like this... I didn't compile it so there might be a few syntax errors.
```
public interface IRandomGenerator
{
double Generate(double max);
}
public class SomethingThatUsesRandom
{
private readonly IRandomGenerator _generator;
private class Defa... | Unit Testing with functions that return random results | [
"",
"c#",
".net",
"unit-testing",
"xunit.net",
""
] |
How would I accomplish displaying a line as the one below in a console window by writing it into a variable during design time then just calling Console.WriteLine(sDescription) to display it?
```
Options:
-t Description of -t argument.
-b Description of -b argument.
``... | If I understand your question right, what you need is the @ sign in front of your string. This will make the compiler take in your string literally (including newlines etc)
In your case I would write the following:
```
String sDescription =
@"Options:
-t Description of -t argument.";
```
So far for your... | ```
Console.Write("Options:\n\tSomething\t\tElse");
```
produces
```
Options:
Something Else
```
\n for next line, \t for tab, for more professional layouts try the field-width setting with format specifiers.
<http://msdn.microsoft.com/en-us/library/txafckwd.aspx> | C#: How do you go upon constructing a multi-lined string during design time? | [
"",
"c#",
""
] |
Is it possible to overload the null-coalescing operator for a class in C#?
Say for example I want to return a default value if an instance is null and return the instance if it's not. The code would look like something like this:
```
return instance ?? new MyClass("Default");
```
But what if I would like to use t... | Good question! It's not listed one way or another in the [list of overloadable and non-overloadable operators](http://msdn.microsoft.com/en-us/library/8edha89s.aspx) and nothing's mentioned on [the operator's page](http://msdn.microsoft.com/en-us/library/ms173224.aspx).
So I tried the following:
```
public class Test... | According to the [ECMA-334](http://www.ecma-international.org/publications/standards/Ecma-334.htm) standard, it is not possible to overload the ?? operator.
Similarly, you cannot overload the following operators:
* =
* &&
* ||
* ?:
* ?.
* checked
* unchecked
* new
* typeof
* as
* is | Possible to overload null-coalescing operator? | [
"",
"c#",
".net",
"operator-overloading",
"null-coalescing-operator",
""
] |
Is this defined by the language? Is there a defined maximum? Is it different in different browsers? | JavaScript has two number types: [`Number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) and [`BigInt`](https://developer.mozilla.org/en-US/docs/Glossary/BigInt).
The most frequently-used number type, `Number`, is a 64-bit floating point [IEEE 754](https://en.wikipedia.org/w... | **>= ES6:**
```
Number.MIN_SAFE_INTEGER;
Number.MAX_SAFE_INTEGER;
```
**<= ES5**
From [the reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE):
```
Number.MAX_VALUE;
Number.MIN_VALUE;
```
```
console.log('MIN_VALUE', Number.MIN_VALUE);
console.log('MAX_VALU... | What is JavaScript's highest integer value that a number can go to without losing precision? | [
"",
"javascript",
"math",
"browser",
"cross-browser",
""
] |
In my program I have one array with 25 double values 0.04
When I try to sum these values in a loop I get following results:
```
0.0 + 0.04 = 0.04
0.04 + 0.04 = 0.08
0.08 + 0.04 = 0.12
0.12 + 0.04 = 0.16
0.16 + 0.04 = 0.2
0.2 + 0.04 = 0.24000000000000002
0.24000000000000002 + 0.04 = 0.28
0.28 + 0.04 = 0.32
0.32 + 0.04 ... | The most common storage for floating-point values in programming languages - [IEEE singles and doubles](http://en.wikipedia.org/wiki/IEEE_754) - does not have exact representations for most decimal fractions.
The reason is that they store values in binary floating-point format, rather than decimal floating-point forma... | See also "[What Every Computer Scientist Should Know About Floating Point](http://docs.sun.com/source/806-3568/ncg_goldberg.html)" | Strange floating-point behaviour in a Java program | [
"",
"java",
"math",
""
] |
I've used boost serialization but this doesn't appear to allow me to generate xml that conforms to a particular schema -- it seems it's purpose was to just to persist a class's state.
Platform: linux
What do you guys use to generate NOT parse xml?
So far I'm going down Foredecker's route of just generating it myself... | Some may declare me an XML heretic - but one effective way is to just generate it with your favorite string output tools (print, output streams, etc) - this can go to a buffer or a file.
Once saved - you really should then validate with a schema before committing it our shipping it off.
For one of our projects we hav... | I recently reviewed a bunch of XML libraries specifically for generating XML code.
Executive summary: I chose to go with [TinyXML++](http://code.google.com/p/ticpp/).
TinyXML++ has decent C++ syntax, is built on the mature [TinyXML](http://www.grinninglizard.com/tinyxml/) C libraries, is free & open source (MIT licen... | what's the easiest way to generate xml in c++? | [
"",
"c++",
"xml",
"serialization",
""
] |
For my application, I want a [Combo Box](http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html) that displays its elements when dropped down as a [Tree](http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html). Problem is, I'm not versed well enough in Swing to know how to go about doing... | I think I would implement this as a JTree component in a JViewPort, followed by an expansion button. When collapsed, it would look like a combo box. When you click the expansion button, the viewport would expand, allowing you to scroll and select a node in the JTree. When you selected the node, the view port would coll... | Hey, guess what! This is your lucky day.
I've used this framework in the past. It is very complete. I didn't know they have this
already.
[JIDE Soft](http://www.jidesoft.com/)
[alt text http://img89.imageshack.us/img89/8324/combotreejj1.png](http://img89.imageshack.us/img89/8324/combotreejj1.png)
Is not too expensi... | How do I combine a Combo Box with a Tree in Swing? | [
"",
"java",
"swing",
"combobox",
"tree",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.