Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Back in the day when I did most of my work in C and C++, as a matter of course, I would manually apply [deMorgan's theorem](http://en.wikipedia.org/wiki/De_Morgan_theorem) to optimize any non-trivial boolean expressions.
Is it useful to do this in C# or does the optimizer render this unnecessary? | On processors this fast, it's virtually impossible for rearranging boolean expressions to make any actual difference in speed. And the C# compiler is very smart, it will optimize it as well. Optimize for readability and clarity! | Your first goal should be to optimize such statements for developer comprehension and ease of maintenance.
DeMorgan's theorem can be a useful tool for this. | Is it useful in C# to apply DeMorgan's theorem to manually optimize boolean expressions in conditional statements (e.g. if conditions) | [
"",
"c#",
"optimization",
"compiler-construction",
"boolean-logic",
""
] |
I just ran into a problem with the version of JAX-WS in JDK 1.6.0 being different than the one in JDK 1.6.0\_14.
I've been searching around for a list of the various libraries that are packaged in the JDK that shows the versions of the library included in the version of the JDK.
I haven't had any luck yet.
Is there such a list? | Usually this information can be found by digging around in the JavaDocs for the release (not the API docs, but the release notes and spec notes (e.g. for [Java 6](http://java.sun.com/javase/6/docs/) ). It's in there somewhere, but sometimes that kind of info is tricky to find. | It is probably in JSR 270 (<http://jcp.org/en/jsr/detail?id=270>) which defines exactly what is Java6. But I havent checked and JSR are not the most pleasant readings ;-) | Versions of libraries included in the JDK | [
"",
"java",
""
] |
my question today is pretty simple: why can't the compiler infer template parameters from class constructors, much as it can do from function parameters? For example, why couldn't the following code be valid:
```
template <typename obj>
class Variable {
obj data;
public:
Variable(obj d) { data = d; }
};
int main() {
int num = 2;
Variable var(num); // would be equivalent to Variable<int> var(num),
return 0; // but actually a compile error
}
```
As I say, I understand that this isn't valid, so my question is *why* isn't it? Would allowing this create any major syntactic holes? Is there an instance where one wouldn't want this functionality (where inferring a type would cause issues)? I'm just trying to understand the logic behind allowing template inference for functions, yet not for suitably-constructed classes. | I think it is not valid because the constructor isn't always the only point of entry of the class (I am talking about copy constructor and operator=). So suppose you are using your class like this :
```
MyClass m(string s);
MyClass *pm;
*pm = m;
```
I am not sure if it would be so obvious for the parser to know what template type is the MyClass pm;
Not sure if what I said make sense but feel free to add some comment, that's an interesting question.
## C++ 17
It is accepted that C++17 will have type deduction from constructor arguments.
Examples:
```
std::pair p(2, 4.5);
std::tuple t(4, 3, 2.5);
```
[Accepted paper](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0091r2.html). | You can't do what you ask for reasons other people have addressed, but you can do this:
```
template<typename T>
class Variable {
public: Variable(T d) {}
};
template<typename T>
Variable<T> make_variable(T instance) {
return Variable<T>(instance);
}
```
which for all intent and purposes is the same thing you ask for.
If you love encapsulation you can make make\_variable a static member function. That's what people call named constructor. So not only does it do what you want, but it's almost called what you want: the compiler is infering the template parameter from the (named) constructor.
NB: any reasonable compiler will optimize away the temporary object when you write something like
```
auto v = make_variable(instance);
``` | Why not infer template parameter from constructor? | [
"",
"c++",
"templates",
"parameters",
"inference",
""
] |
Is there w way to achieve following using an SQL 2000 query, i looked everywhere but could not find any working snippet.
I have contiguous date segments and requirement is to get the min effective date and maximum effective dates for each contiguous dates.
if that is not possible getting min effective date and max termdate for an contiguous segment using different queries will also work for me.
```
ID effdate termdate
1 2007-05-01 2007-05-31
2 2007-06-01 2007-06-30
3 2007-07-01 2007-09-30
4 2008-03-01 2008-03-31
5 2008-05-01 2008-05-31
6 2008-06-01 2008-06-30
```
Expected Result :
```
2007-05-01 2007-09-30
2008-03-01 2008-03-31
2008-05-01 2008-06-30
``` | I did something like this to get the effdate and same for termdate, made them as two separate views and got the final result.
```
SELECT distinct e0.effdate,e0.ID
FROM dbo.datatable e0 LEFT OUTER JOIN dbo.datatable PREV ON
PREV.ID = e0.ID
AND PREV.termdate = DATEADD(dy, -1, e0.Effdate)
WHERE PREV.ID IS NULL
``` | Unfortunately you're probably going to have to use a cursor. Something like this should work.
```
DECLARE @Results TABLE
(
effdate DATETIME,
termdate DATETIME
)
DECLARE @Date1 DATETIME,
@Date2 DATETIME,
@StartDate DATETIME,
@EndDate DATETIME
DECLARE @Cursor CURSOR
SET @Cursor = CURSOR FAST_FORWARD
FOR
SELECT effdate, termdate FROM <TABLE>
OPEN @Cursor
FETCH NEXT FROM @Cursor
INTO @Date1,@Date2
WHILE @@FETCH_STATUS = 0
BEGIN
IF @StartDate IS NULL
BEGIN
SELECT @StartDate = @Date1,
@EndDate = @Date2
END
ELSE
BEGIN
IF DateDiff(d,@EndDate,@Date1) = 1
BEGIN
SET @EndDate = @Date2
END
ELSE
BEGIN
INSERT INTO @Results
SELECT @StartDate, @EndDate
SELECT @StartDate = @Date1,
@EndDate = @Date2
END
END
FETCH NEXT FROM @Cursor
INTO @Date1,@Date2
END
INSERT INTO @Results
SELECT @StartDate, @EndDate
CLOSE @Cursor
DEALLOCATE @Cursor
SELECT * FROM @Results
``` | Min effective and termdate for contiguous dates | [
"",
"sql",
"sql-server",
""
] |
I want to split my processing.js code into several files but I'm not sure how. I tried doing
```
<script type="application/processing" src="main.pjs">
```
to load my processing.js file "main.pjs" but it didn't work. | Try <http://www.hyper-metrix.com/misc/Processing.AJAX.init.zip> | I know this has already been answered, but I thought I'd add some more explanation:
The problem with your initial approach is that the browser does not know what to do with a file of type "application/processing", so it is never even pulled from the server. The init() package that TML posted looks for these and pulls them by means of XHR. | processing.js loading external files | [
"",
"javascript",
"processing.js",
""
] |
I would like to write a Console class that can output coloured text to the console.
So I can do something like (basically a wrapper for printf):
```
Console::Print( "This is a non-coloured message\n" );
Console::Warning( "This is a YELLOW warning message\n" );
Console::Error( "This is a RED error message\n" );
```
How would I print different coloured text to the Windows Console? | Check out [this guide](http://www.infernodevelopment.com/set-console-text-color). I would make a custom manipulator so I could do something like:
```
std::cout << "standard text" << setcolour(red) << "red text" << std::endl;
```
[Here](http://www.informit.com/articles/article.aspx?p=171014&seqNum=2)'s a small guide on how to implement your own manipulator.
A quick code example:
```
#include <iostream>
#include <windows.h>
#include <iomanip>
using namespace std;
enum colour { DARKBLUE = 1, DARKGREEN, DARKTEAL, DARKRED, DARKPINK, DARKYELLOW, GRAY, DARKGRAY, BLUE, GREEN, TEAL, RED, PINK, YELLOW, WHITE };
struct setcolour
{
colour _c;
HANDLE _console_handle;
setcolour(colour c, HANDLE console_handle)
: _c(c), _console_handle(0)
{
_console_handle = console_handle;
}
};
// We could use a template here, making it more generic. Wide streams won't
// work with this version.
basic_ostream<char> &operator<<(basic_ostream<char> &s, const setcolour &ref)
{
SetConsoleTextAttribute(ref._console_handle, ref._c);
return s;
}
int main(int argc, char *argv[])
{
HANDLE chandle = GetStdHandle(STD_OUTPUT_HANDLE);
cout << "standard text" << setcolour(RED, chandle) << " red text" << endl;
cin.get();
}
``` | I did a search for "c++ console write colored text" and came up with [this page](http://www.dreamincode.net/code/snippet680.htm) at about 4 or 5. As the site has a copy & paste section I thought I'd post it here (another question on link rot also prompted this):
```
#include <stdlib.h>
#include <windows.h>
#include <iostream>
using namespace std;
enum Color { DBLUE=1,GREEN,GREY,DRED,DPURP,BROWN,LGREY,DGREY,BLUE,LIMEG,TEAL,
RED,PURPLE,YELLOW,WHITE,B_B };
/* These are the first 16 colors anyways. You test the other hundreds yourself.
After 15 they are all combos of different color text/backgrounds. */
bool quit;
void col(unsigned short color)
{
HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hcon,color);
}
istream &operator>> ( istream &in, Color &c )
{
int tint;
cin >> tint;
if (tint==-1) quit=true;
c=(Color)tint;
}
int main()
{
do {
col(7); // Defaults color for each round.
cout << "Enter a color code, or -1 to quit... ";
Color y;
cin >> y; // Notice that >> is defined above for Color types.
col(y); // Sets output color to y.
if (!quit) cout << "Color: " << (int)y << endl;
} while (!quit);
return 0;
}
```
For C# there's [this page](http://support.microsoft.com/kb/319883) | Print Coloured Text to Console in C++ | [
"",
"c++",
"programming-languages",
"text",
"console",
"terminal",
""
] |
I would like to convert a string of delimited dimension values into floating numbers.
For example
```
152.15 x 12.34 x 11mm
```
into
```
152.15, 12.34 and 11
```
and store in an array such that:
```
$dim[0] = 152.15;
$dim[1] = 12.34;
$dim[2] = 11;
```
I would also need to handle scenarios where the delimiting text is different and the numbers may be followed by a unit expression like:
```
152.15x12.34x11 mm
152.15mmx12.34mm x 11mm
``` | ```
$str = '152.15 x 12.34 x 11mm';
preg_match_all('!\d+(?:\.\d+)?!', $str, $matches);
$floats = array_map('floatval', $matches[0]);
print_r($floats);
```
The `(?:...)` regular expression construction is what's called a [non-capturing group](http://www.regular-expressions.info/named.html). What that means is that chunk isn't separately returned in part of the `$mathces` array. This isn't strictly necessary **in this case** but is a useful construction to know.
**Note:** calling [`floatval()`](https://www.php.net/floatval) on the elements isn't strictly necessary either as PHP will generally juggle the types correctly if you try and use them in an arithmetic operation or similar. It doesn't hurt though, particularly for only being a one liner. | ```
<?php
$s = "152.15 x 12.34 x 11mm";
if (preg_match_all('/\d+(\.\d+)?/', $s, $matches)) {
$dim = $matches[0];
}
print_r($dim);
?>
```
gives
```
Array
(
[0] => 152.15
[1] => 12.34
[2] => 11
)
``` | Extract floating point numbers from a delimited string in PHP | [
"",
"php",
"regex",
"floating-point",
"text-parsing",
"text-extraction",
""
] |
Is there a maven client that isn't mvn (the binary included with the maven distribution) I could use to pull down an artifact from a maven repository without using a pom? I'd like to use a maven repository as the repo for our ops team to pick up builds (including snapshots of
builds) but I don't want them to have to mess around with writing poms and declaring dependencies in them. Ideally, I'm looking for just a cli client that I could just pass in a repo url and coordinates and download a given artifact. Does such a thing exist or am I better off writing a one-off script for this? | Use Nexus. It provides a web interface that other teams can use to download artifacts. <http://nexus.sonatype.org/> | I see 3 easy options:
1. Just send them a link pointing on your artifact in your repository and have them use their browser.
2. Install and use `wget` (`wget http://path/to/artifact.extension`).
3. Install and use [`mvn dependency:get`](http://maven.apache.org/plugins/maven-dependency-plugin/get-mojo.html) (requires `mvn` but **doesn't** require a `pom.xml`, see [this answer](https://stackoverflow.com/questions/1776496/a-simple-command-line-to-download-a-remote-maven2-artifact-to-the-local-repositor/1776808#1776808) for more details). | Utility for downloading artifacts from maven repo without mvn/poms | [
"",
"java",
"maven-2",
"repository",
"aether",
""
] |
```
myfile = open("wrsu"+str(i)+'_'+str(j)+'_'+str(TimesToExec)+".txt",'w')
sys.stdout = myfile
p1 = subprocess.Popen([pathname,"r", "s","u",str(i),str(j),str(runTime)],stdout=subprocess.PIPE)
output = p1.communicate()[0]
print output,
```
When I use this to redirect the output of a exe to my own file, it always
a carriage return after each line, How to suppress it? | Here's how I removed the carriage return:
```
p = Popen([vmrun_cmd, list_arg], stdout=PIPE).communicate()[0]
for line in p.splitlines():
if line.strip():
print line
``` | ```
def Popenstrip(self):
p = Popen([vmrun_cmd, list_arg], stdout=PIPE).communicate()[0]
return (line for line in p.splitlines() if line.strip())
``` | How to suppress the carriage return in python 2? | [
"",
"python",
"io",
""
] |
I must sometimes write software to establish a socket with a particular server residing within a Cisco VPN. I simply write my software as if there were no VPN (making use of the standard sockets library). When it is time to run this program, I manually connect to the VPN using the client software installed on my computer, then run the program itself.
However, it would be desirable to write the software to take advantage of a specialized socket library capable of communicating over the VPN directly, without the use of any installed client software.
Here is some Java code illustrating the functionality I would like:
```
String vpnHost = ...;
String vpnUser = ...;
String vpnPassword = ...;
VPNConnection vpnConnection = new CiscoVPNConnection(vpnHost, vpnUser, vpnPassword);
String serverHost = ...;
int serverPort = ...;
Socket socket = vpnConnection.openSocket(serverHost, serverPort);
```
Is it possible to establish such a connection to a VPN without installing any client software? | This depends on how the VPN server is configured.
Most VPN products use IPSEC, a standard protocol for encrypting TCP/IP connections. Most products also use ISAKMP, the Internet Security Architecture Key Management Protocol, also a standard, to set up the session. Source code for IPSEC and ISAKMP is readily available, and may already be installed on your system.
Now for the bad news: although everything I've already mentioned is standard, the authentication schemes that can be used with ISAKMP are almost all proprietary. The two "standard" authentication schemes are pre-shared key, and X.509 certificates. If the VPN server is configured to permit either of these then you have a chance. Otherwise, you cannot really use the VPN, as the protocol is truly proprietary and almost impossible to reverse engineer as the authentication conversation is encrypted.
A far easier path: do you really need a VPN, or is there a way you can tunnel over SSL? I think Java supports SSL; you can just create the secure socket you need and go from there.
If you know what client system you're using, then consider shelling out to invoke the Cisco VPN client for that system.
Otherwise, you'll have to replicate what a VPN client does. The VPN client performs authentication and session setup with ISAKMP, and installs the result into the kernel to create the VPN connection. ISAKMP implementations are available; you need only figure out what authentication is being used and try to set that up. At which point you will have written your own VPN client. | I use the vpnc package on linux in order to connect to my company's Cisco VPN, since we don't have a compatible linux client. vpnc is written in c though, so you'll have to perform a port. | Connecting to a VPN without installation of client software | [
"",
"java",
"sockets",
"vpn",
"cisco",
""
] |
I am writing a GUI app in [Pyglet](http://www.pyglet.org/) that has to display tens to hundreds of thumbnails from the Internet. Right now, I am using [urllib.urlretrieve](http://docs.python.org/library/urllib.html#urllib.urlretrieve) to grab them, but this blocks each time until they are finished, and only grabs one at a time.
I would prefer to download them in parallel and have each one display as soon as it's finished, without blocking the GUI at any point. What is the best way to do this?
I don't know much about threads, but it looks like the [threading](http://docs.python.org/library/threading.html) module might help? Or perhaps there is some easy way I've overlooked. | You'll probably benefit from `threading` or [`multiprocessing`](http://docs.python.org/library/multiprocessing.html#using-a-pool-of-workers) modules. You don't actually need to create all those `Thread`-based classes by yourself, there is a simpler method using `Pool.map`:
```
from multiprocessing import Pool
def fetch_url(url):
# Fetch the URL contents and save it anywhere you need and
# return something meaningful (like filename or error code),
# if you wish.
...
pool = Pool(processes=4)
result = pool.map(f, image_url_list)
``` | As you suspected, this is a perfect situation for threading. [Here](http://www.wellho.net/solutions/python-python-threads-a-first-example.html) is a short guide I found immensely helpful when doing my own first bit of threading in python. | How to do a non-blocking URL fetch in Python | [
"",
"python",
"multithreading",
"blocking",
"pyglet",
""
] |
Suppose I have an existing assembly, and some of the classes have overloaded methods, with default behavior or values assumed for some of those overloads. I think this is a pretty typical pattern;
```
Type2 _defaultValueForParam2 = foo;
Type3 _defaultValueForParam3 = bar;
public ReturnType TheMethod(Type1 param1)
{
return TheMethod(param1, _defaultValueForParam2);
}
public ReturnType TheMethod(Type1 param1, Type2 param2)
{
return TheMethod(param1, param2, _defaultValueForParam3);
}
public ReturnType TheMethod(Type1 param1, Type2 param2, Type3 param3)
{
// actually implement the method here.
}
```
And I understand that optional params in C# is supposed to let me consolidated that down to a single method. If I produce a method with some params marked optional, will it work with downlevel callers of the assembly?
---
**EDIT**: By "work" I mean, a *downlevel caller*, an app compiled with the C# 2.0 or 3.5 compiler, will be able to invoke the method with one, two or three params, just as if I had used overloads, and the downlevel compiler won't complain.
I do want to refactor and eliminate all the overloads in my library, but I don't want to force the downlevel callers using the refactored library to provide every parameter. | I haven't read the docs on the new language standard, but I would assume that your pre-4.0 callers will have to pass **all** declared parameters, just as they do now. This is because of the way parameter-passing works.
When you call a method, the arguments are pushed onto the stack. If three 32-bit arguments are passed, then 12 bytes will be pushed onto the stack; if four 32-bit arguments are passed, then 16 bytes will be pushed onto the stack. The number of bytes pushed onto the stack is implicit in the call: the callee assumes that the correct number of arguments was passed.
So if a function takes four 32-bit parameters, it will look on the stack at the 16 bytes preceding the return address of the caller. If the caller has passed only 12 bytes, then the callee will read 4 bytes of whatever was already on the stack before the call was made. It has no way of knowing that all 16 expected bytes was not passed.
This is the way it works now. There's no changing that for existing compilers.
To support optional parameters, one of two things has to happen:
1. The caller can pass an additional value that explicitly tells the callee how many arguments (or bytes) were pushed onto the stack. The callee can then fill in the default values for any omitted parameters.
2. The caller can continue passing all declared parameters, substituting default values (which would be read from the callee's metadata) for any optional parameters omitted in the code. The callee then reads all parameter values from the stack, just as it does now.
I suspect that it will be implemented as in (2) above. This is similar to how it's done in C++ (although C++, lacking metadata, requires that the default parameters be specified in the header file), is more efficient that option (1), as it is all done at compile time and doesn't require an additional value to pushed onto the stack, and is the most straightforward implementation. The drawback to option (2) is that, if the default values change, all callers must be recompiled, or else they will continue to pass the old defaults, since they've been compiled in as constants. This is similar to the way public constants work now. Note that option (1) does not suffer this drawback.
Option (1) also does not support named parameter passing, whereby given a function declared like this:
```
static void Foo(int a, int b = 0, int c = 0){}
```
it can be called like this:
```
Foo(1, c: 2);
```
Option (1) could be modified to allow for this, by making the extra hidden value a bitmap of omitted arguments, where each bit represents one optional parameter. This arbitrarily limits the number of optional parameters a function can accept, although given that this limitation would be at least 32, that may not be such a bad thing. It does make it exceedingly unlikely that this is the actual implementation, however.
Given either implementation, the calling code **must** understand the mechanics of optional parameters in order to omit any arguments in the call. Additionally, with option (1), an extra hidden parameter must be passed, which older compilers would not even know about, unless it was added as a formal parameter in the metadata. | In c# 4.0, when an optional parameter is omitted, a default value for that parameter is substituted, to wit:
```
public void SendMail(string toAddress, string bodyText, bool ccAdministrator = true, bool isBodyHtml = false)
{
// Full implementation here
}
```
For your downlevel callers, this means that if they use one of the variants that is missing parameters, c# will *substitute the default value you have provided for the missing parameter*. [This article explains the process in greater detail](https://web.archive.org/web/20201026022658/http://geekswithblogs.net/michelotti/archive/2009/02/05/c-4.0-optional-parameters.aspx).
Your existing downlevel calls should all still work, but [you will have to recompile your clients in c# 4.0](https://dzone.com/articles/c-40-feature-focus-part-1-opti). | Will downlevel callers be able to benefit from optional params in assemblies produced with C# 4.0? | [
"",
"c#",
".net",
"c#-4.0",
""
] |
I have two ArrayLists.
**ArrayList A contains:**
```
['2009-05-18','2009-05-19','2009-05-21']
```
**ArrayList B contains:**
```
['2009-05-18','2009-05-18','2009-05-19','2009-05-19','2009-05-20','2009-05-21','2009-05-21','2009-05-22']
```
I have to compare ArrayList A and ArrayList B. The result ArrayList
should contain the List which does not exist in ArrayList A.
**ArrayList result should be:**
```
['2009-05-20','2009-05-22']
```
how to compare ? | In Java, you can use the [`Collection`](http://docs.oracle.com/javase/8/docs/api/java/util/Collection.html) interface's [`removeAll`](http://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeAll-java.util.Collection-) method.
```
// Create a couple ArrayList objects and populate them
// with some delicious fruits.
Collection firstList = new ArrayList() {{
add("apple");
add("orange");
}};
Collection secondList = new ArrayList() {{
add("apple");
add("orange");
add("banana");
add("strawberry");
}};
// Show the "before" lists
System.out.println("First List: " + firstList);
System.out.println("Second List: " + secondList);
// Remove all elements in firstList from secondList
secondList.removeAll(firstList);
// Show the "after" list
System.out.println("Result: " + secondList);
```
The above code will produce the following output:
```
First List: [apple, orange]
Second List: [apple, orange, banana, strawberry]
Result: [banana, strawberry]
``` | You already have the right answer.
And if you want to make more complicated and interesting operations between Lists (collections) use [apache commons collections](http://commons.apache.org/collections/) ([CollectionUtils](http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/CollectionUtils.html))
It allows you to make conjuction/disjunction, find intersection, check if one collection is a subset of another and other nice things. | How can I calculate the difference between two ArrayLists? | [
"",
"java",
"arraylist",
""
] |
I'm developing a real time strategy game clone on the Java platform and I have some conceptional questions about where to put and how to manage the game state. The game uses Swing/Java2D as rendering. In the current development phase, no simulation and no AI is present and only the user is able to change the state of the game (for example, build/demolish a building, add-remove production lines, assemble fleets and equipment). Therefore, the game state manipulation can be performed in the event dispatch thread without any rendering lookup. The game state is also used to display various aggregated information to the user.
However, as I need to introduce simulation (for example, building progress, population changes, fleet movements, manufacturing process, etc.), changing the game state in a Timer and EDT will surely slow down the rendering.
Lets say the simulation/AI operation is performed in every 500ms and I use SwingWorker for the computation of about 250ms in length. How can I ensure, that there is no race condition regarding the game state reads between the simulation and the possible user interaction?
I know that the result of the simulation (which is small amount of data) can be efficiently moved back to the EDT via the SwingUtilities.invokeLater() call.
The game state model seems to be too complex to be infeasible for just using immutable value classes everywhere.
Is there a relatively correct approach to eliminate this read race condition? Perhaps doing a full/partial game state cloning on every timer tick or change the living space of the game state from EDT into some other thread?
**Update:** (from the comments I gave)
The game operates with 13 AI controlled players, 1 human player and has about 10000 game objects (planets, buildings, equipment, research, etc.). A game object for example has the following attributes:
```
World (Planets, Players, Fleets, ...)
Planet (location, owner, population, type,
map, buildings, taxation, allocation, ...)
Building (location, enabled, energy, worker, health, ...)
```
In a scenario, the user builds a new building onto this planet. This is performed in EDT as the map and buildings collection needs to be changed. Parallel to this, a simulation is run on every 500ms to compute the energy allocation to the buildings on all game planets, which needs to traverse the buildings collection for statistics gathering. If the allocation is computed, it is submitted to the EDT and each building's energy field gets assigned.
Only human player interactions have this property, because the results of the AI computation are applied to the structures in EDT anyway.
In general, 75% of the object attributes are static and used only for rendering. The rest of it is changeable either via user interaction or simulation/AI decision. It is also ensured, that no new simulation/AI step is started until the previous one has written back all changes.
My objectives are:
* Avoid delaying the user interaction, e.g. user places the building onto the planet and only after 0.5s gets the visual feedback
* Avoid blocking the EDT with computation, lock wait, etc.
* Avoid concurrency issues with collection traversal and modification, attribute changes
Options:
* Fine grained object locking
* Immutable collections
* Volatile fields
* Partial snapshot
All of these have advantages, disadvantages and causes to the model and the game.
**Update 2:** I'm talking about [this](http://en.wikipedia.org/wiki/Imperium_Galactica) game. My clone is [here](http://code.google.com/p/open-ig/). The screenshots might help to imagine the rendering and data model interactions.
**Update 3:**
I'll try to give a small code sample for clarify my problem as it seems from the comments it is misunderstood:
```
List<GameObject> largeListOfGameObjects = ...
List<Building> preFilteredListOfBuildings = ...
// In EDT
public void onAddBuildingClicked() {
Building b = new Building(100 /* kW */);
largeListOfGameObjects.add(b);
preFilteredListOfBuildings.add(b);
}
// In EDT
public void paint(Graphics g) {
int y = 0;
for (Building b : preFilteredListOfBuildings) {
g.drawString(Integer.toString(b.powerAssigned), 0, y);
y += 20;
}
}
// In EDT
public void assignPowerTo(Building b, int amount) {
b.powerAssigned = amount;
}
// In simulation thread
public void distributePower() {
int sum = 0;
for (Building b : preFilteredListOfBuildings) {
sum += b.powerRequired;
}
final int alloc = sum / (preFilteredListOfBuildings.size() + 1);
for (final Building b : preFilteredListOfBuildings) {
SwingUtilities.invokeLater(=> assignPowerTo(b, alloc));
}
}
```
So the overlapping is between the onAddBuildingClicked() and distributePower(). Now imagine the case where you have 50 of these kind of overlappings between various parts of the game model. | This sounds like it could benefit from a client/server approach:
The player is a client - interactivity and rendering happen on that end. So the player presses a button, the request goes to the server. The reply from the server comes back, and the player's state is updated. At any point between these things happening, the screen can be re-painted, and it reflects the state of the game as the client currently knows it.
The AI is likewise a client - it's the equivalent of a bot.
The simulation is the server. It gets updates from its clients at various times and updates the state of the world, then sends out these updates to everyone as appropriate. Here's where it ties in with your situation: The simulation/AI requires a static world, and many things are happening at once. The server can simply queue up change requests and apply them before sending the updates back to the client(s). So as far as the server's concerned, the game world isn't actually changing in real time, it's changing whenever the server darn well decides it is.
Finally, on the client side, you can prevent the delay between pressing the button and seeing a result by doing some quick approximate calculations and displaying a result (so the immediate need is met) and then displaying the more correct result when the server gets around to talking to you.
Note that this does not actually have to be implemented in a TCP/IP over-the-internet sort of way, just that it helps to think of it in those terms.
Alternately, you can place the responsibility for keeping the data coherent during the simulation on a database, as they're already built with locking and coherency in mind. Something like sqlite could work as part of a non-networked solution. | If changing the game state is fast (once you know what to change it to) you can treat the game state like other Swing models and only change or view the state in the EDT. If changing the game state is not fast, then you can either synchronize state change and do it in swing worker/timer (but not the EDT) or you can do it in separate thread that you treat similarly to the EDT (at which point you look at using a `BlockingQueue` to handle change requests). The last is more useful if the UI never has to retrieve information from the game state but instead has the rendering changes sent via listeners or observers. | How to manage the game state in face of the EDT? | [
"",
"java",
"swing",
"event-dispatch-thread",
""
] |
I am working with Window Service project. that have to write data to a sheet in Excel file in a sequence times.
But sometimes, just sometimes, the service throw out the exception "Exception from HRESULT: 0x800A03EC" while it's trying to get range with cell's name.
I have put the code of opening excel sheet, and getting cell here.
* OS: window server 2003 Office:
* Microsoft Office 2003 sp2
1: Opening excel sheet
```
m_WorkBook = m_WorkBooks.Open(this.FilePath, 0, false, 5,
"", "", true, Excels.XlPlatform.xlWindows, ";",
true, false, 0, true, 0, 0);
```
2: Getting cell to write
```
protected object m_MissingValue = System.Reflection.Missing.Value;
Range range = m_WorkSheet.get_Range(cell.CellName, m_MissingValue);
// error from this method, and cell name is string.
``` | The error code `0x800A03EC` (or -2146827284) means NAME\_NOT\_FOUND; in other words, you've asked for something, and Excel can't find it.
This is a generic code, which can apply to lots of things it can't find e.g. using properties which aren't valid at that time like `PivotItem.SourceNameStandard` throws this when a PivotItem doesn't have a filter applied. `Worksheets["BLAHBLAH"]` throws this, when the sheet doesn't exist etc. In general, you are asking for something with a specific name and it doesn't exist. As for why, that will taking some digging on your part.
Check your sheet definitely does have the Range you are asking for, or that the `.CellName` is definitely giving back the name of the range you are asking for. | I ran into this error because I was attempting to write a string to a cell which started with an "=".
The solution was to put an "'" (apostrophe) before the equals sign, which is a way to tell excel that you're not, in fact, trying to write a formula, and just want to print the equals sign. | Excel error HRESULT: 0x800A03EC while trying to get range with cell's name | [
"",
"c#",
"excel",
"exception",
"vsto",
""
] |
What is the best way to convert a List to SortedList? Any good way to do it without cycling through it? Any clever way to do it with an OrderBy()?
**WRAP UP**
Please read all answers and comments. | ```
var list = new List<string>();
var sortedList = new SortedList<string, string>(list.ToDictionary(s => s));
```
Now I have no clue how efficient this is, but it's one line of code :) Also, in this example I just used the string itself as the selector. In a real scenario, you should know ahead of time what you'd like to use as a selector. | Do you mean:
1. you have a `List<T>` and wish it to be sorted in place?
2. you have a `List<T>` and wish to create another 'list' which is itself sorted
3. you have a `List<T>` and wish to make a `SortedList<T,T>` where the key is the same as the value
Assuming input:
```
var x = new List<int>() { 3, 2, 1 };
```
1 is trivial
```
x.Sort();
```
2 is trivial
```
// sx is an IOrderedEnumerable<T>, you can call ToList() on it if you want
var sx = x.OrderBy(i => i);
```
3 is trivial with a copy
```
var s = new SortedList<int,int>(t.ToDictionary(i => i));
```
and more efficiently:
```
var s = new SortedList<int,int>();
foreach (var i in x) { s[i] = [i]; }
```
I can't see *why* you would want to do 3 but there you go. | .NET / C# - Convert List to a SortedList | [
"",
"c#",
".net",
"list",
"lambda",
"sortedlist",
""
] |
With Excel 2003 and higher it is possible to use the SpreadsheetML format to generate Excel spreadsheets with just an XML stylesheet and XML data file. I've used this in some project and works quite nice, even though it's not easy to do.
From the Microsoft Download site I've downloaded the XSD's that make up SpreadsheetML and in my ignorance, I've tried to convert them to C# classes. Unfortunately, xsd.exe isn't very happy about these schema files so I tend to be stuck.
I don't need an alternative solution to SpreadsheetML since it works fine for my needs. It's just that my code would be a bit easier to maintain for my team members if it's not written in a complex stylesheet. (It sucks to be the only XSLT expert in your company.)
All I want to know if someone has successfully created Excel SpreadsheetML files with .NET without the use of third-party code and without XSLT. And if you do, how did you solve this?
(Or maybe I just have to discover how to add namespaces to XML elements within XML.Linq...) | A while ago I used the XmlDocument and friends to create a SpreadsheetML document with formulae, formats and so on, so it is possible if a bit fiddly.
This [MSDN page](http://msdn.microsoft.com/en-us/library/bb387042.aspx) is what you need to get started with using the namespace in LINQ. | I have used this library and there is even a tool to generate the C# code that you need from an exsisting excel file.
<http://www.carlosag.net/Tools/ExcelXmlWriter/> | Creating an Excel SpreadsheetML in code. (Without Excel!) | [
"",
"c#",
"excel",
""
] |
I have a large dataset that needs to be displayed for users and looking for Swing's `JTable` like component in `JavaFX`. | I recommend you read Amy Fowler's recent blog post (especially point 6):
*Any Swing component can be embedded in a JavaFX scene graph using the SwingComponent wrap() function. This conveniently allows you to directly leverage those Swing components which you've already configured, customized, and hooked to your application data; all that Java code can remain happily unmodified. Once you've created the structure of your scene's layout, you can pull your Swing components into the appropriate locations.*
<http://weblogs.java.net/blog/aim/archive/2009/06/insiders_guide.html> | Use a `TableView` control.
* [javadoc](http://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TableView.html)
* [tutorial](http://docs.oracle.com/javase/8/javafx/user-interface-tutorial/table-view.htm)
A TableView is a "virtualized" control which efficiently reuses a small number of node cells to present a view into potentially very large data sets.

Note, other answers on this page which were written before 2012 concern JavaFX 1.x and are obsolete. | JavaFX component that emulates JTable | [
"",
"java",
"swing",
"frameworks",
"jtable",
"javafx",
""
] |
I am using (a slightly extended version of) the following code in a factory-pattern style function:
public class SingleItemNew : CheckoutContext
{
public BookingContext Data { get; set; }
public SingleItemNew(BookingContext data)
{
Data = data;
}
}
public CheckoutContext findContext(BookingContext data)
{
Type contextType = Type.GetType("CheckoutProcesses." + data.Case.ToString());
CheckoutContext output =
Activator.CreateInstance(contextType, BindingFlags.CreateInstance, new[] { data }) as CheckoutContext;
return output;
}
however, it throws a constuctor not found exception when run, and I cannot figure out why.
The data.Case.ToString() method returns the name of a class, SingleItemNew, that has a constructor taking a single argument.
Does anyone have any idea what the problem is?
Cheers, Ed | Try this one:
```
Type contextType = Type.GetType("CheckoutProcesses." + data.Case.ToString());
CheckoutContext output =
(CheckoutContext)Activator.CreateInstance(contextType, data);
```
The reason you code doesn't work is that `Activator.CreateInstance` doesn't really have the overload you want. So you might wonder why the code compiles at all! The reason is, it has an overload that takes `(Type type, params object[] args)` which matches your method call so it compiles but at runtime, it searches your type for a constructor taking a `BindingFlags` and a `BookingContext[]` which is clearly not what your type has. | Is the constructor public?
Is the single parameter of type `BookingContext`?
The trouble is, this is clearly part of a bigger system - it would be *much* easier to help you if you could produce a [short but complete program](http://pobox.com/~skeet/csharp/complete.html) which demonstrated the problem. Then we could fix the problem in that program, and you could port your fix back to your real system. Otherwisewise we're really just guessing :( | Activator.CreateInstance(t, 42, args) cannot find constructor | [
"",
"c#",
".net",
"types",
"activator",
"createinstance",
""
] |
Is there a simple and reliable way to determine the URL of the currently-executing JavaScript file (inside a web page)?
My only thought on this is to scan the DOM for all the script `src` attributes to find how the current file was referenced and then figure out the absolute URL by applying it to `document.location`. Anyone have other ideas, is there some super-easy method I completely overlooked?
UPDATE: Script elements accessed via the DOM already have a `src` property which contains the full URL. I don't know how ubiquitous/standard that is, but alternatively you can use `getAttribute("src")` which will return whatever raw attribute value is in the [X]HTML. | Put this in the js file that needs to know it's own url.
**Fully Qualified** (eg `http://www.example.com/js/main.js`):
```
var scriptSource = (function(scripts) {
var scripts = document.getElementsByTagName('script'),
script = scripts[scripts.length - 1];
if (script.getAttribute.length !== undefined) {
return script.src
}
return script.getAttribute('src', -1)
}());
```
Or
**As it appears in source** (eg `/js/main.js`):
```
var scriptSource = (function() {
var scripts = document.getElementsByTagName('script'),
script = scripts[scripts.length - 1];
if (script.getAttribute.length !== undefined) {
return script.getAttribute('src')
}
return script.getAttribute('src', 2)
}());
```
See <http://www.glennjones.net/Post/809/getAttributehrefbug.htm> for explanation of the `getAttribute` parameter being used (it's an IE bug). | For recent browsers, you can use document.currentScript to get this information.
```
var mySource = document.currentScript.src;
```
The upside is that it's more reliable for scripts that are loaded asynchronously. The downside is that it's not, as best I know, universally supported. It should work on Chrome >= 29, FireFox >= 4, Opera >= 16. Like many useful things, it doesn't seem to work in IE.
When I need to get a script path, I check to see if document.currentScript is defined, and, if not, use the method described in the accepted answer.
```
if (document.currentScript) {
mySource = document.currentScript.src;
} else {
// code omitted for brevity
}
```
<https://developer.mozilla.org/en-US/docs/Web/API/document.currentScript> | What is my script src URL? | [
"",
"javascript",
"dom",
"absolute-path",
"src",
""
] |
I have a high-level goal of creating a **static** utility class that encapsulates the encryption for my .NET application. Inside I'd like to minimize the object creations that aren't necessary.
My question is: **what is the thread-safety of the classes which implement symmetric encryption within the .NET Framework?** Specifically `System.Security.Cryptography.RijndaelManaged` and the `ICryptoTransform` types it generates.
For instance, in my class constructor can I simply do something along the following lines?
```
static MyUtility()
{
using (RijndaelManaged rm = new RijndaelManaged())
{
MyUtility.EncryptorTransform = rm.CreateEncryptor(MyUtility.MyKey, MyUtility.MyIV);
MyUtility.DecryptorTransform = rm.CreateDecryptor(MyUtility.MyKey, MyUtility.MyIV);
}
}
```
*Side-stepping the issue of is it secure to have Key and IV exist within this class*, this example block brings up a number of other questions:
1. Can I continually reuse the EncryptorTransform and DecryptorTransform over and over? The `*.CanReuseTransform` and `*.CanTransformMultipleBlocks` properties imply "yes", but are there any caveats I should be aware of?
2. Since `RijndaelManaged` implements `IDisposable` my inclination is to put it within a `using` block especially since it probably ties into external OS-level libs. Are there any caveats with this since I'm keeping the `ICryptoTransform` objects around?
3. Potentially the most important question, in a highly multithreaded environment, will I run into issues with sharing the `ICryptoTransform` objects between threads?
4. If the answer to #3 is that it isn't thread-safe, will I experience serious performance degradation from locking while I use the `ICryptoTransform` objects? (Depends on load I suppose.)
5. Would it be more performant to simply instantiate new `RijndaelManaged` each time? Or store one `RijndaelManaged` and generate `new RijndaelManaged().CreateEncryptor(...)` each time?
I am hoping that someone out there knows how these work under the hood or are experienced with issues from similar implementations. I've found that a lot of these kinds of performance and thread-related issues typically do not manifest themselves until there is a sizable amount of load.
Thanks! | 1) Yes.
2) One you dispose of it, you cannot use it. Up until then, you can share/use it (but see below)
3-4) From [MSDN](http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx):
"Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe. "
If you want to keep this around, and share it between threads, you'll need to implement locking and treat it as a locked resource. Otherwise, I'd recommend just making separate versions as needed, and disposing of them when you're done.
5) I would recommend creating these as needed, and then trying to optimize it if later you find you have a performance problem. Don't worry about the performance implications of creating a new version until you see that's its a problem after profiling. | One could solve the concurrency problem simply with a cache based on a concurrent stack:
```
static ConcurrentStack<ICryptoTransform> decryptors = new ConcurrentStack<ICryptoTransform>();
void Encrypt()
{
// Pop decryptor from cache...
ICryptoTransform decryptor;
if (!decryptors.TryPop(out decryptor))
{
// ... or create a new one since cache is depleted
AesManaged aes = new AesManaged();
aes.Key = key;
aes.IV = iv;
decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
}
try
{
//// use decryptor
}
finally
{
decryptors.Push(decryptor);
}
}
``` | Thread Safety of .NET Encryption Classes? | [
"",
"c#",
"encryption",
"cryptography",
"thread-safety",
"rijndaelmanaged",
""
] |
I have searched for other posts, as I felt this is a rather common problem, but all other Python exception questions I have found didn't reflect my problem.
I will try to be as specific here as I can, so I will give a direct example. And pleeeeease do not post any workarounds for this specific problem. I am not specifically interested how you can send an email much nicer with xyz.
I want to know how you generally deal with dependent, error prone statements.
My question is, how to handle exceptions nicely, ones that depend on one another, meaning:
Only if the first step was successful, try the next, and so on. One more criterion is: All exceptions have to be caught, this code has to be robust.
For your consideration, an example:
```
try:
server = smtplib.SMTP(host) #can throw an exception
except smtplib.socket.gaierror:
#actually it can throw a lot more, this is just an example
pass
else: #only if no exception was thrown we may continue
try:
server.login(username, password)
except SMTPAuthenticationError:
pass # do some stuff here
finally:
#we can only run this when the first try...except was successful
#else this throws an exception itself!
server.quit()
else:
try:
# this is already the 3rd nested try...except
# for such a simple procedure! horrible
server.sendmail(addr, [to], msg.as_string())
return True
except Exception:
return False
finally:
server.quit()
return False
```
This looks extremely unpythonic to me, and the error handling code is triple the real business code, but on the other hand how can I handle several statements that are dependent on one another, meaning statement1 is prerequisite for statement2 and so on?
I am also interested in proper resource cleanup, even Python can manage that for itself.
Thanks, Tom | Instead of using the try/except's else block, you could simply return when it errors:
```
def send_message(addr, to, msg):
## Connect to host
try:
server = smtplib.SMTP(host) #can throw an exception
except smtplib.socket.gaierror:
return False
## Login
try:
server.login(username, password)
except SMTPAuthenticationError:
server.quit()
return False
## Send message
try:
server.sendmail(addr, [to], msg.as_string())
return True
except Exception: # try to avoid catching Exception unless you have too
return False
finally:
server.quit()
```
That's perfectly readable and Pythonic..
Another way of doing this is, rather than worry about the specific implementation, decide how you want your code to look, for example..
```
sender = MyMailer("username", "password") # the except SocketError/AuthError could go here
try:
sender.message("addr..", ["to.."], "message...")
except SocketError:
print "Couldn't connect to server"
except AuthError:
print "Invalid username and/or password!"
else:
print "Message sent!"
```
Then write the code for the `message()` method, catching any errors you expect, and raising your own custom one, and handle that where it's relevant. Your class may look something like..
```
class ConnectionError(Exception): pass
class AuthError(Exception): pass
class SendError(Exception): pass
class MyMailer:
def __init__(self, host, username, password):
self.host = host
self.username = username
self.password = password
def connect(self):
try:
self.server = smtp.SMTP(self.host)
except smtplib.socket.gaierror:
raise ConnectionError("Error connecting to %s" % (self.host))
def auth(self):
try:
self.server.login(self.username, self.password)
except SMTPAuthenticationError:
raise AuthError("Invalid username (%s) and/or password" % (self.username))
def message(self, addr, to, msg):
try:
server.sendmail(addr, [to], msg.as_string())
except smtplib.something.senderror, errormsg:
raise SendError("Couldn't send message: %s" % (errormsg))
except smtp.socket.timeout:
raise ConnectionError("Socket error while sending message")
``` | In general, you want to use as few try blocks as possible, distinguishing failure conditions by the kinds of exceptions they throw. For instance, here's my refactoring of the code you posted:
```
try:
server = smtplib.SMTP(host)
server.login(username, password) # Only runs if the previous line didn't throw
server.sendmail(addr, [to], msg.as_string())
return True
except smtplib.socket.gaierror:
pass # Couldn't contact the host
except SMTPAuthenticationError:
pass # Login failed
except SomeSendMailError:
pass # Couldn't send mail
finally:
if server:
server.quit()
return False
```
Here, we use the fact that smtplib.SMTP(), server.login(), and server.sendmail() all throw different exceptions to flatten the tree of try-catch blocks. In the finally block we test server explicitly to avoid invoking quit() on the nil object.
We could also use three *sequential* try-catch blocks, returning False in the exception conditions, if there are overlapping exception cases that need to be handled separately:
```
try:
server = smtplib.SMTP(host)
except smtplib.socket.gaierror:
return False # Couldn't contact the host
try:
server.login(username, password)
except SMTPAuthenticationError:
server.quit()
return False # Login failed
try:
server.sendmail(addr, [to], msg.as_string())
except SomeSendMailError:
server.quit()
return False # Couldn't send mail
return True
```
This isn't quite as nice, as you have to kill the server in more than one place, but now we can handle specific exception types different ways in different places without maintaining any extra state. | Correct way of handling exceptions in Python? | [
"",
"python",
"exception",
""
] |
I work on a somewhat large web application, and the backend is mostly in PHP. There are several places in the code where I need to complete some task, but I don't want to make the user wait for the result. For example, when creating a new account, I need to send them a welcome email. But when they hit the 'Finish Registration' button, I don't want to make them wait until the email is actually sent, I just want to start the process, and return a message to the user right away.
Up until now, in some places I've been using what feels like a hack with exec(). Basically doing things like:
```
exec("doTask.php $arg1 $arg2 $arg3 >/dev/null 2>&1 &");
```
Which appears to work, but I'm wondering if there's a better way. I'm considering writing a system which queues up tasks in a MySQL table, and a separate long-running PHP script that queries that table once a second, and executes any new tasks it finds. This would also have the advantage of letting me split the tasks among several worker machines in the future if I needed to.
Am I re-inventing the wheel? Is there a better solution than the exec() hack or the MySQL queue? | I've used the queuing approach, and it works well as you can defer that processing until your server load is idle, letting you manage your load quite effectively if you can partition off "tasks which aren't urgent" easily.
Rolling your own isn't too tricky, here's a few other options to check out:
* [GearMan](http://gearman.org/) - this answer was written in 2009, and since then GearMan looks a popular option, see comments below.
* [ActiveMQ](http://activemq.apache.org/) if you want a full blown open source message queue.
* [ZeroMQ](http://www.zeromq.org/) - this is a pretty cool socket library which makes it easy to write distributed code without having to worry too much about the socket programming itself. You could use it for message queuing on a single host - you would simply have your webapp push something to a queue that a continuously running console app would consume at the next suitable opportunity
* [beanstalkd](http://xph.us/software/beanstalkd/) - only found this one while writing this answer, but looks interesting
* [dropr](https://github.com/s0enke/dropr/wiki/) is a PHP based message queue project, but hasn't been actively maintained since Sep 2010
* [php-enqueue](https://github.com/php-enqueue/enqueue-dev) is a recently (2017) maintained wrapper around a variety of queue systems
* Finally, a blog post about using [memcached for message queuing](http://broddlit.wordpress.com/2008/04/09/memcached-as-simple-message-queue/)
Another, perhaps simpler, approach is to use [ignore\_user\_abort](http://php.net/ignore_user_abort) - once you've sent the page to the user, you can do your final processing without fear of premature termination, though this does have the effect of appearing to prolong the page load from the user perspective. | When you just want to execute one or several HTTP requests without having to wait for the response, there is a simple PHP solution, as well.
In the calling script:
```
$socketcon = fsockopen($host, 80, $errno, $errstr, 10);
if($socketcon) {
$socketdata = "GET $remote_house/script.php?parameters=... HTTP 1.1\r\nHost: $host\r\nConnection: Close\r\n\r\n";
fwrite($socketcon, $socketdata);
fclose($socketcon);
}
// repeat this with different parameters as often as you like
```
On the called script.php, you can invoke these PHP functions in the first lines:
```
ignore_user_abort(true);
set_time_limit(0);
```
This causes the script to continue running without time limit when the HTTP connection is closed. | Run PHP Task Asynchronously | [
"",
"php",
"asynchronous",
"background",
"queue",
"task",
""
] |
I've got a Customer class that has a List`<string`> Roles property. Much of the time I want to access that property *as* a list of strings, but on occasion I want to see it as a comma-delimited list.
I could certainly do that in a new method, and if I anticipated wanting to get the value of the variable in different formats (comma-delimited, tab-delimited, &ct) I would certainly do so. However, I'm toying with the idea of using two different properties to access the variable value, something along the lines of
```
public List<string> Roles
{
get { return this._Roles; }
set { this._Roles = value; }
}
```
and
```
public string RolesToString
{
get { do some work here to comma-delimit the list; }
}
```
Essentially I want to override the ToString() method of this *particular* list. Are there compelling reasons for doing 1 over the other? Is using two different properties to return the same variable value sufficiently non-standard to cause red flags? | I would make your second "property" a method. It's doing additional processing on your list, and returning something that isn't a direct "property" of the object, but more a processed version of the object's property. This seems like a reasonable method candidate.
My preference would be:
```
public List<string> Roles
{
get { return this._Roles; }
set { this._Roles = value; }
}
public string GetRolesAsString()
{
// Do processing on Roles
}
``` | As Reed says it should probably be a Method, but thats kindof subjective.
Note that you don't need much code to do it - just a call to Join()
```
public string RolesAsString()
{
return String.Join(", ", this._Roles);
}
```
And given that string joining is so easy in .NET, do you really need a method/property for it? | using two different public properties to "get" the same private variable with different return types | [
"",
"c#",
"properties",
""
] |
How how do you do this in c#?
```
<TextBlock Text={Binding MyProperty}/>
```
Assume the DataContext is set to a class of Type MyClass | You can call [FrameworkElement.SetBinding()](http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.setbinding.aspx) to build data binding from C#. | Assuming your `TextBlock` is called `_textBlock`:
```
var binding = new Binding("MyProperty");
BindingOperations.SetBinding(_textBlock, TextBlock.TextProperty, binding);
``` | Programmatic databinding | [
"",
"c#",
"wpf",
"xaml",
"mvvm",
""
] |
Is there a cleaner way to write long regex patterns in python? I saw this approach somewhere but regex in python doesn't allow lists.
```
patterns = [
re.compile(r'<!--([^->]|(-+[^->])|(-?>))*-{2,}>'),
re.compile(r'\n+|\s{2}')
]
``` | You can use verbose mode to write more readable regular expressions. In this mode:
* Whitespace within the pattern is ignored, except when in a character class or preceded by an unescaped backslash.
* When a line contains a '#' neither in a character class or preceded by an unescaped backslash, all characters from the leftmost such '#' through the end of the line are ignored.
The following two statements are equivalent:
```
a = re.compile(r"""\d + # the integral part
\. # the decimal point
\d * # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
```
(Taken from the documentation of [verbose mode](http://docs.python.org/library/re.html#re.VERBOSE)) | Though @Ayman's suggestion about `re.VERBOSE` is a better idea, if all you want is what you're showing, just do:
```
patterns = re.compile(
r'<!--([^->]|(-+[^->])|(-?>))*-{2,}>'
r'\n+|\s{2}'
)
```
and Python's automatic concatenation of adjacent string literals (much like C's, btw) will do the rest;-). | Clean Python Regular Expressions | [
"",
"python",
"regex",
"list",
""
] |
How can I make a WPF textbox cut, copy and paste restricted? | Cut, Copy, and Paste are the common commands used any application.
```
<TextBox CommandManager.PreviewExecuted="textBox_PreviewExecuted"
ContextMenu="{x:Null}" />
```
In the above textbox code we can restrict these commands in PreviewExecuted event of CommandManager Class.
In the code behind add the code below and your job is done.
```
private void textBox_PreviewExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (e.Command == ApplicationCommands.Copy ||
e.Command == ApplicationCommands.Cut ||
e.Command == ApplicationCommands.Paste)
{
e.Handled = true;
}
}
``` | The commandName method will not work on a System with Japanese OS as the commandName=="Paste" comparision will fail. I tried the following approach and it worked for me. Also I do not need to disable the context menu manually.
In the XaML file:
```
<PasswordBox.CommandBindings>
<CommandBinding Command="ApplicationCommands.Paste"
CanExecute="CommandBinding_CanExecutePaste"></CommandBinding>
</PasswordBox.CommandBindings>
```
In the code behind:
```
private void CommandBinding_CanExecutePaste(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = false;
e.Handled = true;
}
``` | Make WPF textbox as cut, copy and paste restricted | [
"",
"c#",
"wpf",
"wpf-controls",
""
] |
[webmin](http://www.webmin.com/) is a administration/UI framework for configuring software. I am curious if anyone know what the Java equivalent might be? | since there is no "java operating system" it will be hard to find an exact equivalent.
a good tool for inspecting and configuring a *single JVM* is the JMX protocol and its clients [visualvm](https://visualvm.dev.java.net/) and the [Jconsole](http://java.sun.com/j2se/1.5.0/docs/guide/management/jconsole.html) | Webmin looks to be by definition absolutely platform dependant (at least to Unix systems). A Java equivalent would make no sense - sure, you could write such a tool in Java, but it would not be portable and probably require significant amounts of non-Java code to access platform specific APIs | What is the Java equivalent to webmin? | [
"",
"java",
"linux",
"apache",
"configuration",
"frameworks",
""
] |
How can I determine by reflection if the type of an object is defined by a class in my own assembly or by the .NET Framework?
I dont want to supply the name of my own assembly in code, because it should work with any assembly and namespace. | Where would third-party types come in? You might want to differentiate between types which claim to be provided by Microsoft and types which don't.
```
using System;
using System.Linq;
using System.Reflection;
class Test
{
static void Main()
{
Console.WriteLine(IsMicrosoftType(typeof(string)));
Console.WriteLine(IsMicrosoftType(typeof(Test)));
}
static bool IsMicrosoftType(Type type)
{
object[] attrs = type.Assembly.GetCustomAttributes
(typeof(AssemblyCompanyAttribute), false);
return attrs.OfType<AssemblyCompanyAttribute>()
.Any(attr => attr.Company == "Microsoft Corporation");
}
}
```
Of course, any type could *claim* to be a Microsoft one given this scheme, but if you're actually only going to call it on your own types and framework ones, I suspect this should work fine.
Alternatively, you could use the assembly's public key token. This is likely to be harder to fake. It relies on Microsoft using a common public key for all their assemblies, which they don't (according to Mehrdad's comment below). However, you could easily adapt this solution for a *set* of accepted "this is from Microsoft" public keys. Perhaps combine the two approaches somehow and report any differences for further inspection...
```
static bool IsMicrosoftType(Type type)
{
AssemblyName name = type.Assembly.GetName();
byte[] publicKeyToken = name.GetPublicKeyToken();
return publicKeyToken != null
&& publicKeyToken.Length == 8
&& publicKeyToken[0] == 0xb7
&& publicKeyToken[1] == 0x7a
&& publicKeyToken[2] == 0x5c
&& publicKeyToken[3] == 0x56
&& publicKeyToken[4] == 0x19
&& publicKeyToken[5] == 0x34
&& publicKeyToken[6] == 0xe0
&& publicKeyToken[7] == 0x89;
}
``` | Based on Jon's answer and Mehrdad's comment, it appears that the following three values are used for the public key token (from AssemblyName.FullName) for the .NET Framework provided assemblies from .NET 2.0 and later:
**PublicKeyToken=b77a5c561934e089**
* mscorlib
* System.Data
* System.Data.OracleClient
* System.Data.SqlXml
* System
* System.Runtime.Remoting
* System.Transactions
* System.Windows.Forms
* System.Xml
* SMDiagnostics
* System.Runtime.Serialization
* System.ServiceModel
* System.ServiceModel.Install
* System.ServiceModel.WasHosting
**PublicKeyToken=b03f5f7f11d50a3a**
* Accessibility
* AspNetMMCExt
* cscompmgd
* CustomMarshalers
* IEExecRemote
* IEHost
* IIEHost
* ISymWrapper
* Microsoft.Build.Conversion
* Microsoft.Build.Engine
* Microsoft.Build.Framework
* Microsoft.Build.Tasks
* Microsoft.Build.Utilities
* Microsoft.JScript
* Microsoft.VisualBasic.Compatibility.Data
* Microsoft.VisualBasic.Compatibility
* Microsoft.VisualBasic
* Microsoft.VisualBasic.Vsa
* Microsoft.VisualC
* Microsoft.Vsa
* Microsoft.Vsa.Vb.CodeDOMProcessor
* Microsoft\_VsaVb
* sysglobl
* System.Configuration
* System.Configuration.Install
* System.Deployment
* System.Design
* System.DirectoryServices
* System.DirectoryServices.Protocols
* System.Drawing.Design
* System.Drawing
* System.EnterpriseServices
* System.Management
* System.Messaging
* System.Runtime.Serialization.Formatters.Soap
* System.Security
* System.ServiceProcess
* System.Web
* System.Web.Mobile
* System.Web.RegularExpressions
* System.Web.Services
* Microsoft.Transactions.Bridge
* Microsoft.Transactions.Bridge.Dtc
* Microsoft.Build.Tasks.v3.5
* Microsoft.CompactFramework.Build.Tasks
* Microsoft.Data.Entity.Build.Tasks
* Microsoft.VisualC.STLCLR
* Sentinel.v3.5Client
**PublicKeyToken=31bf3856ad364e35**
* PresentationCFFRasterizer
* PresentationUI
This was generated from the following code:
```
private void PrintAssemblyInfo(string fullName)
{
string[] parts = fullName.Split(',');
Console.WriteLine(" - {0}, {1}", parts[0], parts[3]);
}
private void GenerateInfo(string path)
{
foreach (var file in Directory.GetFiles(path,
"*.dll",
SearchOption.AllDirectories))
{
try
{
Assembly assembly = Assembly.ReflectionOnlyLoadFrom(file);
PrintAssemblyInfo(assembly.GetName().FullName);
}
catch { }
}
}
private void GenerateInfo()
{
GenerateInfo(@"C:\Windows\Microsoft.NET\Framework\v2.0.50727");
GenerateInfo(@"C:\Windows\Microsoft.NET\Framework\v3.0");
GenerateInfo(@"C:\Windows\Microsoft.NET\Framework\v3.5");
}
``` | Detect if the type of an object is a type defined by .NET Framework | [
"",
"c#",
".net",
"reflection",
""
] |
i wanna inherit QLabel to add there click event processing.
I'm trying this code:
```
class NewLabel(QtGui.QLabel):
def __init__(self, parent):
QtGui.QLabel.__init__(self, parent)
def clickEvent(self, event):
print 'Label clicked!'
```
But after clicking I have no line 'Label clicked!'
**EDIT:**
Okay, now I'm using not 'clickEvent' but 'mousePressEvent'. And I still have a question. How can i know what exactly label was clicked? For example, i have 2 edit box and 2 labels. Labels content are pixmaps. So there aren't any text in labels, so i can't discern difference between labels. How can i do that?
**EDIT2:**
I made this code:
```
class NewLabel(QtGui.QLabel):
def __init__(self, firstLabel):
QtGui.QLabel.__init__(self, firstLabel)
def mousePressEvent(self, event):
print 'Clicked'
#myLabel = self.sender() # None =)
self.emit(QtCore.SIGNAL('clicked()'), "Label pressed")
```
In another class:
```
self.FirstLang = NewLabel(Form)
QtCore.QObject.connect(self.FirstLang, QtCore.SIGNAL('clicked()'), self.labelPressed)
```
Slot in the same class:
```
def labelPressed(self):
print 'in labelPressed'
print self.sender()
```
But there isn't sender object in self. What i did wrong? | Answering your second question, I'll continue based on @gnud example:
* subclass QLabel, override mouseReleaseEvent and add a signal to the class, let's call it clicked.
* check which button was clicked in mouseReleaseEvent, if it's the left one emit the clicked signal.
* connect a slot to your labels clicked signal and use [sender()](http://doc.trolltech.com/4.5/qobject.html#sender) inside to know which QLabel was clicked. | There is no function `clickEvent` in QWidget/QLabel. You could connect that function to a Qt signal, or you could do:
```
class NewLabel(QtGui.QLabel):
def __init__(self, parent=None):
QtGui.QLabel.__init__(self, parent)
self.setText('Lorem Ipsum')
def mouseReleaseEvent(self, event):
print 'Label clicked!'
``` | PyQt - QLabel inheriting | [
"",
"python",
"qt",
"inheritance",
"pyqt",
"label",
""
] |
If I have some text in a String, how can I copy that to the clipboard so that the user can paste it into another window (for example, from my application to Notepad)? | You can use `System.Windows.Forms.Clipboard.SetText(...)`. | [`System.Windows.Forms.Clipboard.SetText`](http://msdn.microsoft.com/en-us/library/ydby206k.aspx) (Windows Forms) or [`System.Windows.Clipboard.SetText`](http://msdn.microsoft.com/en-us/library/ms597043.aspx) (WPF) | How do I copy the contents of a String to the clipboard in C#? | [
"",
"c#",
".net",
"clipboard",
""
] |
Whenever a new user signs up on my site, I want to do some pre-processing to shorten their searches in the future. This involves anywhere from 30 to 2 minutes processing time. Obviously I cannot do this when they click the submit button on signup... or on any PHP page they visit. However, I would like this done within 5 minutes of them signing up (or less).
**Cron Route**
I THINK this needs to be in a cron job, and if so, how should I setup the cron job? If so, what should my cron line look like to run every 2 minutes, and how can I insure that I don't have the same cron job overlapping the next?
**Event/Fork Route - Preferred**
If I can possibly throw some event to my server without disrupting my users experience or fork a process off of the users signup (instead of a cron job) how could I do this? | I would recommend neither solution.
Instead, you would be best off with a long running process (daemon) that gets its jobs from a [message queue](http://en.wikipedia.org/wiki/Message_queue). The message queue itself could be off a database if that is your preferred method.
You will post an identifier for the job to your database, and then a long running process will iterate through them once in a while and act upon them.
This is as simple as:
```
<?php
while(true) {
jobs = getListOfJobsFromDatabase(); // get the jobs from the databbase
foreach (jobs as job) {
processAJob(job); // do whatever needs to be done for the job
deleteJobFromDatabase(job); //remember to delete the job once its done!
}
sleep(60); // sleep for a while so it doesnt thrash your database when theres nothing to do
}
?>
```
And just run that script from the command line.
The benefits of this over a cron job are that you wont get a race condition.
You may also want to fork off the actually processing of the jobs so many can be done in parallel, rather than processing sequentially. | You can use the following class to invoke a background PHP task.
```
class BackgroundProcess {
static function open($exec, $cwd = null) {
if (!is_string($cwd)) {
$cwd = @getcwd();
}
@chdir($cwd);
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
$WshShell = new COM("WScript.Shell");
$WshShell->CurrentDirectory = str_replace('/', '\\', $cwd);
$WshShell->Run($exec, 0, false);
} else {
exec($exec . " > /dev/null 2>&1 &");
}
}
static function fork($phpScript, $phpExec = null) {
$cwd = dirname($phpScript);
if (!is_string($phpExec) || !file_exists($phpExec)) {
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
$phpExec = str_replace('/', '\\', dirname(ini_get('extension_dir'))) . '\php.exe';
if (@file_exists($phpExec)) {
BackgroundProcess::open(escapeshellarg($phpExec) . " " . escapeshellarg($phpScript), $cwd);
}
} else {
$phpExec = exec("which php-cli");
if ($phpExec[0] != '/') {
$phpExec = exec("which php");
}
if ($phpExec[0] == '/') {
BackgroundProcess::open(escapeshellarg($phpExec) . " " . escapeshellarg($phpScript), $cwd);
}
}
} else {
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
$phpExec = str_replace('/', '\\', $phpExec);
}
BackgroundProcess::open(escapeshellarg($phpExec) . " " . escapeshellarg($phpScript), $cwd);
}
}
}
```
Use as such:
```
BackgroundProcess::fork('process_user.php');
``` | PHP- Need a cron for back site processing on user signup... (or fork process) | [
"",
"php",
"apache",
"cron",
""
] |
Take this code:
```
using System;
namespace OddThrow
{
class Program
{
static void Main(string[] args)
{
try
{
throw new Exception("Exception!");
}
finally
{
System.Threading.Thread.Sleep(2500);
Console.Error.WriteLine("I'm dying!");
System.Threading.Thread.Sleep(2500);
}
}
}
}
```
Which gives me this output:
```
Unhandled Exception: System.Exception: Exception!
at OddThrow.Program.Main(String[] args) in C:\Documents and Settings\username
\My Documents\Visual Studio 2008\Projects\OddThrow\OddThrow\Program.cs:line 14
I'm dying!
```
My question is: why does the unhandled exception text occur before the finally's? In my mind, the finally should be excuted as the stack unwinds, before we even **know** that this exception is unhandled. Note the calls to Sleep() - these occur *after* the unhandled exception is printed, as if it was doing this following:
1. Unhandled exception text/message
2. Finally blocks.
3. Terminate application
According to the C# standard, §8.9.5, this behaviour is wrong:
* In the current function member, each try statement that encloses the throw point is examined. For each statement S, starting with the innermost try statement and ending with the outermost try statement, the following steps are evaluated:
* + If the try block of S encloses the throw point and if S has one or more catch clauses, the catch clauses are examined in order of appearance to locate a suitable handler for the exception. The first catch clause that specifies the exception type or a base type of the exception type is considered a match. A general catch clause (§8.10) is considered a match for any exception type. If a matching catch clause is located, the exception propagation is completed by transferring control to the block of that catch clause.
* + Otherwise, if the try block or a catch block of S encloses the throw point and if S has a finally block, control is transferred to the finally block. If the finally block throws another exception, processing of the current exception is terminated. Otherwise, when control reaches the end point of the finally block, processing of the current exception is continued.
* If an exception handler was not located in the current function member invocation, the function member invocation is terminated. The steps above are then repeated for the caller of the function member with a throw point corresponding to the statement from which the function member was invoked.
* If the exception processing terminates all function member invocations in the current thread, indicating that the thread has no handler for the exception, then the thread is itself terminated. The impact of such termination is implementation-defined.
Where am I going wrong? (I've got some custom console error messages, and this is in-the-way. Minor, just annoying, and making me question the language...) | The standard's statements about the order of execution are correct, and not inconsistent with what you are observing. The "Unhandled exception" message is allowed to appear at *any* point in the process, because it is just a message from the CLR, not actually an exception handler itself. The rules about order of execution only apply to code being executed inside the CLR, not to what the CLR itself does.
What you've actually done is expose an implementation detail, which is that unhandled exceptions are recognised by looking at a stack of which try{} blocks we are inside, rather than by actually exploring all the way to the root. Exceptions may or may not be *handled* by looking at this stack, but unhandled exceptions are recognised this way.
As you may be aware, if you put a top-level try{}catch{} in your main function, then you will see the behaviour you expect: each function's finally will be executed before checking the next frame up for a matching catch{}. | I could be way off base in the way I'm reading things...but you have a try finally block without a catch.
Juding by the description you posted, since the Exception is never caught, it bubbles up to the caller, works it's way up through the stack, is eventually unhandled, the call terminates, and then the finally block is called. | C# Time of finally execution | [
"",
"c#",
"exception",
"finally",
""
] |
I have a temporary table, that isn't going away. I want to see what is in the table to determine what bad data might be in there. How can I view the data in the temporary table?
I can see it in `tempdb`. I ran
```
SELECT * FROM tempdb.dbo.sysobjects WHERE Name LIKE '#Return_Records%'
```
to get the name of the table.
I can see it's columns and its object id in
```
select c.*
from tempdb.sys.columns c
inner join tempdb.sys.tables t ON c.object_id = t.object_id
where t.name like '#Return_Records%'
```
How can I get at the data?
By the way, this doesn't work
```
SELECT * FROM #Return_Records
``` | One way of getting at the data in a low-level and not particularly easy to manipulate manner is to use the DBCC PAGE command as described in a blog post by Paul Randal:
<http://blogs.msdn.com/sqlserverstorageengine/archive/2006/06/10/625659.aspx>
You should be able to find the fileid and page number of the first page in the object by querying on sysindexes .. the last time I did this was on SQL Server 7.
If the data is in the database, then DBCC page will be able to dump it.
pjjH | SQL Server limits access to Local Temp Tables (#TableName) to the connection that created the table. Global temp tables (##TableName) can be accessible by other connections as long as the connection that created it is still connected.
Even though you can see the table in the table catalog, it is not accessible when trying to do a SELECT. It gives you an "Invalid Object Name" error.
There's no documented way of accessing the data in Local Temp Tables created by other connections. I think you may be out of luck in this case. | Export/View data from a SQL Server temporary table | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
How do I exit a `while` loop immediately without going to the end of the block?
For example,
```
while (choice != 99)
{
cin >> choice;
if (choice == 99)
//Exit here and don't get additional input
cin>>gNum;
}
```
Any ideas? | Use break?
```
while(choice!=99)
{
cin>>choice;
if (choice==99)
break;
cin>>gNum;
}
``` | ```
cin >> choice;
while(choice!=99) {
cin>>gNum;
cin >> choice
}
```
You don't need a break, in that case. | Immediate exit of 'while' loop in C++ | [
"",
"c++",
"while-loop",
"break",
""
] |
ok; i am making a project for school and its a game similar to falling sand. but in order for the gravity to work i have to have the sand sorted by its position from down to up (the y variable of sand) this method should sort it; although i cannot get .clone() to work and i can't hard copy any other way i know. so i don't know how to replace all the comments in this code with something that will do what they say.
to explain how i want this to work; i want it to, one by one, remove elements from world while i place them sorted in sorted.
```
public void sort(){
//method to sort elements by y value
ArrayList<sand> sorted=new ArrayList<sand>();
if(world.size()!=0){
//code to take 0 from world and place it into sorted at 0
while(world.size()>0){
boolean check=true;
for(int i=0;i<sorted.size();i++){
if(world.get(0).y<sorted.get(i).y){
//code to take 0 from world and place it into sorted at i
check=false;
}
}
if(check){
//code to take 0 from world and place it at the end
}
}
}
//code to make sorted the contents of world
}
```
the error i am getting with clone is:
```
awesomesand.java:48: clone() has protected access in java.lang.Object
sand a=world.get(0).clone();
```
and, yes world is of type sand.
---
EDIT
now i am getting an error on cloning.
```
awesomesand.java:48: incompatible types
found : java.lang.Object
required: awesomesand.sand
sand a=world.get(0).clone();
^
``` | You are getting the clone exception because it has protected access in `Object`. However, sorting an ArrayList does not need `clone()` if you invoke the standard sorting mechanisms of [Collections](http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html#sort%5C(java.util.List,java.util.Comparator%5C)).
As for why you're getting the clone error, a class must override `clone()` with public access. This is to assure that you handle the specifics of your class:
```
public class Sand implements Cloneable {
public Object clone() throws CloneNotSupportedException {
Sand copy = (Sand) super.clone();
// Sand specific copying done here
return copy;
}
}
```
However, easier, more efficient, and more likely correct, is to just sort the collection of sand objects directly. Here I've defined a possible version of Sand, and show the use of Collections.sort:
```
public class Sand {
public int x;
public int y;
}
public class SandComparator implements Comparator<Sand> {
public int compare(Sand s1, Sand s2) {
// reverse these to sort in the opposite order
return s1.y - s2.y;
}
public boolean equals(Object o) {
return o instanceof SandComparator;
}
}
public class App {
ArrayList<Sand> world;
...
public void sort() {
Collections.sort(world, new SandComparator());
}
}
``` | If I understand this correctly, I think you want to just sort an array. If that's the case, I don't think clone is really necessary.
Perhaps you could try using a Comparator and the Collections.sortList() method to sort your world array into the right order (where the order is determined by the implementation of the Comparator). If you need to use a different array instead of world, you could simply make a copy of world first, using the appropriate ArrayList copy constructor, or System.arraycopy, and then sort that array instead. | sorting an arraylist of a self-made class by one of its variables and clone() will not work | [
"",
"java",
"sorting",
""
] |
I want to make an Applet write to a text file. I think have overcome the security problem with my own certificate, but the text file isn't receiving the output.
My Applet can be seen at [tomrenn.com/fallball](http://tomrenn.com/fallball), and should ask if you trust the certificate.
I'm not sure an Applet can write to a text file within the web hosted contents, so I'm asking if this is possible; and if not, at least be able to do it on the local machine. I had been using a `FileOutputStream`, but my teacher recommended this very basic output method.
```
public void writeToFile()
{
try {
java.io.File file = new java.io.File("highscores.txt");
java.io.PrintWriter output = new java.io.PrintWriter(file);
output.print(name + " " +score);
output.close();
} catch (IOException e) {
System.err.println ("Unable to write to file");
System.exit(-1);
}
}
```
This is not what I would be implementing, just trying to see if I get any output. Thanks for looking over my question! | From an Applet, you cannot directly write to the server's file system. You can issue a request to the server that causes the server to write to its own file system, but an Applet does not have a way to write to a file system on a remote machine. (Of course, unless it's mounted NFS or otherwise.) To issue such a request, you could use [Apache HttpClient](http://hc.apache.org/httpclient-3.x/) to issue HTTP requests, for example. This may be more heavyweight than you are looking for. You can also have the client issue a POST to the server to say, "This is my high score," and let the server manage high scores.
A signed Applet has every right to write to the local file system of the person running the Applet. If you are writing to the "current directory" (rather than an absolute full path), then make sure you know what directory the Applet is running in. Otherwise you may indeed create a file, but not be able to find it! | If you want an applet to store data on the local machine, from 6u10 the `javax.jnlp.PersistenceService` is available. Creating a secure "signed applet" is difficult, and I wouldn't recommend it to anyone. | Signed Java Applet writing to a text file | [
"",
"java",
"file",
"text",
"applet",
"signed-applet",
""
] |
I'm working on a script that takes the elements from `companies` and pairs them up with the elements of `people`. The goal is to optimize the pairings such that the sum of all pair values is maximized (the value of each individual pairing is precomputed and stored in the dictionary `ctrPairs`).
They're all paired in a 1:1, each company has only one person and each person belongs to only one company, and the number of companies is equal to the number of people. I used a top-down approach with a memoization table (`memDict`) to avoid recomputing areas that have already been solved.
I believe that I could vastly improve the speed of what's going on here but I'm not really sure how. Areas I'm worried about are marked with `#slow?`, any advice would be appreciated (the script works for inputs of lists n<15 but it gets incredibly slow for n > ~15)
```
def getMaxCTR(companies, people):
if(memDict.has_key((companies,people))):
return memDict[(companies,people)] #here's where we return the memoized version if it exists
if(not len(companies) or not len(people)):
return 0
maxCTR = None
remainingCompanies = companies[1:len(companies)] #slow?
for p in people:
remainingPeople = list(people) #slow?
remainingPeople.remove(p) #slow?
ctr = ctrPairs[(companies[0],p)] + getMaxCTR(remainingCompanies,tuple(remainingPeople)) #recurse
if(ctr > maxCTR):
maxCTR = ctr
memDict[(companies,people)] = maxCTR
return maxCTR
``` | To all those who wonder about the use of learning theory, this question is a good illustration. The right question is not about a "fast way to bounce between lists and tuples in python" — the reason for the slowness is something deeper.
What you're trying to solve here is known as the [assignment problem](http://en.wikipedia.org/wiki/Assignment_problem): given two lists of n elements each and n×n values (the value of each pair), how to assign them so that the total "value" is maximized (or equivalently, minimized). There are several algorithms for this, such as the [Hungarian algorithm](http://en.wikipedia.org/wiki/Hungarian_algorithm) ([Python implementation](http://www.clapper.org/software/python/munkres/)), or you could solve it using more general min-cost flow algorithms, or even cast it as a linear program and use an LP solver. Most of these would have a running time of O(n3).
What your algorithm above does is to try each possible way of pairing them. (The memoisation only helps to avoid recomputing answers for pairs of subsets, but you're still looking at all pairs of subsets.) This approach is at least Ω(n222n). For n=16, n3 is 4096 and n222n is 1099511627776. There are constant factors in each algorithm of course, but see the difference? :-) (The approach in the question is still better than the naive O(n!), which would be much worse.) Use one of the O(n^3) algorithms, and I predict it should run in time for up to n=10000 or so, instead of just up to n=15.
"Premature optimization is the root of all evil", as Knuth said, but so is delayed/overdue optimization: you should first carefully consider an appropriate algorithm before implementing it, not pick a bad one and then wonder what parts of it are slow. :-) Even badly implementing a good algorithm in Python would be orders of magnitude faster than fixing all the "slow?" parts of the code above (e.g., by rewriting in C). | i see two issues here:
1. efficiency: you're recreating the same `remainingPeople` sublists for each company. it would be better to create all the `remainingPeople` and all the `remainingCompanies` once and then do all the combinations.
2. memoization: you're using tuples instead of lists to use them as `dict` keys for memoization; but tuple identity is order-sensitive. IOW: `(1,2) != (2,1)` you better use `set`s and `frozenset`s for this: `frozenset((1,2)) == frozenset((2,1))` | How to tractably solve the assignment optimisation task | [
"",
"python",
"algorithm",
"optimization",
"dynamic-programming",
""
] |
I have a PHP script that needs to be run at certain times every weekday. Is `cron` or Windows task scheduler the only way to do this?
Is there a way to set this up from within another PHP script? | Depends how exact the timing needs to be. A technique I've seen used (dubbed "poor man's cron") is to have a frequently accessed script (a site's home page, for example) fire off a task on the first page load after a certain time (kept track of in the database).
If you need any sort of guaranteed accuracy, though, cron or a Windows scheduled task is really the best option. If your host doesn't support them, it's time to get a better one. | Apart from `cron` or `Scheduled Tasks`, you can have your PHP script to always run it. The process should sleep (within a loop) until the time has reached. Then, the process could execute the remaining functions/methods. Or, you can set up another script (which will act as a daemon) to check for the time and execute the other script. | What options are there for executing a PHP script at a certain time every day? | [
"",
"php",
"cron",
""
] |
What does this from General Recommandation #3 mean?
> Don't control the execution of worker
> threads from your main program (using
> events, for example). Instead, design
> your program so that worker threads
> are responsible for waiting until work
> is available, executing it, and
> notifying other parts of your program
> when finished. If your worker threads
> do not block, consider using thread
> pool threads. Monitor.PulseAll is
> useful in situations where worker
> threads block.
Can someone explain by examples please?
-- Source: [MSDN - Managed Threading Best Practices](http://msdn.microsoft.com/en-us/library/1c9txz50.aspx) | Well, there are basically two ways you can dole out work to your worker threads. The first is to store work items in a queue. When you have work to do, you push it onto the queue and signal the workers. Your worker threads would look something like this:
```
while( !quit ) {
WaitForWork();
GetWorkItem();
ExecuteWorkItem();
}
```
This is the approach you're supposed to take, according to the recommendation.
The other approach is to maintain a queue of workers. When you have work that you need to do, you grab a worker from the queue (or create one if its empty) and tell it to run the item. This second approach is more difficult to code and is generally less efficient. | I take this to mean that you shouldn't manually create worker threads to handle tasks (e.g. save a file), but rather have a system in place (or use [ThreadPool.QueueUserWorkItem](http://msdn.microsoft.com/en-us/library/system.threading.threadpool.queueuserworkitem.aspx)) where you can enqueue a task/job and an existing worker is waiting for a task to arrive (perhaps using a monitor Wait or an AutoResetEvent). Doing it this way means you can re-use threads rather than having to constantly create and destroy them.
.NET 4.0 has a new built-in [Task](http://msdn.microsoft.com/en-us/library/system.threading.tasks(VS.100).aspx) class with a bunch of supporting classes to make this style of programming easier so that you don't have to re-invent this in each project. | Managed Threading General Recommendation #3 | [
"",
"c#",
".net",
"multithreading",
"msdn",
""
] |
I saw an [answer to a question regarding timing](https://stackoverflow.com/questions/890847/uint64-utc-time) which used \_\_sync\_synchronize().
* What does this function do?
* And when is it necessary to be used? | It is a atomic builtin for [full memory barrier](http://gcc.gnu.org/onlinedocs/gcc-4.6.2/gcc/Atomic-Builtins.html).
> No memory operand will be moved across the operation, either forward
> or backward. Further, instructions will be issued as necessary to
> prevent the processor from speculating loads across the operation and
> from queuing stores after the operation.
Check details on the link above. | It forces a [memory fence](http://en.wikipedia.org/wiki/Memory_fence) I guess. | What does __sync_synchronize do? | [
"",
"c++",
"c",
"linux",
""
] |
I can get it as a string:
```
Assembly.GetExecutingAssembly().GetName().Version()
```
How can I convert this number to an int?
---
### Example input:
> 8.0.0.1
### Expected output:
> 8001 | If you really have to do this conversion, you should at least reserve **an adequate amount of digits** for every version part.
Two digits for Major, Minor and Revision and four for Build:
```
var version = Assembly.GetExecutingAssembly().GetName().Version();
Debug.Assert(version.Major >= 0 && version.Major < 100)
Debug.Assert(version.Minor >= 0 && version.Minor < 100)
Debug.Assert(version.Build >= 0 && version.Build < 10000)
Debug.Assert(version.Revision >= 0 && version.Revision < 100)
long longVersion = version.Major * 100000000L +
version.Minor * 1000000L +
version.Build * 100L +
version.Revision;
int intVersion = (int) longVersion;
Debug.Assert((long)intVersion == longVersion)
```
*Note that this method will still fail for some exotic versions!*
Don't even think about version 21.47.4836.48 :)
**EDIT:** Added assertions. | They are numbers, so you could just convert them to strings and stack them after each other:
```
Version v = Assembly.GetExecutingAssembly().GetName().Version;
string compacted = string.Format("{0}{1}{2}{3}", v.Major, v.Minor, v.Build, v.Revision);
int compactInt = int.Parse(compacted);
```
This of course only works well as long as each component is less than ten. After that you can't determine what the actual version is. The string "12345" can be 1.23.4.5 or 12.3.4.5 or 1.2.34.5 or...
If you know that they are all below ten, you could do it numerically:
```
Version v = Assembly.GetExecutingAssembly().GetName().Version;
int compactInt = v.Major * 1000 + v.Minor * 100 + v.Build * 10 + v.Revision;
```
If you don't know that, it gets a bit more complicated, but you can still do it without creating a string and parse it. It would be a bit faster, but it's 10 - 20 lines of code. | How can I get the assembly version as a integer in C#? | [
"",
"c#",
".net",
""
] |
Working on a PHP /html content management system and found Free RTE online which is a free rich text editor.
Have no idea how to integrate it into my own stuff.
There are sample codes with it alrite, but they are not very clear.
Anyone used it before or have any knowledge of integrating it??? | I haven't but i use <http://www.ecardmax.com/index.php?step=Hoteditor> which is in my opinion nice and easy to use, if it helps | RTE are usually very simple to embed. The process is to give an ID to your textarea and then initialize your RTE through Javascript calling for this textarea's ID. Javascript will transform this textarea into a fully-featured RTE on page load.
Usually well documented on RTE's examples and howtos. Which one are you using? | Free RTE [Rich text editor] help needed integrating it | [
"",
"php",
"html",
"rte",
""
] |
I'm playing around with a Python application on CentOS 5.2.
It uses the Boto module to communicate with Amazon Web Services, which requires communication through a HTTPS connection.
When I try running my application I get an error regarding HTTPSConnection being missing:
"AttributeError: 'module' object has no attribute 'HTTPSConnection'"
Google doesn't really return anything relevant, I've tried most of the solutions but none of them solve the problem.
Has anyone come across anything like it?
Here's the traceback:
```
Traceback (most recent call last):
File "./chatter.py", line 114, in <module>
sys.exit(main())
File "./chatter.py", line 92, in main
chatter.status( )
File "/mnt/application/chatter/__init__.py", line 161, in status
cQueue.connect()
File "/mnt/application/chatter/tools.py", line 42, in connect
self.connection = SQSConnection(cConfig.get("AWS", "KeyId"), cConfig.get("AWS", "AccessKey"));
File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/sqs/connection.py", line 54, in __init__
self.region.endpoint, debug, https_connection_factory)
File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/connection.py", line 418, in __init__
debug, https_connection_factory)
File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/connection.py", line 189, in __init__
self.refresh_http_connection(self.server, self.is_secure)
File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/connection.py", line 247, in refresh_http_connection
connection = httplib.HTTPSConnection(host)
AttributeError: 'module' object has no attribute 'HTTPSConnection'
``` | citing from the python documentation (<http://docs.python.org/library/httplib.html>):
**Note** HTTPS support is only available if the socket module was compiled with SSL support.
You should find out how python on the CentOS you are using was built. | Please install openssl and openssl-devel before you install python2.6.
You can simply install those packages using yum, and do a re-install of python2.6 (no need to remove already installed python2.6)
```
]# yum install openssl openssl-devel
Python-2.6.x]# ./configure
Python-2.6.x]# make && make altinstall
``` | HTTPSConnection module missing in Python 2.6 on CentOS 5.2 | [
"",
"python",
"centos",
""
] |
I'm working at a complex script which could be processing upto 500,000 records. Here's my question.
Basically my code will parse a text file to get each of those 500,000 or so records. Each record will have a category, my code will need to check if a new record in the `categories` table had been created for that category during that particular processing, and if not, it will create that record.
So I have 2 options:
1) I store an array of keys=>values containing category name and ID, so I could do this:
```
if (array_key_exists($category,$allCategories))
$id=$allCategories[$category];
else
{
mysql_query("INSERT INTO categories (procId,category)
VALUES ('$procId''$category')");
$id=mysql_insert_id();
$allCategories[$category]=$id;
}
```
2) Each time this text file is processed, it will get its own process ID. So rather than checking the `$allCategories` variable which could grow to have 100,000+ entries, I could do this:
```
SELECT id FROM categories WHERE procId='$procId' AND category='$category'
```
The downside here is that this query will be run for each of the 500,000+ records. Whereas the disadvantage of holding all the categories in an array is that I could run out of memory or the server could crash.
Any thoughts? | Can you just keep a list of the ids that you've already inserted? If they are integer ids, that's 4 bytes each times 100,000 entries would use only about 400K of memory.
ETA:
To avoid storing the category name, hash the name and store the hash. With a 128 bit MD5 hash, that's 16 bytes per hash or only about 1.6MB of memory + overhead. | Given that your average category name is 30 bytes, you'd only need 30 \* 500000 bytes = 15000000 bytes = 15000 kilobytes = 1.5 megabytes.
I think you have this much memory. | Memory / Optimization concern | [
"",
"php",
"mysql",
"optimization",
"memory-management",
""
] |
I am using VSTS 2008 with C# to develop Silverlight application embedded in web page of an ASP.Net web application. I have embedded in XAML a MediaElement item. My question is, I want to embed the page a Silverlight media player, which could let end user to control the MediaElement item manually to -- play/pause/stop/rewind/forward. Are there any references samples?
thanks in advance,
George
EDIT1: add more accurate requirements,
Actually, I want to control play manually, which means I want to handle the player play/pause/stop/rewind/forward events and add my code for the event handlers to control the MediaElement and do something else.
EDIT2: My needs are, I want to play two overlapped video. Screen as background video and camera as foreground video (place at right bottom corner). Here is my modification of code, my current issue is, only background video is played, foreground right bottom video is never played. Does anyone have any ideas why?
BTW: my modified code and current work is based on <http://www.codeplex.com/sl2videoplayer>
<http://www.yourfilehost.com/media.php?cat=other&file=sl2videoplayer_24325_new.zip>
Here is a brief description of my major modified code,
mediaControls.xaml.cs
```
private MediaElement _media = null;
private MediaElement _camera = null;
public MediaElement Camera
{
set
{
_camera = value;
}
}
void btnPlay_Checked(object sender, RoutedEventArgs e)
{
_camera.Play();
_media.Play();
OnPlayClicked();
}
```
Page.xaml
```
<MediaElement HorizontalAlignment="Stretch" Margin="0,0,0,0" x:Name="mediaPlayer" Stretch="Uniform" VerticalAlignment="Stretch" AutoPlay="false"/>
<MediaElement Width="100" Height="100" x:Name="cameraPlayer" AutoPlay="false" HorizontalAlignment="Right" VerticalAlignment="Bottom"/>
```
Page.xaml.cs
```
cameraPlayer.Source = App.Current.Resources["c"] as Uri;
```
App.xaml.cs (Application\_Startup function)
```
else if (item.Key.ToLower() == "c")
{
FormatUri(e.InitParams["c"].ToString(), "c", false);
}
```
default.html
```
<param name="initParams" value="cc=true,markers=true,markerpath=markers_movie21.xml,m=http://localhost/screen.wmv,c=http://localhost/camera.wmv" />
``` | Oh baby have I got the media player for you: [Sl2 Video Player](http://www.codeplex.com/sl2videoplayer). MSPL open sourced and awesome.
To add the ability to control the player pragmatically, add ScriptableMembers.
You'll see the registration statement already in the code:
```
HtmlPage.RegisterScriptableObject("Page", page);
```
Now look at an example ScriptableMember:
```
[ScriptableMember]
public void SeekPlayback(string time)
{
TimeSpan tsTime = TimeSpan.Parse(time);
mediaControls.Seek(tsTime);
}
```
already exists in the code. Add more methods to do what you want to have happen. Then you can call the methods from managed code in another SL player:
```
HtmlElement videoPlugin = HtmlPage.Document.GetElementById("VideoPlayer");
if (videoPlugin != null)
{
ScriptObject mediaPlayer = (ScriptObject)((ScriptObject)videoPlugin.GetProperty("Content")).GetProperty("Page");
mediaPlayer.Invoke("SeekPlayback", TimeSpan.FromSeconds(seconds).ToString());
}
```
or from javascript:
```
var sl = document.getElementById("VideoPlayer");
var content = sl.Content.Page;
content.SeekPlayback('55');
``` | If they are two seperate xap packages, there will be no way for the two to communicate since Silverlight sandboxes both individually. | Silverlight media player | [
"",
"c#",
"silverlight",
"xaml",
"media-player",
""
] |
I want my (ExtJS) toolbar buttons **not** to grab the focus on the web page when they are clicked, but to do their "thing" while leaving the focus unchanged by the click. How do I do that? | Cancelling the default behavior of `onmousedown` prevents an element from getting the focus:
```
// Prevent capturing focus by the button.
$('button').on('mousedown',
/** @param {!jQuery.Event} event */
function(event) {
event.preventDefault();
}
);
``` | document.activeElement stores the currently focussed element.
So on your toolbar, you can add a "mousedown" handler to this function :
```
function preventFocus() {
var ae = document.activeElement;
setTimeout(function() { ae.focus() }, 1);
}
```
Try this example :
```
<html>
<head>
<script>
function preventFocus() {
var ae = document.activeElement;
setTimeout(function() { ae.focus() }, 1);
}
</script>
</head>
<body>
<input type="text"/>
<input type="button" onmousedown="preventFocus()" onclick="alert('clicked')" value="Toolbar" />
</body>
</html>
``` | How do a get buttons not to take the focus? | [
"",
"javascript",
"button",
"extjs",
"focus",
""
] |
I am using the .NET 2.0/3.5 framework for my application. I need to run several SQL commands across multiple connections and each connection is on a different server (Oracle, SQL Server). I need to make sure these commands are transactional.
For example: I need to perform an INSERT in a table on both Oracle and SQL Server databases, then commit them if no exceptions were thrown. If there was an exception, I would like to roll-back on both servers if needed.
I suspect I will need to use System.Transactions and TransactionScope. This will require that I setup the Microsoft Distributed Transaction Coordinator (MSDTC) on the database servers and also the application server.
I have looked high and low and could not find any articles describing step by step setting up MSDTC with mutual authentication (including configuring firewall settings and MSDTC settings.) I looked at the Microsoft documentation on setting up MSDTC, but it seems completely worthless and not fully documented (unless you can find me a really good MSDN article on how to set it up.)
Is using MSDTC the only way to get my job done?
If so, how the heck do I configure it properly?
EDIT:
* I am using Windows Server 2003 for all machines.
* I have two SQL Server's. One is SQL Server 2000 and the other is 2005.
* I have one Oracle server and it is version 11g
* The application we are developing sometimes must alter/create records across all three database in a transactional manner.
* It's not a problem between the keyboard and the chair. We read the articles on MSDN on how to set up everything regarding MSDTC, but we cannot get DTCPing and other testing applications to work. We were looking for a step by step article detailing the process. I have come across MSDN documentation on more than one occasion that 'left out' steps to do certain things. | Sadly both official documentation from both vendors seem happy to mention the interop provider or the other but both seem loath to acknowledge the existence of the other's database offering.
You may prefer need the documentation on [Oracle Services for Microsoft Transaction Server](http://www.oracle.com/technology/tech/windows/ora_mts/index.html).
* Oracle Documentation:
+ [10g](http://download.oracle.com/docs/cd/B19306_01/win.102/b14320/toc.htm)
+ [9i](http://www.oracle.com/technology/tech/windows/ora_mts/htdocs/oramtsfov9i.html)
+ Older versions exist but much appears to have changed after 8
From ODP.NET 10.2.0.3 onwards you should (if you have appropriately configured MS DTC and the OraMTS dll is present) be able to simply use the System.Transactions TransactionScope just as you would if co-ordinating between two sql server databases but using a sql server and oracle connection. Oracle 10 onwards may be required for this to work pretty simply out of the box.
[Here is a guide to using DTC from .net 2.0 and Sql Server 2005 onwards](http://blogs.msdn.com/angelsb/archive/2004/07/06/174215.aspx). In particular it notes the OS requirements (which should largely no longer be an issue but are worth noting).
In addition, unless both databases and the client are on the same machine, then network DTC must be enabled. | I use linked servers for all my tasks like this. It makes it easier for us to manage connection info and credentials. Basically one stop shopping for all our needs.
Edit: more details - We have one database used strictly for reporting. We get our data from server all over the corporation. We don't have one single account to access these servers, some of them we use a functional id, other our AD credentials. Wrapping all these connections up into separate linked servers has worked best for us. On our reporting server we currently have 16 linked servers.
We also wrap up our queries into views for easier access into our applications and crystal reports. So instead of having to create multiple connection strings in our code we use just one single global string to connect to the reporting Db. | Multiple SQL Transactional Commands Across Different Database Connections | [
"",
".net",
"sql",
"t-sql",
"transactions",
"msdtc",
""
] |
I have a ComboBox that is bound to a DataSource. I want to dynamically add items to the ComboBox based on certain conditions. So what I've done is add the options to a new list, and then change the DataSource of the ComboBox like so:
```
cbo.DataSource = null;
cbo.DataSource = cbos;
cbo.DisplayMember = "Title";
cbo.ValueMember = "Value";
```
Then, I check `cbo.Items.Count`, and it has not incremented - it does not equal the count of the DataSource. Any ideas what I can do here?
Note this is WinForms and not ASP.NET. | If anyone experiences this problem on a dynamically added combobox, the answer is to ensure that you add the combobox to the controls of a container in the form.
By adding "this.Controls.Add(cbo);" to the code before setting the datasource, the problem goes away. | Did you check the Count immediately or at a later time? There is the possibility that the ComboBox does not actually update it's contents until there is an operation such as a UI refresh and hence the count will be off until that time.
On case where this may happen is if you update the DataSource before the Handle is created for the ComboBox. I dug through the code a bit on reflector and it appears the items will not be updated in this case until the ComboBox is actually created and rendered. | ComboBox items.count doesn't match DataSource | [
"",
"c#",
"winforms",
"data-binding",
"combobox",
""
] |
Is it possible to use a database for authentication with Trac?
.htpasswd auth is not desired in this install.
Using Trac .11 and MySQL as the database. Trac is currently using the database, but provides no authentication. | Out of the box, [Trac doesn't actually do its own authentication](http://trac.edgewall.org/wiki/TracAuthenticationIntroduction), it leaves it up to the web server. So, you've got a wealth of Apache-related options available to you. You could maybe look at something like [auth\_mysql](http://sourceforge.net/projects/modauthmysql) to let you keep user credentials in a database.
Alternatively, take a look at the [AccountManagerPlugin](http://trac-hacks.org/wiki/AccountManagerPlugin) on trac-hacks.org | You can use [Account Manager Plugin with SessionStore](http://trac-hacks.org/wiki/AccountManagerPlugin#SessionStore)
The AccountManagerPlugin offers several features for managing user accounts:
* allow users to register new accounts
* login via an HTML form instead of using HTTP authentication
* allow existing users to change their passwords or delete their accounts
* send a new password to users who’ve forgotten their password
* administration of user accounts | Trac Using Database Authentication | [
"",
"python",
"mysql",
"apache",
"trac",
""
] |
I am searching for a java framework that would allow me to share a cache between multiple JVMs.
What I would need is something like [**Hazelcast**](http://www.hazelcast.com/) but without the "distributed" part. I want to be able to add an item in the cache and have it automatically synced to the other "group member" cache. If possible, I'd like the cache to be sync'd via a reliable multicast (or something similar).
I've looked at [**Shoal**](https://shoal.dev.java.net/) but sadly the "Distributed State Cache" seems like an insufficient implementation for my needs.
I've looked at [**JBoss Cache**](http://www.jboss.org/jbosscache/) but it seems a little overkill for what I need to do.
I've looked at [**JGroups**](http://www.jgroups.org/), which seems to be the most promising tool for what I need to do. Does anyone have experiences with JGroups ? Preferably if it was used as a shared cache ?
Any other suggestions ?
Thanks !
**EDIT** : We're starting tests to help us decide between Hazelcast and Infinispan, I'll accept an answer soon.
**EDIT** : Due to a sudden requirements changes, we don't need a distributed map anymore. We'll be using JGroups for a low level signaling framework. Thanks everyone for you help. | After some more searching, I found [**JGroup's ReplicatedHashMap**](http://www.jgroups.org/manual/html_single/index.html#d0e1949). It has not been thoroughly tested but it seems like an excellent start. It fills all my requirements without giving me too much features I don't need. It's also quite flexible. I'm still searching for the "perfect" answer though :)
Thanks for your answers. | How about this?
Have a local ConcurrentHashMap as your local cache.
Create a Hazelcast distributed map/cache.
Start listening for the distributed map events and update your local ConcurrentHashMap.
Now local caches on each member will be the same. Auto-synched.
```
import com.hazelcast.core.IMap;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.EntryListener;
import com.hazelcast.core.EntryEvent;
import java.util.concurrent.ConcurrentHashMap;
public class Sample implements EntryListener {
Map localCache = new ConcurrentHashMap ();
public static void main(String[] args) {
Sample sample = new Sample();
IMap map = Hazelcast.getMap("default");
//Listen for all added/updated/removed entries
map.addEntryListener(sample, true);
}
public void entryAdded(EntryEvent event) {
localCache.put(event.getKey(), event.getValue());
}
public void entryRemoved(EntryEvent event) {
localCache.remove(event.getKey());
}
public void entryUpdated(EntryEvent event) {
localCache.put(event.getKey(), event.getValue());
}
}
``` | Cluster Shared Cache | [
"",
"java",
"caching",
"distributed-computing",
"cluster-computing",
""
] |
Is it possible check if there is a value for history.go(-1)? I know you can't access history.previous directly.
I am trying to stay away from document.referrer because I know it can be blocked in some instances.
Here is what I am trying to do. I have an error page, on this page I would like to either have a BACK button (if it's not the only item in history) or a close button (if it is). | ```
if (history.length) {
//There is history to go back to
history.go(-1);
}
``` | Actually, `history.length` is always one or more, since the current page counts. Also, if you have a forward history (i.e. you used the back button), those pages also count. So you need a more complicated check:
```
if( (1 < history.length) && document.referrer ) {
``` | Page history - back button exists? | [
"",
"javascript",
""
] |
Just wondering if any know of an elegant solution for the following.
If I have 30 June 2009 and I add a month I want it to go to 31 July 2009, not the 30 July 2009.
This logic is based on the fact that the 30 June 2009 was the end of the month of June and when I add a month I want to go to the end of the next month.
But if I have 29 June 2009 and I add a month it should go to 29 July 2009.
Note I need to be able to add any number of months and I need to take into account leap years.
Also I know the logic here is questionable but it is a business requirement that works with end of month contracts going to the end of the month for a month in the future.
I have thought of several solution but none that are very elegant. Hence I was thinking someone might have a better way.
Cheers
Anthony | To check if a date is the end of the month, you check if the next day is day one of some month. your algorithm should then be "If the day is not end of month, add 1 month. If it is the end of the month, add one day, add one month, subtract one day."
```
bool IsEndOfMonth(DateTime date) {
return date.AddDays(1).Day == 1;
}
DateTime AddMonthSpecial(DateTime date) {
if (IsEndOfMonth(date))
return date.AddDays(1).AddMonths(1).AddDays(-1);
else
return date.AddMonths(1);
}
``` | ```
DateTime exampleDate = DateTime.Parse("12/31/2009");
bool isLastDayOfMonth = (exampleDate.AddDays(1).Month != exampleDate.Month);
if (isLastDayOfMonth)
Console.WriteLine(exampleDate.AddDays(1).AddMonths(1).AddDays(-1));
else
Console.WriteLine(new DateTime(exampleDate.Year, exampleDate.Month, 1).AddMonths(2).AddDays(-1));
```
EDIT: I read your question again. You will need to put a check to see if its last day of the month.
Sorry, I wish I had read the question clearly of what is needed.
Hope this is good enough to give you an idea of what is needed. | End of month calculations | [
"",
"c#",
".net",
"datetime",
"date",
"logic",
""
] |
I have a password string that must be passed to a method. Everything works fine but I don't feel comfortable storing the password in clear text. Is there a way to obfuscate the string or to truly encrypt it? I'm aware that obfuscation can be reverse engineered, but I think I should at least try to cover up the password a bit. At the very least it wont be visible to a indexing program, or a stray eye giving a quick look at my code.
I am aware of pyobfuscate but I don't want the whole program obfuscated, just one string and possibly the whole line itself where the variable is defined.
Target platform is GNU Linux Generic (If that makes a difference) | If you just want to prevent casually glancing at a password, you may want to consider encoding/decoding the password to/from [base64](http://docs.python.org/library/base64.html). It's not secure in the least, but the password won't be casually human/robot readable.
```
import base64
# Encode password (must be bytes type)
encoded_pw = base64.b64encode(raw_pw)
# Decode password (must be bytes type)
decoded_pw = base64.b64decode(encoded_pw)
``` | Obviously your best option is to delegate this to a third party. If you can authenticate with whatever you're connecting to using some other credential (eg. the user account your process is running as), you can leave the permission levels up to the OS layer. Alternatively, if sufficiently important / possible you could prompt the user (storing the key in the (arguably) slightly less hackable wetware instead)
If you *do* need to store some password or key, I'd recommend you store it *seperate* from your code, in a file you read in, and de-obfusticate if neccessary. This has the advantages that:
* You can set the file permissions on the file as tight as possible (ie. only readable by the account your program runs as), unlike the rest of your program which may be read by more people.
* You won't accidently check it into your version control system!
* No need to be restricted to printable characters (or use awkward escaping) for a python string, so you can use an arbitrary keyfile if possible, rather than a human readable password. If it's non human-entered, there's no reason to have all the weaknesses of passwords.
To obfusticate, you can use base64 as suggested, or some home-brew scheme like XORing or decrypting with another key stored elsewhere, requiring both locations to be looked at. Be aware that this doesn't protect against anything beyond opportunistic shoulder surfing (if that) - make sure that there is some level of *real* security as well (including obvious ones like physical access to the machine!) | Obfuscate strings in Python | [
"",
"python",
"linux",
"encryption",
"passwords",
"obfuscation",
""
] |
I have a masked text box bound to a nullabe datetime, but when the date is blanked out, the validation on the masked text box won't complete. Is there a way to force this behaviour? I want a blanked out text box to equal a null DateTime.
When the textbox is already null, the validation works. It only breaks when there is a date already bound and I try to blank it out. | I figured out it didn't have to do with the validation. It was when the date was being parsed back to the datetime.
This may not be the most elegant way to do this, but it does work. If anyone knows a better way, please let me know.
I have this code now.
```
public static void FormatDate(MaskedTextBox c) {
c.DataBindings[0].Format += new ConvertEventHandler(Date_Format);
c.DataBindings[0].Parse += new ConvertEventHandler(Date_Parse);
}
private static void Date_Format(object sender, ConvertEventArgs e) {
if (e.Value == null)
e.Value = "";
else
e.Value = ((DateTime)e.Value).ToString("MM/dd/yyyy");
}
static void Date_Parse(object sender, ConvertEventArgs e) {
if (e.Value.ToString() == " / /")
e.Value = null;
}
``` | I use this with `maskedtextbox` for `datetime` type
```
this.txtDateBrth.DataBindings.Add("Text", bsAgent, "DateBrth", true, DataSourceUpdateMode.OnPropertyChanged, null, "dd/MM/yyyy");
```
if need `null` date value, use nullable datetime type in class declaration :
```
private DateTime? _DateBrth;
public DateTime? DateBrth
{
get { return _DateBrth; }
set { _DateBrth = value; }
}
``` | Bind nullable DateTime to MaskedTextBox | [
"",
"c#",
"data-binding",
"datetime",
"nullable",
"maskedtextbox",
""
] |
I have a program written in C++ which does some computer diagnostics. Before the program exits, I need it to launch Internet Explorer and navigate to a specific URL. How do I do that from C++?
Thanks. | Here you are... I am assuming that you're talking MSVC++ here...
```
// I do not recommend this... but will work for you
system("\"%ProgramFiles%\\Internet Explorer\\iexplore.exe\"");
// I would use this instead... give users what they want
#include <windows.h>
void main()
{
ShellExecute(NULL, "open", "http://stackoverflow.com/questions/982266/launch-ie-from-a-c-program", NULL, NULL, SW_SHOWNORMAL);
}
``` | if you really need to launch internet explorer you should also look into using CoCreateInstance(CLSID\_InternetExplorer, ...) and then navigating. depending on what else you want to do it might be a better option. | Launch IE from a C++ program | [
"",
"c++",
"internet-explorer",
""
] |
Is there a simple way to get the current URL from an iframe?
The viewer would going through multiple sites.
I'm guessing I would be using something in javascript. | For security reasons, you can only get the url for as long as the contents of the iframe, and the referencing javascript, are served from the same domain. As long as that is true, something like this will work:
```
document.getElementById("iframe_id").contentWindow.location.href
```
If the two domains are mismatched, you'll run into cross site reference scripting security restrictions.
See also [answers to a similar question](https://stackoverflow.com/questions/44359/how-do-i-get-the-current-location-of-an-iframe). | If your iframe is from another domain, (cross domain), the other answers are not going to help you... you will simply need to use this:
```
var currentUrl = document.referrer;
```
and - here you've got the main url! | Get current URL from IFRAME | [
"",
"javascript",
"url",
"iframe",
""
] |
When I copy an Eclipse project directory, it contains the .classpath and .project files so that when I take that same directory to another Eclipse instance, I don't have to setup my build path and such (assuming that all the resources are contained in the project, and not external.)
However, this procedure doesn't cause launch profiles to "travel" with the directory.
Is there some other file/directory structure I can "carry around" to another instance of Eclipse that will include my launch profiles? | Try choosing a shared file location inside your workspace from the "Common" tab of the launch configurations (profiles). | The .launch xml files (launcher definition) are found in
```
[eclipse-workspace]\.metadata\.plugins\org.eclipse.debug.core\.launches
```
Just copy them into your `<project>/.settings` directory.
Refresh your project, and there you have it: those launcher configuration are available, and you can copy them along the rest of your project files.
Warning: do **uncheck the option "Delete configurations when associated resource is deleted"** in the Run/Launching/Launch Configuration preference panel: it is common ot soft-delete a project in order to import it back again, to force a reinitialization of the eclipse metadata,... but this option, if checked, will removed your detailed launch parameters!
See also [Which eclipse files belong under Version Control](https://stackoverflow.com/questions/337304/which-eclipse-files-belong-under-version-control), and [where are the external tools launch configurations in Eclipse](https://stackoverflow.com/questions/452571/where-are-the-external-tools-launch-configurations-in-eclipse).
---
[Jared](https://stackoverflow.com/users/44757/jared) adds:
> There is no .settings directory in my project directory - I created it and put the .launch file in there, refreshed my project, and it doesn't have any Run profiles. Do you have to mirror the directory structure under .metadata?
Just create the `.settings` directory (it is actually created when you have project specific settings as illustrated in the question "[Maintaining a common set of Eclipse preferences](https://stackoverflow.com/questions/951509/maintaining-a-common-set-of-eclipse-preferences/951824#951824)").
Then delete the same `.launch` file from the `.metadata` directory.
Then refresh your project and go to the "Run Configurations" Panel: you will see your launch configurations still available, except they are stored where they belong: within your project directory and not buried under an obscure workspace metadata thingy.
---
Update June 2012
I always seen my launch configurations, saved under `PROJECT_LOC/.settings`, automatically imported when reloading the Eclipse workspace.
However, as described in "[Tip: Creating and Sharing Launch Configurations (2007)](http://eclipsesnippets.blogspot.fr/2007/07/tip-creating-and-sharing-launch.html)", you should be able to reference a launch configuration saved into any subdirectory of your project if you go to the "Common" tab of your "Run Configurations" wizard.

So saving your launcher anywhere in the project won't display them *automatically* in the "Run Configurations" section of the preferences.
But declaring a new one, sharing its launcher as a "Shared file" (as illustrated above), and then overwriting that launcher with the actual one you had previously saved would update that run configuration. | How do I save Eclipse launch profiles across workspaces? | [
"",
"java",
"eclipse",
""
] |
I need an application to be running in the background on my web server, but I need to be able to start/stop the application with root privileges.
In order to do this, I want to have a service running that has root privileges, so that it can kill the application, and start it up again if need be.
Finally, I need to be able to send the start and kill commands to the service via Apache/PHP, so that it can be indirectly controlled through the web.
How do I create a Linux service?
How do I communicate with a Linux service in this manner?
Thanks in advance! | Use the exec command in your PHP script to call shell files. The shell files can be setup with the "setuser" bit so it will run as its owner (instead of running with the web server's permissions).
Of course, you'll need to be very careful--lots of testing, monitoring, etc.
Finally, think about the service running as a dedicated user, not as root. Eg like apache and most other well done services do.
Added: Re: running a service in Linux. Depends on your flavor of Linux. If you want to be sure that your app service will be automatically re-started if it fails, plus logging, checkout Runit:
<https://web.archive.org/web/1/http://blogs.techrepublic%2ecom%2ecom/opensource/?p=202>
<http://smarden.org/runit>
Added: Instead of setuid bit, I think Frank's suggestion (in comment) of using sudo system is better. | So, you have three pieces here :
* Your web server without root privilege
* An application
* A daemon that is monitoring the application
Your problem is not launching the daemon, it is writing it, and communicating with it from the web server, without needing root privilege.
A daemon can be as simple as a non interactive application launched in the background :
```
# my_dameon &
```
I am not a php developper, but searching for message queue and php, I discovered [beanstalkd](http://xph.us/software/beanstalkd/)
Looking at the example on the first page it seems you can use it to do the following :
* The apache/php sends some message to beanstalkd
* Your daemon reads the message from beanstalkd. Based on the command it starts or kill or reload the background application.
You can write your daemon in php, since there are [client in many languages](http://xph.us/software/beanstalkd/client.html)
You can also check [this question](https://stackoverflow.com/questions/909791/asynchronous-processing-or-message-queues-in-php-cakephp) | How to make a Linux Service that Accepts Commands via Web Server? | [
"",
"php",
"linux",
"service",
"background-process",
"background-service",
""
] |
Consider the following tsql...
```
create function dbo.wtfunc(@s varchar(50)) returns varchar(10) begin return left(@s, 2); end
GO
select t.* into #test from (
select 'blah' as s union
select 'foo' union
select 'bar'
) t
select * from #test;
declare @s varchar(100);
set @s = '';
select @s = @s + s from #test order by s;
select @s;
set @s = '';
select @s = @s + s from #test order by dbo.wtfunc(s);
select @s;
/* 2005 only*/
select cast((select s+'' from #test order by dbo.wtfunc(s) for xml path('')) as varchar(100))
drop function dbo.wtfunc;
drop table #test;
```
I've tried it on mssql 2000 and 2005 and both do not concat the string when using a function in the order by. On 2005, the for xml path('') does work. The output is...
```
bar
blah
foo
barblahfoo
foo --nothing concatenated?
barblahfoo
```
I can't find where this is documented. Can someone shed some light on why this doesn't work?
EDIT:
Here are the actual execution plans. Obviously the sort and compute scalar are not in the same order...
[](https://i.stack.imgur.com/wUJud.png)
[](https://i.stack.imgur.com/lDokW.png) | It would appear that this is a [known issue with Aggregate Concatenation Queries](http://support.microsoft.com/default.aspx/kb/287515).
From the link:
*"The ANSI SQL-92 specification requires that any column referenced by an ORDER BY clause match the result set, defined by the columns present in the SELECT list. When an expression is applied to a member of an ORDER BY clause, that resulting column is not exposed in the SELECT list, resulting in undefined behavior."* | You can do this by using a computed column, for instance:
```
DROP TABLE dbo.temp;
CREATE TABLE dbo.temp
(
s varchar(20)
,t AS REVERSE(s)
);
INSERT INTO dbo.temp (s) VALUES ('foo');
INSERT INTO dbo.temp (s) VALUES ('bar');
INSERT INTO dbo.temp (s) VALUES ('baz');
INSERT INTO dbo.temp (s) VALUES ('blah');
GO
-- Using the function directly doesn't work:
DECLARE @s varchar(2000);
SELECT s, REVERSE(s) FROM dbo.temp ORDER BY REVERSE(s);
SET @s = '';
SELECT @s = @s + s FROM dbo.temp ORDER BY REVERSE(s);
SELECT @s;
GO
-- Hiding the function in a computed column works:
DECLARE @s varchar(2000);
SELECT s, t FROM dbo.temp ORDER BY t;
SET @s = '';
SELECT @s = @s + s FROM dbo.temp ORDER BY t;
SELECT @s;
GO
``` | tsql string concat with select and order by does not work with function in order by clause? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Sometimes one has to refer to another method when commenting. Here some example in PHP:
```
class A
{
/**
* @see B::bar
*/
public function foo()
{
B::bar();
}
}
class B
{
public static function bar()
{
// ...
}
}
```
So what if there would be a non-static method `bar` in class `B`?
What is the best way to name other methods in comments?
**Edit**
The PHP manual seems to use `mysqli->affected_rows` as well as `PDO::beginTransaction`. But what it does not is including the parentheses after the method's name. What is pro and con here? I mean it is quite obvious that a method is followed by parentheses, so why no leave 'em out?
Thx in advance! | You could use the `->` operator to reference an instance/object method rather than a class method. PHP.net does that in their manual as well (see [MySQLi class](http://docs.php.net/manual/class.mysqli.php) for example). | I would write:
```
class A {
// see B::bar()
public function foo() {
B::bar();
}
}
```
My most strongly held opinion concerning my various changes is that letterbox comments are the work of the Devil. Regarding your static vs. non-static thing, I understand and use `B::bar()` to refer to the function definition for conversational purposes, whether or not `bar()` is static.
The above example is, of course, for illustrative purposes only, because if there were actually a function `A::foo()` that did nothing but call `B::bar()`, I would not include the comment, because if the person reading my code is an idiot, I do not wish to help him. | What is the preferred way of notating methods in comments? | [
"",
"php",
"naming-conventions",
"comments",
"naming",
"comment-conventions",
""
] |
What advantages are there in accessing vector elements using an iterator vs an index? | Why are iterators better than indexes?
* In the cases where index is not available (like with std::list, for
example).
* In the case where a generic function accepting an iterator
is called.
* When writing a function template that is supposed to work with
more than one container type.
* They exist to create *uniformity* among all containers and ability to use
all containers' iterators as well as regular pointers in all standard
algorithms.
* Iterators can point to sequences that don't exist except as a concept.
For instance, you can make an iterator class that steps through prime
numbers without actually having to build a container of primes.
However, if ignoring container types that do not support random access (list, set, etc.), iterators still offer
* Pointer like semantics (think of string::iterator vs. char \*).
* Generalized concept usable beyond iteration over elements inside a
container.
* Better performance than container member functions in a few cases. | Modularity is the answer. Suppose you wrap your logic in a function call (a good practice). In that case making it receive iterator will make it generic, so that it can operate on a C style array (pointer), an C++ stl vector or anything really that behaves like an iterator container, such as a linked list for instance. | What is the difference between accessing vector elements using an iterator vs an index? | [
"",
"c++",
"vector",
"iterator",
""
] |
I've run through the Google Web Toolkit [StockWatcher Tutorial](http://code.google.com/webtoolkit/tutorials/1.6/gettingstarted.html) using [Eclipse](http://www.eclipse.org/downloads/) and the [Google Plugin](http://code.google.com/eclipse/docs/getting_started.html), and I'm attempting to make some basic changes to it so I can better understand the RPC framework.
I've modified the "getStocks" method on the StockServiceImpl server-side class so that it returns an array of Stock objects instead of String objects. The application compiles perfectly, but the Google Web Toolkit is returning the following error:
"No source code is available for type com.google.gwt.sample.stockwatcher.server.Stock; did you forget to inherit a required module?"
[](https://i.stack.imgur.com/ovOcV.jpg)
It seems that the client-side classes can't find an implementation of the Stock object, even though the class has been imported. For reference, here is a screenshot of my package hierarchy:
[](https://i.stack.imgur.com/itjpK.jpg)
I suspect that I'm missing something in web.xml, but I have no idea what it is. Can anyone point me in the right direction?
**EDIT:** Forgot to mention that the Stock class is persistable, so it needs to stay on the server-side. | After much trial and error, I managed to find a way to do this. It might not be the best way, but it works. Hopefully this post can save someone else a lot of time and effort.
These instructions assume that you have completed both the [basic StockWatcher tutorial](http://code.google.com/webtoolkit/tutorials/1.6/gettingstarted.html) and the [Google App Engine StockWatcher modifications](http://code.google.com/webtoolkit/tutorials/1.6/appengine.html).
## Create a Client-Side Implementation of the Stock Class
There are a couple of things to keep in mind about GWT:
1. Server-side classes can import client-side classes, but not vice-versa (usually).
2. The client-side can't import any Google App Engine libraries (i.e. com.google.appengine.api.users.User)
Due to both items above, the client can never implement the Stock class that we created in com.google.gwt.sample.stockwatcher.server. Instead, we'll create a new client-side Stock class called StockClient.
### StockClient.java:
```
package com.google.gwt.sample.stockwatcher.client;
import java.io.Serializable;
import java.util.Date;
public class StockClient implements Serializable {
private Long id;
private String symbol;
private Date createDate;
public StockClient() {
this.createDate = new Date();
}
public StockClient(String symbol) {
this.symbol = symbol;
this.createDate = new Date();
}
public StockClient(Long id, String symbol, Date createDate) {
this();
this.id = id;
this.symbol = symbol;
this.createDate = createDate;
}
public Long getId() {
return this.id;
}
public String getSymbol() {
return this.symbol;
}
public Date getCreateDate() {
return this.createDate;
}
public void setId(Long id) {
this.id = id;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
}
```
## Modify Client Classes to Use StockClient[] instead of String[]
Now we make some simple modifications to the client classes so that they know that the RPC call returns StockClient[] instead of String[].
### StockService.java:
```
package com.google.gwt.sample.stockwatcher.client;
import com.google.gwt.sample.stockwatcher.client.NotLoggedInException;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
@RemoteServiceRelativePath("stock")
public interface StockService extends RemoteService {
public Long addStock(String symbol) throws NotLoggedInException;
public void removeStock(String symbol) throws NotLoggedInException;
public StockClient[] getStocks() throws NotLoggedInException;
}
```
### StockServiceAsync.java:
```
package com.google.gwt.sample.stockwatcher.client;
import com.google.gwt.sample.stockwatcher.client.StockClient;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface StockServiceAsync {
public void addStock(String symbol, AsyncCallback<Long> async);
public void removeStock(String symbol, AsyncCallback<Void> async);
public void getStocks(AsyncCallback<StockClient[]> async);
}
```
### StockWatcher.java:
Add one import:
```
import com.google.gwt.sample.stockwatcher.client.StockClient;
```
All other code stays the same, except addStock, loadStocks, and displayStocks:
```
private void loadStocks() {
stockService = GWT.create(StockService.class);
stockService.getStocks(new AsyncCallback<String[]>() {
public void onFailure(Throwable error) {
handleError(error);
}
public void onSuccess(String[] symbols) {
displayStocks(symbols);
}
});
}
private void displayStocks(String[] symbols) {
for (String symbol : symbols) {
displayStock(symbol);
}
}
private void addStock() {
final String symbol = newSymbolTextBox.getText().toUpperCase().trim();
newSymbolTextBox.setFocus(true);
// Stock code must be between 1 and 10 chars that are numbers, letters,
// or dots.
if (!symbol.matches("^[0-9a-zA-Z\\.]{1,10}$")) {
Window.alert("'" + symbol + "' is not a valid symbol.");
newSymbolTextBox.selectAll();
return;
}
newSymbolTextBox.setText("");
// Don't add the stock if it's already in the table.
if (stocks.contains(symbol))
return;
addStock(new StockClient(symbol));
}
private void addStock(final StockClient stock) {
stockService.addStock(stock.getSymbol(), new AsyncCallback<Long>() {
public void onFailure(Throwable error) {
handleError(error);
}
public void onSuccess(Long id) {
stock.setId(id);
displayStock(stock.getSymbol());
}
});
}
```
## Modify the StockServiceImpl Class to Return StockClient[]
Finally, we modify the getStocks method of the StockServiceImpl class so that it translates the server-side Stock classes into client-side StockClient classes before returning the array.
### StockServiceImpl.java
```
import com.google.gwt.sample.stockwatcher.client.StockClient;
```
We need to change the addStock method slightly so that the generated ID is returned:
```
public Long addStock(String symbol) throws NotLoggedInException {
Stock stock = new Stock(getUser(), symbol);
checkLoggedIn();
PersistenceManager pm = getPersistenceManager();
try {
pm.makePersistent(stock);
} finally {
pm.close();
}
return stock.getId();
}
```
All other methods stay the same, except getStocks:
```
public StockClient[] getStocks() throws NotLoggedInException {
checkLoggedIn();
PersistenceManager pm = getPersistenceManager();
List<StockClient> stockclients = new ArrayList<StockClient>();
try {
Query q = pm.newQuery(Stock.class, "user == u");
q.declareParameters("com.google.appengine.api.users.User u");
q.setOrdering("createDate");
List<Stock> stocks = (List<Stock>) q.execute(getUser());
for (Stock stock : stocks)
{
stockclients.add(new StockClient(stock.getId(), stock.getSymbol(), stock.getCreateDate()));
}
} finally {
pm.close();
}
return (StockClient[]) stockclients.toArray(new StockClient[0]);
}
```
## Summary
The code above works perfectly for me when deployed to Google App Engine, but triggers an error in Google Web Toolkit Hosted Mode:
```
SEVERE: [1244408678890000] javax.servlet.ServletContext log: Exception while dispatching incoming RPC call
com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract com.google.gwt.sample.stockwatcher.client.StockClient[] com.google.gwt.sample.stockwatcher.client.StockService.getStocks() throws com.google.gwt.sample.stockwatcher.client.NotLoggedInException' threw an unexpected exception: java.lang.NullPointerException: Name is null
```
Let me know if you encounter the same problem or not. The fact that it works in Google App Engine seems to indicate a bug in Hosted Mode. | GWT needs the .java file in addition to the .class file. Additionally, Stock needs to be in the "client" location of a GWT module. | Problems passing class objects through GWT RPC | [
"",
"java",
"google-app-engine",
"gwt",
"gwt-rpc",
""
] |
Can anyone suggest to me how I can pass a parameter to a thread?
Also, how does it work for anonymous classes? | You need to pass the parameter in the constructor to the Runnable object:
```
public class MyRunnable implements Runnable {
public MyRunnable(Object parameter) {
// store parameter for later user
}
public void run() {
}
}
```
and invoke it thus:
```
Runnable r = new MyRunnable(param_value);
new Thread(r).start();
``` | ### For Anonymous classes:
In response to question edits here is how it works for Anonymous classes
```
final X parameter = ...; // the final is important
Thread t = new Thread(new Runnable() {
p = parameter;
public void run() {
...
};
t.start();
```
---
### Named classes:
You have a class that extends Thread (or implements Runnable) and a constructor with the parameters you'd like to pass. Then, when you create the new thread, you have to pass in the arguments, and then start the thread, something like this:
```
Thread t = new MyThread(args...);
t.start();
```
Runnable is a much better solution than Thread BTW. So I'd prefer:
```
public class MyRunnable implements Runnable {
private X parameter;
public MyRunnable(X parameter) {
this.parameter = parameter;
}
public void run() {
}
}
Thread t = new Thread(new MyRunnable(parameter));
t.start();
```
This answer is basically the same as this similar question: [How to pass parameters to a Thread object](https://stackoverflow.com/questions/705037/how-to-pass-parameters-to-a-thread-object) | How can I pass a parameter to a Java Thread? | [
"",
"java",
"multithreading",
""
] |
I have an array of 200 items. I would like to output the array but group the items with a common value. Similar to SQL's GROUP BY method. This should be relatively easy to do but I also need a count for the group items.
Does anyone have an efficient way of doing this? This will happen on every page load so I need it to be fast and scalable.
Could I perhaps dump the results into something like Lucene or SQLite then run a query on that document on each page load? | Just iterate over the array and use another array for the groups. It should be fast enough and is probably faster than the overhead involved when using sqlite or similar.
```
$groups = array();
foreach ($data as $item) {
$key = $item['key_to_group'];
if (!isset($groups[$key])) {
$groups[$key] = array(
'items' => array($item),
'count' => 1,
);
} else {
$groups[$key]['items'][] = $item;
$groups[$key]['count'] += 1;
}
}
``` | ```
$groups = array();
foreach($items as $item)
$groups[$item['value']][] = $item;
foreach($groups as $value => $items)
echo 'Group ' . $value . ' has ' . count($items) . ' ' . (count($items) == 1 ? 'item' : 'items') . "\n";
``` | Group rows in a 2d array and count number of rows in each respective group | [
"",
"php",
"arrays",
"multidimensional-array",
"grouping",
"counting",
""
] |
I'm trying to determine if the MethodInfo object that I get from a GetMethod call on a type instance is implemented by the type or by it's base.
For example:
```
Foo foo = new Foo();
MethodInfo methodInfo = foo.GetType().GetMethod("ToString",BindingFlags|Instance);
```
the ToString method may be implemented in the Foo class or not. I want to know if I'm getting the foo implementation?
> **Related question**
>
> [Is it possible to tell if a .NET virtual method has been overriden in a derived class?](https://stackoverflow.com/questions/839984/is-it-possible-to-tell-if-a-net-virtual-method-has-been-overriden-in-a-derived-c) | Check its `DeclaringType` property.
```
if (methodInfo.DeclaringType == typeof(Foo)) {
// ...
}
``` | Instead of using reflection a much faster way is to use delegates!
Especially in the new version of the framework the operation is really fast.
```
public delegate string ToStringDelegate();
public static bool OverridesToString(object instance)
{
if (instance != null)
{
ToStringDelegate func = instance.ToString;
return (func.Method.DeclaringType == instance.GetType());
}
return false;
}
``` | How to determine if the MethodInfo is an override of the base method | [
"",
"c#",
".net",
"reflection",
"overriding",
"methodinfo",
""
] |
I thought I knew this, but today I'm being proven wrong - again.
Running VS2008, .NET 3.5 and C#. I added the User settings to the Properties Settings tab with default values, then read them in using this code:
```
myTextBox.Text = Properties.Settings.Default.MyStringProperty;
```
Then, after the user edits the value in the options dialog I save it like this:
```
Properties.Settings.Default.MyStringProperty = myTextBox.Text;
Properties.Settings.Default.Save();
```
My question is, where is this new value saved? the MyApp.exe.config file in the executable directory is not updated, it still contains the default values. Plus, as far as I can tell, none of the other files in that directory are updated either! However, when the program reads the value back in, it gets the changed value, so I know it's saved somewhere...
This isn't just academic, I needed to be able to manually edit the value this morning and got myself stumped when I couldn't find anything that was changing. | In order to work with newer versions of Windows' policy of only allowing read access by default to the Program Files folder (unless you prompt for elevation with UAC, but that's another topic...), your application will have a settings folder under `%userprofile%\appdata\local` or `%userprofile%\Local Settings\Application Data` depending on which version of Windows you're running, for settings that are user specific. If you store settings for all users, then they'll be in the corresponding folder under `C:\users` or `C:\Documents and Settings` for all user profiles (ex: `C:\users\public\appdata\local`). | You can get the path programmatically:
```
using System.Configuration; // Add a reference to System.Configuration.dll
...
var path = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath;
``` | Where are the Properties.Settings.Default stored? | [
"",
"c#",
".net",
"settings",
""
] |
That's a simple question: is there an API to draw a [B-tree](http://en.wikipedia.org/wiki/B-tree) in Java? I just dont want to spend much time reinventing the wheel. I am not having trouble with the algorithm *per si*, mine works perfectly fine after a lot of reading (specially Lafore's Data Structures & Algorithms in Java), I just dont know how to print a B-tree in a good way.
Thanks in advance. | You've got a couple of options to "render" a graph to screen -
* Graphviz has a Java API (Edit: an addon called LJV which gives the API).
* I think you ought to be able to use the free version of JGraph to do the same. | Have a look at [yEd](http://www.yworks.com/en/products_yed_about.html). I'm pretty sure, licensing yFiles just for an API to display tree structures is a bit exaggerated, but the graph editor is free of license costs and you can use it to render your trees. I usually dump my raw graph data in one of the supported file formats, open the output file with yEd and let it do the layout. | Is there an API to draw a B-TREE? | [
"",
"java",
"user-interface",
"b-tree",
""
] |
In an [answer](https://stackoverflow.com/questions/855759/python-try-else/855783#855783) (by [S.Lott)](https://stackoverflow.com/users/10661/s-lott) to a question about Python's `try...else` statement:
> Actually, even on an if-statement, the
> else: can be abused in truly terrible
> ways creating bugs that are very hard
> to find. [...]
>
> Think twice about else:. It is
> generally a problem. Avoid it except
> in an if-statement and even then
> consider documenting the else-
> condition to make it explicit.
**Is this a widely held opinion? Is `else` [considered harmful](http://meyerweb.com/eric/comment/chech.html)?**
Of course you can write confusing code with it but that's true of any other language construct. Even Python's `for...else` seems to me a very handy thing to have (less so for `try...else`). | S.Lott has obviously seen some bad code out there. Haven't we all? I do not consider else harmful, though I've seen it used to write bad code. In those cases, all the surrounding code has been bad as well, so why blame poor else? | No it is not harmful, it is necessary.
There should always be a catch-all statement. All switches should have a default. All pattern matching in an ML language should have a default.
The argument that it is impossible to reason what is true after a series of if statements is a fact of life. The computer is the biggest finite state machine out there, and it is silly to enumerate every single possibility in every situation.
If you are really afraid that unknown errors go unnoticed in else statements, is it really that hard to raise an exception there? | "else" considered harmful in Python? | [
"",
"python",
"if-statement",
""
] |
I have written a game in java script and while it works, it is slow responding to multiple clicks. Below is a very simplified version of the code that I am using to handle clicks and it is still fails to respond to a second click of 2 if you don't wait long enough. Is this something that I need to just accept or is there a faster way to be ready for the next click?
BTW, I attach this function using AddEvent from the quirksmode recoding contest.
```
var selected = false;
var z = null;
function handleClicks(evt) {
evt = (evt)?evt:((window.event)?window.event:null);
if (selected) {
z.innerHTML = '<div class="rowbox a">a</div>';
selected = false;
} else {
z.innerHTML = '<div class="rowbox selecteda">a</div>';
selected = true;
}
}
```
The live code may be seen at <http://www.omega-link.com/index.php?content=testgame> | I think your problem is that the 2nd click is registering as a dblclick event, not as a click event. The change is happening quickly, but the 2nd click is ignored unless you wait. I would suggest changing to either the mousedown or mouseup event. | You could try to only change the classname instead of removing/adding a div to the DOM (which is what the innerHTML property does).
Something like:
```
var selected = false;
var z = null;
function handleClicks(evt)
{
var tmp;
if(z == null)
return;
evt = (evt)?evt:((window.event)?window.event:null);
tmp = z.firstChild;
while((tmp != null) && (tmp.tagName != 'DIV'))
tmp = tmp.firstChild;
if(tmp != null)
{
if (selected)
{
tmp.className = "rowbox a";
selected = false;
} else
{
tmp.className = "rowbox selecteda";
selected = true;
}
}
}
``` | Performance issues in javascript onclick handler | [
"",
"javascript",
"performance",
"browser",
"user-interface",
"cross-browser",
""
] |
I have two classes, Person and Company, derived from another class Contact. They are represented as polymorphically in two tables (Person and Company). The simplified classes look like this:
```
public abstract class Contact {
Integer id;
public abstract String getDisplayName();
}
public class Person extends Contact {
String firstName;
String lastName;
public String getDisplayName() {
return firstName + " " + lastName;
}
}
public class Company extends Contact {
String name;
public String getDisplayName() {
return name;
}
}
```
The problem is that I need to make a query finding all contacts with displayName containing a certain string. I can't make the query using displayName because it is not part of either table. Any ideas on how to do this query? | Because you do the concatenation in the Java class, there is no way that Hibernate can really help you with this one, sorry. It can simply not see what you are doing in this method, since it is in fact not related to persistence at all.
The solution depends on how you mapped the inheritance of these classes:
If it is table-per-hierarchy you can use this approach: Write a SQL where clause for a criteria query, and then use a case statement:
```
s.createCriteria(Contact.class)
.add(Restrictions.sqlRestriction("? = case when type='Person' then firstName || ' '|| lastName else name end"))
.list();
```
If it is table per-concrete-subclass, then you are better of writing two queries (since that is what Hibernate will do anyway). | You could create a new column in the `Contact` table containing the respective `displayName`, which you could fill via a Hibernate [Interceptor](http://docs.jboss.org/hibernate/stable/core/reference/en/html/events.html) so it would always contain the right string automatically.
The alternative would be having two queries, one for the `Person` and one for the `Company` table, each containing the respective search logic. You may have to use native queries to achieve looking for a concatenated string via a LIKE query (I'm not a HQL expert, though, it may well be possible).
If you have large tables, you should alternatively think about full-text indexing, as `LIKE '%...%'` queries require a full table scan unless your database supports full text indexes. | Hibernate polymorphic query | [
"",
"java",
"hibernate",
"hql",
"polymorphism",
""
] |
```
if len(sys.argv) < 2:
sys.stderr.write('Usage: sys.argv[0] ')
sys.exit(1)
if not os.path.exists(sys.argv[1]):
sys.stderr.write('ERROR: Database sys.argv[1] was not found!')
sys.exit(1)
```
This is a portion of code I'm working on. The first part I'm trying to say if the user doesn't type `python programname something` then it will exit.
The second part I'm trying to see if the database exists. On both places I'm unsure if I have the correct way to write out the sys.argv's by stderr or not. | BTW you can pass the error message directly to sys.exit:
```
if len(sys.argv) < 2:
sys.exit('Usage: %s database-name' % sys.argv[0])
if not os.path.exists(sys.argv[1]):
sys.exit('ERROR: Database %s was not found!' % sys.argv[1])
``` | In Python, you can't just embed arbitrary Python expressions into literal strings and have it substitute the value of the string. You need to either:
```
sys.stderr.write("Usage: " + sys.argv[0])
```
or
```
sys.stderr.write("Usage: %s" % sys.argv[0])
```
Also, you may want to consider using the following syntax of `print` (for Python earlier than 3.x):
```
print >>sys.stderr, "Usage:", sys.argv[0]
```
Using `print` arguably makes the code easier to read. Python automatically adds a space between arguments to the `print` statement, so there will be one space after the colon in the above example.
In Python 3.x, you would use the `print` function:
```
print("Usage:", sys.argv[0], file=sys.stderr)
```
Finally, in Python 2.6 and later you can use `.format`:
```
print >>sys.stderr, "Usage: {0}".format(sys.argv[0])
``` | python and sys.argv | [
"",
"python",
""
] |
Given a table **A** of people, their native language, and other columns C3 .. C10 represented by **...**
### Table A
```
PERSON LANGUAGE ...
bob english
john english
vlad russian
olga russian
jose spanish
```
How do I construct a query which selects all columns of one row for each distinct language?
### Desired Result
```
PERSON LANGUAGE ...
bob english
vlad russian
jose spanish
```
It doesn't matter to me which row of each distinct language makes the result. In the result above, I chose the lowest row number of each language. | Eric Petroelje almost has it right:
```
SELECT * FROM TableA
WHERE ROWID IN ( SELECT MAX(ROWID) FROM TableA GROUP BY Language )
```
Note: using ROWID (row unique id), not ROWNUM (which gives the row number within the result set) | This will be more efficient, plus you have control over the ordering it uses to pick a value:
```
SELECT DISTINCT
FIRST_VALUE(person)
OVER(PARTITION BY language
ORDER BY person)
,language
FROM tableA;
```
If you really don't care which person is picked for each language, you can omit the ORDER BY clause:
```
SELECT DISTINCT
FIRST_VALUE(person)
OVER(PARTITION BY language)
,language
FROM tableA;
``` | Oracle 11g SQL to get unique values in one column of a multi-column query | [
"",
"sql",
"oracle",
"distinct",
""
] |
Having worked for Java for 7 years I'm now moving into a project in .net. The team I'm working in have recently used a technology stack that we are fairly happy with in the business layer and below:
* Spring for dependency injection, transaction management, security and for adding interceptors and for getting the possibility to inject different implementations of interfaces when in unit-test as oppose to deployed on a server.
* JUnit for unit tests.
* JPA/Hibernate for ORM
Could you use this stack in .net? I've heard of nHibernate, spring.net and nUnit.
Are these the translations into .net? or are those projects dead, bad implementations or what?
Are there other superior techniques/frameworks?
Appreciate your thougts! | You nailed it - NHibernate, Spring.NET and NUnit are all widely used frameworks on the .NET side that compliment their sister frameworks on the java side.
None of those projects are anywhere near dead. I think NUnit just released a new version last month, actually. | I would recommend xUnit.net over nUnit. It has a rationalised approach and some very nice features which set it apart from the other frameworks.
`Assert.Throws()` is just wonderful (beats `[ExpectedException]` hands down) and the Extensions assembly provides `[Theory]` which, combined with `[InlineData()]`, is incredibly powerful. For more info see [the project homepage](http://www.codeplex.com/xunit) | This java technology stack in .net? | [
"",
"java",
".net",
"frameworks",
""
] |
I have tried many algorithms for finding π using Monte Carlo.
One of the solutions (in Python) is this:
```
def calc_PI():
n_points = 1000000
hits = 0
for i in range(1, n_points):
x, y = uniform(0.0, 1.0), uniform(0.0, 1.0)
if (x**2 + y**2) <= 1.0:
hits += 1
print "Calc2: PI result", 4.0 * float(hits) / n_points
```
The sad part is that even with 1000000000 the precision is VERY bad (**3.141...**).
Is this the maximum precision this method can offer?
The reason I choose Monte Carlo was that it's very easy to break it in parallel parts.
Is there another algorithm for π that is easy to break into pieces and calculate? | This is a classic example of Monte Carlo. But if you're trying to break the calculation of pi into parallel parts, why not just use an infinite series and let each core take a range, then sum the results as you go?
<http://mathworld.wolfram.com/PiFormulas.html> | Your fractional error goes by `sqrt(N)/N = 1/sqrt(N)`, So this is a very inefficient way to get a precise estimate. This limit is set by the statistical nature of the measurement and can't be beaten.
You should be able to get about `floor(log_10(N))/2-1` digits of good precision for `N` throws. Maybe `-2` just to be safe...
Even at that it assumes that you are using a real RNG or a good enough PRNG. | Finding PI digits using Monte Carlo | [
"",
"python",
"statistics",
"montecarlo",
"pi",
""
] |
I'm following the example on the android tutorial about the GridView, but instead of showing image, i want to just simple show some text using a TextView. it turns out seems to be harder than i thought. it might seems like this is totally unnecessary and it doesn't have a valid use case, but i'm trying this out to just get myself familiar with the sdk.
so my code is pretty much the same as the GridView example in <http://developer.android.com/guide/tutorials/views/hello-gridview.html>, but instead of using a ImageAdapter, i created a dummy adapter like following:
```
public class MyAdapter extends BaseAdapter {
private Context context;
private String[] texts = {"aaa", "bbb", "ccc", "ddd", "eee", "fff", "eee", "hhh", "iii"};
public MyAdapter(Context context) {
this.context = context;
}
public int getCount() {
return 9;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv;
if (convertView == null) {
tv = new TextView(context);
tv.setLayoutParams(new GridView.LayoutParams(85, 85));
}
else {
tv = (TextView) convertView;
}
tv.setText(texts[position]);
return tv;
}
}
```
it all seems valid to me, but running this gives me nothing on the screen. and there's no error message. there are some selectable/clickable (invisible) blocks if i click them, but the text is obvious not shown. i wonder is my layout doesn't have the android:text causing this problem? or anything else?
any feedback will be appreciated and thanks for your help! | I am not sure what could be causing your problem. I followed the step by step instructions on the page that you linked to to set up "Hello, GridView", and used your code and was able to see the text.
The only things I changed was rather than creating a class for ImageAdapter I used your MyAdapter. In the activity HelloGridView.java onCreate I used "MyAdapter" rather than "ImageAdapter". I didn't change the layout at all.
[](https://i.stack.imgur.com/zh37q.png)
Here is a Screenshot of what I get when running your code. | I see GridView so I'm almost assuming that this is similar to SWT?
If so you need to show the relationship between your view and the ViewGroup parent | Android: Simple GridView that displays text in the grids | [
"",
"java",
"android",
""
] |
what type could contain a number like 2023209999 in java?
do you think that using a string type to represent a telephone number is a good idea? | Using a string is a very good idea. Remember that the point of OOP is that different types of data have different usage patterns. So let's look at a phone number patterns.
* Do we add phone numbers or perform other arithmetic on them?
* Do we split it based on length, match against parts of it, replace parts of it?
The answer to the first question is no. So we don't manipulate them like numbers. The answer to the second question is yes, so we manipulate them like strings.
Now, many here are advocating making phones a class by itself. There is merit in this regard, but I'm addressing the more pressing concern of how do you *store* the phone number, which is something you need to do no matter if a phone is a class or not. A phone class which stored its data as a number would not be a good fit. | I would write a PhoneNumber class, which uses String as an underlying storage, and adds validation / pretty formatting functionality. | what primitive or what type should we use to represent a telephone number in java? | [
"",
"java",
"types",
""
] |
I'm mostly convinced of the benefits of unit testing, and I would like to start applying the concept to a large existing codebase written in PHP. Less than 10% of this code is object-oriented.
I've looked at several unit testing frameworks (PHPUnit, SimpleTest, and phpt). However, I haven't found examples for any of these that test procedural code. What's the best framework for my situation and are there any examples of unit testing PHP using non-OOP code? | You can unit-test procedural PHP, no problem. And you're definitely not out of luck if your code is mixed in with HTML.
At the application or acceptance test level, your procedural PHP probably depends on the value of the superglobals (`$_POST, $_GET, $_COOKIE`, etc.) to determine behavior, and ends by including a template file and spitting out the output.
To do application-level testing, you can just set the superglobal values; start an output buffer (to keep a bunch of html from flooding your screen); call the page; assert against stuff inside the buffer; and trash the buffer at the end.
So, you could do something like this:
```
public function setUp()
{
if (isset($_POST['foo'])) {
unset($_POST['foo']);
}
}
public function testSomeKindOfAcceptanceTest()
{
$_POST['foo'] = 'bar';
ob_start();
include('fileToTest.php');
$output = ob_get_flush();
$this->assertContains($someExpectedString, $output);
}
```
Even for enormous "frameworks" with lots of includes, this kind of testing will tell you if you have application-level features working or not. This is going to be really important as you start improving your code, because even if you're convinced that the database connector still works and looks better than before, you'll want to click a button and see that, yes, you can still login and logout through the database.
At lower levels, there are minor variations depending on variable scope and whether functions work by side-effects (returning true or false), or return the result directly.
Are variables passed around explicitly, as parameters or arrays of parameters between functions? Or are variables set in many different places, and passed implicitly as globals? If it's the (good) explicit case, you can unit test a function by (1) including the file holding the function, then (2) feeding the function test values directly, and (3) capturing the output and asserting against it. If you're using globals, you just have to be extra careful (as above, in the $\_POST example) to carefully null out all the globals between tests. It's also especially helpful to keep tests very small (5-10 lines, 1-2 asserts) when dealing with a function that pushes and pulls lots of globals.
Another basic issue is whether the functions work by returning the output, or by altering the params passed in, returning true/false instead. In the first case, testing is easier, but again, it's possible in both cases:
```
// assuming you required the file of interest at the top of the test file
public function testShouldConcatenateTwoStringsAndReturnResult()
{
$stringOne = 'foo';
$stringTwo = 'bar';
$expectedOutput = 'foobar';
$output = myCustomCatFunction($stringOne, $stringTwo);
$this->assertEquals($expectedOutput, $output);
}
```
In the bad case, where your code works by side-effects and returns true or false, you still can test pretty easily:
```
/* suppose your cat function stupidly
* overwrites the first parameter
* with the result of concatenation,
* as an admittedly contrived example
*/
public function testShouldConcatenateTwoStringsAndReturnTrue()
{
$stringOne = 'foo';
$stringTwo = 'bar';
$expectedOutput = 'foobar';
$output = myCustomCatFunction($stringOne, $stringTwo);
$this->assertTrue($output);
$this->Equals($expectedOutput, $stringOne);
}
```
Hope this helps. | What unit tests do well, and what you should use them for, is when you have a piece of code that you give some number of inputs, and you expect to get some number of outputs back out. The idea being, when you add functionality later, you can run your tests and make sure it's still performing the old functionality the same way.
So, if you have a procedural code-base, you can accomplish this calling your functions in the test methods
```
require 'my-libraries.php';
class SomeTest extends SomeBaseTestFromSomeFramework {
public function testSetup() {
$this->assertTrue(true);
}
public function testMyFunction() {
$output = my_function('foo',3);
$this->assertEquals('expected output',$output);
}
}
```
This trick with PHP code bases is, often your library code will interfere with the running of your test framework, as your codebase and the test frameworks will have a lot of code related to setting up an application environment in a web browser (session, shared global variables, etc.). Expect to spend sometime getting to a point where you can include your library code and run a dirt simple test (the testSetup function above).
If your code doesn't have functions, and is just a series of PHP files that output HTML pages, you're kind of out of luck. Your code can't be separated into distinct units, which means unit testing isn't going to be of much use to you. You'd be better off spending your time at the "acceptance testing" level with products like [Selenium](http://seleniumhq.org/) and [Watir](http://wtr.rubyforge.org/). These will let you automated a browser, and then check the pages for content as specific locations/in forms. | How do I write unit tests in PHP with a procedural codebase? | [
"",
"php",
"unit-testing",
"phpunit",
"simpletest",
"paradigms",
""
] |
```
foo.cpp(33918) : fatal error C1854: cannot overwrite information formed
during creation of the precompiled header in object file: 'c:\somepath\foo.obj'
```
Consulting MSDN about this gives me the following information:
> You specified the /Yu (use precompiled
> header) option after specifying the
> /Yc (create precompiled header) option
> for the same file. Certain
> declarations (such as declarations
> including \_\_declspec dllexport) make
> this invalid.
We are using dllexport and precompiled headers in this case. Have anyone encountered this before and know of any workaround? Any input to shed some light on this problem is greatly appreciated.
Thanks | I think you can find the answer here: <http://social.msdn.microsoft.com/forums/en-US/vclanguage/thread/b3aa10fa-141b-4a03-934c-7e463f92b2a5/>
Basically, you need to set the stdafx.cpp file to "Create Precompiled Headers" and all the other .cpp files to "Use Precompiled Headers" | I had this problem too.
Make sure the precompiler header output file is set to the correct location. Mine was actually outputted to the right location, but there were problems reading it just because the path had a little artifact inside. | error C1854: cannot overwrite information formed during creation of the precompiled header in object file | [
"",
"c++",
"visual-studio",
"precompiled-headers",
"dllexport",
""
] |
I am writing some servlets with plain old mostly-JDBC patterns. I realized that I have several objects that would like to share a single transaction, and I'd like to enforce that one HTTP transaction = one database transaction.
I think I can do this via passing a Connection around in a ThreadLocal variable, and then having a servlet filter handling the creation/commit/rollback of said Connection.
Is there an existing framework that does this that I'm not privy to, or is this a reasonable late-00's way to do things? | [Spring](http://www.springframework.org) transaction management does exactly what you describe, it might be a little over whelming at first glance but all you will be needing (for the simplest case) is:
[org.springframework.jdbc.datasource.DataSourceTransactionManager](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/jdbc/datasource/DataSourceTransactionManager.html)
[org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/jdbc/datasource/TransactionAwareDataSourceProxy.html)
[org.springframework.transaction.support.TransactionTemplate](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/transaction/support/TransactionTemplate.html)
Wire up your existing DataSource and wrap it in the TransctionAwareDataSourceProxy then create a DataSourceTransactionManager with the wrapped data source, keep these in your ServletContext. Then for each transaction create a TransactionTemplate passing in the transaction manager and call the execute(TransactionCallback) method to run your code. eg:
```
new TransactionTemplate(transactionManager).execute(new TransactionCallback(){
public void doInTransaction(TransactionStatus ts){
// run your code here...use the dataSource to get a connection and run stuff
Connection c = dataSourceProxy.getConnection();
// to rollback ... throw a RuntimeException out of this method or call
st.setRollbackOnly();
}
});
```
The connection will be bound to a thread local so as long as you always get the connection form the same datasource i.e. the wrapped one, you'll get the same connection in the same transaction.
Note this is the simplest possible spring transaction setup ... not nessarly the best or recommended one, for that have a look at the spring reference doc's or read spring in action.
... so I guess as a direct answer, **yes** it is a reasonable thing to be doing, it's what the spring framework has been doing for a long time. | Most appServer todays support JTA (Java Transaction Api): A transaction that spans over multiple open/close jdbc connections. It does the "threadLocal" stuff for you and it's J2EE compliant.
You use it like this in your filter:
```
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
UserTransaction transaction = null;
try {
transaction = (UserTransaction)new InitialContext().lookup("java:comp/UserTransaction");
transaction.begin();
chain.doFilter(request, response);
transaction.commit();
} catch (final Exception errorInServlet) {
try {
transaction.rollback();
} catch (final Exception rollbackFailed) {
log("No ! Transaction failed !",rollbackFailed);
}
throw new ServletException(errorInServlet);
}
}
```
On the app-server, declare a Datasource with a jndi name, and use it in your code to retrieve a connection (do NOT make cx.commit(), cx.rollback() or cx.setAutocommit() stuff, it will interfere with JTA). You can open and close your connection several times in the same HTTP transaction, JTA will take care of it:
```
public void doingDatabaseStuff() throws Exception {
DataSource datasource = (DataSource)new InitialContext().lookup("/path/to/datasource");
Connection connection = datasource.getConnection();
try {
// doing stuff
} finally {
connection.close();
}
}
``` | ThreadLocal + java.sql.Connection + servlet filter = 2009? | [
"",
"java",
"servlets",
"jdbc",
"servlet-filters",
"thread-local",
""
] |
Say you're writing a C++ application doing lots of floating point arithmetic. Say this application needs to be portable accross a reasonable range of hardware and OS platforms (say 32 and 64 bits hardware, Windows and Linux both in 32 and 64 bits flavors...).
How would you make sure that your floating point arithmetic is the same on all platforms ? For instance, how to be sure that a 32 bits floating point value will really be 32 bits on all platforms ?
For integers we have [stdint.h](http://en.wikipedia.org/wiki/Stdint.h) but there doesn't seem to exist a floating point equivalent.
---
[EDIT]
I got very interesting answers but I'd like to add some precision to the question.
For integers, I can write:
```
#include <stdint>
[...]
int32_t myInt;
```
and be sure that whatever the (C99 compatible) platform I'm on, myInt is a 32 bits integer.
If I write:
```
double myDouble;
float myFloat;
```
am I certain that this will compile to, respectively, 64 bits and 32 bits floating point numbers on all platforms ? | ## Non-IEEE 754
Generally, you cannot. There's always a trade-off between consistency and performance, and C++ hands that to you.
For platforms that don't have floating point operations (like embedded and signal processing processors), you cannot use C++ "native" floating point operations, at least not portably so. While a software layer would be possible, that's certainly not feasible for this type of devices.
For these, you could use 16 bit or 32 bit fixed point arithmetic (but you might even discover that long is supported only rudimentary - and frequently, div is very expensive). However, this will be much slower than built-in fixed-point arithmetic, and becomes painful after the basic four operations.
I haven't come across devices that support floating point in a different format than [IEEE 754](http://en.wikipedia.org/wiki/IEEE_754). From my experience, your best bet is to hope for the standard, because otherwise you usually end up building algorithms and code around the capabilities of the device. When `sin(x)` suddenly costs 1000 times as much, you better pick an algorithm that doesn't need it.
## IEEE 754 - Consistency
The only non-portability I found here is when you expect bit-identical results across platforms. The biggest influence is the optimizer. Again, you can trade accuracy and speed for consistency. Most compilers have a option for that - e.g. "floating point consistency" in Visual C++. But note that this is always accuracy *beyond* the guarantees of the standard.
*Why results become inconsistent?*
First, FPU registers often have higher resolution than double's (e.g. 80 bit), so as long as the code generator doesn't store the value back, intermediate values are held with higher accuracy.
Second, the equivalences like `a*(b+c) = a*b + a*c` are not exact due to the limited precision. Nonetheless the optimizer, if allowed, may make use of them.
Also - what I learned the hard way - printing and parsing functions are not necessarily consistent across platforms, probably due to numeric inaccuracies, too.
## float
It is a common misconception that float operations are intrinsically faster than double. working on large float arrays is faster usually through less cache misses alone.
Be careful with float accuracy. it can be "good enough" for a long time, but I've often seen it fail faster than expected. Float-based FFT's can be much faster due to SIMD support, but generate notable artefacts quite early for audio processing. | Use fixed point.
However, if you want to approach the realm of possibly making portable floating point operations, you at least need to use `controlfp` to ensure consistent FPU behavior as well as ensuring that the compiler enforces ANSI conformance with respect to floating point operations. Why ANSI? Because it's a standard.
And even then you aren't guaranteeing that you can generate identical floating point behavior; that also depends on the CPU/FPU you are running on. | How to write portable floating point arithmetic in c++? | [
"",
"c++",
"floating-point",
""
] |
I have started using gettext for translating text and messages i send to user.
I am using poedit as an editor, but i am struggling with dynamic messages.
For example i have things like the login where i have a variable that tells the type of error.
```
$this->translate('page-error-' . $error);
```
When i auto update from poedit this gets read like "page-error-".
What i do is have a file where i place dummy calls to the translate method with all the possible keys to have them added in my poedit when auto updating.
I don't particularly like this situation.
How do you guys do it.
Thanks for your ideas | No -- this is not possible, because the editor (and the `gettext` tools) are reading your sources, not executing your program. You'll have to keep the dummy calls or add the keys to the translation files yourself. | Are you trying something like
```
$this->translate(sprintf('page-error-%s', $error));
``` | poedit workaround for dynamic gettext | [
"",
"php",
"internationalization",
"gettext",
"poedit",
""
] |
I have a table, and when the user clicks on each cell, some details should appear in a small popup div that appears where the user clicked. I'm using jQuery, but not to bind the function to the onClick event.
```
function detailPopup(cell, event, groupName, groupID, ...)
{
var newDiv = document.createElement("div");
newDiv.id = "detailPop" + groupID;
newDiv.className = "priceDetailPopup";
newDiv.innerHTML = "<p>" + groupName + "</p>"; // more will go here
$(newDiv).click(function()
{
$(this).fadeOut("fast").remove();
}
);
$("#main").append(newDiv);
$(newDiv).css({"left" : event.pageX, "top" : event.pageY}).fadeIn("fast");
}
```
Everything is working wonderfully in FF, Safari, and Chrome. In IE, it all works except that the detail div appears below the table. **event.pageX/Y aren't working.** I know jQuery will fix those for IE if I bind the function through jQuery like this:
```
$(cell).click(function(e) { ... e.pageX ... })
```
But I can't do that. (I don't think I can - if you do, please explain how I can get six variables into that function without having to use non-xhtml tags in the cell.)
Is there a way to have jQuery "fix" the event object without binding the function through jQuery? $JQuery.fixEvent(event); or something? I can't find any reference to doing so on their site. | ```
e = jQuery.event.fix(e); //you should rename your event parameter to "e"
```
I found the `fix` function by searching through the jQuery source code.
Alternatively, you could use this to get the mouse coordinates *without* jQuery...
```
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
```
Via PPK: <http://www.quirksmode.org/js/events_properties.html> | This blog post seems to be relevant: <http://www.barneyb.com/barneyblog/2009/04/10/jquery-bind-data/>
Seems it's just `jQuery("#selector").bind("click", {name: "barney"}, clickHandler);`, then `e.data.name` to access it in the event. | event.pageX - Use jQuery Event in a function not bound through jQuery? | [
"",
"javascript",
"jquery",
"events",
""
] |
Let's say I want to have a function which reads data from the SerialPort
and returns a byte[].
```
public byte[] RequestData(byte[] data)
{
//See code below
}
```
Something as simple as this really doesn't work/perform well and isn't very reliable:
```
byte[] response = new byte[port.ReadBufferSize];
port.Open();
port.Write(data, 0, data.Length);
Thread.Sleep(300); //Without this it doesn't even work at all
Console.WriteLine("Bytes to read: {0}", port.BytesToRead);
int count = port.Read(response, 0, port.ReadBufferSize);
Console.WriteLine("Read {0} bytes", count);
port.Close();
port.Dispose();
return response.GetSubByteArray(0, count);
```
I also tried replacing the Thread.Sleep with something like:
```
while (port.BytesToRead < 14)
{
//Maybe Thread.Sleep(10) here?
}
```
But that causes problems to. (PS: I know I need at least 14 bytes)
Of course a better way (I think) would be to have something like:
```
port.ReceivedBytesThreshold = 14;
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
port.Open();
port.Write(data, 0, data.Length);
```
And then having a handler of course:
```
void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
var port = (SerialPort)sender;
while (port.BytesToRead > 0)
{
//Read the data here
}
}
```
But then I can't return the data as the result of the function I wanted to define?
The client code using this would have to subscribe to an event raised by this code,
but then how would it know the response is really the response to the request it just made.
(Multiple messages might be sent, and I can imagine one message taking longer to process on the other side than the other, or something).
Any advise would be welcome
**UPDATE**
The following code works a lot better, but if I remove the Thread.Sleep() statements it once again stops working properly. For example, the serial port monitoring tool clearly indicates 17 bytes have been written on the serial line. The first time BytesToRead = 10 and the next time BytesToRead = 4 , but then BytesToRead remains 0 so where did the last 3 bytes go to ?
```
void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(100);
while (port.BytesToRead > 0)
{
Console.WriteLine("Bytes to read: {0}", port.BytesToRead);
var count = port.BytesToRead;
byte[] buffer = new byte[count];
var read = port.Read(buffer, 0, count);
if (count != read)
Console.WriteLine("Count <> Read : {0} {1}", count, read);
var collectAction = new Action(() =>
{
var response = dataCollector.Collect(buffer);
if (response != null)
{
this.OnDataReceived(response);
}
});
collectAction.BeginInvoke(null, null);
Thread.Sleep(100);
}
}
``` | Problem solved:
```
void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
var count = port.BytesToRead;
byte[] buffer = new byte[count];
var read = port.Read(buffer, 0, count);
var response = dataCollector.Collect(buffer);
if (response != null)
{
this.OnDataReceived(response);
}
}
```
It seems the problem wasn't actually this code but the code in the `dataCollector.Collect()` method. | Here's how I've done it:
I have a wrapper for the class that accepts the vital data for the connection in the constructor and does the basic setup in that constructor. The consumer of the class calls a Connect method, which fires off another thread to perform the connection (non-blocking).
When the connection is complete, a StateEvent is fired indicating the connection is completed. At this time a Send queue is setup, a thread to work that queue is fired off and a read thread is also setup. The read thread reads 128 characters of data from the SerialPort, converts that to a string and then fires an event to pass along the received data. This is wrapped in a while thread that loops as long as the connection is maintained. When the consumer wants to send something, a Send method simply enqueues the data to be sent.
As far as knowing that the response is in response to something that was sent really isn't the job of a connection class. By abstracting away the connection into something as easy to handle as that, the consumer of the class can cleanly maintain the logic to determine if the response is what it expected. | Obviously this is not the correct way to read with SerialPort | [
"",
"c#",
".net",
"asynchronous",
"serial-port",
""
] |
I'm getting a C++ compiler error which I'm not familiar with. Probably a really stupid mistake, but I can't quite put my finger on it.
Error:
```
test.cpp:27: error: member initializer expression list treated as compound expression
test.cpp:27: warning: left-hand operand of comma has no effect
test.cpp:27: error: invalid initialization of reference of type ‘const Bar&’ from expression of type ‘int’
```
Code:
```
1 #include <iostream>
2
3 class Foo {
4 public:
5 Foo(float f) :
6 m_f(f)
7 {}
8
9 float m_f;
10 };
11
12 class Bar {
13 public:
14 Bar(const Foo& foo, int i) :
15 m_foo(foo),
16 m_i(i)
17 {}
18
19 const Foo& m_foo;
20 int m_i;
21 };
22
23
24 class Baz {
25 public:
26 Baz(const Foo& foo, int a) :
27 m_bar(foo, a)
28 {}
29
30 const Bar& m_bar;
31 };
32
33 int main(int argc, char *argv[]) {
34 Foo a(3.14);
35 Baz b(a, 5.0);
36
37 std::cout << b.m_bar.m_i << " " << b.m_bar.m_foo.m_f << std::endl;
38
39 return 0;
40 }
```
Note:
It looks like the compiler is evaluating the commas in line 27 like here:
<http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/co.htm>
**edit:**
Okay, I understand the problem as Alan explained it. Now, for extra imaginary points, can someone explain how the compiler (g++) came up with the error message it gave? | m\_bar is a reference, so you can't construct one.
As others have noted, you can initialise references with the object it refers to, but you can't construct one like you're trying to do.
Change line 30 to
```
const Bar m_bar
```
and it'll compile / run properly. | m\_bar is declared as a "const reference" and therefore can't be instantiated with the constructor you've supplied.
Consider making m\_bar a member, or passing a pre-constructed Bar object to the constructor. | C++ error - "member initializer expression list treated as compound expression" | [
"",
"c++",
""
] |
I know that I can use `$.html` to set the HTML content of something, and `$.text` to set the content (and that this escapes the HTML).
Unfortunately, I'm using `$.append`, which doesn't escape the HTML.
I've got something like this:
```
function onTimer() {
$.getJSON(url, function(data) {
$.each(data, function(i, item) {
$('#messages').append(item);
}
}
}
```
...where the url returns an array of strings. Unfortunately, if one of those strings is (e.g.) `<script>alert('Hello')</script>`, this gets executed.
How do I get it to escape HTML? | Check out how jQuery does it:
```
text: function( text ) {
if ( typeof text !== "object" && text != null )
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
var ret = "";
jQuery.each( text || this, function(){
jQuery.each( this.childNodes, function(){
if ( this.nodeType != 8 )
ret += this.nodeType != 1 ?
this.nodeValue :
jQuery.fn.text( [ this ] );
});
});
return ret;
},
```
So something like this should do it:
```
$('#mydiv').append(
document.createTextNode('<b>Hey There!</b>')
);
```
**EDIT**: Regarding your example, it's as simple as:
```
$('#messages').append(document.createTextNode(item));
``` | You're appending an element which already has content? Or you're adding the content after you append? Either way, you still need to do .text(...) on that element.
If you're using append and passing HTML as the argument, then try creating the element first, and passing it to append.
Ex:
```
$('<div/>').text('your content here').appendTo('div#someid')
``` | Escaping text with jQuery append? | [
"",
"javascript",
"jquery",
""
] |
I have the following script element in my web page:
```
<script src="default.js" type="text/javascript"></script>
```
Using JavaScript, I want to be able to retrieve the content of the script file. I know I could use an ajax request to get the data but then I am getting something from the server that I already have locally.
So what I would prefer to do is retrieve the content from the DOM (if that's possible) or something that has the same result.
Cheers
Anthony
UPDATE
I was trying to simplify the question, maybe a bad a idea, I thought this way would cause less questions.
The real situation I have is as follows, I actually have
```
<script type="text/html" class="jq-ItemTemplate_Approval">
...
html template that is going to be consumed by jQuery and jTemplate
...
</script>
```
Now this works fine but it means each time the page loads I have to send down the template as part of the HTML of the main page. So my plan was to do the following:
```
<script src="template.html" type="text/html"></script>
```
This would mean that the browser would cache the content of template.html and I would not have to send it down each time. But to do this I need to be able to get the content from the file.
Also in this case, as far as I know, requesting the content via ajax isn't going to help all that much because it has to go back to the server to get the content anyway. | I think what you want to do is to assign a variable inside template.js. Then you have the variable available for use wherever you want in jquery. Something like:
```
var tpl = "<div> ... </div>"
```
Wouldn't this be a simpler solution to your problem? We do this in Ext JS. I think this will work for you in jQuery. | If I understand you correctly, you don't want to use Ajax to load an html template text, but rather have it loaded with the rest of the page. If you control the server side, you can always include the template text in an invisible div tag that you then reference from Javascript:
```
<div id="template" style="display:none;">
...template text...
</div>
<script>
// pops up the template text.
alert(document.getElementById("template").innerHTML);
</script>
```
If you are just looking for to load the template so that you can have it cached, you can put the contents in a variable like this:
```
<script>
var template = "template text..";
</script>
```
or you can load it using ajax and store the template in a variable so it is accessible. It's pretty trivial in jquery:
```
var template;
$.get("template.html", function(data){
template = data;
});
``` | Getting content of a script file using Javascript | [
"",
"javascript",
"html",
"dom",
"scripting",
""
] |
Just learning PHP and I'm having some trouble understanding mysql\_query. My understanding is that mysql\_query is supposed to return FALSE if the record is not found. However, it seems that it always returns true because "FOUND!" is always the result:
```
$q = "SELECT * FROM users WHERE username = 'doesnotexist'";
$r = mysql_query($q);
if (!$q) {
echo "<p>NOT FOUND!</p>";
} else {
echo "<p>FOUND!</p>";
}
mysql_close();
```
Thanks in advance for any light you can shed. | [mysql\_query](https://www.php.net/mysql_query) returns false if there is an error, not if there are no results found. From the documentation:
> For SELECT, SHOW, DESCRIBE, EXPLAIN
> and other statements returning
> resultset, `mysql_query()` returns a
> resource on success, or FALSE on
> error.
>
> For other type of SQL statements,
> INSERT, UPDATE, DELETE, DROP, etc,
> `mysql_query()` returns TRUE on success
> or FALSE on error.
>
> `mysql_query()` will also fail and
> return FALSE if the user does not have
> permission to access the table(s)
> referenced by the query.
If you want to check to see if there were results returned by your query, use [`mysql_num_rows()`](https://www.php.net/mysql_num_rows). See the documentation:
> Use `mysql_num_rows()` to find out how
> many rows were returned for a SELECT
> statement or `mysql_affected_rows()` to
> find out how many rows were affected
> by a DELETE, INSERT, REPLACE, or
> UPDATE statement. | You are checking the '$q' variable (your sql statement) instead of the '$r' variable (the mysql result) | PHP mysql_query not returning false | [
"",
"php",
"mysql",
""
] |
I have group checkboxes and I like if this group have behaviour like radiobuttons with same name atribute.
Each checkbox has different name.
Only one can be chosen from checkboxes.
How I can do this?
---
**Solution**
Why I need this?
Because we need consistency webUI.
Please, this is not question about our application architecture. :)
**HTML Sample**
```
<div class="multiCheckBox">
<span class="multiGroup">
<div><input class="multiItem" value="111" name="list" type="checkbox" />111</div>
<div><input class="multiItem" value="112" name="list" type="checkbox" />112</div>
<div><input class="multiItem" value="113" name="list" type="checkbox" />113</div>
</span>
<span>
<div><input class="multiItem" value="121" name="list" type="checkbox" />121</div>
<div><input class="multiItem" value="122" name="list" type="checkbox" />122</div>
<div><input class="multiItem" value="133" name="list" type="checkbox" />123</div>
</span>
<span>
<div><input class="multiItem" value="131" name="list" type="checkbox" />131</div>
<div><input class="multiItem" value="132" name="list" type="checkbox" />132</div>
<div><input class="multiItem" value="133" name="list" type="checkbox" />133</div>
</span>
</div>
```
**JavaScript**
```
var $groups = $("span.multiGroup", $that);
$groups.each(function() {
var $group = $(this);
var $checkboxes = $(":checkbox", $group);
$checkboxes.click(function() {
var $activeCheckbox = $(this);
var state = $activeCheckbox.attr('checked');
$checkboxes.attr('checked', false);
$activeCheckbox.attr('checked', state);
});
});
``` | Here's a hint: Use radio buttons. ;)
I wouldn't recommend doing this because it would be considered bad for usability and would certainly violate the principle of least surprise. Users have been conditioned to expect radios to accept 1 check and checkboxes to accept many. [Don't make your users think.](http://www.sensible.com/)
If you have your reasons, though, here's how to go about doing this with jQuery:
```
<input type='checkbox' name='mygroup1' value='1' class='unique'>
<input type='checkbox' name='mygroup2' value='2' class='unique'>
<input type='checkbox' name='mygroup3' value='3' class='unique'>
```
And the jQuery:
```
var $unique = $('input.unique');
$unique.click(function() {
$unique.filter(':checked').not(this).removeAttr('checked');
});
```
And here's a [live sample](http://jsbin.com/uwewi).
**EDIT**:
As pointed out in the comments, this would allow the user to deselect all checkboxes even if they chose one initially, which isn't exactly like radio buttons. If you want this, then the jQuery would look like this:
```
var $unique = $('input.unique');
$unique.click(function() {
$unique.removeAttr('checked');
$(this).attr('checked', true);
});
``` | Why don't you use radio buttons, then?
The difference is there for a reason. It has been designed this way, and from a user perspective radio buttons mean "select one", and checkboxes mean "select many".
Don't break user's expectations by changing this well-tried paradigm. It's a bad thing when application developers prefer "looks" over usability and convention, so don't be one of them.
User interfaces work because the metaphors used (checkboxes, buttons, the shape of the mouse pointer, colors, etc.) are and behave a certain way. Users will have problems with your app and may not even know why when you do things like this.
This is an anti-pattern that falls into the same category as changing the label with the checkbox state:
```
[ ] enable option vs. [ ] option
[x] disable option [x] option
``` | jQuery - checkboxes like radiobuttons | [
"",
"javascript",
"jquery",
""
] |
I've seen this on occasion in books I've read. But I've found no explanation.
```
for (;;)
{
// Do some stuff.
}
```
Is it kind of like "while(true)"? Basically an endless loop for polling or something? Basically something you'd do until you intentionally break the loop? | > Is it kind of like "while(true)"?
Yes. It loops forever.
---
Also note the comment by Andrew Coleson:
> Languages like C don't have built-in boolean primitives, so some people prefer for(;;) over while(1) | Yes.
In a for if nothing is provided:
* The initialisation does nothing.
* The condition is always true
* The count statement does nothing
It is equivalent to while(true). | What does "for(;;)" do in C#? | [
"",
"c#",
".net",
""
] |
Javascript Objects and JScript Dictionary are both associative Arrays
```
obj = new Object ;
dic = new ActiveXObject("Scripting.Dictionary") ;
```
My question is... Is there any difference between them in terms of efficiency (either space or time) ??
In terms of functionality, I know a Dictionary is better because it allows more than just scalar types as keys. But putting that aside, which one is better/faster?
**EDIT:**
This is for Windows scripting, not for web development.
**EDIT2:**
I'm particularly interested in the lookup efficiency, since I'll need to work with big collections. | It appears from this document that the lookup is quicker using Dictionary; however the inserts are slower.
<https://web.archive.org/web/20181223064604/http://www.4guysfromrolla.com:80/webtech/100800-1.2.shtml> | Scripting.Dictionary is a COM/ActiveX component (can be used in any of MS scripting languages).
I wouldn't recommend it because every time you access it, you're calling into the COM component, which is very slow.
But if you need its functionality, you can use it, but beware that it only works in IE... | Javascript Object vs JScript Dictionary | [
"",
"javascript",
"scripting",
"associative-array",
"jscript",
"wsh",
""
] |
I am doing an application which is used to clear the Temp files, history etc, when the user log off. So how can I know if the system is going to logoff (in C#)? | There is a property in **Environment** class that tells about if shutdown process has started:
```
Environment.HasShutDownStarted
```
But after some googling I found out that this may be of help to you:
```
using Microsoft.Win32;
//during init of your application bind to this event
SystemEvents.SessionEnding +=
new SessionEndingEventHandler(SystemEvents_SessionEnding);
void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
{
if (Environment.HasShutdownStarted)
{
//Tackle Shutdown
}
else
{
//Tackle log off
}
}
```
But if you only want to clear temp file then I think distinguishing between shutdown or log off is not of any consequence to you. | If you specifically need the log-off event, you can modify the code provided in TheVillageIdiot's answer as follows:
```
using Microsoft.Win32;
//during init of your application bind to this event
SystemEvents.SessionEnding +=
new SessionEndingEventHandler(SystemEvents_SessionEnding);
void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
{
if (e.Reason == SessionEndReasons.Logoff)
{
// insert your code here
}
}
``` | Get Log off event from system | [
"",
"c#",
".net",
"wpf",
"logout",
""
] |
I'm building a game in XNA 3 and I have the levels stored in XML format. What solution would you recommend for deserializing those XML files into level objects? it needs to be able to work on the Xbox. | I wouldn't recommend (de)serializing the actual levels, just create a simple container class that contains the information to construct a level object from it.
something like:
```
[Serializable()]
public class LevelDefinition
{
public Vector3 PlayerStartPosition { get; set; }
public string LevelName { get; set; }
public List<Enemy> Enemies { get; set; }
... etc
}
```
This will result in nice, clean XML.
And then just use the `XmlSerializer` class to deserialize it. | I haven't tried it on the 360 (I bet it will work), but XmlSerializer is a great simple way to save/load your object graphs into XML. Basically, you take your xml file and run xsd.exe against it. That will generate a set of C# classes that you can deserialize your XML into. In your code you will write something like:
```
var serializer = new XmlSerializer(typeof(LevelType));
var level = (LevelType)serializer.Deserialize(streamToYourLevel);
```
All done. | XML XNA Object Deserialization | [
"",
"c#",
"xml",
"xna",
"serialization",
""
] |
I am a Java guy and therefore would prefer a Java based framework for an auction site that I am planning to develop from scratch. But all my colleagues and friends have pointed out to me that the better sites that are coming up now-a-days are mostly written either using Ruby on Rails, Django or ASP.net MVC framework.
I was wondering if anyone here has done a comparisons of some Java-based frameworks like Struts 2 v/s any of the other frameworks with a focus on limited resources and performance? | There are some very big sites that run on Java based frameworks. I know that Sky News in the UK runs on Grails which uses Spring MVC under the covers. Not evidence per se but an indication that it is possible. If you need a comparison with RoR then Grails might be just the thing. Make sure you take into account the scaling possibilities that Java application servers give you. | I haven't seen any *good* performance comparisons. For example, the PetShop comparisons between Java and .NET from a long time ago were widely regarded as heavily flawed.
However, I'd expect that a *well-written* application, put through appropriate profiling and load testing, will be fine on any of those platforms. A poorly written application which guesses at performance bottlenecks will fail on any of those platforms.
In other words, it's more what you do with the platform than the choice of platform itself. Obviously that's not *universally* true, but for the choices you've given I believe you should be fine.
Now, you're more likely to do a good job on a platform you're familiar with (although it won't provide the same learning opportunities of course). So are you going to be the sole developer, or will there be a team? If you're going to be part of a team, what do the other members think? (It's not clear whether the friends/colleagues you mention are working on the project.) Are you doing this for fun, or to make money? (That may well change the emphasis you put on learning vs doing what you know.) | Performance comparisons of Frameworks to Use for an Auction Web Site | [
"",
"java",
"asp.net",
"ruby",
"django",
"struts2",
""
] |
I can see two ways to hook up the ViewModel to the View. One is in XAML and the other thru dependancy injection in the code behind.
Which method is more preferable? I prefer the xaml method because I don't want any code in the code behind at all, but is there any issues with one over the other?
```
<navigation:Page x:Class="MyNamespace.MyViewModel"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ViewModel="clr-namespace:MyNameSpace.MyViewModel"
xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
Title="ViewModel Page" >
<navigation:Page.Resources>
<ViewModel:MyViewModel x:Key="ViewModel"></ViewModel:MyViewModel>
</navigation:Page.Resources>
<Grid x:Name="LayoutRoot" Background="White"
DataContext="{StaticResource ViewModel}">
</Grid>
</navigation:Page>
```
**OR**
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
namespace MyNamespace
{
public partial class MyView : Page
{
public MyView()
{
InitializeComponent(MyViewModel viewModel);
this.DataContext = viewModel;
}
}
}
``` | Shawn has a good post on [View or ViewModel](http://wildermuth.com/2009/05/22/Which_came_first_the_View_or_the_Model) first. Having the VM in the XAML gives you Blendability (seeing sample data in Blend) which is cool, but the price is having to push info back into the View. John Papa has moved away from this approach for this reason.
I'm using Shawn's Marriage idea (see the link above).
HTH
-Erik | I use a class I dub a "Screen" that handles the MVVM triad. I started out iwth a V being inject into a VM, then a VM as a resource in a V, but in the end the Screen concept worked best for me. It allows me to use a V and a VM without being coupled to each other. It also abstracts away other functionality in my overall presentation framework. Here is the constructor for my Screen class as an example:
```
public CatalogItemScreen(IUnityContainer container) : base(container)
{
this.ViewModel = Container.Resolve<ICatalogItemViewModel>();
this.View = Container.Resolve<CatalogItemView>();
this.View.DataContext = this.ViewModel;
}
```
Notice that VM is created in the Screen, the V is created here, and the 2 are bound to each other. This sample uses Unity and Prism, but it is not necessary to achieve this. | Hooking up the ViewModel to the View in Silverlight | [
"",
"c#",
"silverlight",
"mvvm",
""
] |
I am trying this. I have built asp.net website.
When I publish to IIS through VS2008 it works fine.
Lets say my site is at c:\projects\Website1\
I want to publish it to c:\Inetpub\wwwroot\WebsiteOne
I am trying to mimic publish from studio. That is publish and remove anything that is in side.
I tried this:
aspnet\_compiler -v/WebsiteOne -f c:\Inetpub\wwwroot\WebsiteOne
Error:
error ASPRUNTIME: The precompilation target directory (c:\Inetpub\wwwroot\WebsiteOne) cannot be in the same tree as the source application directory (c:\inetpub\wwwroot\WebsiteOne).
When I tried this:
aspnet\_compiler -v/WebsiteOne
I get error This application is already precompiled.
Anyone who could give me an insight on how to do compile line building and publishing of website
Thanks | I solved the problem in meantime. You just need to pass the physical path, because it picks up one from IIS
```
aspnet_compiler -v /WebsiteOne -p c:\projects\Website1 -f c:\Inetpub\wwwroot\WebsiteOne
```
in case someone else encountered same problem.. | Also, you might consider using MSBuild on your solution file, and using the Publish target.
That's what VStudio is doing under the covers anyway. :-) | Trying to Build and Publish Asp.net website from command line using aspnet_compiler | [
"",
"c#",
"asp.net",
"command-line",
"aspnet-compiler",
""
] |
I'm developing an ASP.NET app (c#) that need to authenticate users. To do that I have a SQL Server database with the users of this application.
Which is the best way to do that?
I've been reading this:
[How to: Implement Simple Forms Authentication](http://msdn.microsoft.com/en-us/library/xdt4thhy.aspx)
In the example I will to replace this code:
```
<script runat="server">
void Logon_Click(object sender, EventArgs e)
{
if ((UserEmail.Text == "jchen@contoso.com") &&
(UserPass.Text == "37Yj*99Ps"))
{
FormsAuthentication.RedirectFromLoginPage
(UserEmail.Text, Persist.Checked);
}
else
{
Msg.Text = "Invalid credentials. Please try again.";
}
}
</script>
```
With my ADO.NET Entity code to search the user on the database. It will work?
Another way is Membership ([<http://msdn.microsoft.com/en-us/library/tw292whz.aspx][2]>) but I think it is the hardest way.
Or maybe I can use Windows Live ID but I don't know how to connect Live ID with my users table.
Thank you! | Membership is the easiest way to provide authentication IMO.
If you're interested in using it I recommend this [tutorial](https://web.archive.org/web/20210513220018/http://aspnet.4guysfromrolla.com/articles/120705-1.aspx) by Scott Mitchell: | One of the most important security rules (#7 on the OWASP top 10) is NOT to write your own authentication mechanism when there are tried and tested mechanisms available. ASP.Net Authentication is simple to use, and tried and tested, and you are setting yourself up for all kinds of pain if you proceed down the path of writing your own mechanism.
[Top 10 2007-Broken Authentication and Session Management](http://www.owasp.org/index.php/Top_10_2007-A7) | How to authenticate on ASP.NET | [
"",
"c#",
"asp.net",
"authentication",
""
] |
I would like to perform a test to check if an object is of a generic type. I've tried the following without success:
```
public bool Test()
{
List<int> list = new List<int>();
return list.GetType() == typeof(List<>);
}
```
What am I doing wrong and how can I perform this test? | If you want to check if it's an instance of a generic type:
```
return list.GetType().IsGenericType;
```
If you want to check if it's a generic `List<T>`:
```
return list.GetType().GetGenericTypeDefinition() == typeof(List<>);
```
As Jon points out, this checks the exact type equivalence. Returning `false` doesn't necessarily mean `list is List<T>` returns `false` (i.e. the object cannot be assigned to a `List<T>` variable). | I assume that you don't just want to know if the type is generic, but if an object is an instance of a particular generic type, without knowing the type arguments.
It's not terribly simple, unfortunately. It's not too bad if the generic type is a class (as it is in this case) but it's harder for interfaces. Here's the code for a class:
```
using System;
using System.Collections.Generic;
using System.Reflection;
class Test
{
static bool IsInstanceOfGenericType(Type genericType, object instance)
{
Type type = instance.GetType();
while (type != null)
{
if (type.IsGenericType &&
type.GetGenericTypeDefinition() == genericType)
{
return true;
}
type = type.BaseType;
}
return false;
}
static void Main(string[] args)
{
// True
Console.WriteLine(IsInstanceOfGenericType(typeof(List<>),
new List<string>()));
// False
Console.WriteLine(IsInstanceOfGenericType(typeof(List<>),
new string[0]));
// True
Console.WriteLine(IsInstanceOfGenericType(typeof(List<>),
new SubList()));
// True
Console.WriteLine(IsInstanceOfGenericType(typeof(List<>),
new SubList<int>()));
}
class SubList : List<string>
{
}
class SubList<T> : List<T>
{
}
}
```
EDIT: As noted in comments, this may work for interfaces:
```
foreach (var i in type.GetInterfaces())
{
if (i.IsGenericType && i.GetGenericTypeDefinition() == genericType)
{
return true;
}
}
```
I have a sneaking suspicion there may be some awkward edge cases around this, but I can't find one it fails for right now. | Testing if object is of generic type in C# | [
"",
"c#",
".net",
"generics",
"reflection",
"types",
""
] |
in a production environment running nginx reversing back to apache mpm-prefork/mod\_wsgi, im seeing **90** apache child processes, when i would expect that 40 would be the maximum, as configured below. the configuration/setup is nothing exciting:
1. nginx is reverse proxying to apache via `proxy_pass`, and serving static media
2. apache only serves dynamic requests
relevant nginx config:
```
worker_processes 15;
events {
worker_connections 1024;
}
keepalive_timeout 10;
```
relevant apache config:
```
KeepAlive Off
MaxKeepAliveRequests 100
KeepAliveTimeout 15
<IfModule mpm_prefork_module>
StartServers 20
MinSpareServers 7
MaxSpareServers 10
MaxClients 200
MaxRequestsPerChild 0
</IfModule>
```
mod\_wsgi config, where `webapp` is the name of the process:
```
WSGIDaemonProcess webapp user=www group=users threads=1 processes=40
```
am i missing something? | The mod\_wsgi daemon processes will appear to be Apache server child processes even though they aren't the same. This is because the mod\_wsgi daemon processes are a fork of Apache parent process and not a fork/exec. In other words, they executable name doesn't change.
To be able to distinguish mod\_wsgi daemon processes from normal Apache server child processes, supply the 'display-name' option to WSGIDaemonProcess. This option allows you to rename the process as viewable in output from 'ps' program and some variants of programs like 'top'. See documentation of WSGIDaemonProcess directive on mod\_wsgi site.
<http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIDaemonProcess> | You are using `mod_wsgi` in daemon mode, so `mod_wsgi` processes and Apache handler process are independent.
By your configuration right after the apache starts you have:
* 40(processes=) `mod_wsgi` processes are started the same time.
* 20(StartServers) Apache handler processes that can be automatically reduced to 10(MaxSpareServers) if there is not incoming activity.
Then on load, Apache handler processes can grow up to 200(MaxClients). But `mod_wsgi` processes count will be the same - 40.
My advice is to use worker mpm than Apache processes only dynamic content. It can help to reduce memory consumption and better scalability. | apache prefork/mod_wsgi spawned process count seemingly past configuration | [
"",
"python",
"apache",
"mod-wsgi",
""
] |
Let's say I have an animal and now I want to make it a dog. How do I go about doing this in java?
Right now I have a constructor that looks like
```
public Dog(Animal animal) {
this.setProperty(animal.getProperty);
...
}
```
While this works, it's fragile. Any other suggestions? | If your Dog extends Animal, you can create a constructor that takes an Animal and initializes the super(parent) constructor:
```
public class Dog extends Animal {
public Dog(Animal animal) {
super(animal);
}
}
```
Assuming you have an Animal class that has a copy constructor in this form:
```
public class Animal {
public Animal(Animal animal) {
// copies all properties from animal to this
}
}
```
You can create a Dog from an Animal by doing something like this:
```
Dog newDog = new Dog(myExistingAnimal);
``` | Try and use a factory. Rather than basing it on the constructor, use a factory to return a specific type of Animal based on whatever is your constraints. | How to copy an ancestor to a descendant | [
"",
"java",
"inheritance",
"copy",
"clone",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.