Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I am trying to create an array or list that could handle in theory, given adequate hardware and such, as many as 100^100 BigInteger entries. The problem with using an array or standard list is that they can only hold Integer.MAX\_VALUE number of entries. How would you work around this limitations? A whole new class/interface? A wrapper for list? another data type entirely? | A 22-dimensional java array would have enough space to hold the data - in theory.
But we should keep in mind, that the number of atoms in the whole universe is estimated to 10^78 ([ref in German](http://www.harri-deutsch.de/verlag/hades/clp/kap09/cd236b.htm)).
So, before starting to implement, you'd have to think how to store 10^23 bytes on every atom in the universe...
**Edit**
In general, if you need large datastructures that support access in O(1), you can create multidimensional arrays.
A 2-dimensional array *array[Integer.MAX\_VALUE][Integer.MAX\_VALUE]* can hold about *4.6x10^18* values. You can address each value *ai* by *array[ai mod Integer.MAX\_VALUE][ai div Integer.MAX\_VALUE]*. And of course this works for higher-dimensional arrays aswell. | 100^100 = 10^200. Assuming BigInteger's memory footprint being 28 bytes (it has 7 `int` fields) that's 2.8 \* 10^201 bytes or 2.8 \* 10^192 gigabytes. There's no adequate hardware and there never will be :-) | How would you handle making an array or list that would have more entries than the standard implementation would allow you to access | [
"",
"java",
"types",
"large-data-volumes",
""
] |
I have been reading over some code lately and came across some lines such as:
```
somevar &= 0xFFFFFFFF;
```
What is the point of anding something that has all bits turned on; doesn't it just equal somevar in the end? | "somevar" could be a 64-bit variable, this code would therefore extract the bottom 32 bits.
**edit:** if it's a 32-bit variable, I can think of other reasons but they are much more obscure:
* the constant 0xFFFFFFFF was automatically generated code
* someone is trying to trick the compiler into preventing something from being optimized
* someone intentionally wants a no-op line to be able to set a breakpoint there during debugging. | Indeed, this wouldn't make sense if `somevar` is of type `int` (32-bit integer). If it is of type `long` (64-bit integer), however, then this would mask the upper (most significant) half of the value.
Note that a `long` value is not guaranteed to be 64 bits, but typically *is* on a 32-bit computer. | AND with full bits? | [
"",
"c++",
"c",
"bit-manipulation",
""
] |
1. I have excel file with such contents:
* A1: SomeString
* A2: 2
All fields are set to String format.
2. When I read the file in java using POI, it tells that A2 is in numeric cell format.
3. The problem is that the value in A2 can be 2 or 2.0 (and I want to be able to distinguish them) so I can't just use `.toString()`.
What can I do to read the value as string? | ## Set cell type to string
I had same problem. I did `cell.setCellType(Cell.CELL_TYPE_STRING);` before reading the string value, which solved the problem regardless of how the user formatted the cell. | ## `DataFormatter`
I don't think we had this class back when you asked the question, but today there is an easy answer.
What you want to do is use the [DataFormatter class](http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/DataFormatter.html). You pass this a cell, and it does its best to return you a string containing what Excel would show you for that cell. If you pass it a string cell, you'll get the string back. If you pass it a numeric cell with formatting rules applied, it will format the number based on them and give you the string back.
For your case, I'd assume that the numeric cells have an integer formatting rule applied to them. If you ask DataFormatter to format those cells, it'll give you back a string with the integer string in it.
Also, note that lots of people suggest doing `cell.setCellType(Cell.CELL_TYPE_STRING)`, but the [Apache POI JavaDocs quite clearly state that you shouldn't do this](https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html#setCellType%28int%29)! Doing the `setCellType` call will loose formatting, as the [javadocs explain](https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html#setCellType%28int%29) the only way to convert to a String with formatting remaining is to use the [DataFormatter class](http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/DataFormatter.html).
A simple example of using this class:
```
DataFormatter dataFormatter = new DataFormatter();
String formattedCellStr = dataFormatter.formatCellValue(cell);
``` | How can I read numeric strings in Excel cells as string (not numbers)? | [
"",
"java",
"excel",
"apache-poi",
""
] |
I want to print all the prime numbers between two numbers. This is my code:
```
package sphere;
import java.math.BigInteger;
import java.io.*;
class PrimeTest2 {
public static void main(String args[]) throws java.lang.Exception {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String s = r.readLine();
String [] splitted = s.split(" ");
BigInteger lower = new BigInteger(splitted[0]);
BigInteger upper = new BigInteger(splitted[1]);
int lowerAsInt = Integer.parseInt(splitted[0]);
int upperAsInt = Integer.parseInt(splitted[1]);
BigInteger intermediate = lower;
for (int i=lowerAsInt; i<upperAsInt; i++) {
intermediate = intermediate.nextProbablePrime();
System.out.println(intermediate);
}
}
}
```
When it's run with 1 10 the output is:
```
2
3
5
7
11
13
17
19
23
```
Why doesn't it stop at 7? | Because your program says run times (1 to 9) not stop below 10. Instead of your loop you probably want:
```
BigIntegerupper = BigInteger.valueOf(upperAsInt);
while (intermediate.compareTo(upper) <= 0) {
System.out.println(intermediate);
intermediate = intermediate.nextProbablePrime();
}
```
See the difference? Yours starts at 1 and stops at 9 (less than 10), printing a number on each iteration. The above stops when the number is greater than the upper bound. | You have it set to run where (i<10), not to stop when the value of a prime is greater than 10 | Working with Java's BigInteger probable primes | [
"",
"java",
"primes",
"biginteger",
""
] |
In C#, how does one obtain a reference to the base class of a given class?
For example, suppose you have a certain class, `MyClass`, and you want to obtain a reference to `MyClass`' superclass.
I have in mind something like this:
```
Type superClass = MyClass.GetBase() ;
// then, do something with superClass
```
However, it appears there is no suitable `GetBase` method. | Use Reflection from the Type of the current class.
```
Type superClass = myClass.GetType().BaseType;
``` | ```
Type superClass = typeof(MyClass).BaseType;
```
Additionally, if you don't know the type of your current object, you can get the type using GetType and then get the BaseType of that type:
```
Type baseClass = myObject.GetType().BaseType;
```
[documentation](http://msdn.microsoft.com/en-us/library/system.type.basetype.aspx) | C# : how do you obtain a class' base class? | [
"",
"c#",
"superclass",
""
] |
I am new to programming in general so please keep that in mind when you answer my question.
I have a program that takes a large 3D array (1 billion elements) and sums up elements along the various axis to produce a 2D array of a projection of each side of the data. The problem here is that it is very ram intensive as the program is constantly fetching information from the ram, both reading and writing.
The question is, will i gain any performance increases if i multithread the program or will I end up running into a RAM access bottleneck? When i say multithreading, i only mean multithreading for 2 or 4 cores, no more.
If it helps, my current computer configuration is 2.4ghz core2 quad, 1033 fsb, 4gb ram at 667mhz.
Thanks in advance,
-Faken
Edit:
It seems to me that people here are much more interested in this question that I had first expected. I'll expand the question and post some code for those who are interested.
First of all, a little background on me so you understand where I'm coming from. I am a mechanical engineering graduate student who some how managed to pick a topic that pretty much had nothing to do with mechanical engineering. I have taken 1 course in introductory java (forced) approximately 5 years ago and have never touched programming until about a month ago when i started my thesis in earnest. I have also taken (again forced, still don't know why) a course in electronics and computer engineering, we dealt with micro-controllers (8-bit), their inner workings, and some ASM coding for them. Other than that, I know next to nothing about programming.
Here is the code:
```
int dim = 1000;
int steps = 7 //ranges from 1 to 255
for (int stage = 1; stage < steps; stage++)
for (int j = 0; j < dim; j++)
for (int i = 0; i < dim; i++)
{
sum = 0;
for (int k = 0; k < dim; k++)
if (partMap[(((i * dim) + k) * dim) + j] >= stage)
sum++;
projection[(j*dim) + i] = sum;
}
```
This section of code operates on the z-axis only. The main data, due to the way it was constructed, has a strange addressing system but you don't need to worry about that. There is also other code for doing the projections of other sides of the cube but they do very different things. | There is only one way to optimize code: figure out what you're doing that's slow, and do less of it. A special case of "doing less of it" is to do something else instead that's faster.
So first of all, here's what I'm doing based on your posted code:
```
#include <fstream>
#include <sstream>
using std::ios_base;
template<typename Iterator, typename Value>
void iota(Iterator start, Iterator end, Value val) {
while (start != end) {
*(start++) = val++;
}
}
int main() {
const int dim = 1000;
const int cubesize = dim*dim*dim;
const int squaresize = dim*dim;
const int steps = 7; //ranges from 1 to 255
typedef unsigned char uchar;
uchar *partMap = new uchar[cubesize];
// dummy data. I timed this separately and it takes about
// a second, so I won't worry about its effect on overall timings.
iota(partMap, partMap + cubesize, uchar(7));
uchar *projection = new uchar[squaresize];
for (int stage = 1; stage < steps; stage++) {
for (int j = 0; j < dim; j++) {
for (int i = 0; i < dim; i++)
{
int sum = 0;
for (int k = 0; k < dim; k++)
if (partMap[(((i * dim) + k) * dim) + j] >= stage)
sum++;
projection[(j*dim) + i] = sum;
}
}
std::stringstream filename;
filename << "results" << stage << ".bin";
std::ofstream file(filename.str().c_str(),
ios_base::out | ios_base::binary | ios_base::trunc);
file.write((char *)projection, squaresize);
}
delete[] projection;
delete[] partMap;
}
```
(Edit: just noticed that "projection" should be an array of int, not uchar. My bad. This will make a difference to some of the timings, but hopefully not too big of one.)
Then I copied `result*.bin` to `gold*.bin`, so I can check my future changes as follows:
```
$ make big -B CPPFLAGS="-O3 -pedantic -Wall" && time ./big; for n in 1 2 3 4 5
6; do diff -q results$n.bin gold$n.bin; done
g++ -O3 -pedantic -Wall big.cpp -o big
real 1m41.978s
user 1m39.450s
sys 0m0.451s
```
OK, so 100 seconds at the moment.
So, speculating that it's striding through the billion-item data array that's slow, let's try only going through once, instead of once per stage:
```
uchar *projections[steps];
for (int stage = 1; stage < steps; stage++) {
projections[stage] = new uchar[squaresize];
}
for (int j = 0; j < dim; j++) {
for (int i = 0; i < dim; i++)
{
int counts[256] = {0};
for (int k = 0; k < dim; k++)
counts[partMap[(((i * dim) + k) * dim) + j]]++;
int sum = 0;
for (int idx = 255; idx >= steps; --idx) {
sum += counts[idx];
}
for (int stage = steps-1; stage > 0; --stage) {
sum += counts[stage];
projections[stage][(j*dim) + i] = sum;
}
}
}
for (int stage = 1; stage < steps; stage++) {
std::stringstream filename;
filename << "results" << stage << ".bin";
std::ofstream file(filename.str().c_str(),
ios_base::out | ios_base::binary | ios_base::trunc);
file.write((char *)projections[stage], squaresize);
}
for (int stage = 1; stage < steps; stage++) delete[] projections[stage];
delete[] partMap;
```
It's a bit faster:
```
$ make big -B CPPFLAGS="-O3 -pedantic -Wall" && time ./big; for n in 1 2 3 4 5
6; do diff -q results$n.bin gold$n.bin; done
g++ -O3 -pedantic -Wall big.cpp -o big
real 1m15.176s
user 1m13.772s
sys 0m0.841s
```
Now, `steps` is quite small in this example, so we're doing a lot of unnecessary work with the "counts" array. Without even profiling, I'm guessing that counting to 256 twice (once to clear the array and once to sum it) is quite significant compared with counting to 1000 (to run along our column). So let's change that:
```
for (int j = 0; j < dim; j++) {
for (int i = 0; i < dim; i++)
{
// steps+1, not steps. I got this wrong the first time,
// which at least proved that my diffs work as a check
// of the answer...
int counts[steps+1] = {0};
for (int k = 0; k < dim; k++) {
uchar val = partMap[(((i * dim) + k) * dim) + j];
if (val >= steps)
counts[steps]++;
else counts[val]++;
}
int sum = counts[steps];
for (int stage = steps-1; stage > 0; --stage) {
sum += counts[stage];
projections[stage][(j*dim) + i] = sum;
}
}
}
```
Now we're only using as many buckets as we actually need.
```
$ make big -B CPPFLAGS="-O3 -pedantic -Wall" && time ./big; for n in 1 2 3 4 5
6; do diff -q results$n.bin gold$n.bin; done
g++ -O3 -pedantic -Wall big.cpp -o big
real 0m27.643s
user 0m26.551s
sys 0m0.483s
```
Hurrah. The code is nearly 4 times as fast as the first version, and produces the same results. All I've done is change what order the maths is done: we haven't even looked at multi-threading or prefetching yet. And I haven't attempted any highly technical loop optimisation, just left it to the compiler. So this can be considered a decent start.
However it's still taking an order of magnitude longer than the 1s which iota runs in. So there are probably big gains still to find. One main difference is that iota runs over the 1d array in sequential order, instead of leaping about all over the place. As I said in my first answer, you should aim to always use sequential order on the cube.
So, let's make a one-line change, switching the i and j loops:
```
for (int i = 0; i < dim; i++)
for (int j = 0; j < dim; j++) {
```
This still isn't sequential order, but it does mean we're focussing on one million-byte slice of our cube at a time. A modern CPU has at least 4MB cache, so with a bit of luck we'll only hit main memory for any given part of the cube once in the entire program. With even better locality we could reduce the traffic in and out of L1 cache, too, but main memory is the slowest.
How much difference does it make?
```
$ make big -B CPPFLAGS="-O3 -pedantic -Wall" && time ./big; for n in 1 2 3 4 5
6; do diff -q results$n.bin gold$n.bin; done
g++ -O3 -pedantic -Wall big.cpp -o big
real 0m8.221s
user 0m4.507s
sys 0m0.514s
```
Not bad. In fact, this change alone brings the original code from 100s to 20s. So this is responsible for a factor of 5, and everything else I did is responsible for another factor of 5 (I think the difference between 'user' and 'real' time in the above is mostly accounted for by the fact my virus scanner is running, which it wasn't earlier. 'user' is how much time the program occupied a CPU, 'real' includes time spent suspended, either waiting on I/O or giving another process time to run).
Of course, my bucket sort relies on the fact that whatever we're doing with the values in each column is commutative and associative. Reducing the number of buckets only worked because large values are all treated the same. This might not be true for all your operations, so you'll have to look at the inner loop of each one in turn to figure out what to do with it.
And the code is a bit more complicated. Instead of running over the data doing "blah" for each stage, we're computing all the stages at the same time in a single run over the data. If you start doing row and column computations in a single pass, as I recommended in my first answer, this will get worse. You may have to start breaking your code into functions to keep it readable.
Finally, a lot of my performance gain came from an optimisation for the fact that "steps" is small. With `steps=100`, I get:
```
$ make big -B CPPFLAGS="-O3 -pedantic -Wall" && time ./big; for n in 1 2 3 4 5
6; do diff -q results$n.bin gold$n.bin; done
g++ -O3 -pedantic -Wall big.cpp -o big
real 0m22.262s
user 0m10.108s
sys 0m1.029s
```
This isn't so bad. With steps=100 the original code probably takes about 1400 seconds, although I'm not going to run it to prove that. But it's worth remembering that I haven't completely taken away the time dependency on "steps", just made it sub-linear. | Multithreading across multiple cores could reduce the time required to sum across the axes, but special care is required. You might actually get larger performance boosts from some changes you could make to your single thread code:
1. You only need as many threads to match the number of cores available to you. This is a CPU intensive operation, and threads are unlikely to be waiting for I/O.
2. The above assumption might not hold if the entire array does not fit in RAM. If portions of the array are paged in and out, some threads will be waiting for paging operations to complete. In that case, the program might benefit from having more threads than cores. Too many, however, and performance will drop due to the cost of context switching. You might have to experiment with the thread count. The general rule is to minimize the number of context switches between ready threads.
3. If the entire array does not fit in RAM, you want to minimize paging! The order in which each thread accesses memory matters, as does the memory access pattern of all the running threads. To the extent possible, you would want to finish up with one part of the array before moving to the next, never to return to a covered area.
4. Each core would benefit from having to access a completely separate region of memory. You want to avoid memory access delays caused by locks and bus contention. At least for one dimension of the cube, that should be straightforward: set each thread with its own portion of the cube.
5. Each core would also benefit from accessing more data from its cache(s), as opposed to fetching from RAM. That would mean ordering the loops such that inner loops access nearby words, rather than skipping across rows.
6. Finally, depending on the data types in the array, the SIMD instructions of Intel/AMD processors (SSE, at their various generations) can help accelerate single core performance by summing multiple cells at once. VC++ has some [built in support](http://msdn.microsoft.com/en-us/library/t467de55(VS.80).aspx).
7. If you have to prioritize your work, you might want to first minimize disk paging, then concentrate on optimizing memory access to make use of the CPU caches, and only then deal with multithreading. | Will multi threading provide any performance boost? | [
"",
"c++",
"performance",
"multithreading",
"cpu",
"ram",
""
] |
I have been trying to find out why the following lines of code do not work:
```
$('#add-cloud > select').change(function() {
var selected = parseInt($('#add-cloud select option:selected').val());
$("#cloud-calculator table tr:eq(selected)").css("color", "red");
});
```
If I change `:eq(selected)` to `:eq(4)` for example - works fine. How do you pass variable as an argument to `:eq()` ? | You have to concatenate your variable with your selector:
```
$("tr:eq("+selected+")");
``` | The way you're doing it, you're embedding the actual string `"selected"` in the selector. You need to construct a string using your `selected` variable as a part of it:
```
$("#cloud-calculator table tr:eq(" + selected + ")").css("color", "red");
``` | jQuery: Pass variable to :eq() does not work | [
"",
"javascript",
"jquery",
""
] |
I just recently heard of duck typing and I read the [Wikipedia article](http://en.wikipedia.org/wiki/Duck_typing) about it, but I'm having a hard time translating the examples into Java, which would really help my understanding.
Would anyone be able to give a clear example of duck typing in Java and how I might possibly use it? | Java is by design not fit for duck typing. The way you might choose to do it is reflection:
```
public void doSomething(Object obj) throws Exception {
obj.getClass().getMethod("getName", new Class<?>[] {}).invoke(obj);
}
```
But I would advocate doing it in a dynamic language, such as Groovy, where it makes more sense:
```
class Duck {
quack() { println "I am a Duck" }
}
class Frog {
quack() { println "I am a Frog" }
}
quackers = [ new Duck(), new Frog() ]
for (q in quackers) {
q.quack()
}
```
[Reference](http://onestepback.org/articles/groovy/ducktyping.html) | See [this blog post](http://thinking-in-code.blogspot.com/2008/11/duck-typing-in-java-using-dynamic.html). It gives a very detailed account of how to use dynamic proxies to implement duck typing in Java.
In summary:
* create an interface that represents the methods you want to use via duck typing
* create a dynamic proxy that uses this interface and an implementation object that invokes methods of the interface on the underlying object by reflection (assuming the signatures match) | What's an example of duck typing in Java? | [
"",
"java",
"duck-typing",
""
] |
For some reason, ASP.NET code on my server is now returning a format of **dd/MM/yyyy** instead of **MM/dd/yyyy** when I use **DateTime.ToString("g")**.
Rather than replacing all the "g" format strings with a concrete format string or CultureInfo argument, is there a way I can just override, across the application, the default "short date" format?
My preference is actually "yyyy-MM-dd" as the default format, but I can live with the US-centric MM/dd/yyyy, as all users are in the US.
**Clarification:** I do not want to change the entire default culture, which could impact things such as currency and use of decimals/commas in formatting numbers.
I just want to override any ToString("g") call to use the ISO/IEC 8824 date format ("yyyy-MM-dd").
I could search and replace across my code to force a CultureInfo in every ToString() call, but that doesn't strike me as the most maintainable solution.
My current solution is that I've defined a static method for formatting a date, and I call it instead of ToString() across my entire codebase. But again, if I forget to do so somewhere in the code, I'll have a goofy date again. | Setting the culture wasn't an option, nor was depending on the server's regional settings.
I ended up writing a utility function for formatting dates:
```
Public Shared Function FormatShortDate(ByVal d As Date) As String
If d=#1/1/0001# Then Return ""
If d=#1/1/1900# Then Return ""
'ISO/IEC 8824 date format
Return d.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture)
End Function
```
I call this everywhere I need to push a date out to the user. It also handles display of default ("magic") dates.
I wrote some similar functions for and FormatShortDateTime and FormatLongDateTime. | You can set the default culture at the web.config (application level), Page directive or control directive.
I have various apps where the master pages are set up for different cultures, and the pages and controls inherit from there. | Change ASP.NET default Culture for date formatting | [
"",
"c#",
"datetime",
"asp.net-3.5",
"string-formatting",
"cultureinfo",
""
] |
I am going to start working on a website that has already been built by someone else.
The main script was bought and then adjusted by the lead programmer. The lead has left and I am the only programmer.
Never met the lead and there are no papers, documentation or comments in the code to help me out, also there are many functions with single letter names. There are also parts of the code that are all compressed in one line (like where there should be 200 lines there is one).
There are a few hundred files.
My questions are:
Does anyone have any advice on how to understand this system?
Has anyone had any similar experiences?
Does anyone have a quick way of decompressing the lines?
Please help me out here. This is my first big break and I really want this to work out well.
Thanks
EDIT:
On regards to the question:
- Does anyone have a quick way of decompressing the lines?
I just used notepad++ (extended replace) and netbeans (the format option) to change a file from 1696 lines to 5584!!
This is going to be a loooonnngggg project | For reformatting the source, try this online pretty-printer: <http://www.prettyprinter.de/>
For understanding the HTML and CSS, use [Firebug](http://www.getfirebug.com/).
For understanding the PHP code, step through it in a debugger. (I can't personally recommend a PHP debugger, but I've heard good things about [Komodo](http://www.activestate.com/komodo/).)
Start by checking the whole thing into source control, if you haven't already, and then as you work out what the various functions and variables do, rename them to something sensible and check in your changes.
If you can cobble together some rough regression tests (eg. with [Selenium](http://seleniumhq.org/)) before you start then you can be reasonably sure you aren't breaking anything as you go. | Ouch! I feel your pain!
A few things to get started:
1. If you're not using source control, don't do anything else until you get that set up. As you hack away at the files, you need to be able to revert to previous, presumably-working versions. Which source-control system you use isn't as important as using one. Subversion is easy and widely used.
2. Get an editor with a good PHP syntax highlighter and code folder. Which one is largely down to platform and personal taste; I like [JEdit](http://jedit.org/) and [Notepad++](http://notepad-plus.sourceforge.net/uk/site.htm). These will help you navigate the code within a page. JEdit's folder is the best around. Notepad++ has a cool feature that when you highlight a word it highlights the other occurrences in the same file, so you can easily see e.g. where a tag begins, or where a variable is used.
3. Unwind those long lines by search-and-replace '`;`' with '`;\n`' -- at least you'll get every statement on a line of its own. The pretty-printer mentioned above will do the same plus indent. But I find that going in and indenting the code manually is a nice way to start to get familiar with it.
4. Analyze the website's major use cases and trace each one. If you're a front-end guy, this might be easier if you start from the front-end and work your way back to the DB; if you're a back-end guy, start with the DB and see what talks to it, and then how that's used to render pages -- either way works. Use FireBug in Firefox to inspect e.g. forms to see what names the fields take and what page they post to. Look at the PHP page to see what happens next. Use some echo() statements to print out the values of variables at various places. Finally, crack open the DB and get familiar with its schema.
5. Lather, rinse, repeat.
Good luck! | Getting to know a new web-system that you have to work on/extend | [
"",
"php",
"mysql",
"web-applications",
""
] |
I'm working on an application that deals with periodic payments
Payments are done fortnightly i.e.
* payment 1: 2009-06-01
* payment 2: 2009-06-15
* payment 3: 2009-06-29
and now I need a SQL statement that can calculate the closest next payment date from a given date in the WHERE clause
i.e.
SELECT ... FROM ... WHERE someDate < *[CALCULATE NEXT PAY DATE FROM A GIVEN DATE]*
If I were to do this in C# I would go
```
static DateTime CalculateNextPayDateFrom(DateTime fromDate)
{
var firstEverPayment = new DateTime(2009, 6, 1);
var nextPayment = firstEverPayment;
while (nextPayment < fromDate)
{
nextPayment += new TimeSpan(14, 0, 0, 0);
}
return nextPayment;
}
```
So if I do
```
Console.WriteLine(CalculateNextPayDateFrom(new DateTime(2009, 6, 12)).ToString());
Console.WriteLine(CalculateNextPayDateFrom(new DateTime(2009, 6, 20)).ToString());
```
output will be
```
15/06/2009 12:00:00 a.m.
29/06/2009 12:00:00 a.m.
```
but I'm totally stuck when I have to do this in SQL.
Can anyone give me a hand on this? I am using SQL Server 2005
UPDATE:
By the way, I forgot to mention that last payment date is not available in database, it has to be calculated at runtime. | To do the calculation properly you need what I would refer to as the reference date e.g. the date from which you start the 2 week cycle from. (in your code thats the firstEverPayment declaration)
Given that you can datediff the number of days between now and the reference to get the number of days.
Divide by 14, but round down using Floor (e.g. work out how many 2 week intervals have already occured)
Add 1 - to move forward a two week interval.
(You can skip the add 1 by using Ceiling, not floor)
Multiply by 14 - to get the day count
Use Date Add to add those days.
Something like
select dateadd(dd, (Ceiling(datediff (dd, '1/1/09', getdate()) /14) \* 14), '1/1/09')
Where I used 1/1/09 as the reference date. | how about something like this. Grab the current day of the year, divide by 14 to get the remainder, and add the difference from 14 back to your date. You may have to adjust the DaysOfYear to match your first payment of the year...
```
declare @mydate datetime
set @mydate = '20090607'
select DATEADD(dd, 14 - DATEPART(dayofyear, @mydate) % 14, @mydate)
set @mydate = '20090611'
select DATEADD(dd, 14 - DATEPART(dayofyear, @mydate) % 14, @mydate)
set @mydate = '20090612'
select DATEADD(dd, 14 - DATEPART(dayofyear, @mydate) % 14, @mydate)
set @mydate = '20090617'
select DATEADD(dd, 14 - DATEPART(dayofyear, @mydate) % 14, @mydate)
``` | Calculating the closest future periodic payment date in SQL | [
"",
"sql",
"database",
"sql-server-2005",
""
] |
I'm looking for a third-party Oracle Data Provider for .Net (ADO.NET) with a full support of Oracle object types (like geometries). I was foolish enough to use ODP.NET and now I'm paying the price - it's incredibly buggy and I just reached the end of the line (keep crashing IIS Pool - known issue, no resolution). I found dotConnect which is fine, just 4 times slower with object types than ODP.NET. Are any others providers which support Oracle objects? | Are you aware of the Oracle-published ADO.net provider ? this dll ships with the Oracle CLient, and is named Oracle.DataAccess.dll. The version I am using is ver 1.102.4.0, and is dtd 2/11/2008. | As I'm looking into working with Oracle database from C#, here is what I can say as an update to this question.
These are the alternatives:
* Microsoft's **System.data.OracleClient** is part of the .Net framework and requires Oracle Client installed or external dll's (but I think it's not supported anymore)
* **Oracle Data Provider for .Net** (ODP.Net), is the offcial .Net provider from Oracle. I think it is part of Oracle Client install.
* Third party **Devart dotConnect** for Oracle ([follow me](http://www.devart.com/dotconnect/oracle/)).
* Third party **Datadirect ADO.Net provider** for Oracle ([follow me](http://www.datadirect.com/products/net/net-for-oracle/)).
I didn't dig deeper yet, but information is not so easy to find about Oracle connectors, so here is my contribution ;-) | Third-Party Oracle Providers for .Net with object type support | [
"",
"c#",
".net",
"oracle",
"ado.net",
""
] |
It opens neither a tab nor a window: the code for a Google Gadget [here.](http://hosting.gmodules.com/ig/gadgets/file/113238372519026650011/test_open.xml) If you know 'target="\_blank"' from HTML, I am looking for a similar tool for Google Gadgets. More precisely, I cannot understand why the JavaScript piece does not work:
```
window.open("http://www.google.com/");
``` | Well, if you want to open the new window, do it explicitly.
```
var query = "bijection";
var searchUrl = "http://www.google.com/search?q=";
if (query != "" && searchUrl != "") {
searchUrl += escape(query);
window.open(searchUrl); //You can pass additional parameters, look for window.open examples on the Internet.
return false;
}
```
The target attribute is for link element () which instructs browser to open the URL in new window if user clicks on it. | Open a new window with that target instead of replacing the current’s window URL:
```
var query = "bijection";
var searchUrl = "http://www.google.com/search?q=";
if (query != "" && searchUrl != "") {
searchUrl += escape(query);
var newWindow = window.open(searchUrl, '_blank');
return false;
}
``` | How to open a new window in Google Gadget? | [
"",
"javascript",
"google-gadget",
"igoogle",
""
] |
I'm checking out some `PHP 5.3.0` features and ran across some code on the site that looks quite funny:
```
public function getTotal($tax)
{
$total = 0.00;
$callback =
/* This line here: */
function ($quantity, $product) use ($tax, &$total)
{
$pricePerItem = constant(__CLASS__ . "::PRICE_" .
strtoupper($product));
$total += ($pricePerItem * $quantity) * ($tax + 1.0);
};
array_walk($this->products, $callback);
return round($total, 2);
}
```
as one of the examples on [anonymous functions](http://www.php.net/manual/en/functions.anonymous.php).
Does anybody know about this? Any documentation? And it looks evil, should it ever be used? | This is how PHP expresses a [closure](http://en.wikipedia.org/wiki/Closure_(computer_science)). This is not evil at all and in fact it is quite powerful and useful.
Basically what this means is that you are allowing the anonymous function to "capture" local variables (in this case, `$tax` and a reference to `$total`) outside of it scope and preserve their values (or in the case of `$total` the reference to `$total` itself) as state within the anonymous function itself. | A simpler answer.
`function ($quantity) use ($tax, &$total) { .. };`
1. The closure is a function assigned to a variable, so you can pass it around
2. A closure is a separate namespace, normally, you can not access variables defined outside of this namespace. There comes the ***use*** keyword:
3. ***use*** allows you to access (use) the succeeding variables inside the closure.
4. ***use*** is early binding. That means the variable values are COPIED upon DEFINING the closure. So modifying `$tax` inside the closure has no external effect, unless it is a pointer, like an object is.
5. You can pass in variables as pointers like in case of `&$total`. This way, modifying the value of `$total` DOES HAVE an external effect, the original variable's value changes.
6. Variables defined inside the closure are not accessible from outside the closure either.
7. Closures and functions have the same speed. Yes, you can use them all over your scripts.
As @Mytskine [pointed out](https://stackoverflow.com/questions/1065188/in-php-5-3-0-what-is-the-function-use-identifier/10304027?noredirect=1#comment-16428234) probably the best in-depth explanation is the [RFC for closures](https://wiki.php.net/rfc/closures). (Upvote him for this.) | In PHP, what is a closure and why does it use the "use" identifier? | [
"",
"php",
"closures",
""
] |
Hi here I'm trying to call a [webmethod] on bodyunload method.
But it is getting fired on page load itself only. How do i prevent it?
Here's the code I am using:
```
[WebMethod]
public static void AbandonSession()
{
HttpContext.Current.Session.Abandon();
}
<script language="javascript" type="text/javascript">
//<![CDATA[
function HandleClose() {
PageMethods.AbandonSession();
}
//]]>
</script>
<body onunload="HandleClose()">
....
....
....
</body>
```
Thank you,
Nagu | I have tested with below code and it is working fine.
**In Aspx page**
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
//<![CDATA[
function HandleClose()
{
PageMethods.AbandonSession();
}
//]]>
</script>
</head>
<body onunload="HandleClose()">
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
</form>
</body>
</html>
```
**In Codebehind**
```
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
public partial class ClearSessionOnPageUnload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static void AbandonSession()
{
HttpContext.Current.Session.Abandon();
}
}
```
You can put breakpoint at AbandonSession method to verify that it is getting hit at unload. | What you are attempting to do is a bad idea. Consider putting less data in the session, or lowering the timeout.
Perhaps you don't realise that onunload fires when the user refreshes or navigates away from the page. So assuming your code actually worked, if you user refreshed their page then their session would be terminated. If they visited any other page on the site their session would also be terminated!
Probably not the functionality you were hoping for! | Calling a Page Method when the Browser Closes | [
"",
"c#",
"asp.net",
"web-services",
"asmx",
"pagemethods",
""
] |
Greets.
So, I'm running Fedora Core 8 on an Amazon EC2. I installed httpd, php5 and libcurl, and a bunch of other stuff. Seemed to be working great, but then I realized that POST data isn't being sent by curl in my php scripts. Same request in the command line works tho. I also ran the same php scripts on my local machine (Win XP) and another remote machine (Ubuntu), and they run fine, the POST data is being sent, but not on the FC8. Does it require any special configuration? Any firewall issues?
Here's the PHP code:
```
error_reporting(E_ALL);
$ch = curl_init("http://foller.me/tmp/postdump.php");
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, "something=somewhere");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_NOBODY, 0);
$response = curl_exec($ch);
echo $response;
curl_close($ch);
```
Here's the corresponding curl command:
```
curl -d "something=somethingelse" http://foller.me/tmp/postdump.php
```
I also found the corresponding entry in the apache error\_log, and here's what I came up with:
```
* About to connect() to foller.me port 80 (#0)
* Trying 75.101.138.148... * connected
* Connected to foller.me (75.101.138.148) port 80 (#0)
> GET /tmp/postdump.php HTTP/1.1
Host: foller.me
Accept: */*
< HTTP/1.1 200 OK
< Date: Tue, 07 Jul 2009 10:32:18 GMT
< Server: Apache/2.2.9 (Fedora)
< X-Powered-By: PHP/5.2.6
< Content-Length: 31
< Connection: close
< Content-Type: text/html; charset=UTF-8
<
* Closing connection #0
```
The POST data isn't being sent, see? Any ideas?
Thanks in advance everyone.
~ K. | Looks as if this turns the request from POST to GET:
```
curl_setopt($ch, CURLOPT_NOBODY, 0);
```
Remove that line and it works.
> **CURLOPT\_NOBODY**
>
> A non-zero parameter tells the library to not include
> the body-part in the output. This is only relevant for
> protocols that have separate header and body parts. | Not an expert in this field but I've got my own working code which works slightly differently. Maybe this will help
```
// Open the cURL session
$curlSession = curl_init();
// Set the URL
curl_setopt ($curlSession, CURLOPT_URL, $url);
```
It does the curl\_init() first then sets the url, then later...
```
$rawresponse = curl_exec($curlSession);
```
i.e I have no idea but perhaps setting the url after makes a difference somehow...? | Sending POST data with curl and php | [
"",
"php",
"linux",
"apache",
"curl",
""
] |
I am writing a quickie BlackJack Winforms app to demonstrate a couple of concepts. The engine itself is fairly simple, however, I'd like to display actual playing cards on the WinForm.
Is there a library out there that I can use (preferably free) that allows the display the cards.
There is, of course, the cards.dll from way back in the day, but it's unmanaged. Looking for something managed (or at least a managed wrapper around cards.dll). | There is also this lib which I have actually tested and seems to work great and has a great and easy to understand API.
<http://www.c-sharpcorner.com/UploadFile/samersarhan/Cards.dllinWindowsControlLibray11232005050452AM/Cards.dllinWindowsControlLibray.aspx> | Not sure how good this is, but a quick search found [PlayingCards](http://playingcards.codeplex.com/) on codeplex. It looks like you might be able to pull out the PlayingCardsLibrary project and use that. Or modify it as needed. | Is there an easy way to display playing cards in a WinForms app? | [
"",
"c#",
"blackjack",
"playing-cards",
""
] |
**UPDATED**
See post [#3](https://stackoverflow.com/questions/1060966/big-files-uploading-webexception-the-connection-was-closed-unexpectedly/1066265#1066265) below.
There is a need to upload a file to the web automatically (without browser). Host - [Mini File Host v1.2](http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=mini+file+host) (if this does matter). Didn't find specific api in documentation, so at first i sniffed browser requests in Firebug as follows :
```
Params : do
Value : verify
POST /upload.php?do=verify HTTP/1.1
Host: webfile.ukrwest.net
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; ru; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.8 (.NET CLR 4.0.20506)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: ru,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: windows-1251,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://filehoster.awardspace.com/index.php
Content-Type: multipart/form-data; boundary=---------------------------27368237179714
Content-Length: 445
-----------------------------27368237179714
Content-Disposition: form-data; name="upfile"; filename="Test.file"
Content-Type: application/octet-stream
12345678901011121314151617sample text
-----------------------------27368237179714
Content-Disposition: form-data; name="descr"
-----------------------------27368237179714
Content-Disposition: form-data; name="pprotect"
-----------------------------27368237179714--
```
Here we can see parameter, headers, content type and chunks of information (1 - file name and type, 2 - file contents, 3 - additional params - description and password, not necessarily applied).
So i've created a class that emulates such a behaviour step by step : HttpWebRequest on the url, apply needed parameters to request, form request strings with StringBuilder and convert them to byte arrays, read a file using FileStream, putting all that stuff to MemoryStream and then writing it to request (took major part of a code from an article at CodeProject where it uploads a file to Rapidshare host).
Neat and tidy, but... It doesn't seem to work :(. As result it returns initial upload page, not a result page with links i could parse and present to a user...
Here are main methods of an Uploader class :
```
// Step 1 - request creation
private HttpWebRequest GetWebrequest(string boundary)
{
Uri uri = new Uri("http://filehoster.awardspace.com/index.php?do=verify");
System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
httpWebRequest.CookieContainer = _cookies;
httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.2; ru; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.8 (.NET CLR 4.0.20506)";
httpWebRequest.Referer = "http://filehoster.awardspace.com/index.php";
httpWebRequest.Method = "POST";
httpWebRequest.KeepAlive = true;
httpWebRequest.Timeout = -1;
//httpWebRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
httpWebRequest.Headers.Add("Accept-Charset", "windows-1251,utf-8;q=0.7,*;q=0.7");
httpWebRequest.Headers.Add("Accept-Encoding", "gzip,deflate");
httpWebRequest.Headers.Add("Accept-Language", "ru,en-us;q=0.7,en;q=0.3");
//httpWebRequest.AllowAutoRedirect = true;
//httpWebRequest.ProtocolVersion = new Version(1,1);
//httpWebRequest.SendChunked = true;
//httpWebRequest.Headers.Add("Cache-Control", "no-cache");
//httpWebRequest.ServicePoint.Expect100Continue = false;
return httpWebRequest;
}
// Step 2 - first message part (before file contents)
private string GetRequestMessage(string boundary, string FName, string description, string password)
{
System.Text.StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("--");
stringBuilder.Append(boundary);
stringBuilder.Append("\r\n");
stringBuilder.Append("Content-Disposition: form-data; name=\"");
stringBuilder.Append("upfile");
stringBuilder.Append("\"; filename=\"");
stringBuilder.Append(FName);
stringBuilder.Append("\"");
stringBuilder.Append("\r\n");
stringBuilder.Append("Content-Type: application/octet-stream");
stringBuilder.Append("\r\n");
return stringBuilder.ToString();
}
// Step 4 - additional request parameters. Step 3 - reading file is in method below
private string GetRequestMessageEnd(string boundary)
{
System.Text.StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(boundary);
stringBuilder.Append("\r\n");
stringBuilder.Append("Content-Disposition: form-data; name=\"descr\"");
stringBuilder.Append("\r\n");
stringBuilder.Append("\r\n");
stringBuilder.Append("Default description");
stringBuilder.Append("\r\n");
stringBuilder.Append(boundary);
stringBuilder.Append("\r\n");
stringBuilder.Append("Content-Disposition: form-data; name=\"pprotect\"");
stringBuilder.Append("\r\n");
stringBuilder.Append("\r\n");
stringBuilder.Append("");
stringBuilder.Append("\r\n");
stringBuilder.Append(boundary);
stringBuilder.Append("--");
//stringBuilder.Append("\r\n");
//stringBuilder.Append(boundary);
//stringBuilder.Append("\r\n");
return stringBuilder.ToString();
}
// Main method
public string ProcessUpload(string FilePath, string description, string password)
{
// Chosen file information
FileSystemInfo _file = new FileInfo(FilePath);
// Random boundary generation
DateTime dateTime2 = DateTime.Now;
long l2 = dateTime2.Ticks;
string _generatedBoundary = "----------" + l2.ToString("x");
// Web request creation
System.Net.HttpWebRequest httpWebRequest = GetWebrequest(_generatedBoundary);
// Main app block - form and send request
using (System.IO.FileStream fileStream = new FileStream(_file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
byte[] bArr1 = Encoding.ASCII.GetBytes("\r\n--" + _generatedBoundary + "\r\n");
// Generating pre-content post message
string firstPostMessagePart = GetRequestMessage(_generatedBoundary, _file.Name, description, password);
// Writing first part of request
byte[] bArr2 = Encoding.UTF8.GetBytes(firstPostMessagePart);
Stream memStream = new MemoryStream();
memStream.Write(bArr1, 0, bArr1.Length);
memStream.Write(bArr2, 0, bArr2.Length);
// Writing file
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
memStream.Write(buffer, 0, bytesRead);
}
// Generating end of a post message
string secondPostMessagePart = GetRequestMessageEnd(_generatedBoundary);
byte[] bArr3 = Encoding.UTF8.GetBytes(secondPostMessagePart);
memStream.Write(bArr3, 0, bArr3.Length);
// Preparing to send
httpWebRequest.ContentLength = memStream.Length;
fileStream.Close();
Stream requestStream = httpWebRequest.GetRequestStream();
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
// Sending request
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
requestStream.Close();
}
// Delay (?)
System.Threading.Thread.Sleep(5000);
// Getting response
string strResponse = "";
using (Stream stream = httpWebRequest.GetResponse().GetResponseStream())
using (StreamReader streamReader = new StreamReader(stream/*, Encoding.GetEncoding(1251)*/))
{
strResponse = streamReader.ReadToEnd();
}
return strResponse;
}
```
Plays with ProtocolVersion (1.0, 1.1), AllowAutoRedirect (true/false), even known ServicePoint.Expect100Continue (false) didn't fix an issue. Even a 5sec timeout before getting response (thought in case of a big file it doesn't uploads so quick) didn't help.
Content type "octet-stream" was chosen by purpose to upload any file (could use some switch for most popular jpg/zip/rar/doc etc., but that one seems universal). Boundary is generated randomly from timer ticks, not a big deal. What else? :/
I could give up and forget this, but i feel i'm pretty close to solve and **then** forget about it :P.
In case you need the whole application to run and debug - here it is (70kb, zipped C# 2.0 VS2k8 solution, no ads, no viruses) :
[@Mediafire](http://www.mediafire.com/download.php?no1tlmln3yy)
[@FileQube](http://www.fileqube.com/file/RZPUGRwxE203936)
[@FileDropper](http://www.filedropper.com/uploader) | Update : nope, there is no redirect.
[screenshot](http://i.piccy.info/i3/ab/2d/abb26ac7f33c80910040ba58e5f6.png)
Read [RFC2388](http://www.faqs.org/rfcs/rfc2388.html) few times, rewrote the code and it finally worked (i guess the trouble was in utf-read trailing boundary instead of correct 7 bit ascii). Hooray? Nope :(. Only small files are transfered, big ones throwing "The connection was closed unexpectedly".
```
System.Net.WebException was unhandled by user code
Message="The underlying connection was closed: The connection was closed unexpectedly."
Source="Uploader"
StackTrace:
at Uploader.Upload.ProcessUpload(String FilePath, String description, String password) in F:\MyDocuments\Visual Studio 2008\Projects\Uploader\Uploader.cs:line 96
at Uploader.Form1.backgroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in F:\MyDocuments\Visual Studio 2008\Projects\Uploader\Form1.cs:line 45
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
```
I know that's a bug with .net stack and few solutions exists :
1. increase both `Timeout` and `ReadWriteTimeout` of a request
2. assign `request.KeepAlive = false` and `System.Net.ServicePointManager.Expect100Continue = false`
3. set `ProtocolVersion` to `1.0`
But neither one of them nor all of them altogether help in my case. Any ideas?
**EDIT** - Source code:
```
// .. request created, required params applied
httpWebRequest.ProtocolVersion = HttpVersion.Version10; // fix 1
httpWebRequest.KeepAlive = false; // fix 2
httpWebRequest.Timeout = 1000000000; // fix 3
httpWebRequest.ReadWriteTimeout = 1000000000; // fix 4
// .. request processed, data written to request stream
string strResponse = "";
try
{
using (WebResponse httpResponse = httpWebRequest.GetResponse()) // error here
{
using (Stream responseStream = httpResponse.GetResponseStream())
{
using (StreamReader streamReader = new StreamReader(responseStream))
{
strResponse = streamReader.ReadToEnd();
}
}
}
}
catch (WebException exception)
{
throw exception;
}
``` | "As result it returns initial upload page, not a result page with links i could parse and present to a user..."
Maybe that's just the behaviour of the upload functionality: that after the upload has finished, you can upload another file?
I think you have to call another url for the "browse for file"-page (I suppose that's the one you need).
---
**Edit**: Actually, if the server sends a "redirect" (http 3xx), that's something the browser has to handle, so if you're working with your own client application in stead of a browser, you'll have to implement redirection yourself. Here the [rfc](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3) for more information. | Big files uploading (WebException: The connection was closed unexpectedly) | [
"",
"c#",
".net",
"file",
"upload",
"httpwebrequest",
""
] |
Is there way to override return types in C#? If so how, and if not why and what is a recommended way of doing it?
My case is that I have an interface with an abstract base class and descendants of that. I would like to do this (ok not really, but as an example!) :
```
public interface Animal
{
Poo Excrement { get; }
}
public class AnimalBase
{
public virtual Poo Excrement { get { return new Poo(); } }
}
public class Dog
{
// No override, just return normal poo like normal animal
}
public class Cat
{
public override RadioactivePoo Excrement { get { return new RadioActivePoo(); } }
}
```
`RadioactivePoo` of course inherits from `Poo`.
My reason for wanting this is so that those who use `Cat` objects could use the `Excrement` property without having to cast the `Poo` into `RadioactivePoo` while for example the `Cat` could still be part of an `Animal` list where users may not necessarily be aware or care about their radioactive poo. Hope that made sense...
As far as I can see the compiler doesn't allow this at least. So I guess it is impossible. But what would you recommend as a solution to this? | I know there are a lot of solutions for this problem already but I think I've come up with one that fixes the issues I had with the existing solutions.
**I wasn't happy with the some of the existing solutions for the following reasons:**
* **Paolo Tedesco's first solution:** Cat and Dog do not have a common base class.
* **Paolo Tedesco's second solution:** It is a bit complicated and hard to read.
* **Daniel Daranas's solution:** This works but it would clutter up your code with a lot of unnecessary casting and Debug.Assert() statements.
* **hjb417's solutions:** This solution doesn't let you keep your logic in a base class. The logic is pretty trivial in this example (calling a constructor) but in a real world example it wouldn't be.
**My Solution**
This solution should overcome all of the issues I mentioned above by using both generics and method hiding.
```
public class Poo { }
public class RadioactivePoo : Poo { }
interface IAnimal
{
Poo Excrement { get; }
}
public class BaseAnimal<PooType> : IAnimal
where PooType : Poo, new()
{
Poo IAnimal.Excrement { get { return (Poo)this.Excrement; } }
public PooType Excrement
{
get { return new PooType(); }
}
}
public class Dog : BaseAnimal<Poo> { }
public class Cat : BaseAnimal<RadioactivePoo> { }
```
With this solution you don't need to override anything in Dog OR Cat! Here is some sample usage:
```
Cat bruce = new Cat();
IAnimal bruceAsAnimal = bruce as IAnimal;
Console.WriteLine(bruce.Excrement.ToString());
Console.WriteLine(bruceAsAnimal.Excrement.ToString());
```
This will output: "RadioactivePoo" twice which shows that polymorphism has not been broken.
**Further Reading**
* [Explicit Interface Implementation](http://msdn.microsoft.com/en-us/library/aa288461%28v=vs.71%29.aspx)
* [new Modifier](http://msdn.microsoft.com/en-us/library/51y09td4%28v=vs.71%29.aspx#vclrfnew_newmodifier). I didn't use it in this simplified solution but you may need it in a more complicated solution. For example if you wanted to create an interface for BaseAnimal then you would need to use it in your decleration of "PooType Excrement".
* [out Generic Modifier (Covariance)](http://msdn.microsoft.com/en-us/library/dd469487.aspx). Again I didn't use it in this solution but if you wanted to do something like return `MyType<Poo>` from IAnimal and return `MyType<PooType>` from BaseAnimal then you would need to use it to be able to cast between the two. | What about a generic base class?
```
public class Poo { }
public class RadioactivePoo : Poo { }
public class BaseAnimal<PooType>
where PooType : Poo, new() {
PooType Excrement {
get { return new PooType(); }
}
}
public class Dog : BaseAnimal<Poo> { }
public class Cat : BaseAnimal<RadioactivePoo> { }
```
**EDIT**: A new solution, using extension methods and a marker interface...
```
public class Poo { }
public class RadioactivePoo : Poo { }
// just a marker interface, to get the poo type
public interface IPooProvider<PooType> { }
// Extension method to get the correct type of excrement
public static class IPooProviderExtension {
public static PooType StronglyTypedExcrement<PooType>(
this IPooProvider<PooType> iPooProvider)
where PooType : Poo {
BaseAnimal animal = iPooProvider as BaseAnimal;
if (null == animal) {
throw new InvalidArgumentException("iPooProvider must be a BaseAnimal.");
}
return (PooType)animal.Excrement;
}
}
public class BaseAnimal {
public virtual Poo Excrement {
get { return new Poo(); }
}
}
public class Dog : BaseAnimal, IPooProvider<Poo> { }
public class Cat : BaseAnimal, IPooProvider<RadioactivePoo> {
public override Poo Excrement {
get { return new RadioactivePoo(); }
}
}
class Program {
static void Main(string[] args) {
Dog dog = new Dog();
Poo dogPoo = dog.Excrement;
Cat cat = new Cat();
RadioactivePoo catPoo = cat.StronglyTypedExcrement();
}
}
```
This way Dog and Cat both inherit from Animal (as remarked in the comments, my first solution did not preserve the inheritance).
It's necessary to mark explicitly the classes with the marker interface, which is painful, but maybe this could give you some ideas...
**SECOND EDIT** @Svish: I modified the code to show explitly that the extension method is not enforcing in any way the fact that `iPooProvider` inherits from `BaseAnimal`. What do you mean by "even more strongly-typed"? | C#: Overriding return types | [
"",
"c#",
"inheritance",
"types",
"covariance",
"overriding",
""
] |
I'm working with an old sql server 2000 database, mixing some of it's information with a new app I'm building. I noticed some of the primary keys in several of the tables are floats rather than any type of ints. They aren't foreign keys and are all unique. I can't think of any reason that anyone would want to make their unique primary key IDs floats, but I'm not a SQL expert by any means. So I guess what I'm asking is does whoever designed this fairly extensive database know something I don't? | I'm currently working with a rather big accountant package where EACH of 350+ tables has a primary key of FLOAT(53). All actual values are integers and the system strictly checks that they indeed are (there are special functions that do all the incrementing work).
I did wonder at this design, yet I can understand why it was chosen and give it some credits.
On the one hand, the system is big enough to have billion records in some tables. On the other hand, those primary keys must be easily readable from external applications like Excel or VB6, in which case you don't really want to make them BIGINT.
Hence, float is fine. | I worked with someone who used floats as PKs in SQL Server databases. He was worried about running out of numbers for identifiers if he stuck to INTs. (32 bit on SQL Server.) He just looked at the range of float and did not think about the fact never mind that for larger numbers the ones place is not held in the number, due to limited precision. So his code to take MAX(PK) + 1.0 would at some point return a number equal to MAX(PK). Not good. I finally convinced him to not use float for surrogate primary keys for future databases. He quit before fixing the DB he was working on.
To answer your question, "So I guess what I'm asking is does whoever designed this fairly extensive database know something I don't?" Most likely **NO!** At least not with respect to choosing datatypes. | Sanity Check: Floats as primary keys? | [
"",
"sql",
"database-design",
""
] |
I've got a little game that a friend and I are writing in Java. It's kind of badly coded and we're working on refactoring it, but that's not really the issue right now. We both have 64 bit machines and I guess before we were both using 32 bit JDKs, but recently I had some problems and so I removed all JDKs and installed the latest 64 bit JDK, and I'm not sure when but my friend is also now running a 64 bit JDK. Our game was running fine in the 32 bit JDK, but with the 64 bit version the game won't start. I've been trying to debug it with eclipse, but it's been a bit of a pain.
Our game is networked and multithreaded, and I think we have some issues with how we synchronized things (I didn't fully understand the whole idea of synchronization when I was writing it before) eg. we had made our run() methods synchronized which has no effect, but despite the stupidities of large parts of our code the stuff still runs on a 32 bit JVM (Windows and Linux).
The game starts up where one person hosts a game, and then others can join until the host decides to start the game. It then sends a prompt to all the players, asking if they want to start, and if all say yes the game starts. What is happening on the 64 bit JVM is that it sends the message, but it seems like the response is getting lost or something, or the server isn't counting correctly that everyone has OKed because the game doesn't actually start. Actually, the host gets a few more messages that the other player(s) don't get and gets a little farther in starting the game, but the server seems to get stuck somewhere.
Any ideas what might be the problem? Our code is up on [github](http://github.com/ibrahima/netbang/tree/master) if anyone wants to take a look. I'd be extremely happy if you did, but I don't expect anyone to wade through our ugly code. Thanks!
By the way, we are both running on 64 bit Windows Vista and JDK 1.6 u12 and u14, but we also run Linux although I haven't been able to test it on a 64 bit Linux JVM yet.
Oh, more details about why I'm pretty sure it's a 64 bit JVM isssue:
So we were working on this basically in the fall semester, and stopped working on it for a while. After 6 months we pick it up again, stagger at our horrid code, and start trying to clean it up. Then we realize that neither of us can run it properly. I try to find a revision that works, but I get to the last revision from before we started working on it this summer and it's still not working. I then even checked some binaries (.jars) that I had compiled before and even the earliest revision I have doesn't work on the 64 bit JVM. I then checked in a 32 bit Linux VM running the Sun JDK1.6 JVM, and it worked fine. Thus, I'm pretty sure it's a 64 bit problem since before the same binaries were working perfectly.
I've also noticed that Vista was assigning IPv6 addresses to my sockets for some reason, when connecting to a server on my own machine (0:0:0:0:0:1 instead of 127.0.0.1) but I fixed anything that was IPv4 specific and it's still not working.
I actually have just created another problem on my github repository which is a whole other tale of woe, so I can't test my latest build on another machine right now. But the last build before refactoring works fine on a 32 bit JVM with a dual core, so it doesn't look like a race condition.
Oh, another thing, exact same problem running under OpenJDK 6 64 bit under Linux. I'm guessing it's a race condition that the 64 bit version somehow brings out. | We found out what the issue was. There was a loop in one part where a thread waited on something to become ready that another thread was working on, except it was just a while(!ready){} loop. It seems like in the 64 bit JVM threads don't get preempted or something, because in the 32 bit JVM this loop would get preempted and then the other thread would finish and set the variable to true, but not in the 64 bit JVM. I understand now that we should have used wait/notify and locks to do this, but at least temporarily throwing a sleep() in there fixed it. Not exactly a race condition, more of a quirk of the threading model it seems, so I'm not accepting any of the other answers since they didn't answer the question I asked. | > The game starts up where one person
> hosts a game, and then others can join
> until the host decides to start the
> game. It then sends a prompt to all
> the players, asking if they want to
> start, and if all say yes the game
> starts. What is happening on the 64
> bit JVM is that it sends the message,
> but it seems like the response is
> getting lost or something, or the
> server isn't counting correctly that
> everyone has OKed because the game
> doesn't actually start. Actually, the
> host gets a few more messages that the
> other player(s) don't get and gets a
> little farther in starting the game,
> but the server seems to get stuck
> somewhere.
This sounds like it might be a race condition, i.e. flawed or missing synchronization. Since race conditions are timing-dependant, almost anything (including switching JVMs) can cause them to manifest.
I'd stop worrying about 64bit vs 32bit and try to diagnose the actual problem. Since it involves multiple machines, it's unfortunately going to be very hard (which is generally the case with race conditions).
The best way to do it is probably to make sure all machines have synchronized clocks using NTP, and then log the sending, receiving and processing of messages with millisecond timestamps so you can see where messages get lost or aren't processed properly. | Any bugs or incompatibilities in 64 bit JVM? | [
"",
"java",
"multithreading",
"networking",
"64-bit",
"jvm",
""
] |
I'm trying to output a CDATA section in the result of XSLT using Xalan 2.7.1. I have applied this XSL to the XML in a tool and the result contains CDATA. In the method below, no CDATA is in the result and no exception is thrown. I feel like I'm missing something here.
**test.xml**
```
<?xml version="1.0" encoding="UTF-8"?>
<parentelem>
<childelem>Test text</childelem>
</parentelem>
```
**test.xsl**
```
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="UTF-8" cdata-section-elements="newchildelem" />
<xsl:template match="/">
<parentelem>
<newchildelem><xsl:value-of select="/parentelem/childelem" /></newchildelem>
</parentelem>
</xsl:template>
</xsl:stylesheet>
```
**Transform.java**
```
import java.io.FileReader;
import java.io.StringWriter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stax.StAXResult;
import javax.xml.transform.stax.StAXSource;
public class Transform {
public static void main (String[] args){
try {
XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(
new FileReader("test.xml"));
XMLStreamReader xslReader = XMLInputFactory.newInstance().createXMLStreamReader(
new FileReader("test.xsl"));
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Source xslSource = new StAXSource(xslReader);
Source xmlSource = new StAXSource(xmlReader);
Transformer transf = transformerFactory.newTransformer(xslSource);
StringWriter xmlString = new StringWriter();
XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(
xmlString);
Result transformedXml = new StAXResult(xmlWriter);
transf.transform(xmlSource, transformedXml);
xmlWriter.flush();
System.out.println(xmlString.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
**console output**
```
<?xml version="1.0" encoding="UTF-8"?><parentelem><newchildelem>Test text</newchildelem></parentelem>
``` | 1) I guess it turns out i haven't been using Xalan 2.7.1. The code in [skaffman's](https://stackoverflow.com/questions/1065200/xsl-cdata-section-elements-output-property-with-xalan-j/1065428#1065428) answer made me think to check Version.getVersion() and the signature is "XL TXE Java 1.0.7". This appears to be the default when using IBM java [IBM J9 VM (build 2.4, J2RE 1.6.0)].
2) I switched from using StAXSource and StAXResult to using StreamSource and StreamResult and it works fine (like in [skaffman's](https://stackoverflow.com/questions/1065200/xsl-cdata-section-elements-output-property-with-xalan-j/1065428#1065428) answer). Specifically the change from StAXResult to StreamResult is what worked. Using StAXSource with StreamResult works too. | Are you saying you want to output the CDATA as part of the element?
```
<newchildelem><xsl:value-of select="/parentelem/childelem" /></newchildelem>
```
with
```
<newchildelem><xsl:text><![CDATA[
</xsl:text><xsl:value-of select="/parentelem/childelem" /><xsl:text>]]></xsl:text></newchildelem>
```
or some other form, but with the escaped characters to omit
```
<newchildelem><![CDATA[Test text]]></newchildelem>
```
or am I misunderstanding the question perhaps? | xsl cdata-section-elements output property with Xalan-J | [
"",
"java",
"xml",
"xslt",
"xalan",
""
] |
Could someone provide me with a good way of importing a whole directory of modules?
I have a structure like this:
```
/Foo
bar.py
spam.py
eggs.py
```
I tried just converting it to a package by adding `__init__.py` and doing `from Foo import *` but it didn't work the way I had hoped. | List all python (`.py`) files in the current folder and put them as `__all__` variable in `__init__.py`
```
from os.path import dirname, basename, isfile, join
import glob
modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]
``` | Add the `__all__` Variable to `__init__.py` containing:
```
__all__ = ["bar", "spam", "eggs"]
```
See also <http://docs.python.org/tutorial/modules.html> | How to load all modules in a folder? | [
"",
"python",
"python-import",
""
] |
I will go straight to the example:
```
class Foo:
@execonce
def initialize(self):
print 'Called'
>>> f1 = Foo()
>>> f1.initialize()
Called
>>> f1.initialize()
>>> f2 = Foo()
>>> f2.initialize()
Called
>>> f2.initialize()
>>>
```
I tried to define `execonce` but could not write one that works with methods.
PS: I cannot define the code in `__init__` for `initialize` has to be called *sometime after* the object is initialized. cf - [cmdln issue 13](http://code.google.com/p/cmdln/issues/detail?id=13&can=1) | ```
import functools
def execonce(f):
@functools.wraps(f)
def donothing(*a, **k):
pass
@functools.wraps(f)
def doit(self, *a, **k):
try:
return f(self, *a, **k)
finally:
setattr(self, f.__name__, donothing)
return doit
``` | You could do something like this:
```
class Foo:
def __init__(self):
self.initialize_called = False
def initialize(self):
if self.initalize_called:
return
self.initialize_called = True
print 'Called'
```
This is straightforward and easy to read. There is another instance variable and some code required in the `__init__` function, but it would satisfy your requirements. | Decorator to mark a method to be executed no more than once even if called several times | [
"",
"python",
"class",
"methods",
"decorator",
""
] |
I've posed this problem previiously also [here](https://stackoverflow.com/questions/891334/aspliteral-control-null-in-user-control). I'm facing same type of problem again. I've a user control that shows information from some business object. I'm already using it on two pages. In both the pages I call a method with business object to bind controls (mostly asp labels) on user control to object's properties. I call this method in LoadComplete method of aspx page.
```
protected void Page_LoadComplete(object sender, EventArgs e)
{
control.LoadData(bussinessObject);
}
```
It is working fine on both the pages. Now I've third page where I'm using the same control. Now when I call **LoadData** in this new page I'm getting **NullReference** exception:
```
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information
about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set
to an instance of an object.
Source Error:
Line 91: lblOrgName.Text = obj.Name;
```
EDIT:
lblOrgName is NULL :( Please help me!
EDIT 2:
I stepped through the code. After Page Load of the page containing page, Page\_Load of Masterpage is called and then the problem control's Page Load is called. Stopping at closing brace (}) of this Page Load function I typed lblOrgName in Immediate Window and it show null
:(
Then in LoadComplete of the page containing the user control I stopped and typed the control's name in immediate window. It shows all the labels and other control's in it as null.
EDIT 3:
I've put protected constructor in the UserControl as suggested by [Stendhal](https://stackoverflow.com/questions/1042383/usercontrol-working-in-one-page-but-not-in-others/1042666#1042666) in the answers:
```
protected OrgInfo(){ }
```
Now I'm getting this error:
```
Compiler Error Message: CS0122: 'Controls.OrgInfo.OrgInfo()' is inaccessible
due to its protection level.
```
The aspx page in the root directory of the project and the OrgInfo control is in Controls folder.
EDIT 4:
I tried to create all the controls (mostly labels) in page load method but alas the count of Controls collection is 0 (zero) ! | I put following line in page:
```
<%@ Register src="~/Controls/OrgInfo.ascx" TagName="OrgInfo" TagPrefix="proj1"/>
```
and it works! | How do you put your usercontrol on the page? This has happened to me in the past and the reason was that control was accidently added as a server control and not a user control. All the subcontrols in the control were never instatiated.
You can check this by putting a protected default constructor in the code-behind for the user control:
protected MyUserControl() { }
That way the control cannot be instantiated as a server control. | UserControl working in one page but not in others | [
"",
"c#",
"asp.net",
"user-controls",
""
] |
Say I'm showing the user a form, and using a BackgroundWorker to do some work behind the scenes.
When the user clicks OK, I cannot continue until the BackgroundWorker has completed.
If it hasn't finished when the user clicks Ok, I want to show a WaitCursor until it has, and then continue.
What's the best way to implement this?
I know I could use a plain old Thread, and then do Thread.Join, but I like BackgroundWorker.
Can it be done nicely? | You could use this code, instead of BW
```
var resetEvent = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(state =>
{
Thread.Sleep(5000);//LongRunning task, async call
resetEvent.Set();
});
resetEvent.WaitOne();// blocking call, when user clicks OK
``` | Ideally, you should disable all the relevant controls on the form, then re-enable them when the `BackgroundWorker` completes. That way you won't get a locked UI - and you can have a cancel button etc.
If you wanted to *actually* block until it had finished, you could just run the task synchronously to start with. | How do I "Thread.Join" a BackgroundWorker? | [
"",
"c#",
"multithreading",
"backgroundworker",
""
] |
I have a function in a package that returns a REF CURSOR to a RECORD. I am trying to call this function from a code block. The calling code looks like this:
```
declare
a_record package_name.record_name;
cursor c_symbols is select package_name.function_name('argument') from dual;
begin
open c_symbols;
loop
fetch c_symbols into a_record;
exit when c_symbols%notfound;
end loop;
close c_symbols;
end;
```
The function declaration as part of package\_name looks something like this:
```
TYPE record_name IS RECORD(
field_a varchar2(20);
);
TYPE record_cursor IS REF CURSOR RETURN record_name;
FUNCTION getsymbols(argument IN varchar2) return record_cursor;
```
When I try to run the calling code block, I get the exception: PLS-00386: type mismatch found at 'EXAMPLE\_SYMBOLS' between FETCH cursor and INTO variables.
What should the type of a\_record be and how can I access individual elements of the record I am fetching(of type record\_name)? | I suspect that you think that your cursor should be fetching rows from the REFCURSOR. It's not. The REFCURSOR is itself a cursor, you don't use another cursor to select from it.
What your current cursor is doing is fetching a single row, with a single column, containing the result of the function call. Which is a `record_cursor` not a `record_name`, so you get a type mismatch.
I suspect what you really want to do is something like this:
```
declare
symbol_cursor package_name.record_cursor;
symbol_record package_name.record_name;
begin
symbol_cursor := package_name.function_name('argument');
loop
fetch symbol_cursor into symbol_record;
exit when symbol_cursor%notfound;
-- Do something with each record here, e.g.:
dbms_output.put_line( symbol_record.field_a );
end loop;
CLOSE symbol_cursor;
end;
``` | The function returns a `record_cursor`, so I would expect `a_record` should also be a `record_cursor`. However, it is not clear why you are returning a ref cursor anyway - why can't the function return a `record_name` type instead? | fetch from function returning a ref cursor to record | [
"",
"sql",
"oracle",
"plsql",
"oracle10g",
""
] |
In C++ one can write any of the following statements:
```
10;
true;
someConstant; //if this is really an integer constant
```
or something like
```
int result = obtainResult();
result; // looks totally useless
```
The latter can be used to suppress a compiler warning "A variable is initialized but not referenced" (C4189 in VC++) if a macro that is expanded into an empty string in some configuration is later used with the `result` variable. Like this:
```
int result = obtainResult();
result;
assert( result > 0 ); // assert is often expanded into an empty string in Release versions of code
```
What's the meaning of such statements? How can they be used except for compiler warning suppression? | These statements (called expression-statements in the C++ grammar) are valid because they are expressions.
Expressions are all constructs that calculate some kind of value, such as
* 3 + 5
* someVariable
* someFunctionCall( 2 )
* someVar += 62
* val > 53
I think, to keep the grammar simple, they decided to not differentiate between those expressions that actually have a side effect (such as the function call or the assignment) and those that don't. | This kind of statements is a logical expansion of how other pieces of the language works. Consider having a function that returns a value, for example `int foo()`, that *also* has some side effects. Sometimes you only want those side effects to happen, so you write `foo();` as a statement.
Now, while this does not look exactly like `10;`, the function call will evaluate to an int sooner or later, and nothing happens to that int, just like with `10;`.
Another example of the same issue is that since you can do `a = b = 10;`, that means `b = 10` has to evaluate to `10`, hence you can not do assignment without generating a value that has to be suppressed.
Being able to write such values as statements is just a logical way of building the language, but for the cases you present it might even be a good idea to give a compiler warning for it.
Unless you use it to suppress compiler warnings ;) | What does a "true;" or "10;" statement mean in C++ and how can it be used? | [
"",
"c++",
"compiler-construction",
""
] |
I would like to decompile a .swf file and get all the images from it, in python.
Are there any libraries that do this? | The SWFTools distribution has a command line program, SWFExtract, that can do this. You could call that from python to do what you want:
<http://www.swftools.org/>
<http://www.swftools.org/swfextract.html> | I don't think there are any libraries available for python, but maybe you can have an offline process to decompile swf using [sothink flash decompiler](http://www.sothink.com/product/flashdecompiler/) Also I did not come across any decompiler so far that is 100% accurate. | Decompile .swf file to get images in python | [
"",
"python",
"flash",
""
] |
1) Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.
What does it mean by functions do not change regardless of what happens to the object? How can a function change? Static variables, yes, but functions?
What does "object identity" mean? Would that be for example, a specific house in a house object? (So we deal with a specifically chosen house). So a static class would not work on any house objects?
2) If I don't work with instance state, should I always use static classes? What's the difference between a static and instance class working with instance state? All I can think of is the static class will only be of 1 instance and thus 1 instance means many calls will be queued if the class worked with instance state (if there is thread synchronisation)? Obviously, static state should only need a static class.
Is this correct? | **Answer to question 1)**
Imagine that you have a Car object with a field called speed. If you create a new car object and then set the speed property by using this function
```
public void SetSpeed(int value)
{
this.speed = value
}
```
the function SetSpeed would depend on the car object being initialized so it could access the speed property. Hence, without an initialized car SetSpeed would not be invokable. Had the function, however, been static, then it would not have access to any specific initialized car object, only other static defined objects.
**Answer to question 2)**
A static function does not have access to any instance declared functions or variables, so having a static function work with instance state items does not make sense. | I tend to treat static methods as a way of creating helper functions which to relate to the specific class so I can use them globally without having to instantiate any objects. A very simple example would be:
```
public class Person
{
private string name;
private DateTime dob;
public Person(string name, DateTime dob)
{
this.name = name;
this.dob = dob;
}
public int Age { get { return CalculateAge(this.dob); } }
public string Name { get { return this.name; } }
public static int CalculateAge(DateTime dob)
{
// use dob to work out age.
}
}
```
So in the above scenario you can see if I create a person object, I can encapsulate the calculation of the age using a readonly property. However, if I needed to work out the age of someone based on a date, outwith the specific person object, I can use the static method i.e.
```
// object usage
var p = new Person("Joe Bloggs", DateTime.Parse("10/11/1981"));
Console.WriteLine(p.Age);
// static usage
Console.WriteLine(Person.CalculateAge(DateTime.Parse("10/11/1981"));
``` | What does this mean when justifying static classes? | [
"",
"c#",
""
] |
Is there a canonical way to test to see if the process has administrative privileges on a machine?
I'm going to be starting a long running process, and much later in the process' lifetime it's going to attempt some things that require admin privileges.
I'd like to be able to test up front if the process has those rights rather than later on. | This will check if user is in the local Administrators group (assuming you're not checking for domain admin permissions)
```
using System.Security.Principal;
public bool IsUserAdministrator()
{
//bool value to hold our return value
bool isAdmin;
WindowsIdentity user = null;
try
{
//get the currently logged in user
user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch (UnauthorizedAccessException ex)
{
isAdmin = false;
}
catch (Exception ex)
{
isAdmin = false;
}
finally
{
if (user != null)
user.Dispose();
}
return isAdmin;
}
``` | Starting with Wadih M's code, I've got some additional P/Invoke code to try and handle the case of when UAC is on.
<http://www.davidmoore.info/blog/2011/06/20/how-to-check-if-the-current-user-is-an-administrator-even-if-uac-is-on/>
First, we’ll need some code to support the GetTokenInformation API call:
```
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool GetTokenInformation(IntPtr tokenHandle, TokenInformationClass tokenInformationClass, IntPtr tokenInformation, int tokenInformationLength, out int returnLength);
/// <summary>
/// Passed to <see cref="GetTokenInformation"/> to specify what
/// information about the token to return.
/// </summary>
enum TokenInformationClass
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId,
TokenGroupsAndPrivileges,
TokenSessionReference,
TokenSandBoxInert,
TokenAuditPolicy,
TokenOrigin,
TokenElevationType,
TokenLinkedToken,
TokenElevation,
TokenHasRestrictions,
TokenAccessInformation,
TokenVirtualizationAllowed,
TokenVirtualizationEnabled,
TokenIntegrityLevel,
TokenUiAccess,
TokenMandatoryPolicy,
TokenLogonSid,
MaxTokenInfoClass
}
/// <summary>
/// The elevation type for a user token.
/// </summary>
enum TokenElevationType
{
TokenElevationTypeDefault = 1,
TokenElevationTypeFull,
TokenElevationTypeLimited
}
```
Then, the actual code to detect if the user is an Administrator (returning true if they are, otherwise false).
```
var identity = WindowsIdentity.GetCurrent();
if (identity == null) throw new InvalidOperationException("Couldn't get the current user identity");
var principal = new WindowsPrincipal(identity);
// Check if this user has the Administrator role. If they do, return immediately.
// If UAC is on, and the process is not elevated, then this will actually return false.
if (principal.IsInRole(WindowsBuiltInRole.Administrator)) return true;
// If we're not running in Vista onwards, we don't have to worry about checking for UAC.
if (Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version.Major < 6)
{
// Operating system does not support UAC; skipping elevation check.
return false;
}
int tokenInfLength = Marshal.SizeOf(typeof(int));
IntPtr tokenInformation = Marshal.AllocHGlobal(tokenInfLength);
try
{
var token = identity.Token;
var result = GetTokenInformation(token, TokenInformationClass.TokenElevationType, tokenInformation, tokenInfLength, out tokenInfLength);
if (!result)
{
var exception = Marshal.GetExceptionForHR( Marshal.GetHRForLastWin32Error() );
throw new InvalidOperationException("Couldn't get token information", exception);
}
var elevationType = (TokenElevationType)Marshal.ReadInt32(tokenInformation);
switch (elevationType)
{
case TokenElevationType.TokenElevationTypeDefault:
// TokenElevationTypeDefault - User is not using a split token, so they cannot elevate.
return false;
case TokenElevationType.TokenElevationTypeFull:
// TokenElevationTypeFull - User has a split token, and the process is running elevated. Assuming they're an administrator.
return true;
case TokenElevationType.TokenElevationTypeLimited:
// TokenElevationTypeLimited - User has a split token, but the process is not running elevated. Assuming they're an administrator.
return true;
default:
// Unknown token elevation type.
return false;
}
}
finally
{
if (tokenInformation != IntPtr.Zero) Marshal.FreeHGlobal(tokenInformation);
}
``` | In .NET/C# test if process has administrative privileges | [
"",
"c#",
".net",
"windows",
"security",
""
] |
I am not a python user, I'm just trying to get couchdb-dump up and running and it's in an "egg" file which I guess needs easy\_install. I have Python 2.6.2 running on my computer but it seems to know nothing about easy\_install or setuptools... help! What can I do to fix this???
**edit:** you may note from the [setuptools](http://pypi.python.org/pypi/setuptools#windows) page that there are Windows .exe installers for 2.3, 2.4, and 2.5, but not 2.6. What the heck?!?!
argh, this is a [duplicate question](https://stackoverflow.com/questions/309412/how-to-setup-setuptools-for-python-2-6-on-windows), sorry.
p.s. [this solution](https://stackoverflow.com/questions/309412/how-to-setup-setuptools-for-python-2-6-on-windows/425318#425318) is the one that seemed simplest and it worked for me. | <http://pypi.python.org/pypi/setuptools>
... has been updated and has windows installers for Python 2.6 and 2.7
(note: if you need 64-bit windows installer: <http://www.lfd.uci.edu/~gohlke/pythonlibs/>) | I don't like the whole easy\_install thing either.
But the solution is to download the source, untar it, and type
```
python setup.py install
``` | installing easy_install for Python 2.6.2 (missing?) | [
"",
"python",
"easy-install",
""
] |
i posted the other day with practice questions i was getting stuck with and i am stuck again
Please firstly can i ask you dont post full solutions.
The question is from here
<http://www.javabat.com/prob/p141494>
and reads
Given a string and a second "word" string, we'll say that the word matches the string if it appears at the front of the string, except its first char does not need to match exactly. On a match, return the front of the string, or otherwise return the empty string. So, so with the string "hippo" the word "hi" returns "hi" and "xip" returns "hip". The word will be at least length 1.
startWord("hippo", "hi") → "hi"
startWord("hippo", "xip") → "hip"
startWord("hippo", "i") → "h"
I am getting very stuck, the wording of the question isn't helping me! This is the code i have so far
```
public String startWord(String str, String word)
{
if (str.startsWith(word)){
return str.substring(0, word.length());
}
if (str.substring(1, str.length()).equals(word.substring(1, word.length()))){
return str.substring(0, word.length());
}
return "";
}
```
hopefully someone will be able to help me out here with a pointer or 2, thank you for the help | Your problem is in your second comparison (the general case). You are taking a substring of str to the end of str, and comparing it with a substring of word to the end of word. However, if str="hippo" and word="xip", "ippo" != "ip".
As an additional note, once you fix the second case, you won't really need the first case, as it's covered by the second case. | In the case where you are ignoring the first character, you only want to compare `word.length() - 1` characters -- and the same length for both the string and the word.
Note that you really don't need to test the case where the first letter exactly matches as that is a subset of the case where you are ignoring the first letter. | Java practice questions | [
"",
"java",
""
] |
We're writing Windows desktop apps using C++ and Win32. Our dialog boxes have an ugly appearance with "Windows XP style": the background to the static text is grey. Where the dialog box background is also grey, this is not a problem, but inside a tab control, where the background is white, the grey background to the text is very noticeable.
In the past we have done a lot of our own drawing of controls, but these days we are trying to use the standard look'n'feel as much as possible, and to avoid overriding standard behaviour as much as possible.
We are using the Win32 API, which is getting a bit dated, but I think the problem occurs even with ATL. We are creating a DIALOGTEMPLATE. The text is in a "static" control (0x0082). The only flag we set for the style is "SS\_LEFT". The text control is inside a tab control: "SysTabControl32" with only one flag: WS\_CLIPSIBLINGS set on it. I've experimented with SS\_WHITERECT and WS\_EX\_TRANSPARENT and other settings, to no avail.
All of this gets drawn with the standard Windows dialog box message handler. My main question is "what are we doing wrong?" rather than "how can I work around it?", although I'll settle for the latter if no-one can help me with the first.
Any ideas? | We're not overriding the WM\_CTLCOLORSTATIC message. There's no occurrence of this string in our source code and nothing like it in our message handlers.
We've worked around this problem by overriding the WM\_DRAWITEM message for tab controls to paint their contents with the grey background (standard for dialog boxes without tab controls) rather than the white background (standard for the contents of tab controls).
```
brush = CreateSolidBrush(GetSysColor(COLOR_MENU));
FillRect(lpdis->hDC, &lpdis->rcItem, brush);
SetBkColor(lpdis->hDC, GetSysColor(COLOR_MENU));
wtext = ToWideStrdup(c->u.tabcontrol.Tabs[lpdis->itemID].name);
rect = lpdis->rcItem;
rect.top += DlgMarginY - 1;
rect.bottom += DlgMarginY;
DrawTextW(lpdis->hDC, wtext, -1, &rect, DT_CENTER | DT_VCENTER);
free(wtext);
DeleteObject(brush);
```
This is obviously a workaround, not a proper answer to my question.
Incidentally, we initialise the "common controls", of which I believe the tab control is one, using code like this...I don't suppose this is related to the issue?
```
#pragma comment(linker, "/manifestdependency:\"type='win32' " \
"name='Microsoft.Windows.Common-Controls' " \
"version='6.0.0.0' " \
"processorArchitecture='*' " \
"publicKeyToken='6595b64144ccf1df' " \
"language='*'\"")
...
hCommCtrl = GetModuleHandle("comctl32.dll");`
if (hCommCtrl) {
ptrInit = (TfcInit_fn) GetProcAddress(hCommCtrl, "InitCommonControlsEx");
if (ptrInit) {
data.dwSize = sizeof(INITCOMMONCONTROLSEX);
data.dwICC = ctrlClass;
if (ptrInit(&data) )
gCommCtrlsInitialized |= ICC_TAB_CLASSES | ICC_BAR_CLASSES;
}
}
``` | The usual way of implementing pages in a tab control is required to access MS's solution to this problem :-
Instead of creating individual controls in the tab area, create a modeless child dialog for each page and have the controls on that. Create the page dialogs with the main dialog (not the tab) as their parent and as the user switches between tabs, simply show and hide the relevant page dialog.
In the `WM_INITDIALOG` handler for each page, call the uxtheme API [`EnableThemeDialogTexture`](http://msdn.microsoft.com/en-us/library/bb773320(VS.85).aspx)
With the `ETDT_ENABLETAB` flag this automatically changes the background color of the dialog and all its child controls to paint appropriately on a tab.
If you have overridden `WM_ERASEBKGND` or `WM_CTLCOLOR*` in your pages DialogProc you will need to revert to default handling (return FALSE) as these methods are where the dialog code is going to do its heavy lifting. The style bits should simply be set as though the child page dialog page was going to be created on a normal windows 9X tabbed dialog. | Windows XP Style: Why do we get dark grey background on static text widgets? | [
"",
"c++",
"user-interface",
"winapi",
"xp-theme",
""
] |
I´m developing a software in C# that uses static functions from a C++ .dll file through a Wrapper.
The problem is that some of these functions are slow and unstable, so in order to solve this I created a Thread that executes them. However, when I abort that thread from the main thread, the program isn´t letting me use those functions again, even though I define a new instance of the thread every time I call a function.
Is there any way I can fix this?
Thanks in advance.
PS: Here is some code from my program:
```
public partial class MainForm : Form, IMultiLanguage
{
//...
//This method is subscribed to the event of pressing the 'Abort' button
private void StopCurrentAnalisis()
{
try
{
this.analisisManagerController.AnalisisThread.Abort();
}
catch (Exception e){ }
finally
{
MessageBox.Show("Analisis has been cancelled by user", "Analisis Interrupted", MessageBoxButtons.OK, MessageBoxIcon.Stop);
CerrarNowLoadingForm();
}
}
//..
}
public class AnalisisManager: IAnalisisManagerController
{
//..
private Thread analisisThread;
public Thread AnalisisThread{get{return this.analisisThread;}}
public void MakePadrobAnalisis(TipoAnalisis tipoAnalisis,
Dictionary<string, Dictionary<int, double>> parametros)
{
object[] arregloParams = new object[]{tipoAnalisis,parametros};
analisisThread = new Thread(new ParameterizedThreadStart(MakeAnalisisInOtherThread));
analisisThread.Start(arregloParams);
}
private void MakeAnalisisInOtherThread(object o)
{
object[] arregloParams = o as object[];
TipoAnalisis tipoAnalisis = (TipoAnalisis) arregloParams[0];
Dictionary<string, Dictionary<int, double>> parametros = arregloParams[1] as Dictionary<string, Dictionary<int, double>>;
//This launches an event telling the GUI the unstable analisis has started.
//The method that makes the 'Abort' button to appear on the GUI is subscribed to this event
StartAnalisis();
//The Thread executes DLL functions according to tipoAnalisis, for example:
case InvKinematicsMinTorque:
{
WrapperPadirob.InverseKinematicsMinTorqueConfigAnalisis();
break;
}
//..
}
}
``` | > However, when I abort that thread
> from the main thread
That's your problem. You should not be using Thread.Abort. Check out "Non-Evil Cancellation" in [this article](http://www.interact-sw.co.uk/iangblog/2004/11/12/cancellation) for a better approach. From there ...
> The approach I always recommend is
> dead simple. Have a volatile bool
> field that is visible both to your
> worker thread and your UI thread. If
> the user clicks cancel, set this flag.
> Meanwhile, on your worker thread, test
> the flag from time to time. If you see
> it get set, stop what you're doing.
Also, very good discussion of this in this [SO thread](https://stackoverflow.com/questions/1054554/how-to-pause-thread-and-rerunning-it-again).
Per comment:
You own this thread ...
```
Thread AnalisisThread{get{return this.analisisThread;}}
```
... it executes a delegate pointing to ...
```
private void MakeAnalisisInOtherThread(object o)
```
... you also own that method. If the C++ interface does not have a reasonable .StopAnalysis method (or something similar), you must wait until the analysis is done and then poll the main thread as discussed in the articles. Blowing up your thread to stop the analysis is not the right thing to do. | BTW, is your C++ dll written to work in multiple threads? It's possible that it uses techniques that only work when it's being used with only one thread. Run it in multiple threads, and very nasty things could happen, like different users accessing each others data, or the code overwriting the C runtime library heap. | I need some help using Threads in C# | [
"",
"c#",
"multithreading",
"process",
""
] |
If we don't use exec("ls -l") in PHP, but use readdir() or scandir() to get the list of files, and want to list the file sizes and maybe modification date as well, do we need to call stat() 1000 times if there are 1000 files? Is there a simpler or faster way?
Will calling stat() 1000 times hit the file system a lot? Or maybe the OS will cache all the data in memory so it involves only access to RAM but not to the disk.
**Update:** it looks good to use DirectoryIterator(), but how do you sort the items? | LS calls the stat function in the background for you. Listing a directory will only give you the names of the files/folders in question, so you must manually stat each filename returned to get information about each file itself. So yes, you must call stat 1000 times for 1000 files to get all their info. Ideally you will do it in loop. | Why using `exec()` command? This is cleaner and a good solution if you have php5.x. :)
```
$files = new DirectoryIterator('/www/test/');
foreach ($files as $file) {
if ($file->isFile()) echo $file->getSize();
}
```
<http://php.net/manual/en/book.spl.php> | If not using exec("ls -l") in PHP, do we need to call stat() to get the file sizes 1000 times if there are 1000 files? | [
"",
"php",
""
] |
When I'm writing my DAL or other code that returns a set of items, should I always make my return statement:
```
public IEnumerable<FooBar> GetRecentItems()
```
or
```
public IList<FooBar> GetRecentItems()
```
Currently, in my code I have been trying to use IEnumerable as much as possible but I'm not sure if this is best practice? It seemed right because I was returning the most generic datatype while still being descriptive of what it does, but perhaps this isn't correct to do. | It really depends on why you are using that specific interface.
For example, `IList<T>` has several methods that aren't present in `IEnumerable<T>`:
* `IndexOf(T item)`
* `Insert(int index, T item)`
* `RemoveAt(int index)`
and Properties:
* `T this[int index] { get; set; }`
If you need these methods in any way, then by all means return `IList<T>`.
~~Also, if the method that consumes your `IEnumerable<T>` result is expecting an `IList<T>`, it will save the CLR from considering any conversions required, thus optimizing the compiled code.~~ | Framework design guidelines recommend using the class [Collection](http://msdn.microsoft.com/en-us/library/ms132397.aspx) when you need to return a collection that is modifiable by the caller or [ReadOnlyCollection](http://msdn.microsoft.com/en-us/library/ms132474.aspx) for read only collections.
The reason this is preferred to a simple `IList` is that `IList` does not inform the caller if its read only or not.
If you return an `IEnumerable<T>` instead, certain operations may be a little trickier for the caller to perform. Also you no longer will give the caller the flexibility to modify the collection, something that you may or may not want.
Keep in mind that LINQ contains a few tricks up its sleeve and will optimize certain calls based on the type they are performed on. So, for example, if you perform a `Count` and the underlying collection is a List it will NOT walk through all the elements.
Personally, for an ORM I would probably stick with `Collection<T>` as my return value. | Should I always return IEnumerable<T> instead of IList<T>? | [
"",
"c#",
"ienumerable",
""
] |
I have some Java code that is throwing out of memory exceptions after running for a while. I've investigated the netbeans profiler, and when I do one specific operation the Surviving Generations Metric goes up. However when I reset the program status (not kill it), the Surviving Generations Metric does not decrease.
Why is the surviving generations metric not decreasing? | Have you looked at [What Do The Surviving Generations Metrics Mean?](http://www.netbeans.org/kb/articles/nb-profiler-uncoveringleaks_pt1.html) | Run it under 1.6, and use the Java VisualVM (jvisualvm).
Select your process, right click and choose Heap Dump.
Let it run a while and take another heap dump.
Then use File > Compare Memory Snapshots to compare the two dumps. | Netbeans memory management | [
"",
"java",
"netbeans",
"profiling",
"out-of-memory",
""
] |
I'm looking for a framework I can use in my new webproject.
The main concern for me is handling my users, therefore I'm on the lookout for a framwork that can handle them for me. I develop in PHP, so preferably that's the language it should use.
I would like the framework to take care of new users signing up and I would also like it to handle the sessions and authentication process.
What kind of options do I have, and what do people recommend? | if the only thing you want to do is user management then you may use some libraries ( classes ) instead of full framework, because there is nothing ( as far as I know ) called framework for user management only..
I'm working now to make a framework called aiki, and it's gpl, so here is the class I wrote for user management it may help you
```
<?php
class membership
{
var $permissions;
var $full_name;
var $username;
var $group_level;
function membership(){
session_start();
}
function login ($username, $password){
global $db, $layout;
$password = stripslashes($password);
$password = md5(md5($password));
$get_user = $db->get_row("SELECT * FROM aiki_users where username='".$username."' and password='".$password."' limit 1");
if($get_user->username == $username and $get_user->password == $password){
$host_name = $_SERVER['HTTP_HOST'];
$user_ip = $this->get_ip();
$usersession = $this->generate_session(100);
$_SESSION['aiki'] = $usersession;
$insert_session = $db->query("INSERT INTO aiki_users_sessions (`session_id`,`user_id`,`user_name`,`session_date`,`user_session`, `user_ip`) VALUES ('','$get_user->userid','$username',NOW(),'$usersession','$user_ip')");
$update_acces = $db->query("UPDATE `aiki_users` SET `last_login`= NOW(),`last_ip`='$user_ip', `logins_number`=`logins_number`+1 WHERE `userid`='$get_user->userid' LIMIT 1");
} else{
}
}
function isUserLogged ($userid){
global $db;
$user_session = $db->get_var("SELECT user_id FROM aiki_users_sessions where user_session='$_SESSION[aiki]'");
if ($user_session == $userid){
return true;
}else{
return false;
}
}
function getUserPermissions ($user){
global $db;
$user = mysql_escape_string($user);
$user = $db->get_row("SELECT userid, usergroup, full_name, username FROM aiki_users where username='$user'");
if ($user->userid and $this->isUserLogged($user->userid)){
$group_permissions = $db->get_row("SELECT group_permissions, group_level FROM aiki_users_groups where id='$user->usergroup'");
$this->full_name = $user->full_name;
$this->username = $user->username;
$this->group_level= $group_permissions->group_level;
}else{
$this->permissions = "";
}
$this->permissions = $group_permissions->group_permissions;
}
//function from Membership V1.0
//http://AwesomePHP.com/gpl.txt
function get_ip(){
$ipParts = explode(".", $_SERVER['REMOTE_ADDR']);
if ($ipParts[0] == "165" && $ipParts[1] == "21") {
if (getenv("HTTP_CLIENT_IP")) {
$ip = getenv("HTTP_CLIENT_IP");
} elseif (getenv("HTTP_X_FORWARDED_FOR")) {
$ip = getenv("HTTP_X_FORWARDED_FOR");
} elseif (getenv("REMOTE_ADDR")) {
$ip = getenv("REMOTE_ADDR");
}
} else {
return $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
//Generate session
function generate_session($strlen){
return substr(md5(uniqid(rand(),true)),1,$strlen);
}
function LogOut(){
global $db, $layout;
$domain = $_SERVER['HTTP_HOST'];
$path = $_SERVER['SCRIPT_NAME'];
$queryString = $_SERVER['QUERY_STRING'];
$thisurlnologout = "http://" . $domain . $path . "?" . $queryString;
$thisurlnologout = str_replace("&operators=logout", "", $thisurlnologout);
$make_offline = $db->query("UPDATE `aiki_guests` SET `is_online`='0' WHERE `guest_session`='$_SESSION[aiki]' LIMIT 1");
$delete_session_data = $db->query("DELETE FROM aiki_users_sessions where user_session='$_SESSION[aiki]'");
unset($_SESSION['aiki']);
session_destroy();
session_unset();
$layout->html_output .= '<META HTTP-EQUIV="refresh" content="1;URL=http://'.$domain.$path.'"><center><b>Logging out</b></center>';
//die();
}
}
?>
```
and here is a simple sql dump for that
```
CREATE TABLE IF NOT EXISTS `aiki_guests` (
`userid` int(9) unsigned NOT NULL auto_increment,
`first_login` datetime NOT NULL,
`last_hit` datetime NOT NULL,
`last_hit_unix` int(11) NOT NULL,
`ip` varchar(40) NOT NULL,
`last_ip` varchar(40) NOT NULL,
`username` varchar(255) NOT NULL,
`guest_session` varchar(255) NOT NULL,
`hits` int(11) NOT NULL,
`is_online` int(11) NOT NULL,
PRIMARY KEY (`userid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=54 ;
-- --------------------------------------------------------
--
-- Table structure for table `aiki_users`
--
CREATE TABLE IF NOT EXISTS `aiki_users` (
`userid` int(9) unsigned NOT NULL auto_increment,
`username` varchar(100) NOT NULL default '',
`full_name` varchar(255) NOT NULL,
`country` varchar(255) NOT NULL,
`sex` varchar(25) NOT NULL,
`job` varchar(255) NOT NULL,
`password` varchar(100) NOT NULL default '',
`usergroup` int(10) NOT NULL default '0',
`email` varchar(100) NOT NULL default '',
`avatar` varchar(255) NOT NULL,
`homepage` varchar(100) NOT NULL default '',
`first_ip` varchar(40) NOT NULL default '0',
`first_login` datetime NOT NULL,
`last_login` datetime NOT NULL,
`last_ip` varchar(40) NOT NULL,
`user_permissions` text NOT NULL,
`maillist` int(1) NOT NULL,
`logins_number` int(11) NOT NULL,
`randkey` varchar(255) NOT NULL,
`is_active` int(5) NOT NULL,
PRIMARY KEY (`userid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
-- --------------------------------------------------------
--
-- Table structure for table `aiki_users_groups`
--
CREATE TABLE IF NOT EXISTS `aiki_users_groups` (
`id` int(3) NOT NULL auto_increment,
`app_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`group_permissions` varchar(255) NOT NULL,
`group_level` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;
-- --------------------------------------------------------
--
-- Table structure for table `aiki_users_sessions`
--
CREATE TABLE IF NOT EXISTS `aiki_users_sessions` (
`session_id` int(11) NOT NULL auto_increment,
`user_id` int(11) NOT NULL,
`user_name` varchar(255) NOT NULL,
`session_date` datetime NOT NULL,
`user_session` varchar(255) NOT NULL,
`user_ip` varchar(100) NOT NULL,
PRIMARY KEY (`session_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
```
now all you need is to add the db and create users inside it
remember that you will have to md5 the password twice, like:
```
$password = "what ever";
$password = md5(md5($password));
```
and to use this class:
build a form then
$membership = new membership();
Login:
$membership->login($\_POST['username'], $\_POST['password']);
and you can build groups inside the groups table then
$membership->getUserPermissions($username);
then you can do thing based on the returned $membership->permissions value
like :
switch ($membership->permissions){
} | If you don't want a full CMS, the [Zend Framework](http://framework.zend.com/manual/en/) is excellent for drop-in components.
You would be most interested in the Zend\_Acl, Zend\_Auth, and Zend\_Session components.
I hope this is what you're looking for. | Framework for administrating users | [
"",
"php",
"frameworks",
"user-administration",
""
] |
In SQL Server (2005+) I need to index a column (exact matches only) that is `nvarchar(2000+)`. What is the most scalable, performant way to approach this?
In SQL Server (2005+), what would be the practical difference in indexing on a column with the following types:
* `nvarchar(2000)`
* `char(40)`
* `binary(16)`
E.g. would a lookup against an indexed `binary(16)` column be measurably faster than a lookup against an indexed `nvarchar(2000)`? If so, how much?
Obviously smaller is always better in some regard, but I am not familiar enough with how SQL Server optimizes its indexes to know how it deals with length. | You're thinking about this from the wrong direction:
* Do create indexes you need to meet performance goals
* Do NOT create indexes you don't need
Whether a column is a `binary(16)` or `nvarchar(2000)` makes little difference there, because you don't just go add indexes willy nilly.
Don't let index choice dictate your column types. If you need to index an `nvarchar(2000)` consider a fulltext index or adding a hash value for the column and index that.
---
Based on your update, I would probably create either a checksum column or a computed column using the `HashBytes()` function and index that. Note that a checksum isn't the same as a cryptographic hash and so you are somewhat more likely have collisions, but you can also match the entire contents of the text and it will filter with the index first. HashBytes() is less likely to have collisions, but it is still possible and so you still need to compare the actual column. HashBytes is also more expensive to compute the hash for each query and each change. | **OF COURSE** a binary(16) will be MUCH faster - just do the quickest of calculations:
* a SQL Server page is always 8K
* if you have 16 bytes per entry, you can store 500 entries on a page
* with 4000 bytes per entry (nvarchar) you'll end up with 2 entries per page (worst case, if your NVARCHAR(2000) are fully populated)
If you have a table with 100'000 entries, you'll have to have 200 pages for the index with a binary(16) key, while you'll need 50'000 pages for the same index with nvarchar(2000)
Even just the added I/O to read and scan all those pages is going to kill any performance you might have had........
Marc
UPDATE:
For my usual indexes, I try to avoid compound indexes as much as I can - referencing them from other tables just gets rather messy (WHERE clauses with several equality comparisons).
Also, regularly check and maintain your indices - if you have more than 30% fragmentation, rebuild - if you have 5-30% fragmentation, reorganize. Check out an automatic, well tested DB Index maintenance script at <http://sqlfool.com/2009/06/index-defrag-script-v30/>
For the **clustered key** on a SQL Server table, try to avoid GUID's since they're random in nature and thus cause potentially massive index fragmentation and therefore hurt performance. Also, while not a hard requirement, try to make sure your clustered key is unique - if it's not, SQL Server will add a four-byte uniqueifier to it. Also, the clustered key gets added to each and every entry in each and every non-clustered index - so in the clustered key, it's extremely important to have a small, unique, stable (non-changing) column (optimally it's ever-increasing , that gives you the best characteristics and performance --> INT IDENTITY is perfect). | SQL Server Index performance - long column | [
"",
"sql",
"sql-server",
"performance",
"indexing",
""
] |
I have a class (`EAGLView`) which calls a member function of a `C++` class without problems. Now, the problem is that I need to call in that `C++` class a `objective-C` `function` `[context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer*)self.layer];` which I cannot do in `C++` syntax.
I could wrap this `Objective-C` call to the same `Objective-C` class which in the first place called the C++ class, but then I need to somehow call that method from `C++`, and I cannot figure out how to do it.
I tried to give a pointer to `EAGLView` object to the C++ member function and include the "`EAGLView.h`" in my `C++` class header but I got 3999 errors..
So.. how should I do this? An example would be nice.. I only found pure `C` examples of doing this. | You can mix C++ with Objective-C if you do it carefully. There are a few caveats but generally speaking they can be mixed. If you want to keep them separate, you can set up a standard C wrapper function that gives the Objective-C object a usable C-style interface from non-Objective-C code (pick better names for your files, I have picked these names for verbosity):
### MyObject-C-Interface.h
```
#ifndef __MYOBJECT_C_INTERFACE_H__
#define __MYOBJECT_C_INTERFACE_H__
// This is the C "trampoline" function that will be used
// to invoke a specific Objective-C method FROM C++
int MyObjectDoSomethingWith (void *myObjectInstance, void *parameter);
#endif
```
### MyObject.h
```
#import "MyObject-C-Interface.h"
// An Objective-C class that needs to be accessed from C++
@interface MyObject : NSObject
{
int someVar;
}
// The Objective-C member function you want to call from C++
- (int) doSomethingWith:(void *) aParameter;
@end
```
### MyObject.mm
```
#import "MyObject.h"
@implementation MyObject
// C "trampoline" function to invoke Objective-C method
int MyObjectDoSomethingWith (void *self, void *aParameter)
{
// Call the Objective-C method using Objective-C syntax
return [(id) self doSomethingWith:aParameter];
}
- (int) doSomethingWith:(void *) aParameter
{
// The Objective-C function you wanted to call from C++.
// do work here..
return 21 ; // half of 42
}
@end
```
### MyCPPClass.cpp
```
#include "MyCPPClass.h"
#include "MyObject-C-Interface.h"
int MyCPPClass::someMethod (void *objectiveCObject, void *aParameter)
{
// To invoke an Objective-C method from C++, use
// the C trampoline function
return MyObjectDoSomethingWith (objectiveCObject, aParameter);
}
```
The wrapper function ***does not need*** to be in the same `.m` file as the Objective-C class, but the file that it does exist in ***needs to be compiled as Objective-C code***. The header that declares the wrapper function needs to be included in both CPP and Objective-C code.
(NOTE: if the Objective-C implementation file is given the extension ".m" it will not link under Xcode. The ".mm" extension tells Xcode to expect a combination of Objective-C and C++, i.e., Objective-C++.)
---
You can implement the above in an Object-Orientented manner by using the [PIMPL idiom](http://c2.com/cgi/wiki?PimplIdiom). The implementation is only slightly different. In short, you place the wrapper functions (declared in "MyObject-C-Interface.h") inside a class with a (private) void pointer to an instance of MyClass.
### MyObject-C-Interface.h *(PIMPL)*
```
#ifndef __MYOBJECT_C_INTERFACE_H__
#define __MYOBJECT_C_INTERFACE_H__
class MyClassImpl
{
public:
MyClassImpl ( void );
~MyClassImpl( void );
void init( void );
int doSomethingWith( void * aParameter );
void logMyMessage( char * aCStr );
private:
void * self;
};
#endif
```
Notice the wrapper methods no longer require the void pointer to an instance of MyClass; it is now a private member of MyClassImpl. The init method is used to instantiate a MyClass instance;
### MyObject.h *(PIMPL)*
```
#import "MyObject-C-Interface.h"
@interface MyObject : NSObject
{
int someVar;
}
- (int) doSomethingWith:(void *) aParameter;
- (void) logMyMessage:(char *) aCStr;
@end
```
### MyObject.mm *(PIMPL)*
```
#import "MyObject.h"
@implementation MyObject
MyClassImpl::MyClassImpl( void )
: self( NULL )
{ }
MyClassImpl::~MyClassImpl( void )
{
[(id)self dealloc];
}
void MyClassImpl::init( void )
{
self = [[MyObject alloc] init];
}
int MyClassImpl::doSomethingWith( void *aParameter )
{
return [(id)self doSomethingWith:aParameter];
}
void MyClassImpl::logMyMessage( char *aCStr )
{
[(id)self doLogMessage:aCStr];
}
- (int) doSomethingWith:(void *) aParameter
{
int result;
// ... some code to calculate the result
return result;
}
- (void) logMyMessage:(char *) aCStr
{
NSLog( aCStr );
}
@end
```
Notice that MyClass is instantiated with a call to MyClassImpl::init. You could instantiate MyClass in MyClassImpl's constructor, but that generally isn't a good idea. The MyClass instance is destructed from MyClassImpl's destructor. As with the C-style implementation, the wrapper methods simply defer to the respective methods of MyClass.
### MyCPPClass.h *(PIMPL)*
```
#ifndef __MYCPP_CLASS_H__
#define __MYCPP_CLASS_H__
class MyClassImpl;
class MyCPPClass
{
enum { cANSWER_TO_LIFE_THE_UNIVERSE_AND_EVERYTHING = 42 };
public:
MyCPPClass ( void );
~MyCPPClass( void );
void init( void );
void doSomethingWithMyClass( void );
private:
MyClassImpl * _impl;
int _myValue;
};
#endif
```
### MyCPPClass.cpp *(PIMPL)*
```
#include "MyCPPClass.h"
#include "MyObject-C-Interface.h"
MyCPPClass::MyCPPClass( void )
: _impl ( NULL )
{ }
void MyCPPClass::init( void )
{
_impl = new MyClassImpl();
}
MyCPPClass::~MyCPPClass( void )
{
if ( _impl ) { delete _impl; _impl = NULL; }
}
void MyCPPClass::doSomethingWithMyClass( void )
{
int result = _impl->doSomethingWith( _myValue );
if ( result == cANSWER_TO_LIFE_THE_UNIVERSE_AND_EVERYTHING )
{
_impl->logMyMessage( "Hello, Arthur!" );
}
else
{
_impl->logMyMessage( "Don't worry." );
}
}
```
You now access calls to MyClass through a private implementation of MyClassImpl. This approach can be advantageous if you were developing a portable application; you could simply swap out the implementation of MyClass with one specific to the other platform ... but honestly, whether this is a better implementation is more a matter of taste and needs. | You can compile your code as Objective-C++ - the simplest way is to rename your .cpp as .mm. It will then compile properly if you include `EAGLView.h` (you were getting so many errors because the C++ compiler didn't understand any of the Objective-C specific keywords), and you can (for the most part) mix Objective-C and C++ however you like. | Calling Objective-C method from C++ member function? | [
"",
"c++",
"objective-c",
""
] |
I have a ModalPopup that will contain a gridview and 4 fields to enter items into the gridview itself.
Is it possible to postback to the server and update the gridview while keeping the modal open?
When you submit the fields and the postback occurs the modal closes has anyone done this before? Someone mentioned a solution using jQuery, but this was long ago. | The key to doing this is going to be using AJAX of some flavor -- Microsoft.Ajax or jQuery Ajax. If the UpdatePanel is not working, then I'd suggest using jQuery to submit back to the server using AJAX. This would involve creating a WebMethod to accept the AJAX post on the server side and instrumenting the client-side with jQuery to send the request/receive the response. Without seeing your HTML it's a little hard to be very specific.
Basic idea:
```
$(function() {
$('#modalSubmitButton').click( function() {
$.ajax({
url: 'path-to-your-web-method',
dataType: 'json', // or html, xml, ...
data: function() {
var values = {};
values['field1'] = $('#field1ID').val();
...
values['field4'] = $('#field4ID').val();
return values;
},
success: function(data,status) {
... update page based on returned information...
}
... error handling, etc. ...
});
return false; // stop any default action from the button clicked
});
});
``` | Wrapping the popup's content (i.e. not the popup itself!) in an UpdatePanel worked for me.
My popup content is a search panel with sortable/pageable grid of results. The UpdatePanel gave me the exact behaviour I require with no additional code.
Thanks to [Patel Shailesh](http://patelshailesh.com/index.php/why-does-modalpopup-close-on-postback) for the idea.
```
<asp:Panel runat="server" ID="PopupPanel" Height="650" Width="900" Style="display: none">
<asp:UpdatePanel runat="server" ID="UpdatePanel1">
<ContentTemplate>
<!-- popup content -->
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
<ajax:ModalPopupExtender runat="server" ID="PopupExtender" PopupControlID="PopupPanel"
TargetControlID="PopupButton" />
<asp:Button runat="server" ID="PopupButton" Text="Popup" />
``` | PostingBack from ModalPopup, but keeping it visible? | [
"",
"c#",
"ajax",
"gridview",
"postback",
""
] |
I would like to make a deep copy of an entity in JPA. I found an interesting discussion here:
<http://forums.java.net/jive/thread.jspa?messageID=253092&tstart=0>
It sounded like the proposed solution was to set all @Id's to zero. Here's my basic code:
```
//Start a JPA session.
EntityManager em= emf.createEntityManager();
em.getTransaction().begin();
//Get the object I want to copy.
MyClass myObject=em.find(MyClass.class,id);
//Use reflection to find @Id's and set them to zero for all @OneToMany and @OneToOne relations.
//TODO: write the ugly recursive code to do this.
//Hoping this will create a deep copy.
em.merge(myObject);
//Close the session.
em.getTransaction().commit();
em.close();
```
Is this a good strategy? Might anyone have this TODO code already written that they can share???
Thanks! | I was able to get a deep copy to work as described in the question. It is necessary to eagerly load the whole graph and reset the @Id's to null or zero. I found that the Hibernate SessionFactory actually has methods to help with this process.
The other recommendations above for deep copies didn't seem to work. Granted, the problem may have been between keyboard and chair. But it's working now.
Thanks everyone! | **I SOLVED THIS.**
I created a component that makes this whole process for you based on the annotations of the package (`javax.persistence`).
Component already sets the id of the entity to null. He does all the analysis of the algorithm to be applied based on the type of each attribute relationship `@OneToMany`, `@OneToOne` or `@ManyToMany`.
**Example**
```
Person person = personDAO.find(1);
PersistenceCloner cloner = new PersistenceCloner(person);
Person personCopy = cloner.generateCopyToPersist();
```
**Download** JAR and SOURCES: [jpa-entitycloner](https://github.com/vlindberg/jpa-entitycloner) | Deep Copy in JPA | [
"",
"java",
"jpa",
""
] |
I have an application that allows users to enter time they spend working, and I'm trying to get some good reporting built for this which leverages LINQ to Entities. Because each `TrackedTime` has a `TargetDate` which is just the "Date" portion of a `DateTime`, it is relatively simple to group the times by user and date (I'm leaving out the "where" clauses for simplicity):
```
var userTimes = from t in context.TrackedTimes
group t by new {t.User.UserName, t.TargetDate} into ut
select new
{
UserName = ut.Key.UserName,
TargetDate = ut.Key.TargetDate,
Minutes = ut.Sum(t => t.Minutes)
};
```
Thanks to the `DateTime.Month` property, grouping by user and Month is only slightly more complicated:
```
var userTimes = from t in context.TrackedTimes
group t by new {t.User.UserName, t.TargetDate.Month} into ut
select new
{
UserName = ut.Key.UserName,
MonthNumber = ut.Key.Month,
Minutes = ut.Sum(t => t.Minutes)
};
```
Now comes the tricky part. Is there a reliable way to group by Week? I tried the following based on [this response](https://stackoverflow.com/questions/687968/need-some-groupby-linq2sql-help-please/688071#688071) to a similar LINQ to SQL question:
```
DateTime firstDay = GetFirstDayOfFirstWeekOfYear();
var userTimes = from t in context.TrackedTimes
group t by new {t.User.UserName, WeekNumber = (t.TargetDate - firstDay).Days / 7} into ut
select new
{
UserName = ut.Key.UserName,
WeekNumber = ut.Key.WeekNumber,
Minutes = ut.Sum(t => t.Minutes)
};
```
But LINQ to Entities doesn't appear to support arithmetic operations on DateTime objects, so it doesn't know how to do `(t.TargetDate - firstDay).Days / 7`.
I've considered creating a View in the database that simply maps days to weeks, and then adding that View to my Entity Framework context and joining to it in my LINQ query, but that seems like a lot of work for something like this. Is there a good work-around to the arithmetic approach? Something that works with Linq to Entities, that I can simply incorporate into the LINQ statement without having to touch the database? Some way to tell Linq to Entities how to subtract one date from another?
## Summary
I'd like to thank everyone for their thoughtful and creative responses. After all this back-and-forth, it's looking like the real answer to this question is "wait until .NET 4.0." I'm going to give the bounty to Noldorin for giving the most practical answer that still leverages LINQ, with special mention to Jacob Proffitt for coming up with a response that uses the Entity Framework without the need for modifications on the database side. There were other great answers, too, and if you're looking at the question for the first time, I'd strongly recommend reading through all of the ones that have been up-voted, as well as their comments. This has really been a superb example of the power of StackOverflow. Thank you all! | You should be able to force the query to use LINQ to Objects rather than LINQ to Entities for the grouping, using a call to the `AsEnumerable` extension method.
Try the following:
```
DateTime firstDay = GetFirstDayOfFirstWeekOfYear();
var userTimes =
from t in context.TrackedTimes.Where(myPredicateHere).AsEnumerable()
group t by new {t.User.UserName, WeekNumber = (t.TargetDate - firstDay).Days / 7} into ut
select new
{
UserName = ut.Key.UserName,
WeekNumber = ut.Key.WeekNumber,
Minutes = ut.Sum(t => t.Minutes)
};
```
This would at least mean that the `where` clause gets executed by LINQ to Entities, but the `group` clause, which is too complex for Entities to handle, gets done by LINQ to Objects.
Let me know if you have any luck with that.
## Update
Here's another suggestion, which might allow you to use LINQ to Entities for the whole thing.
```
(t.TargetDate.Days - firstDay.Days) / 7
```
This simply expands the operation so that only integer subtraction is performed rather than `DateTime` subtraction.
It is currently untested, so it may or may not work... | You can use SQL functions also in the LINQ as long as you are using SQLServer:
```
using System.Data.Objects.SqlClient;
var codes = (from c in _twsEntities.PromoHistory
where (c.UserId == userId)
group c by SqlFunctions.DatePart("wk", c.DateAdded) into g
let MaxDate = g.Max(c => SqlFunctions.DatePart("wk",c.DateAdded))
let Count = g.Count()
orderby MaxDate
select new { g.Key, MaxDate, Count }).ToList();
```
This sample was adapted from MVP Zeeshan Hirani in this thread:
[a MSDN](http://social.msdn.microsoft.com/Forums/sv-SE/adodotnetentityframework/thread/dc44ebe6-e41e-488c-9667-0a3833c2bd5d) | Group by Weeks in LINQ to Entities | [
"",
"c#",
"linq",
"entity-framework",
"linq-to-entities",
""
] |
In C# VS2008 how to replace
```
intA = (int)obj.GetStr("xxx");
```
to
```
intA = int.Parse(obj.GetStr("xxx"));
```
I have thounds of lines code have this pattern. I just want to pass compile by using some regular expression. | This is a variation on what LBushkin suggested:
```
find: \(int\){:i\.:i\(:q\)}
replace: int.Parse(\1)
``` | Try search and replace using the following regex:
EDIT: Replace the AAA, BBB, CCC values with the appropriate method names you want to match and replace. Be careful of using the :i (identifier) match predicate, as that would match any method call - which you probably don't want.
Find: (looks for any call on any expression to GetStr)
`\(int\){.+}\.{(GetStr|AAA|BBB|CCC)}\({.*}\);`
Replace With:
`Convert.ToInt32(\1.\2(\3));`
or (as others have mentioned) replace with:
`Int.Parse(\1.\2(\3));` | In C# VS2008 how to replace intA = (int)obj.GetStr("xxx"); to intA = int.Parse(obj.GetStr("xxx")); | [
"",
"c#",
"vb.net",
""
] |
I would like to use a COM object in my application.
How can I make sure the object is registered in the machine?
The only solution I found (also [on SO](https://stackoverflow.com/questions/710000/programmatically-determine-if-a-com-library-dll-is-installed)) was to use a try-catch block around the initialization:
```
try {
Foo.Bar COM_oObject = new Foo.Bar();
} catch (Exception ee) {
// Something went wrong during init of COM object
}
```
Can I do it in any other way?
I feel its wrong to deal with an error by expecting it and reporting it, I would rather know I will fail and avoid it to begin with. | You are using exception handling the right way: to fail gracefully from a specific situation that you know how to recover from.
There's not a problem with using try-catch in this case, but you could at least catch more specifically : ComException. | "I feel its wrong to deal with an error by expecting it and reporting it"
Isn't it exactly the purpose of try-catch? BTW, an Exception occurs when something really bad has happened and since it is a pretty bad thing that the COM object you are referring to is not registered, therefore, an Exception is the perfect solution. And you can't handle an exception in any other way.
I think this is the right way to do it. | C# interop - validate object exists | [
"",
"c#",
"validation",
"com",
"interop",
""
] |
I am attemping to use NetUseAdd to add a share that is needed by an application. My code looks like this.
```
[DllImport("NetApi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern uint NetUseAdd(
string UncServerName,
uint Level,
IntPtr Buf,
out uint ParmError);
```
...
```
USE_INFO_2 info = new USE_INFO_2();
info.ui2_local = null;
info.ui2_asg_type = 0xFFFFFFFF;
info.ui2_remote = remoteUNC;
info.ui2_username = username;
info.ui2_password = Marshal.StringToHGlobalAuto(password);
info.ui2_domainname = domainName;
IntPtr buf = Marshal.AllocHGlobal(Marshal.SizeOf(info));
try
{
Marshal.StructureToPtr(info, buf, true);
uint paramErrorIndex;
uint returnCode = NetUseAdd(null, 2, buf, out paramErrorIndex);
if (returnCode != 0)
{
throw new Win32Exception((int)returnCode);
}
}
finally
{
Marshal.FreeHGlobal(buf);
}
```
This works fine on our server 2003 boxes. But in attempting to move over to Server 2008 and IIS7 this doesnt work any more. Through liberal logging i have found that it hangs on the line `Marshal.StructureToPtr(info, buf, true);`
I have absolutely no idea why this is can anyone shed any light on it for tell me where i might look for more information? | The reason is:
You pulled the p/invoke signature off pinvoke.net and you didn't verify it. The fool who initially wrote this p/invoke sample code had no idea what he was doing and created one that "works" on 32-bit systems but does not work on 64-bit systems. He somehow turned a very simple p/invoke signature into some amazingly complicated mess and it spread like wildfire on the net.
The correct signature is:
```
[DllImport( "NetApi32.dll", SetLastError = true, CharSet = CharSet.Unicode )]
public static extern uint NetUseAdd(
string UncServerName,
UInt32 Level,
ref USE_INFO_2 Buf,
out UInt32 ParmError
);
[StructLayout( LayoutKind.Sequential, CharSet = CharSet.Unicode )]
public struct USE_INFO_2
{
public string ui2_local;
public string ui2_remote;
public string ui2_password;
public UInt32 ui2_status;
public UInt32 ui2_asg_type;
public UInt32 ui2_refcount;
public UInt32 ui2_usecount;
public string ui2_username;
public string ui2_domainname;
}
```
And your code should read:
```
USE_INFO_2 info = new USE_INFO_2();
info.ui2_local = null;
info.ui2_asg_type = 0xFFFFFFFF;
info.ui2_remote = remoteUNC;
info.ui2_username = username;
info.ui2_password = password;
info.ui2_domainname = domainName;
uint paramErrorIndex;
uint returnCode = NetUseAdd(null, 2, ref info, out paramErrorIndex);
if (returnCode != 0)
{
throw new Win32Exception((int)returnCode);
}
```
Hope this was of some help. I just spent half a day knee deep remote debugging someone elses trash code trying to figure out what was going on and it was this. | What kind of layout do you have for your struct? I believe the `USE_INFO_2` needs to be [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)].
Also, have you tried just passing the structure by ref rather than needing to Marshal.StructureToPtr? | C# - NetUseAdd from NetApi32.dll on Windows Server 2008 and IIS7 | [
"",
"c#",
"winapi",
"iis-7",
"interop",
""
] |
I am trying to read a binary file from a program that writes a log (of sorts) to a dat file which I have worked out reasonably well the format of using Java. I am loading it as so:
```
DataInputStream in = new DataInputStream(new FileInputStream("file.dat"));
System.out.println("Bytes skipped: " + in.skipBytes(4));
System.out.println(in.readLong());
```
The problem is the value from readLong() is different to what I am expecting, in Hex Workshop I highlight the hex blocks
```
BF02 0000
```
and reports that it is a valid signed short/long number - however the output is very different to what I am expecting. Looking at the Java Docs it states that it classes a long as 64 bit (8 bytes) whereas other sources show a signed long integer should be 32 bits - is there a way to get around this?
Cheers,
Tom | primitive types means different things in different languages and different platforms. (e.g. In C, it's not uncommon that a a long is 32 bit on some platforms and 64bits on others.
First you have to know the type in your .dat file, and the byte order (big/little endian).
Then assemble the individual bytes into an appropriate java type.
If the .dat files specifies a 32 bit signed integer, an int in java would be suitable.
If it was an unsigned 32 bit integer, you probably would need to use a long in java to capture all the possible values, since java does not have unsigned types.
Read it as follows if the integer in the file is little endian:
```
int i = (in.readByte()) | (in.readByte() << 8) | (in.readByte() << 16) | (in.readByte() << 24)
```
and if it's big endian, do
```
int i = (in.readByte() << 24) | (in.readByte() << 16) | (in.readByte() << 8) | (in.readByte())
```
(I don't remember atm. the promotion rules in java here, you might need to and them with &0xff to produce an int before the bit shifting)
Of course, you can read in a byte array and operate on that array instead of calling in.readByte() individually if you want. | A long in Java is *always* 8 bytes (64 bits). Different languages and platforms use different terminology. If you want to read 4 bytes, read an int. | Trying to read non Java primitives from a binary file | [
"",
"java",
"binary",
"load",
""
] |
I'm just looking for clarification on this.
Say I have a small web form, a 'widget' if you will, that gets data, does some client side verification on it or other AJAX-y nonsense, and on clicking a button would direct to another page.
If I wanted this to be an 'embeddable' component, so other people could stick this on their sites, am I limited to basically encapsulating it within an iframe?
And are there any limitations on what I can and can't do in that iframe?
For example, the button that would take you to another page - this would load the content in the iframe? So it would need to exist outwith the iframe?
And finally, if the button the user clicked were to take them to an https page to verify credit-card details, are there any specific security no-nos that would stop this happening?
EDIT: For an example of what I'm on about, think about embedding either googlemaps or multimap on a page.
EDIT EDIT: Okay, I think I get it.
There are Two ways.
One - embed in an IFrame, but this is limited.
Two - create a Javascript API, and ask the consumer to link to this. But this is a lot more complex for both the consumer and the creator.
Have I got that right?
Thanks
Duncan | There's plus points for both methods. I for one, wouldn't use another person's Javascript on my page unless I was absolutely certain I could trust the source. It's not hard to make a malicious script that submits the values of all input boxes on a page. If you don't need access to the contents of the page, then using an iframe would be the best option.
Buttons and links can be "told" to navigate the top or parent frame using the target attribute, like so:
```
<a href="http://some.url/with/a/page" target="_top">This is a link</a>
<form action="http://some.url/with/a/page" target="_parent"><button type="submit">This is a button</button></form>
```
In this situation, since you're navigating away from the hosting page, the same-origin-policy wouldn't apply.
In similar situations, widgets are generally iframes placed on your page. iGoogle and Windows Live Gadgets (to my knowlege) are hosted in iframes, and for very good reason - security. | If you are using AJAX I assume you have a server written in C# or Java or some OO language.
It doesn't really matter what language only the syntax will vary.
Either way I would advise against the iFrame methods.
It will open up way way too many holes or problems like Http with Https (or vice-versa) in an iFrame will show a mixed content warning.
So what do you do?
1. Do a server-side call to the remote site
2. Parse the response appropriately on the server
3. Return via AJAX what you need
4. Display returned content to the user
You know how to do the AJAX just add a server-side call to the remote site.
Java:
```
URL url = new URL("http://www.WEBSITE.com");
URLConnection conn = url.openConnection();
```
or
C#:
```
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://www.WEBSITE.com");
WebResponse res = req.GetResponse();
``` | Embedding web controls across sites - using IFrames/Javascript | [
"",
"javascript",
"iframe",
""
] |
I have a thousands of data parsed from huge XML to be inserted into database table using PHP and MySQL. My Problem is it takes too long to insert all the data into table. Is there a way that my data are split into smaller group so that the process of insertion is by group? How can set up a script that will process the data by 100 for example? Here's my code:
```
foreach($itemList as $key => $item){
$download_records = new DownloadRecords();
//check first if the content exists
if(!$download_records->selectRecordsFromCondition("WHERE Guid=".$guid."")){
/* do an insert here */
} else {
/*do an update */
}
```
}
\*note: $itemList is around 62,000 and still growing. | Using a for loop?
But the quickest option to load data into MySQL is to use the [LOAD DATA INFILE](http://dev.mysql.com/doc/refman/5.1/en/load-data.html) command, you can create the file to load via PHP and then feed it to MySQL via a different process (or as a final step in the original process).
If you cannot use a file, use the following syntax:
```
insert into table(col1, col2) VALUES (val1,val2), (val3,val4), (val5, val6)
```
so you reduce to total amount of sentences to run.
EDIT: Given your snippet, it seems you can benefit from the [INSERT ... ON DUPLICATE KEY UPDATE](http://www.bitbybit.dk/carsten/blog/?p=113) syntax of MySQL, letting the database do the work and reducing the amount of queries. This assumes your table has a primary key or unique index.
To hit the DB every 100 rows you can do something like (**PLEASE REVIEW IT AND FIX IT TO YOUR ENVIRONMENT**)
```
$insertOrUpdateStatement1 = "INSERT INTO table (col1, col2) VALUES ";
$insertOrUpdateStatement2 = "ON DUPLICATE KEY UPDATE ";
$counter = 0;
$queries = array();
foreach($itemList as $key => $item){
$val1 = escape($item->col1); //escape is a function that will make
//the input safe from SQL injection.
//Depends on how are you accessing the DB
$val2 = escape($item->col2);
$queries[] = $insertOrUpdateStatement1.
"('$val1','$val2')".$insertOrUpdateStatement2.
"col1 = '$val1', col2 = '$val2'";
$counter++;
if ($counter % 100 == 0) {
executeQueries($queries);
$queries = array();
$counter = 0;
}
}
```
And executeQueries would grab the array and send a single multiple query:
```
function executeQueries($queries) {
$data = "";
foreach ($queries as $query) {
$data.=$query.";\n";
}
executeQuery($data);
}
``` | You should put it as said before in a temp directory with a cron job to process files, in order to avoid timeouts (or user loosing network).
Use only the web for uploads.
If you really want to import to DB on a web request you can either do a bulk insert or use at least a transaction which should be faster.
Then for limiting inserts by batches of 100 (commiting your trasnsaction if a counter is count%100==0) and repeat until all your rows were inserted. | Batch insertion of data to MySQL database using php | [
"",
"php",
"mysql",
"load-data-infile",
""
] |
Let's say I have a class Point:
```
class Point {
int x, y;
public:
Point& operator+=(const Point &p) { x=p.x; y=p.y; return *this; }
};
```
Why can I not call this as such:
```
Point p1;
p1 += Point(10,10);
```
And is there any way to do this, while still having a reference as the argument? | Here's the code you need:
```
class Point {
int x,y;
public:
Point(int x=0,int y=0) : x(x), y(y) {}
Point& operator+=(const Point&p) {x+=p.x;y+=p.y;return *this;}
};
```
As Konrad pointed out, you need a constructor. Also you need to explicitly perform the additions inside your operator overload. | > Why can I not call this as such:
Because you forgot to declare a matching constructor. Other than that, this call looks fine.
(Also, the code inside your `operator +=` is wrong: it overwrites the values instead of doing additions). | C++ operators and arguments | [
"",
"c++",
"operator-overloading",
""
] |
In python, it is illegal to create new attribute for an object instance like this
```
>>> a = object()
>>> a.hhh = 1
```
throws
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hhh'
```
However, for a function object, it is OK.
```
>>> def f():
... return 1
...
>>> f.hhh = 1
```
What is the rationale behind this difference? | The reason function objects support arbitrary attributes is that, before we added that feature, several frameworks (e.g. parser generator ones) were abusing function docstrings (and other attribute of function objects) to stash away per-function information that was crucial to them -- the need for such association of arbitrary named attributes to function objects being proven by example, supporting them directly in the language rather than punting and letting (e.g.) docstrings be abused, was pretty obvious.
To support arbitrary instance attributes a type must supply every one of its instances with a `__dict__` -- that's no big deal for functions (which are never tiny objects anyway), but it might well be for other objects *intended* to be tiny. By making the `object` type as light as we could, and also supplying `__slots__` to allow avoiding per-instance `__dict__` in subtypes of `object`, we supported small, specialized "value" types to the best of our ability. | Alex Martelli posted an awesome answer to your question. For anyone who is looking for a good way to accomplish arbitrary attributes on an empty object, do this:
```
class myobject(object):
pass
o = myobject()
o.anything = 123
```
Or more efficient (and better documented) if you know the attributes:
```
class myobject(object):
__slots__ = ('anything', 'anythingelse')
o = myobject()
o.anything = 123
o.anythingelse = 456
``` | Python Language Question: attributes of object() vs Function | [
"",
"python",
"function",
"object",
""
] |
I'm getting the error in the title occasionally from a process the parses lots of XML files.
The files themselves seem OK, and running the process again on the same files that generated the error works just fine.
The exception occurs on a call to `XMLReader.parse(InputStream is)`
Could this be a bug in the parser (I use [piccolo](http://piccolo.sourceforge.net/))? Or is it something about how I open the file stream?
No multithreading is involved.
Piccolo seemed like a good idea at the time, but I don't really have a good excuse for using it. I will to try to switch to the default SAX parser and see if that helps.
**Update:** It didn't help, and I found that Piccolo is considerably faster for some of the workloads, so I went back. | I should probably tell the end of this story: it was a stupid mistake. There were two processes: one that produces XML files and another that reads them. The reader just scans the directory and tries to process every new file it sees.
Every once in a while, the reader would detect a file before the producer was done writing, and so it legitimately raised an exception for "Unexpected end of file". Since we're talking about small files here, this event was pretty rare. By the time I came to check, the producer would already finish writing the file, so to me it seemed like the parser was complaining for nothing.
I wrote "No multithreading was involved". Obviously this was very misleading.
One solution would be to write the file elsewhere and move it to the monitored folder only after it was done. A better solution would be to use a proper message queue. | I'm experiencing something similar with Picolo under XMLBeans. After a quick Google, I came across the following post:
[XMLBEANS-226 - Exception "Unexpected end of file after null"](https://issues.apache.org/jira/browse/XMLBEANS-226?focusedCommentId=12585704&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-12585704)
The post states that use of the Apache Commons (v1.4 onwards) class [**org.apache.commons.io.input.AutoCloseInputStream**](https://commons.apache.org/proper/commons-io/javadocs/api-1.4/org/apache/commons/io/input/AutoCloseInputStream.html) may resolve this exception (not tried it myself, apologies). | SAXException: Unexpected end of file after null | [
"",
"java",
"xml",
"sax",
""
] |
How do I program a partial class in C# in multiple files and in different namespaces? | You can't. From [here](http://msdn.microsoft.com/en-us/library/wa80x488(VS.80).aspx) ...
> Using the partial keyword indicates
> that other parts of the class, struct,
> or interface can be defined within the
> namespace
Must be in the same namespace.
Per comment: Here's [an article](http://msdn.microsoft.com/en-us/library/ms973231.aspx) that discusses defining a namespace cross multiple assemblies. From there ...
> Strictly speaking, assemblies
> and namespaces are orthogonal. That
> is, you can declare members of a
> single namespace across multiple
> assemblies, or declare multiple
> namespaces in a single assembly. | You cannot have a partial class in multiple namespaces. Classes of the same name in different [namespaces](http://msdn.microsoft.com/en-us/library/z2kcy19k(VS.80).aspx) are by definition *different classes*. | C# partial class | [
"",
"c#",
".net",
"partial-classes",
""
] |
Is the source code for the Java shipped with Mac OS X available anywhere (official)? I know that the Sun implementation is GPL nowadays. | No, it is not. While Sun has released the JVM under the GPL, they own the copyrights so they can (and do) license to other parties under other terms. Apple has been shipping the JVM (based on Sun's code) for over a decade, since well before it was GPLed, so they clearly originally licensed it under some other terms.
At some point in the future Sun (or Oracle) could opt not renew proprietary licenses, but that seems unlikely. It is actually a fairly common practice to make something available under the GPL and then grant an alternate license to some people (usually for a fee). You can look at licensing page of projects like [Sphinx](http://www.sphinxsearch.com/licensing.html) to see examples of this. | The current Sun version of the JRE is not GPL. The JDK7 implementation has multiple licences including GPL. OpenJDK 6 (6-open) is a backport of the JDK7 implementation to JDK6. [There is a port of OpenJDK 7 to Mac OS X.](http://landonf.bikemonkey.org/code/java/SoyLatte_Meets_OpenJDK.20080819.html) I am not a lawyer. | Apple Java source code available | [
"",
"java",
"macos",
"open-source",
""
] |
I have been attempting to get log4net logging in my asp.net web application with no success or any noticable errors. I am attempting to use the ADONetAppender appender with the following config:
```
<log4net>
<appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
<bufferSize value="1" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="server=" />
<commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception],[Context]) VALUES
(@log_date, @thread, @log_level, @logger, @message, @exception, @context)" />
<parameter>
<parameterName value="@log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="@thread" />
<dbType value="String" />
<size value="32" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%t" />
</layout>
</parameter>
<parameter>
<parameterName value="@log_level" />
<dbType value="String" />
<size value="512" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%p" />
</layout>
</parameter>
<parameter>
<parameterName value="@context" />
<dbType value="String" />
<size value="512" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%x" />
</layout>
</parameter>
<parameter>
<parameterName value="@logger" />
<dbType value="String" />
<size value="512" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%c" />
</layout>
</parameter>
<parameter>
<parameterName value="@message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%m" />
</layout>
</parameter>
<parameter>
<parameterName value="@exception" />
<dbType value="String" />
<size value="2000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="ADONetAppender" />
</root>
```
In my global.asax Application\_Start I call
```
log4net.Config.XmlConfigurator.Configure();
```
Then to attempt to log:
```
protected static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected void Page_Load(object sender, EventArgs e)
{
log.Info("did I log yet?");
}
```
All of this does nothing as far as I can tell. | Have you added added the following section under under Configuration->Configsections
```
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
```
Although it is possible to add your log4net configuration settings to your project’s app.config or web.config file, it is preferable to place them in a separate configuration file. Aside from the obvious benefit of maintainability, it has the added benefit that log4net can place a `FileSystemWatcher` object on your config file to monitor when it changes and update its settings dynamically.
To use a separate config file, add a file named `Log4Net.config` to your project and add the following attribute to your `AssemblyInfo.cs` file:
```
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)]
```
**Note**: for web applications, this assumes Log4Net.config resides in the web root. Ensure the log4net.config file is marked as “Copy To Output” -> “Copy Always” in Properties.
From [here](http://mitch-wheat.blogspot.com/2007/04/log4net-net-logging-tool.html). | you can also set the following appsettings to enable internal log4net debugging information
```
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
```
The internal debug messages are written to the console (if you have one) or the trace (such as the debug window in visual studio or dbgview from sysintenals). This will help you to troubleshoot log4net issues. | Log4Net doesn't log or error | [
"",
"c#",
"asp.net",
"log4net",
""
] |
The problem i have is i could DELETE but then when i hit refresh and send the post data it will try to delete again. Which isnt a problem but now the second statment is a problem since it decreases when it shouldnt.
What is a concurrent safe way to decrease but only if delete has removed an entry? note msgId is a PK so i'll either delete 0 or 1
```
public void removeMediaMsg(long userId, long msgId)
{
using (var dbTrans = connection.BeginTransaction())
{
command.CommandText = "DELETE FROM user_media_subscription "
+ "WHERE msgId=@msgId AND recipientId=@recipientId;";
command.Parameters.Add("@msgId", DbType.Int64).Value = msgId;
command.Parameters.Add("@recipientId", DbType.Int64).Value = userId;
command.ExecuteNonQuery();
command.CommandText = "UPDATE user_data SET mediaMsgCount=mediaMsgCount-1 WHERE userId=@userId;";
command.Parameters.Add("@userId", DbType.Int64).Value = userId;
command.ExecuteNonQuery();
dbTrans.Commit();
}
}
``` | ExecuteNonQuery() returns the numbers of rows affected, so something like this might work
```
public void removeMediaMsg(long userId, long msgId)
{
using (var dbTrans = connection.BeginTransaction())
{
command.CommandText = "DELETE FROM user_media_subscription "
+ "WHERE msgId=@msgId AND recipientId=@recipientId;";
command.Parameters.Add("@msgId", DbType.Int64).Value = msgId;
command.Parameters.Add("@recipientId", DbType.Int64).Value = userId;
int affected = command.ExecuteNonQuery();
if (affected == 1) {
command.CommandText = "UPDATE user_data SET mediaMsgCount=mediaMsgCount-1 WHERE userId=@userId;";
command.Parameters.Add("@userId", DbType.Int64).Value = userId;
command.ExecuteNonQuery();
}
dbTrans.Commit();
}
}
```
That said, you should program your app to avoid replaying a command when refreshing. One way to do that is by using redirect or just rendering a different view after a successful remove. | I'm guessing from the "when I hit refresh" statement that you're executing this from ASP.NET. What I've found useful is to follow the transaction with a Response.Redirect to the summary page. That way hitting refresh does not repeat the Delete command. | How do i fail when DELETE doesnt DELETE? | [
"",
"c#",
"sqlite",
"concurrency",
""
] |
Suppose I'd like to upload some eggs on the Cheese Shop. Do I have any obligation? Am I required to provide a license? Am I required to provide tests? Will I have any obligations to the users of this egg ( if any ) ?
I haven't really released anything as open source 'till now, and I'd like to know the process. | 1. You have an obligation to register the package with a useful description. Nothing is more frustrating than finding a Package that *may* be good, but you don't know, because there is no description.
Typical example of Lazy developer: <http://pypi.python.org/pypi/gevent/0.9.1>
Better: <http://pypi.python.org/pypi/itty/0.6.0>
Fantastic (even a changelog!): <http://pypi.python.org/pypi/jarn.mkrelease/2.0b2>
2. On CheeseShop you can also choose to just register the package, but not upload the code. Instead you can provide your own downloading URL. *DO NOT DO THAT!* That means that your software gets unavailable when cheeseshop is down *or* when your server is down. That means that if you want to install a system that uses your software, the chances that it will fail because a server is down somewhere doubles. And with a big system, when you have five different servers involved... Always upload the package to the CheeseShop as well as registering it!
3. You also have the obligation not to remove the egg (except under exceptional circumstances) as people who starts to depend on a specific version of your software will fail if you remove that version.
If you don't want to support the software anymore, upload a new version, with a big fat "THIS IS NO LONGER SUPPORTED SOFTWARE" or something, on top of the description.
And don't upload development versions, like "0.1dev-r73183".
4. And although you may not have an "obligation" to License your software, you kinda have to, or the uploading gets pointless. If you are unsure, go with GPL.
That's it as far as I'm concerned. Sorry about the ranting. ;-) | See [CheeseShopTutorial](http://wiki.python.org/moin/CheeseShopTutorial) and [Writing the Setup Script](http://docs.python.org/distutils/setupscript.html). | Do I have any obligations if I upload an egg to the CheeseShop? | [
"",
"python",
"egg",
"pypi",
""
] |
Lets say I have an object with two boolean properties:
```
public bool AdvancedMode{ get; set; }
public bool DumpDiagnostics{ get; set; }
```
The domain rules state that DumpDiagnostics is not allowed unless AdvancedMode is also true. So throughout the code you might see statements like this:
```
if( options.AdvancedMode && options.DumpDiagnostics ){ ... }
```
The problem with this is that it's easy to forget to add the check forAdvancedMode and accidentally check only for DumpDiagnostics.
```
if( options.DumpDiagnostics ) // Oh no!
```
So there are two solutions that I can think of:
### Option 1: DumpDiagnostics only returns true when AdvancedMode is true.
```
public bool DumpDiagnostics
{
get{ return AdvancedMode && _dumpDiagnostics; }
set{ _dumpDiagnostics = value; }
}
```
### Option 2: New property that reflects the condition I'm looking for
```
public bool CanDumpDiagnostics{ get{ return AdvancedMode && DumpDiagnostics; } }
```
### Question: Which is better?
Option #1 seems pretty easy and less prone to error. There's always one authority on whether diagnostics can be dumped. But, it does change the set -> get semantics where you can assign DumpDiagnostics = true, followed by if( DumpDiagnostics ) where it returns false.
Option #2 is good because it isolates the logic and makes it clear what the purpose is. The biggest drawback I see with it is that it's still easy to just check for DumpDiagnostics instead of using the new CanDumpDiagnostics property.
p.s. I know it's an awkward title but couldn't come up with something more precise, feel free to modify. | Option 2 makes more sense to me. I don't like properties which can be set but don't "take hold". I was going to suggest throwing an exception in the setter, but then remembered that you'd *also* have to throw an exception in the setter for `AdvancedMode` in case that was reset to false.
I'd rename `DumpDiagnostics` to something like `DiagnosticDumpRequested` to make it clearer that it doesn't guarantee it'll be honoured. | Alternately, pick option 3... turn the two booleans into an enum:
```
public enum Mode
{
Normal,
Advanced,
AdvancedWithDiagnostics
}
```
(with names that are more appropriate for what you are doing)
**Addendum**:
If you want to go really "advanced", you can even use the following:
```
public enum Mode
{
Normal = 0,
Advanced = 1,
AdvancedWithDiagnostics = 3
}
```
And use the following properties (again, pick better naming than mine!):
```
public Mode SelectedMode { get; set; }
public bool AdvancedMode { get { return (SelectedMode & 1) != 0; } }
public bool DumpDiagnostics { get { return (SelectedMode & 2) != 0; } }
``` | Dependent boolean properties | [
"",
"c#",
""
] |
I'm trying to use PHP's split() (preg\_split() is also an option if your answer works with it) to split up a string on 2 or more `\r\n`'s. My current effort is:
```
split("(\r\n){2,}",$nb);
```
The problem with this is it matches every time there is 2 or 3 `\r\n`'s, then goes on and finds the next one. This is ineffective with 4 or more `\r\n`'s.
I need all instances of two or more `\r\n`'s to be treated the same as two `\r\n`'s. For example, I'd need
```
Hello\r\n\r\nMy\r\n\r\n\r\n\r\n\r\n\r\nName is\r\nShadow
```
to become
```
array('Hello','My','Name is\r\nShadow');
``` | Adding the `PREG_SPLIT_NO_EMPTY` flag to preg\_replace() with Tomalak's pattern of `"/(\\r\\n){2,}/"` accomplished this for me. | `preg_split()` *should* do it with
```
$pattern = "/(\\r\\n){2,}/";
``` | Regex with multiple newlines in sequence | [
"",
"php",
"regex",
""
] |
Hey All, I currently use Google's API to include jQuery into my sites like this:
```
<script src="http://www.google.com/jsapi"></script>
<script>google.load("jquery", "1.3.2");</script>
```
How would I accomplish the same for the jQuery UI javascript and css files? | For consistency with the way you're doing it you want:
```
google.load("jquery", "1.3.2");
google.load("jqueryui", "1.7.2");
```
<http://code.google.com/apis/ajaxlibs/documentation/index.html#jqueryUI> | For the jQuery UI:
```
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
```
This is the latest version. | Insert jQuery's UI into page using Google | [
"",
"javascript",
"jquery",
"jquery-ui",
"google-api",
""
] |
I need to find out how many times the number greater than or less than `1` appears in the array.
For example, if I have an array:
```
{1,1,1,2,3,-18,45,1}
```
here numbers that are greater than or less than one appear just once
Another example, if I have an array
```
{1,1,1,2,3,-18,45,1,0}
```
here numbers that are greater than or less than one appear twice, that is at the second to last there is a `1` and after that there is a `0`
One more example
```
{1,1,2,3,1,-18,26,1}
```
here numbers that are greater than or less than one appear twice, one set is `{2,3}` thats once and another set is `{-18,26}` so thats twice.
So far ive been able to loop the array but im stuck .. how to do this
```
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine(isOneBalanced(new int[] { 1, 1, 1, 2, -18, 45, 1 }));
}
static int isOneBalanced(int[] a)
{
foreach(int a1 in a)
{
}
return 0;
}
}
```
how to do this can anybody help me? | Okay...in a nutshell you want to iterate over this loop once, figure out when you're "between 1's", and increment a counter.
There's an additional trick or two, though...one "trick" is that you should pay special attention to keeping track of whether you've already incremented for a particular set or not. If your series is {1, 3, 5, 1}, you don't want to do something like:
```
1: don't increment
3: increment
5: increment // this is bad!
1: don't increment
```
because you'll end up with 2, instead of 1. So keep track of whether you've already incremented with a boolean...call it something like "haveIncremented", and you'll end up with a line like:
```
// if (haveIncremented is false)
// increment my counter
// set haveIncremented to true
```
Then, of course, you'll need to make sure that you set haveIncremented set back to false again, when you start a new set. This will happen when you read in a new "1", and are now ready to start a new "set".
I'm trying to walk a fine line between coding and explaining and helping. Hopefully this will help while not giving away the whole farm.
Good luck. | [Iterate through the array](http://msdn.microsoft.com/en-us/library/2h3zzhdw(VS.80).aspx) in a foreach loop, and [test each value against 1](http://msdn.microsoft.com/en-us/library/6a71f45d.aspx). If it's less than 1, increment num\_greater by 1, and if it's less, increment nun\_less by 1. | Finding repeating numbers above or below 1, in an array | [
"",
"c#",
"comparison",
"iteration",
""
] |
I tried things like $\_ENV['CLIENTNAME'] == 'Console' but that seems to work on only certain OS's (worked in windows, not linux).
I tried !empty($\_ENV['SHELL']) but that doesn't work always either...
Is there a way to check this that will work in all OS's/environments? | Use [`php_sapi_name()`](http://php.net/php_sapi_name)
> Returns a lowercase string that
> describes the type of interface (the
> Server API, SAPI) that PHP is using.
> For example, in CLI PHP this string
> will be "cli" whereas with Apache it
> may have several different values
> depending on the exact SAPI used.
For example:
```
$isCLI = (php_sapi_name() == 'cli');
```
You can also use the constant `PHP_SAPI` | Check on <http://php.net/manual/en/features.commandline.php#105568>
"PHP\_SAPI" Constant
```
<?php
if (PHP_SAPI === 'cli')
{
// ...
}
?>
``` | How to check with PHP if the script is being run from the console or browser request? | [
"",
"php",
"shell",
"console",
"command-line-interface",
""
] |
I'm getting into using the Repository Pattern for data access with the [Entity Framework](http://en.wikipedia.org/wiki/ADO.NET_Entity_Framework) and [LINQ](http://en.wikipedia.org/wiki/Language_Integrated_Query) as the underpinning of implementation of the non-Test Repository. Most samples I see return AsQueryable() when the call returns N records instead of List<T>. What is the advantage of doing this? | AsQueryable just creates a query, the instructions needed to get a list. You can make futher changes to the query later such as adding new Where clauses that get sent all the way down to the database level.
AsList returns an actual list with all the items in memory. If you add a new Where cluse to it, you don't get the fast filtering the database provides. Instead you get all the information in the list and then filter out what you don't need in the application.
So basically it comes down to waiting until the last possible momment before committing yourself. | Returning `IQueryable<T>` has the advantage, that the execution is defferer until you really start enumerating the result and you can compose the query with other queries and still get server side execution.
The problem is that you cannot control the lifetime of the database context in this method - you need an open context and must ensure that it stays open until the query gets executed. And then you must ensure that the context will be disposed. If you return the result as a `List<T>`, `T[]`, or something similar, you loose deffered execution and server side execution of composed queries, but you win control over the lifetime of the database context.
What fits best, of course, depends on the actual requirements. It's another question without a single truth. | Why use AsQueryable() instead of List()? | [
"",
"c#",
"linq",
"repository",
"iqueryable",
""
] |
We need to create a file management interface that integrates with the clients current website built on cakephp.
The file manager must only let the users see the files that they have permissions too.
The user will be able to upload files(of any size) and have other users download those files (if permissions allow).
This is no problem for many file management systems that we can purchase but none that I can find will integrate with their current log in system. The client only wants the users to log in once to access their user CP and their files. So as far as I can see our only option is to build a file management interface ourselves.
What are some of the options that we have to allow uploads using PHP? I understand that we need to increase the php upload limit, but is there a ceiling that php/apache will allow?
The files will likely cap out at approximately 150MB if that is relevant, however there may be situations where the file sizes will be larger.
Also what are the do's and don'ts of file upload/control on a Linux server?
I suppose I have no real 'specific' questions but would like some advise on where to start and some of the typical pitfalls we will run into. | File management is quite easy, actually. Here are some suggestions that may point you in the right direction.
First of all, if this is a load balanced web server situation, you'll need to step up the complexity a little in order to put the files in one common place. If that's the case, ping me and I'll be happy to send you our super-light file server/client we use for that same situation.
There are a few variables you will want to affect in order to allow larger uploads. I recommend using apache directives to limit these changes to a particular file:
```
<Directory /home/deploy/project/uploader>
php_value max_upload_size "200M"
php_value post_max_size "200M"
php_value max_input_time "1800"
# this one depends on how much processing you are doing to the file
php_value memory_limit "32M"
</Directory>
```
**Architecture:**
Create a database table that stores some information about each file.
```
CREATE TABLE `File` (
`File_MNID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`Owner_Field` enum('User.User_ID', 'Resource.Resource_ID') NOT NULL,
`Owner_Key` int(10) unsigned NOT NULL,
`ContentType` varchar(64) NOT NULL,
`Size` int(10) NOT NULL,
`Hash` varchar(40) NOT NULL,
`Name` varchar(128) NOT NULL,
PRIMARY KEY (`File_MNID`),
KEY `Owner` (`Owner_Field`,`Owner_Key`)
) ENGINE=InnoDB
```
What is `Owner_Field` and `Owner_Key`? A simple way to say what "entity" owns the file. In this specific case there were multiple types of files being uploaded. In your case, a simple `User_ID` field may be adequate.
The purpose of storing the owner is so that you can restrict who can download and delete the file. That will be crucial for protecting the downloads.
**Here is a sample class** that can be used to accept the file uploads from the browser. You'll need to modify it to suit, of course.
There are a few things to note about the following code. Since this is used with an Application Server and a File Server, there are a few things to "replace".
1. Any occurrences of `App::CallAPI(...)` will need to be replaced with a query or set of queries that do the "same thing".
2. Any occurrences of `App::$FS->...` will need to be replaced with the correct file handling functions in PHP such as `move_uploaded_file`, `readfile`, etc...
Here it is. Keep in mind that there are functions here which allow you to see files owned by a given user, delete files, and so on and so forth. More explanation at the bottom...
```
<?php
class FileClient
{
public static $DENY = '/\.ade$|\.adp$|\.asp$|\.bas$|\.bat$|\.chm$|\.cmd$|\.com$|\.cpl$|\.crt$|\.exe$|\.hlp$|\.hta$|\.inf$|\.ins$|\.isp$|\.its$| \.js$|\.jse$|\.lnk$|\.mda$|\.mdb$|\.mde$|\.mdt,\. mdw$|\.mdz$|\.msc$|\.msi$|\.msp$|\.mst$|\.pcd$|\.pif$|\.reg$|\.scr$|\.sct$|\.shs$|\.tmp$|\.url$|\.vb$|\.vbe$|\.vbs$|vsmacros$|\.vss$|\.vst$|\.vsw$|\.ws$|\.wsc$|\.wsf$|\.wsh$/i';
public static $MAX_SIZE = 5000000;
public static function SelectList($Owner_Field, $Owner_Key)
{
$tmp = App::CallAPI
(
'File.List',
array
(
'Owner_Field' => $Owner_Field,
'Owner_Key' => $Owner_Key,
)
);
return $tmp['Result'];
}
public static function HandleUpload($Owner_Field, $Owner_Key, $FieldName)
{
$aError = array();
if(! isset($_FILES[$FieldName]))
return false;
elseif(! is_array($_FILES[$FieldName]))
return false;
elseif(! $_FILES[$FieldName]['tmp_name'])
return false;
elseif($_FILES[$FieldName]['error'])
return array('An unknown upload error has occured.');
$sPath = $_FILES[$FieldName]['tmp_name'];
$sHash = sha1_file($sPath);
$sType = $_FILES[$FieldName]['type'];
$nSize = (int) $_FILES[$FieldName]['size'];
$sName = $_FILES[$FieldName]['name'];
if(preg_match(self::$DENY, $sName))
{
$aError[] = "File type not allowed for security reasons. If this file must be attached, please add it to a .zip file first...";
}
if($nSize > self::$MAX_SIZE)
{
$aError[] = 'File too large at $nSize bytes.';
}
// Any errors? Bail out.
if($aError)
{
return $aError;
}
$File = App::CallAPI
(
'File.Insert',
array
(
'Owner_Field' => $Owner_Field,
'Owner_Key' => $Owner_Key,
'ContentType' => $sType,
'Size' => $nSize,
'Hash' => $sHash,
'Name' => $sName,
)
);
App::InitFS();
App::$FS->PutFile("File_" . $File['File_MNID'], $sPath);
return $File['File_MNID'];
}
public static function Serve($Owner_Field, $Owner_Key, $File_MNID)
{
//Also returns the name, content-type, and ledger_MNID
$File = App::CallAPI
(
'File.Select',
array
(
'Owner_Field' => $Owner_Field,
'Owner_Key' => $Owner_Key,
'File_MNID' => $File_MNID
)
);
$Name = 'File_' . $File['File_MNID'] ;
//Content Header for that given file
header('Content-disposition: attachment; filename="' . $File['Name'] . '"');
header("Content-type:'" . $File['ContentType'] . "'");
App::InitFS();
#TODO
echo App::$FS->GetString($Name);
}
public static function Delete($Owner_Field, $Owner_Key, $File_MNID)
{
$tmp = App::CallAPI
(
'File.Delete',
array
(
'Owner_Field' => $Owner_Field,
'Owner_Key' => $Owner_Key,
'File_MNID' => $File_MNID,
)
);
App::InitFS();
App::$FS->DelFile("File_" . $File_MNID);
}
public static function DeleteAll($Owner_Field, $Owner_Key)
{
foreach(self::SelectList($Owner_Field, $Owner_Key) as $aRow)
{
self::Delete($Owner_Field, $Owner_Key, $aRow['File_MNID']);
}
}
}
```
**Notes:**
Please keep in mind that this class DOES NOT implement security. It assumes that the caller has an authenticated Owner\_Field and Owner\_Key before calling `FileClient::Serve(...)` etc...
It's a bit late, so if some of this doesn't make sense, just leave a comment. Have a great evening, and I hope this helps some.
PS. The user interface can be simple tables and file upload fields, etc.. Or you could be fancy and use a flash uploader... | I recommend having a look at the following community-contributed CakePHP code examples:
* [Uploader Plugin](http://www.milesj.me/resources/script/uploader-plugin)
* [WhoDidIt Behavior](http://blog.4webby.com/posts/view/11/whodidit_behavior_monitor_who_has_manipulated_a_record_automagically_in_cakephp)
* [Traceable Behavior](http://code.google.com/p/chieftain/source/browse/trunk/chieftain/models/behaviors/traceable.php) | PHP File Management System | [
"",
"php",
"file",
"cakephp",
"file-management",
""
] |
I'm narrowing in on an underlying problem related to [two](https://stackoverflow.com/questions/1101266/bittorrent-tracker-announce-problem) [prior](https://stackoverflow.com/questions/1105244/uri-encoding-strangeness) questions.
Basically, I've got a URL that when I fetch it manually (paste it into browser) works just fine, but when I run through some code (using the HttpWebRequest) has a different result.
The URL (example):
```
http://208.106.250.207:8192/announce?info_hash=-%CA8%C1%C9rDb%ADL%ED%B4%2A%15i%80Z%B8%F%C&peer_id=01234567890123456789&port=6881&uploaded=0&downloaded=0&left=0&compact=0&no_peer_id=0&event=started
```
The code:
```
String uri = BuildURI(); //Returns the above URL
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
req.Proxy = new WebProxy();
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
... Parse the result (which is an error message from the server claiming the url is incorrect) ...
```
So, how can I GET from a server given a URL? I'm obviously doing something wrong here, but can't tell what.
Either a fix for my code, or an alternative approach that actually works would be fine. I'm not wed at all to the HttpWebRequest method. | Well, the only they might differ is in the HTTP headers that get transmitted. In particular the User-Agent.
Also, why are you using a WebProxy? That is not really necessary and it most likely is not used by your browser.
The rest of your code is fine.. Just make sure you set up the HTTP headers correctly. Check [this link](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers.aspx) out:
I would suggest that you get yourself a copy of [WireShark](http://en.wikipedia.org/wiki/Wireshark) and examine the communication that happens between your browser and the server that you are trying to access. Doing so will be rather trivial using WireShark and it will show you the exact HTTP message that is being sent from the browser.
Then take a look at the communication that goes on between your C# application and the server (again using WireShark) and then compare the two to find out what exactly is different.
If the communication is a pure HTTP GET method (i.e. there is no HTTP message body involved), and the URL is correct then the only two things I could think of are:
1. make sure that your are send the right protocol (i.e. HTTP/1.0 or HTTP/1.1 or whatever it is that you should be sending)
2. make sure that you are sending all required HTTP headers correctly, and obviously that you are not sending any HTTP headers that you shouldn't be sending. | I recommend you use Fiddler to trace both the "paste in web browser" call and the HttpWebRequest call.
Once traced you will be able to see *any* differences between them, whether they are differences in the request url, in the form headers, etc, etc.
It may actually be worth pasting the raw requests from both (obtained from Fiddler) here, if you can't see anything obvious. | How does HttpWebRequest differ (functional) from pasteing a URL into an address bar? | [
"",
"c#",
"httpwebrequest",
""
] |
I am passing a string into a hidden field on the page and then splitting it in order to try to get an array of items I can iterate over and add multiple markers onto a google map. If I hard code the array it works fine, but if I try to split the string and use the same code it does not work. I'm assuming because splitting the string creates a string array instead of Array objects. When I split the string the array ends up with "['Smith Company', 33.61678, -111.90017]" with the double quotes around it. How would I convert these items so that I can use it the same as the hard coded values?
I add the square brackets, single quotes and vert bar in a StringBuilder in the code behind. Using C# for that if it will make a difference. I am not married to doing it this way, but still green with JavaScript so this was my initial solution. My initial string looks like this"
```
"['Jones Company', 26.16683, -98.23342]|['Smith Company', 33.61678, -111.90017]|['Bob Company', 29.70008, -98.03347]|['Blue Company', 37.71675, -122.21672]|['Red Company', 42.46692, -114.48342]"
```
Thanks.
```
function initialize() {
var myOptions = {
zoom: 4,
center: new google.maps.LatLng(26.16683, -98.23342),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//What I try to use when the hard coded is commented out
var myString = document.getElementById('hdnString').value;
var myItems = new Array();
myItems = myString.split("|");
//Hard coded items that I comment out when trying the above
var myItems = [
['Jones Company', 26.16683, -98.23342],
['Smith Company', 33.61678, -111.90017],
['Bob Company', 37.71675, -122.21672],
['Blue Company', 42.46692, -114.48342],
['Red Company', 36.58339, -121.8335]
];
// Add markers to the map
for (var i in myItems){
var myLatLng = new google.maps.LatLng(myItems[i][1], myItems[i][2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: myItems[i][0]
});
}
}
``` | You're going to have to use `eval()` to convert the string representations of arrays to actual javascript arrays.
This code ought to work:
```
var myString = document.getElementById('hdnString').value;
var myItems = [];
var rawItems = myString.split("|");
for (var i=0; i<rawItems.length; i++){
myItems.push(eval(rawItems[i]));
}
```
Do note that [eval is evil](http://blogs.msdn.com/ericlippert/archive/2003/11/01/53329.aspx) except [when it's not](https://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil). | You may want to try using [JSON](http://www.json.org/js.html) formatted text in your hidden field. Then you can parse the JSON into real JavaScript Objects. If I understand your hidden field correctly you would just need a string that looks like
```
<input id="myItemList" type="hidden" value="{'myItems' = [
['Jones Company', 26.16683, -98.23342],
['Smith Company', 33.61678, -111.90017],
['Bob Company', 37.71675, -122.21672],
['Blue Company', 42.46692, -114.48342],
['Red Company', 36.58339, -121.8335]
]}"/>
```
Then in javascript:
```
// this is an array
var myItems = JSON.parse(document.getElementById("myItemList").value)["myItems"];
``` | Turn String array values into array object | [
"",
"javascript",
"google-maps",
""
] |
There are N values in the array, and one of them is the smallest value. How can I find the smallest value most efficiently? | If they are unsorted, you can't do much but look at each one, which is O(N), and when you're done you'll know the minimum.
---
Pseudo-code:
```
small = <biggest value> // such as std::numerical_limits<int>::max
for each element in array:
if (element < small)
small = element
```
A better way reminded by [Ben](https://stackoverflow.com/users/38924/ben) to me was to just initialize small with the first element:
```
small = element[0]
for each element in array, starting from 1 (not 0):
if (element < small)
small = element
```
The above is wrapped in the [algorithm](http://www.cppreference.com/wiki/stl/algorithm/start) header as [std::min\_element](http://www.cppreference.com/wiki/stl/algorithm/min_element).
---
If you can keep your array sorted as items are added, then finding it will be O(1), since you can keep the smallest at front.
That's as good as it gets with arrays. | The stl contains a bunch of methods that should be used dependent to the problem.
```
std::find
std::find_if
std::count
std::find
std::binary_search
std::equal_range
std::lower_bound
std::upper_bound
```
Now it contains on your data what algorithm to use.
This [Artikel](http://www.aristeia.com/Papers/CUJ_Dec_2001.pdf) contains a perfect table to help choosing the right algorithm.
---
In the special case where min max should be determined and you are using std::vector or ???\* array
```
std::min_element
std::max_element
```
can be used. | Finding smallest value in an array most efficiently | [
"",
"c++",
"arrays",
""
] |
Hi I am trying to return a collection which may potentially have null date values.
However, if they are null - I want to keep them that way and not just use a arbitrary date instead.
If it was a string, I'd check for nulls like thus:
```
calEventDTO.occurrenceType = dr.IsDBNull(10) ? null : dr.GetString(10);
```
How would I do the same for a date?
The following doesn't compile (There is no implicit conversion between 'null' and System.DateTime').
```
calEventDTO.recurrenceID = dr.IsDBNull(9) ? null : dr.GetDateTime(9);
```
My dto is set up to deal with null values.
```
public DateTime? recurrenceID
{
get { return _recurrenceID; }
set { _recurrenceID = value; }
}
```
Any hints/help/pointers much appreciated.
thanks | Try:
```
calEventDTO.recurrenceID = dr.IsDBNull(9) ? null : (DateTime?) dr.GetDateTime(9);
```
The ? operator requires both operands (null, and dr.GetDateTime(9) in this case) to be of the same type. | The conditional operator doesn't consider what you assign the result to, so you have to cast either of the operands to DateTime?:
```
calEventDTO.recurrenceID = dr.IsDBNull(9) ? (DateTime?)null : dr.GetDateTime(9);
``` | Dealing with null dates returned from db | [
"",
"c#",
".net",
"sql-server-2005",
"ado.net",
""
] |
I'd like to set a property of an object through Reflection, with a value of type `string`.
So, for instance, suppose I have a `Ship` class, with a property of `Latitude`, which is a `double`.
Here's what I'd like to do:
```
Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, value, null);
```
As is, this throws an `ArgumentException`:
> Object of type 'System.String' cannot be converted to type 'System.Double'.
How can I convert value to the proper type, based on `propertyInfo`? | You can use [`Convert.ChangeType()`](http://msdn.microsoft.com/en-us/library/ms130977.aspx) - It allows you to use runtime information on any `IConvertible` type to change representation formats. Not all conversions are possible, though, and you may need to write special case logic if you want to support conversions from types that are not `IConvertible`.
The corresponding code (without exception handling or special case logic) would be:
```
Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);
``` | As several others have said, you want to use `Convert.ChangeType`:
```
propertyInfo.SetValue(ship,
Convert.ChangeType(value, propertyInfo.PropertyType),
null);
```
In fact, I recommend you look at the entire [`Convert` Class](http://msdn.microsoft.com/en-us/library/system.convert.aspx).
This class, and many other useful classes are part of the [`System` Namespace](http://msdn.microsoft.com/en-us/library/system.aspx). I find it useful to scan that namespace every year or so to see what features I've missed. Give it a try! | Setting a property by reflection with a string value | [
"",
"c#",
"reflection",
"type-conversion",
"propertyinfo",
"setvalue",
""
] |
I need a variable that is available from any function in my code, but is different to all users.
so i wrote:
```
public class classedelcappero
{
private string frasehiragana = String.Empty;
public string ohiragana
{
get
{
return frasehiragana;
}
set
{
frasehiragana = value;
}
}
}
```
and then i put this in my function:
```
protected void Page_Load(object sender, EventArgs e)
{
classedelcappero chepalle = new classedelcappero();
string frasehiragana = chepalle.ohiragana;
}
```
and it works... but if i access it from another function, like
```
protected void ButtonRiprova_Click(object sender, EventArgs e)
```
the value is empty... is that ok?
what to do? Use Session variables? | You may want to take a look at this series of blog posts:
* [User Context](http://blogs.msdn.com/ploeh/archive/2007/08/20/UserContext.aspx)
* [Call Contexts vs. ASP.NET](http://blogs.msdn.com/ploeh/archive/2007/07/28/CallContextsVsAspNet.aspx)
* [Ambient Context](http://blogs.msdn.com/ploeh/archive/2007/07/23/AmbientContext.aspx) | This is one way you can do it,
Create a class that derives from System.Web.UI.Page and add one public property to the class, it will look like.
```
public class MyPage : System.Web.UI.Page
{
public string Frasehiragana
{
get
{
try{
return HttpContext.Current.Application.Contents["_Frasehiragana"] as string;
}
catch
{
return null;
}
}
set
{
HttpContext.Current.Application.Add("_Frasehiragana", value);
}
}
}
```
Then derive all your asp.net pages from MyPage class instead of System.Web.UI.Page, your asp.net page code behind class may look like this after you do this.
```
public partial class _Default : MyPage
.
.
.
```
Now you can use it as following in all your pages.
```
this.Frasehiragana;
```
Thanks, | C# ASP.NET - a variable that's accessible from any function, and is different to any user? | [
"",
"c#",
"asp.net",
"variables",
""
] |
I have a website that uses JSP as its view technology (and Spring MVC underneath). Unfortunately, JSP is just a pain to use for anything that doesn't involve an HTTP session. I would like to be able to occasionally send my users some email, and I want to use something JSP-like to render the email's contents. Technologies I'm aware of include:
* JSP -- It can be forced to work for this sort of thing, I think. Very worst case, I could request the page from my own webserver and render that into an email (ugh!)
* Velocity -- I've heard good things about this one, and am leaning towards it.
* StringTemplate -- Looks okay, but I'm worried that no new releases have come out in a year.
Is there a preferred technology for templating in a Java system? Would folks generally recommend Velocity? Is there a good way to use JSP for more generic tasks? | You should go with Velocity. It's easy to learn and has a low dependency and implementation footprint, especially when using Spring.
But, if it's just one Use Case, you should stick with the String and unless you have no time for experiments ;) | I used [Freemarker](http://freemarker.org/) a lot for e-mail templating and it worked great and was easy to use. | Which Java templating system should I use to generate emails? | [
"",
"java",
"spring",
"jsp",
"velocity",
"templating",
""
] |
Ok I know you can use the dir() method to list everything in a module, but is there any way to see only the functions that are defined in that module? For example, assume my module looks like this:
```
from datetime import date, datetime
def test():
return "This is a real method"
```
Even if i use inspect() to filter out the builtins, I'm still left with anything that was imported. E.g I'll see:
['date', 'datetime', 'test']
Is there any way to exclude imports? Or another way to find out what's defined in a module? | Are you looking for something like this?
```
import sys, inspect
def is_mod_function(mod, func):
return inspect.isfunction(func) and inspect.getmodule(func) == mod
def list_functions(mod):
return [func.__name__ for func in mod.__dict__.itervalues()
if is_mod_function(mod, func)]
print 'functions in current module:\n', list_functions(sys.modules[__name__])
print 'functions in inspect module:\n', list_functions(inspect)
```
EDIT: Changed variable names from 'meth' to 'func' to avoid confusion (we're dealing with functions, not methods, here). | How about the following:
```
grep ^def my_module.py
``` | Find functions explicitly defined in a module (python) | [
"",
"python",
"introspection",
""
] |
I'm curious, how would you test a string and say "yep, that is a comma delimited list!" I'm not so worried about the 'comma delimited' part more that this string has more than one item in it?
Thanks, R. | How about:
```
stringObject.indexOf(",") >= 0
``` | To check if the string has more than one item, try something like:
```
str.split(",").length > 1
```
... although, as suggested in a comment, correct parsing is likely to be bit more complicated than this for the general case.
### Edit:
whoops, misread language as Java - sorry. | Javascript how to ascertain if it is a comma delimited list? | [
"",
"javascript",
""
] |
We have some stuff that may be exported into various formats. Currently we have these formats represented by an enum like this:
```
[Flags]
public enum ExportFormat
{
None = 0x0,
Csv = 0x1,
Tsv = 0x2,
Excel = 0x4,
All = Excel | Csv | Tsv
}
```
Problem is that these must be enumerated and they also need a translation or description in the ui. Currently I solved this by creating two extension methods. They work, but I don't really like them or the solution at all... they feel kind of smelly. Problem is I don't really know how I could do this better. Does anyone have any good alternatives? These are the two methods:
```
public static IEnumerable<ExportFormat> Formats(this ExportFormat exportFormats)
{
foreach (ExportFormat e in Enum.GetValues(typeof (ExportFormat)))
{
if (e == ExportFormat.None || e == ExportFormat.All)
continue;
if ((exportFormats & e) == e)
yield return e;
}
}
public static string Describe(this ExportFormat e)
{
var r = new List<string>();
if ((e & ExportFormat.Csv) == ExportFormat.Csv)
r.Add("Comma Separated Values");
if ((e & ExportFormat.Tsv) == ExportFormat.Tsv)
r.Add("Tab Separated Values");
if ((e & ExportFormat.Excel) == ExportFormat.Excel)
r.Add("Microsoft Excel 2007");
return r.Join(", ");
}
```
Maybe this is the way to do this, but I have a feeling there must be better ways to do it. How could I refactor this? | You could use the Formats method inside Describe to avoid doing all the bit operations at multiple places, like this:
```
private static Dictionary<ExportFormat, string> FormatDescriptions =
new Dictionary<ExportFormat,string>()
{
{ ExportFormat.Csv, "Comma Separated Values" },
{ ExportFormat.Tsv, "Tab Separated Values" },
{ ExportFormat.Excel, "Microsoft Excel 2007" },
};
public static string Describe(this ExportFormat e)
{
var formats = e.Formats();
var descriptions = formats.Select(fmt => FormatDescriptions[fmt]);
return string.Join(", ", descriptions.ToArray());
}
```
This way, it is easy to incorporate the string descriptions from an external source or localization, as hinted above. | The only other way comes to my mind is the usage of the System.Attribute class.
```
public class FormatDescription : Attribute
{
public string Description { get; private set; }
public FormatDescription(string description)
{
Description = description;
}
}
```
And then use Reflection with in your Describe function.
The only benefit of this method would be to have definition and the description at one place. | Replacement of enum that requires translation and enumeration | [
"",
"c#",
"enums",
""
] |
For some time I've been making a 2d tile based sim game, and it's going well! Thanks to this site and its kind people (You!), I have just finished the path-finding part of the game, which is fantastic! THANK YOU!... Anyway, to the question.
At present, the test level is hard-coded into the game. Clearly I need to re-work this. My idea was to have all variables in my Game class saved to a text file in various ways. I could also write the details of each level into a file to be loaded for a level. My question is, should I be using just a text file, or using XML? I understand what XML is basically, but I don't really know how I would use it in conjunction with JAVA, or why it's preferable or not over a plain text file.
I had a bit of a google, and there are WHOLE books on XML and JAVA! I can't see I need to know EVERYTHING about how to use XML with JAVA to make this work, but I do need to know more than I do.
Thanks in advance for your help with this.
Edit:
I will try several of the ideas here until I find the one that works the best, and then that will be chosen as the answer.
Edit: Chose xStream. Easy and simple! | If you have the game state in an object (e.g. a HashMap, or perhaps an object of your own design), then you can write it out as an XML file trivially using [XStream](http://xstream.codehaus.org), and then read it back to a new object using XStream again.
There's a [two minute tutorial](http://xstream.codehaus.org/tutorial.html) to show you how to serialise/deserialise. It'll handle most objects without any difficulty - you don't need to implement or specify any particular interface. Nor do you need JAXP, SAX, DOM etc. | For a 2D tile-based game, XML is probably overkill. XML is good for storing hierarchical data and/or marked-up text, but it sounds like you just need a way of encoding a 2D grid of tile settings, which is far easier to do with a plain old text file.
Just have each line be a row of tiles, and decide how many characters you want per tile (probably one or two would be fine). Then decide how to represent the objects in your 2D world with characters in the text file.
In [SokoBean](http://xenomachina.com/soko/) (a game I wrote over 10 years ago, so not what I'd call my best work, but whatever) I used [text files like this one](http://xenomachina.com/soko/levels/standard/1). In addition to being easier to parse than XML, you can also use a plain old text editor as a level editor. | Loading and saving a tile based game in Java. XML or TXT? | [
"",
"java",
"xml",
"tiles",
""
] |
I'm having trouble getting the Dispatcher to run a delegate I'm passing to it when unit testing. Everything works fine when I'm running the program, but, during a unit test the following code will not run:
```
this.Dispatcher.BeginInvoke(new ThreadStart(delegate
{
this.Users.Clear();
foreach (User user in e.Results)
{
this.Users.Add(user);
}
}), DispatcherPriority.Normal, null);
```
I have this code in my viewmodel base class to get a Dispatcher:
```
if (Application.Current != null)
{
this.Dispatcher = Application.Current.Dispatcher;
}
else
{
this.Dispatcher = Dispatcher.CurrentDispatcher;
}
```
Is there something I need to do to initialise the Dispatcher for unit tests? The Dispatcher never runs the code in the delegate. | By using the Visual Studio Unit Test Framework you don’t need to initialize the Dispatcher yourself. You are absolutely right, that the Dispatcher doesn’t automatically process its queue.
You can write a simple helper method “DispatcherUtil.DoEvents()” which tells the Dispatcher to process its queue.
C# Code:
```
public static class DispatcherUtil
{
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public static void DoEvents()
{
DispatcherFrame frame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
new DispatcherOperationCallback(ExitFrame), frame);
Dispatcher.PushFrame(frame);
}
private static object ExitFrame(object frame)
{
((DispatcherFrame)frame).Continue = false;
return null;
}
}
```
You find this class too in the **[WPF Application Framework (WAF)](https://github.com/jbe2277/waf)**. | We've solved this issue by simply mocking out the dispatcher behind an interface, and pulling in the interface from our IOC container. Here's the interface:
```
public interface IDispatcher
{
void Dispatch( Delegate method, params object[] args );
}
```
Here's the concrete implementation registered in the IOC container for the real app
```
[Export(typeof(IDispatcher))]
public class ApplicationDispatcher : IDispatcher
{
public void Dispatch( Delegate method, params object[] args )
{ UnderlyingDispatcher.BeginInvoke(method, args); }
// -----
Dispatcher UnderlyingDispatcher
{
get
{
if( App.Current == null )
throw new InvalidOperationException("You must call this method from within a running WPF application!");
if( App.Current.Dispatcher == null )
throw new InvalidOperationException("You must call this method from within a running WPF application with an active dispatcher!");
return App.Current.Dispatcher;
}
}
}
```
And here's a mock one that we supply to the code during unit tests:
```
public class MockDispatcher : IDispatcher
{
public void Dispatch(Delegate method, params object[] args)
{ method.DynamicInvoke(args); }
}
```
We also have a variant of the `MockDispatcher` which executes delegates in a background thread, but it's not neccessary most of the time | Using the WPF Dispatcher in unit tests | [
"",
"c#",
".net",
"wpf",
"unit-testing",
"dispatcher",
""
] |
I am trying to figure out when and why to use a `Dictionary` or a `Hashtable`. I have done a bit of a search on here and have found people talking about the generic advantages of the `Dictionary` which I totally agree with, which leads the boxing and unboxing advantage for a slight performance gain.
But I have also read the `Dictionary` will not always return the objects in the order they are inserted, thing it is sorted. Where as a `Hashtable` will. As I understand it this leads to the `Hashtable` being far faster for some situations.
My question is really, what might those situations be? Am I just wrong in my assumptions above? What situations might you use to choose one above the other, (yes the last one is a bit ambiguous). | `System.Collections.Generic.Dictionary<TKey, TValue>` and `System.Collections.Hashtable` classes both maintain a hash table data structure internally. **None of them guarantee preserving the order of items.**
Leaving boxing/unboxing issues aside, most of the time, they should have very similar performance.
The primary structural difference between them is that `Dictionary` relies on *chaining* (maintaining a list of items for each hash table bucket) to resolve collisions whereas `Hashtable` uses *rehashing* for collision resolution (when a collision occurs, tries another hash function to map the key to a bucket).
There is little benefit to use `Hashtable` class if you are targeting for .NET Framework 2.0+. It's effectively rendered obsolete by `Dictionary<TKey, TValue>`. | I guess it doesn't mean anything to you now. But just for reference for people stopping by
[Performance Test - SortedList vs. SortedDictionary vs. Dictionary vs. Hashtable](http://blog.bodurov.com/Performance-SortedList-SortedDictionary-Dictionary-Hashtable/)
**Memory allocation:**
[](https://i.stack.imgur.com/ad4qb.png)
**Time used for inserting:**
[](https://i.stack.imgur.com/uUshQ.png)
**Time for searching an item:**
[](https://i.stack.imgur.com/CErGR.png) | .NET Hashtable vs Dictionary - Can the Dictionary be as fast? | [
"",
"c#",
"performance",
"dictionary",
"collections",
"hashtable",
""
] |
Ok,
I have a LinqToXml query that returns a single record (correct terminology?),
however, I don't want to use a for.. loop to pull that one record from the query. Is there an easier way?
\*bonus if you find a better way to write the query (I'm still learning)
my xml file:
```
<?xml version="1.0"?>
<!-- first draft of LibMappings.xml file -->
<LibMappings>
<File>
<Name>Foundation.dll</Name>
<Map>Lib\Foundation</Map>
</File>
</LibMappings>
```
My Code:
```
private static string GetMapFor(string dllName)
{
//Opens Xml File and gets "Lib" map for dllName
string retVal;
XDocument libMapFile = XDocument.Load(_libMapFilePath);
//This query will return 1 record
IEnumerable<XElement> query = from c in libMapFile.Descendants("File")
where (string)c.Element("Name") == dllName
select c.Element("Map");
if (query.Count() == 1)
{
//there's only gonna be one here.. I might as well do this..
foreach (string x in query)
{
retVal = x;
break;
}
//I'd like to do this:
retVal = query[0];
}
return retVal;
}
``` | ```
IEnumerable<XElement> query = from c in libMapFile.Descendants("File")
where (string)c.Element("Name") == dllName
select c.Element("Map");
XElement element = query.First();
return element.Value;
``` | You are either looking for the First or FirstOrDefault extension method.
These methods will return the first element int the query. They only differ in behavior when the query result is empty. The First method will throw an exception while FirstOrDefault will return the default value for the type of element in the query (typically null).
```
var first = query.First();
``` | Is there an easy way to return the FIRST LinqToXML result? | [
"",
"c#",
"xml",
"linq",
"linq-to-xml",
""
] |
I'm searching for an multi platform OpenGL framework that abstracts the creation of windows and gl contexts in C++.
I'd like to have an OO representation of Window, Context & co where i can instantiate a Window, create a Context and maybe later set the window to fullscreen.
I'm thinking about implementing this myself for xgl, wgl and agl. But before
So here comes the Question:
Which libraries / frameworks should i check out first, before inventing the wheel again?
**Edit:**
So far named libraries:
* [glut](http://www.opengl.org/resources/libraries/glut/)
* [Qt](http://qt.nokia.com/)
* [SDL](http://www.libsdl.org/)
* [gtkglext](http://gtkglext.sourceforge.net/index)
* [wxwdigets](http://www.wxwidgets.org/)
* [SFML](http://www.sfml-dev.org/) | [SMFL](http://www.sfml-dev.org/) is another, similar to [SDL](http://www.libsdl.org/), but takes a more object oriented approach. | You could look at [Glut](http://www.opengl.org/resources/libraries/glut/) (C), [Qt](http://qt.nokia.com/) (C++), [SDL](http://www.libsdl.org/) (C). | C++ OpenGL Window and Context creation framework / library | [
"",
"c++",
"opengl",
"window",
"multiplatform",
""
] |
I'd like to read at most 20 lines from a csv file:
```
rows = [csvreader.next() for i in range(20)]
```
Works fine if the file has 20 or more rows, fails with a StopIteration exception otherwise.
Is there an elegant way to deal with an iterator that could throw a StopIteration exception in a list comprehension or should I use a regular for loop? | You can use [`itertools.islice`](http://docs.python.org/library/itertools.html#itertools.islice). It is the iterator version of list slicing. If the iterator has less than 20 elements, it will return all elements.
```
import itertools
rows = list(itertools.islice(csvreader, 20))
``` | [`itertools.izip`](http://docs.python.org/library/itertools.html#itertools.izip) ([2](http://doc.astro-wise.org/itertools.html#islice)) provides a way to easily make list comprehensions work, but `islice` looks to be the way to go in this case.
```
from itertools import izip
[row for (row,i) in izip(csvreader, range(20))]
``` | Python: StopIteration exception and list comprehensions | [
"",
"python",
"iterator",
"list-comprehension",
"stopiteration",
""
] |
I'm looking for an implementation of java.util.Map that has a method that will return all they keys mapped to a given value, that is, there are multiple keys map to the same value. I've looked at Google Collections and Apache Commons and didn't notice anything. Of course, I could iterate through the keyset and check each corresponding value or use two maps, but I was hoping there was something available already built. | I don't know if that solution is good for you, but you can implement easily that by using a standard map from keys to values and a [MultiMap](http://commons.apache.org/collections/api-3.1/org/apache/commons/collections/MultiMap.html) from values to key.
Of course you'll have to take care of the syncronization of the two structures, IE when you remove a key from the map, you have to remove the key itself from the set of keys mapped to the value in the multimap.
It doesn't seems difficult to implement, maybe a bit heavy from the memory overhead aspect. | What you're looking for here is a [bidirectional map](http://en.wikipedia.org/wiki/Bidirectional_map), for which there is an implementation in [commons collections](http://commons.apache.org/collections/api-3.1/org/apache/commons/collections/BidiMap.html). | Looking for Java Map implementation that supports getKeysForValue | [
"",
"java",
""
] |
I have Android pet-project DroidIn which utilizes HttpClient 4 (built into Android) to do some form based authentication. I started noticing that people who are using WiFi are reporting connection problems. It also doesn't help that site I'm accessing has self-assigned certificate. Well - the question is (I'm quite vague on WiFi details) If WiFi at the hotspot doesn't support HTTPS would that be a good enough reason for connection to fail and is there anything that I can do beside proxying into another appserver using HTTP which then would call HTTPS site? | wifi is just a low level protocol, you are dealing with HTTP & TCP/IP which is unaware of wifi.
So you can ignore the fact that you are using wifi, just try to see if the server is accessible from the client side. (try a telnet on the https port which is 443 by default) | I have the same problem in my Air app. It's called Postal, a mail tracking app for Brazilian service. (I'd appreciate if you try it in wifi and feed me back).
It always works on 2G/3G but rarely works when connected to wi-fi. Everything else works but AIR APPS! Sometimes it works, sometimes it doesnt in the same phone and/or access point. And when it's not working, any other AIR app is not working also.
Even the Tour de Flex Mobile AMF Remoting test app stops working.
Neither HTTPRequests or AMF Remoting works. It just gives Error 404 - Page not found.
It's not a router thing because sometimes it works. I believe it's a problem in AIR when active network adapter changes it keeps trying to go through 2G/3G. It's something Adobe should take a look at. | HTTPS authentication over WiFi using HttpClient 4 | [
"",
"java",
"android",
"ssl",
"https",
"httpclient",
""
] |
My website look and feel is not 100% the same in Internet Explorer 8 as it use to be with Internet Explorer 7. My site is created with VS 2005 and ASP.NET 2.0.
How can I fix this?
Is there a way to fix this?
---
### Edit:
For those who want to see my website, it is [Located Here](http://www.erate.co.za) - Some borders are diff. and the Email/Username text box in the Login Control in WAY at the top and actual Login Control width is less now.
---
### Edit:
Those who view my site from now on will not see what I am talking about from now on since I made some changes to the site and fixed the problems. | Short-term: put [this](http://blogs.msdn.com/ie/archive/2008/06/10/introducing-ie-emulateie7.aspx) in your HTML.
```
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
```
It's a horrid hack and Microsoft should be kicked in the nether regions for it, but it works.
Long-term: fix whatever's breaking to work in IE8. Without seeing the page itself we can't give you all that many suggestions on what specifically to focus on. | Long term answer: you may want to validate the XHTML/HTML output of your site by going to the [W3 Validator](http://validator.w3.org/) website.
As of this writing, your default page has 36 errors and 3 warnings. The validator also provided hints and tips over how to solve the errors. If you're stuck, you can always ask for more information on specific issues here. | Why is Internet Explorer 8 messing up my website look and feel? | [
"",
"c#",
"asp.net",
"vb.net",
"internet-explorer",
""
] |
I have some data in a database that I need represented in an XML file, but the data is different for each request, so the XML file is generated through PHP. For example purposes, let's say this is the text in the db:
`Hello & Goodbye`
I've tried using the following to get the above (set to the `$example` variable) to show up as `Hello & Goodbye` in the generated XML:
`$example = mb_convert_encoding($example, "utf-8", "HTML-ENTITIES" );`
`$example = htmlspecialchars_decode($example);`
`$example = html_entity_decode($example);`
`$example = str_replace("&", "&", $example);`
These lines will replace other entities, like `"`, to their proper characters, but not `&`. Any idea how to get this working correctly? | & is an invalid character in XML, which is never allowed all by itself. Because of that it's likely that whatever XML library you're using is translating it to `&` on the fly. That's the way it should be - otherwise the XML won't be valid. | Your code works to decode the entity, so that isn't the problem.
I'm guessing your XML output library is what's re-escaping the entity. The thing to understand is that this correct behaviour. While quote marks can appear in unescaped form in XML documents (except obviously inside attribute values), ampersands can't be used on there own because in almost all contexts they signify the start of an entity.
Any XML parser reading the output from your code will understand `Hello & Goodbye` in the XML to be a representation of the string value "Hello & Goodbye". | str_replace &: Converting & to its & character in PHP | [
"",
"php",
""
] |
`change()` function works and detects changes on form elements, but is there a way of detecting when a DOM element's content was changed?
This does not work, unless `#content` is a form element
```
$("#content").change( function(){
// do something
});
```
I want this to trigger when doing something like:
```
$("#content").html('something');
```
Also `html()` or `append()` function don't have a callback.
Any suggestions? | These are [mutation events](http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/events.html#Events-MutationEvent).
I have not used mutation event APIs in jQuery, but a cursory search led me to [this project](http://github.com/jollytoad/jquery.mutation-events/tree/master) on GitHub. I am unaware of the project's maturity. | I know this post is a year old, but I'd like to provide a different solution approach to those who have a similar issue:
1. The jQuery change event is used only on user input fields because if anything else is manipulated (e.g., a div), that manipulation is coming from code. So, find where the manipulation occurs, and then add whatever you need to there.
2. But if that's not possible for any reason (you're using a complicated plugin or can't find any "callback" possibilities) then the jQuery approach I'd suggest is:
a. For simple DOM manipulation, use jQuery chaining and traversing, `$("#content").html('something').end().find(whatever)....`
b. If you'd like to do something else, employ jQuery's `bind` with custom event and `triggerHandler`
```
$("#content").html('something').triggerHandler('customAction');
$('#content').unbind().bind('customAction', function(event, data) {
//Custom-action
});
```
Here's a link to jQuery trigger handler: <http://api.jquery.com/triggerHandler/> | Detect element content changes with jQuery | [
"",
"javascript",
"jquery",
"dom",
""
] |
I need to calculate the number of *FULL* month in SQL, i.e.
* 2009-04-16 to 2009-05-15 => 0 full month
* 2009-04-16 to 2009-05-16 => 1 full month
* 2009-04-16 to 2009-06-16 => 2 full months
I tried to use DATEDIFF, i.e.
```
SELECT DATEDIFF(MONTH, '2009-04-16', '2009-05-15')
```
but instead of giving me full months between the two date, it gives me the difference of the month part, i.e.
```
1
```
anyone know how to calculate the number of full months in SQL Server? | The original post had some bugs... so I re-wrote and packaged it as a UDF.
```
CREATE FUNCTION FullMonthsSeparation
(
@DateA DATETIME,
@DateB DATETIME
)
RETURNS INT
AS
BEGIN
DECLARE @Result INT
DECLARE @DateX DATETIME
DECLARE @DateY DATETIME
IF(@DateA < @DateB)
BEGIN
SET @DateX = @DateA
SET @DateY = @DateB
END
ELSE
BEGIN
SET @DateX = @DateB
SET @DateY = @DateA
END
SET @Result = (
SELECT
CASE
WHEN DATEPART(DAY, @DateX) > DATEPART(DAY, @DateY)
THEN DATEDIFF(MONTH, @DateX, @DateY) - 1
ELSE DATEDIFF(MONTH, @DateX, @DateY)
END
)
RETURN @Result
END
GO
SELECT dbo.FullMonthsSeparation('2009-04-16', '2009-05-15') as MonthSep -- =0
SELECT dbo.FullMonthsSeparation('2009-04-16', '2009-05-16') as MonthSep -- =1
SELECT dbo.FullMonthsSeparation('2009-04-16', '2009-06-16') as MonthSep -- =2
``` | ```
select case when DATEPART(D,End_dATE) >=DATEPART(D,sTAR_dATE)
THEN ( case when DATEPART(M,End_dATE) = DATEPART(M,sTAR_dATE) AND DATEPART(YYYY,End_dATE) = DATEPART(YYYY,sTAR_dATE)
THEN 0 ELSE DATEDIFF(M,sTAR_dATE,End_dATE)END )
ELSE DATEDIFF(M,sTAR_dATE,End_dATE)-1 END
``` | Calculating number of full months between two dates in SQL | [
"",
"sql",
"sql-server",
""
] |
Sometimes for testing/developing purposes we make some changes in the code that must be removed in a production build. I wonder if there is an easy way of marking such blocks so that production build would fail as long as they are present or at least it will warn you during the build somehow.
Simple `"//TODO:"` doesn't really work because it is ofter forgotten and mixed with tons of other todos. Is there anything stronger?
Or maybe even if I can create some external txt file and put there instructions on what to do before production, and that ant would check if that file is present then cancel build.
We are using Eclipse/Ant (and java + Spring).
**Update:** I don't mean that there are big chunks of code that are different in local and production. In fact all code is the same and should be the same. Just lets say I comment out some line of code to save lot of time during development and forget to uncomment it or something along those lines. I just want to be able to flag the project somehow that something needs an attention and that production build would fail or show a warning. | You could also just define stronger task comment markers: FIXME (high priority) and XXX (normal priority) are standard in Eclipse, and you could define more task tags (Eclipse Properties -> Java -> Compiler -> Task Tags)
If you want to fail your build, you could use the Ant (1.7) [contains](http://ant.apache.org/manual/Types/selectors.html#containsselect) file selector to look for files containing specified text:
```
<target name="fixmeCheck">
<fail message="Fixmes found">
<condition>
<not>
<resourcecount count="0">
<fileset dir="${pom.build.sourceDirectory}"
includes="**/*.java">
<contains text="FIXME" casesensitive="yes"/>
</fileset>
</resourcecount>
</not>
</condition>
</fail>
</target>
<target name="compile" depends="fixmeCheck">
```
Obviously, change `${pom.build.sourceDirectory}` to your source directory, and `FIXME` to the comment that you want to search for.
Does anyone know a nice way to print out the files found in this fileset in the build file (other than just looking in Eclipse again)? | Avoid the necessity. If you're placing code into a class that shouldn't be there in production, figure out how to do it differently. Provide a hook, say, so that the testing code can do what it needs to, but leave the testing code outside the class. Or subclass for testing, or use Dependency Injection, or any other technique that leaves your code valid and safe for production, while still testable. Many such techniques are well-documented in Michael Feathers' fantastic book, [Working Effectively with Legacy Code](https://rads.stackoverflow.com/amzn/click/com/0131177052). | How to mark some code that must be removed before production? | [
"",
"java",
"eclipse",
"ant",
"todo",
""
] |
```
if (strlen($comment > 2)) {
```
Ok, so I only want to exec this if $comment consist of more than 2 characters
I believe strlen should do this, but it doesn't. Am I using it wrong? | Your closing parenthesis is in the wrong place:
```
if (strlen($comment) > 2) {
}
``` | I don't know php.
But perhaps you should try
```
if (strlen($comment) > 2) {
``` | Min character length, strlen? | [
"",
"php",
"syntax",
""
] |
I have an oddly difficult task to perform. I thought it would be easy, but all my efforts have been fruitless.
I'm converting videos uploaded to a php script from various formats (.avi, .mpg, .wmv, .mov, etc.) to a single .flv format. The conversion is working great but what I'm having trouble with is the resolution of the videos.
This is the command I'm currently running (with PHP vars):
`ffmpeg -i $original -ab 96k -b 700k -ar 44100 -s 640x480 -acodec mp3 $converted`
Both $original and $converted contain the full paths to those files. My problem is that this always converts to 640x480 (like I'm telling it to) even when the source is smaller. Obviously, this is a waste of disk space and bandwidth when the video is downloaded. Also, this doesn't account for input videos being in any aspect ratio other than 4:3, resulting in a "squished" conversion if I upload a 16:9 video.
There are 3 things I need to do:
1. Determine the aspect ratio of the original video.
2. If not 4:3, pad top and bottom with black bars.
3. Convert to 640x480 if either dimension of the original is larger or a 4:3 aspect ratio relating to the width/height of the original (whichever is closer to 640x480).
I've run `ffmpeg -i` on a few videos, but I don't see a consistent format or location to find the original's resolution from. Once I'm able to figure that out, I know I can "do the math" to figure out the right size and specify padding to fix the aspect ratio with -padttop, -padbottom, etc. | This works for me:
```
$data = 'ffmpeg output';
$matches = array();
if (!preg_match('/Stream #(?:[0-9\.]+)(?:.*)\: Video: (?P<videocodec>.*) (?P<width>[0-9]*)x(?P<height>[0-9]*)/',$data,$matches)
preg_match('/Could not find codec parameters \(Video: (?P<videocodec>.*) (?P<width>[0-9]*)x(?P<height>[0-9]*)\)/',$data,$matches)
```
This might not *always* work, but it works most of the times, which was good enough in my case :) | Ok. I have a fully-functional solution. This is for anyone who finds this question wanting to do the same thing. My code may not be very elegant, but it gets the job done.
---
## Getting FFMPEG's output
First I had to get the output from ffmpeg -i, which was a challenge in itself. Thanks to hegemon's answer on [my other question](https://stackoverflow.com/questions/1110655/capture-ffmpeg-output-in-php/1110765#1110765), I was finally able to get it working with `2>&1` at the end of my command. And thanks to Evert's answer to this question, I was able to parse the output with `preg_match` to find the original file's height and width.
```
function get_vid_dim($file)
{
$command = '/usr/bin/ffmpeg -i ' . escapeshellarg($file) . ' 2>&1';
$dimensions = array();
exec($command,$output,$status);
if (!preg_match('/Stream #(?:[0-9\.]+)(?:.*)\: Video: (?P<videocodec>.*) (?P<width>[0-9]*)x(?P<height>[0-9]*)/',implode('\n',$output),$matches))
{
preg_match('/Could not find codec parameters \(Video: (?P<videocodec>.*) (?P<width>[0-9]*)x(?P<height>[0-9]*)\)/',implode('\n',$output),$matches);
}
if(!empty($matches['width']) && !empty($matches['height']))
{
$dimensions['width'] = $matches['width'];
$dimensions['height'] = $matches['height'];
}
return $dimensions;
}
```
---
## Determining the best dimensions
I wrote this function to determine the best dimensions to use for conversion. It takes the original's dimensions, target dimensions, and whether or not to force conversion to the target aspect ratio (determined from its width/height). The target dimensions will always be the largest result this function can return.
```
function get_dimensions($original_width,$original_height,$target_width,$target_height,$force_aspect = true)
{
// Array to be returned by this function
$target = array();
// Target aspect ratio (width / height)
$aspect = $target_width / $target_height;
// Target reciprocal aspect ratio (height / width)
$raspect = $target_height / $target_width;
if($original_width/$original_height !== $aspect)
{
// Aspect ratio is different
if($original_width/$original_height > $aspect)
{
// Width is the greater of the two dimensions relative to the target dimensions
if($original_width < $target_width)
{
// Original video is smaller. Scale down dimensions for conversion
$target_width = $original_width;
$target_height = round($raspect * $target_width);
}
// Calculate height from width
$original_height = round($original_height / $original_width * $target_width);
$original_width = $target_width;
if($force_aspect)
{
// Pad top and bottom
$dif = round(($target_height - $original_height) / 2);
$target['padtop'] = $dif;
$target['padbottom'] = $dif;
}
}
else
{
// Height is the greater of the two dimensions relative to the target dimensions
if($original_height < $target_height)
{
// Original video is smaller. Scale down dimensions for conversion
$target_height = $original_height;
$target_width = round($aspect * $target_height);
}
//Calculate width from height
$original_width = round($original_width / $original_height * $target_height);
$original_height = $target_height;
if($force_aspect)
{
// Pad left and right
$dif = round(($target_width - $original_width) / 2);
$target['padleft'] = $dif;
$target['padright'] = $dif;
}
}
}
else
{
// The aspect ratio is the same
if($original_width !== $target_width)
{
if($original_width < $target_width)
{
// The original video is smaller. Use its resolution for conversion
$target_width = $original_width;
$target_height = $original_height;
}
else
{
// The original video is larger, Use the target dimensions for conversion
$original_width = $target_width;
$original_height = $target_height;
}
}
}
if($force_aspect)
{
// Use the target_ vars because they contain dimensions relative to the target aspect ratio
$target['width'] = $target_width;
$target['height'] = $target_height;
}
else
{
// Use the original_ vars because they contain dimensions relative to the original's aspect ratio
$target['width'] = $original_width;
$target['height'] = $original_height;
}
return $target;
}
```
---
## Usage
Here are a few examples of what you will get from `get_dimensions()` to make things more clear:
```
get_dimensions(480,360,640,480,true);
-returns: Array([width] => 480, [height] => 360)
get_dimensions(480,182,640,480,true);
-returns: Array([padtop] => 89, [padbottom] => 89, [width] => 480, [height] => 360)
get_dimensions(480,182,640,480,false);
-returns: Array([width] => 480, [height] => 182)
get_dimensions(640,480,480,182,true);
-returns: Array([padleft] => 119, [padright] => 119, [width] => 480, [height] => 182)
get_dimensions(720,480,640,480,true);
-returns: Array([padtop] => 27, [padbottom] => 27, [width] => 640, [height] => 480)
get_dimensions(720,480,640,480,false);
-returns: Array([width] => 640, [height] => 427)
```
---
## The Finished Product
Now, to put it all together:
```
$src = '/var/videos/originals/original.mpg';
$original = get_vid_dim($src);
if(!empty($original['width']) && !empty($original['height']))
{
$target = get_dimensions($original['width'],$original['height'],640,480,true);
$command = '/usr/bin/ffmpeg -i ' . $src . ' -ab 96k -b 700k -ar 44100 -s ' . $target['width'] . 'x' . $target['height'];
$command .= (!empty($target['padtop']) ? ' -padtop ' . $target['padtop'] : '');
$command .= (!empty($target['padbottom']) ? ' -padbottom ' . $target['padbottom'] : '');
$command .= (!empty($target['padleft']) ? ' -padleft ' . $target['padleft'] : '');
$command .= (!empty($target['padright']) ? ' -padright ' . $target['padright'] : '');
$command .= ' -acodec mp3 /var/videos/converted/target.flv 2>&1';
exec($command,$output,$status);
if($status == 0)
{
// Success
echo 'Woohoo!';
}
else
{
// Error. $output has the details
echo '<pre>',join('\n',$output),'</pre>';
}
}
``` | PHP and FFMPEG - Performing intelligent video conversion | [
"",
"php",
"ffmpeg",
"video-processing",
""
] |
I have a class that serializes a set of objects (using XML serialization) that I want to unit test.
My problem is it feels like I will be testing the .NET implementation of XML serialization, instead of anything useful. I also have a slight chicken and egg scenario where in order to test the Reader, I will need a file produced by the Writer to do so.
I think the questions (there's 3 but they all relate) I'm ultimately looking for feedback on are:
1. Is it possible to test the Writer, without using the Reader?
2. What is the best strategy for testing the reader (XML file? Mocking with record/playback)? Is it the case that all you will really be doing is testing property values of the objects that have been deserialized?
3. What is the best strategy for testing the writer!
**Background info on Xml serialization**
I'm not using a schema, so all XML elements and attributes match the objects' properties. As there is no schema, tags/attributes which do not match those found in properties of each object, are simply ignored by the XmlSerializer (so the property's value is null or default). Here is an example
```
<MyObject Height="300">
<Name>Bob</Name>
<Age>20</Age>
<MyObject>
```
would map to
```
public class MyObject
{
public string Name { get;set; }
public int Age { get;set; }
[XmlAttribute]
public int Height { get;set; }
}
```
and visa versa. If the object changed to the below the XML would still deserialize succesfully, but FirstName would be blank.
```
public class MyObject
{
public string FirstName { get;set; }
public int Age { get;set; }
[XmlAttribute]
public int Height { get;set; }
}
```
An invalid XML file would deserialize correctly, therefore the unit test would pass unless you ran assertions on the values of the MyObject. | I would argue that it is essential to unit test serialization **if** it is vitally important that you can read data between versions. And you *must* test with "known good" data (i.e. it isn't sufficient to simply write data in the current version and then read it again).
You mention that you don't have a schema... why not generate one? Either by hand (it isn't very hard), or with `xsd.exe`. Then you have something to use as a template, and you can verify this just using `XmlReader`. I'm doing a *lot* of work with xml serialization at the moment, and it is a lot easier to update the schema than it is to worry about whether I'm getting the data right.
Even `XmlSerializer` can get complex; particularly if you involve subclasses (`[XmlInclude]`), custom serialization (`IXmlSerializable`), or non-default `XmlSerializer` construction (passing additional metadata at runtime to the ctor). Another possibility is creative use of `[XmlIngore]`, `[XmlAnyAttribute]` or `[XmlAnyElement]`; for example you might support unexpected data for round-trip (only) in version X, but store it in a known property in version Y.
---
With serialization in general:
The reason is simple: you can break the data! How badly you do this depends on the serializer; for example, with `BinaryFormatter` (and I know the question is `XmlSerializer`), simply changing from:
```
public string Name {get;set;}
```
to
```
private string name;
public string Name {
get {return name;}
set {name = value; OnPropertyChanged("Name"); }
}
```
could be [enough to break serialization](http://marcgravell.blogspot.com/2009/03/obfuscation-serialization-and.html), as the field name has changed (and `BinaryFormatter` loves fields).
There are other occasions when you might accidentally rename the data (even in contract-based serializers such as `XmlSerializer` / `DataContractSerializer`). In such cases you can usually override the wire identifiers (for example `[XmlAttribute("name")]` etc), but it is important to check this!
Ultimately, it comes down to: is it important that you can read old data? It usually is; so don't just ship it... **prove** that you can. | Do you need to be able to do backward compatibility? If so, it may be worth building up unit tests of files produced by old versions which should still be able to be deserialized by new versions.
Other than that, if you ever introduce anything "interesting" it *may* be worth a unit test to just check you can serialize and deserialize just to make sure you're not doing something funky with a readonly property etc. | Is there any point Unit testing serialization? | [
"",
"c#",
"unit-testing",
"serialization",
"xml-serialization",
""
] |
I'm having a bit of trouble with a C# program I'm writing and it'd be great if someone could help.
The background is this, not terribly important, but it's why I need to figure out how to do it:
I'm using a database's Web Services to retrieve information about an entry in the database. Each access to the database returns an Object with many many properties. Using the ID of the database entry, you tell it what information you want filled in about the object it returns by filling an array of which properties to be retrieved. Any property not in the array is left as it's default value (usually null)
The Problem:
I want the user to be able to select a property of an Object (not get the value, just select which property) as below:
```
projectFields[0] = Primavera.Ws.P6.Project.ProjectFieldType.(project_properties.Text);
```
Where project\_properties.Text is a string of the name of the Property I want to set projectFields[0] to.
Can anyone help? Thanks in Advance :)
Edit: Thanks for the answer guys. While they do let me get the value out of Objects Dynamically, that isn't quite what I was looking for... I'm not looking to retrieve a value, I'm only looking to set which Property projectFields[0] is equal too. for example, suppose the user selects Id as the information they want returned about the project. To do that, I'd set:
projectFields[0]=Primavera.Ws.P6.Project.ProjectFieldType.Id;
then I'd make a call to the Database, and I'd get the project Object back, with Id having been filled out for the project while all other properties would be left to their defaults. Basically, if I were to do it the way these examples suggest, I'd have to retrieve every property in the Object first, then access the member the user is interested in which would be slow/inefficent if I can make the way I'm trying to do it work.
I know it's strange how the database is accessed, but I'm using web Services so I don't have the option to change anything about the calls to the database. | You can probably achieve what you want through Reflection ([example](https://stackoverflow.com/questions/798567/property-name-and-need-its-value/)), but I get a distinct feeling that there may be an issue with the design of your system. | C# is a statically typed language. The compiler wants to know you property you mean *at compile time*.
However, you can do this with reflection if you want to. Alternatively, if you know the type of the data in advance, you could use a switch statement. (Example of both approaches coming.)
```
using System;
using System.Reflection;
public class Demo
{
public string Foo { get; set; }
public string Bar { get; set; }
public string Baz { get; set; }
}
public class Test
{
static void Main()
{
Demo demo = new Demo {
Foo = "foo value",
Bar = "bar value",
Baz = "surprise!"
};
ShowProperty(demo, "Foo");
ShowProperty(demo, "Bar");
ShowProperty(demo, "Baz");
ShowDemoProperty(demo, "Foo");
ShowDemoProperty(demo, "Bar");
ShowDemoProperty(demo, "Baz");
}
// Here we don't know the type involved, so we have to use reflection
static void ShowProperty(object x, string propName)
{
PropertyInfo property = x.GetType().GetProperty(propName);
if (property == null)
{
Console.WriteLine("No such property: {0}", propName);
}
else
{
Console.WriteLine("{0}: {1}", propName,
property.GetValue(x, null));
}
}
// Here we *know* it's a Demo
static void ShowDemoProperty(Demo demo, string propName)
{
string value;
// Note that this is very refactoring-unfriendly. Generally icky!
switch (propName)
{
case "Foo": value = demo.Foo; break;
case "Bar": value = demo.Bar; break;
case "Baz": value = demo.Baz; break;
default:
Console.WriteLine("No such property: {0}", propName);
return;
}
Console.WriteLine("{0}: {1}", propName, value);
}
}
```
I agree with the other answers which suggest this probably shows a slightly scary design... | Using strings to select Object Properties | [
"",
"c#",
"oop",
""
] |
I have the following scenario where I want to pass in string and a generic type:
```
public class Worker {
public void DoSomeWork<T>(string value)
where T : struct, IComparable<T>, IEquatable<T> { ... }
}
```
At some point along the way I need to convert the string value to its `T` value. But I don't want to do a straight convert as I need to perform some logic if the string cannot be converted to type `T`.
I was thinking that I could try using `Convert.ChangeType()` but this has the problem that if it doesn't convert it will throw an exception and I will be running the `DoSomeWork()` method often enough to not have to rely on a try/catch to determine whether the convert is valid.
So this got me thinking, I know that I will be working with numeric types, hence T will be any of the following: `int`, `uint`, `short`, `ushort`, `long`, `ulong`, `byte`, `sbyte`, `decimal`, `float`, `double`. Knowing this I thought that it might be possible to come up with a faster solution working with the fact that I know I will be using numeric types (note if `T` isn't a numeric type I throw an exception)...
```
public class NumericWorker {
public void DoSomeWork<T>(string value)
where T : struct, IComparable<T>, IEquatable<T>
{
ParseDelegate<T> tryConverter =
SafeConvert.RetreiveNumericTryParseDelegate<T>();
...
}
}
public class SafeConvert
{
public delegate bool ParseDelegate<T>(string value, out T result);
public static ParseDelegate<T> RetreiveNumericTryParseDelegate<T>()
where T : struct, IComparable<T>, IEquatable<T>
{
ParseDelegate<T> tryParseDelegate = null;
if (typeof(T) == typeof(int))
{
tryParseDelegate = (string v, out T t) =>
{
int typedValue;
bool result = int.TryParse(v, out typedValue);
t = result ? (T)typedValue : default(T);
//(T)Convert.ChangeType(typedValue, typeof(T)) : default(T);
return result;
};
}
else if (typeof(T) == typeof(uint)) { ... }
else if (typeof(T) == typeof(short)) { ... }
else if (typeof(T) == typeof(ushort)) { ... }
else if (typeof(T) == typeof(long)) { ... }
else if (typeof(T) == typeof(ulong)) { ... }
else if (typeof(T) == typeof(byte)) { ... }
else if (typeof(T) == typeof(sbyte)) { ... }
else if (typeof(T) == typeof(decimal)) { ... }
else if (typeof(T) == typeof(float)) { ... }
else if (typeof(T) == typeof(double)) { ... }
return tryParseDelegate;
}
}
```
But the above has the problem that I can't write `t = result ? (T)typedValue : default(T);` as the casting of `typedValue` to `T` causes issues and the only way I have been able to get around it thus far is by writing `(T)Convert.ChangeType(typedValue, typeof(T))`. But if I do this I am just doing another convert.
Hence I was wondering if anyone knows how I could fix this problem (if you think doing the `ChangeType()` is a problem) or if there is a better solution altogether that I haven't considered. | > t = result ? (T)typedValue : default(T);
Try:
```
t = result ? (T)(object)typedValue : default(T);
```
Yes, generics can be kinda annoying at times.
FWIW, I use [a much simpler wrapper](https://stackoverflow.com/questions/170665/helper-functions-for-safe-conversion-from-strings/170731#170731) around `Convert.ChangeType()` that just does a pre-check for empty strings. Unless you're using this for un-checked user input, that'll probably be enough. | Given this:
> hence T will be any of the following: int, uint, short, ushort, long, ulong, byte, sbyte, decimal, float, double.
I would recommend just using Convert.ChangeType, and not worrying about it. The only time you'll get an exception is when your string is misformatted, in which case, you can return default(T).
ie:
```
try
{
result = Convert.ChangeType(value, typeof(T));
}
catch
{
result = default(T);
}
``` | How can I convert to a specific type in a generic version of TryParse()? | [
"",
"c#",
".net",
"generics",
"casting",
""
] |
i have a SQL server database on a server. I have just recently been playing around with asp.net mvc and i am using the membership login control. i see that it creates a default local database called aspnetdb.mdf with teh following tables:
aspnet\_Applications
aspnet\_membership
aspnet\_paths
aspnet\_profiles
aspnet\_users
aspnet\_usersinRoles
. . .
. . .
all in all its about 15 tables.
My question is i am trying to figure out if there is anyway to export these tables and upload them into my SQL Server database that is on the server.
any suggestions ? | Google the Database Publishing Wizard by microsoft.
It will script all your tables, procs and data that you can then import into your SQL Database. | I have recently performed the same thing and there are a few solutions that I have used:
Set up SQL Server as the SQL Membership Provider with the utility ASPNet\_regsql.exe in C:\Windows\Microsoft.net\Framwork\2.0. There is a detailed video describing exactly what you need @ <http://www.asp.net/learn/videos/video-148.aspx> and a detailed article @ asp.net/learn/security/tutorial-04-cs.aspx -- I can only post one hyperlink.
Now the issue of you having built a huge app on the SQL express server. I would re-enter the users into sql server and away you go. If you start transferring the data, you need to make sure the applicationID is the same. This situation is described in the second link above.
If you are pushing these to a hosting site, you may also look into the "Database Publishing Service" a free download @ micosoft. The ins and outs are explained here: asp.net/learn/hosting/tutorial-07-cs.aspx. | trying to export tables from aspnetdb.mdf into another sql server | [
"",
"sql",
"sql-server",
"asp.net-mvc",
""
] |
I've set
```
m_lpD3DDevice->SetRenderTarget(0,Buffer1);
m_lpD3DDevice->SetRenderTarget(1,Buffer2);
m_lpD3DDevice->SetRenderTarget(2,Buffer2);
```
and if I render the pixelshader only affects the first render target.
It's output structure is
```
struct PS_OUTPUT
{
float4 Color0 : COLOR0;
float4 Color1 : COLOR1;
float4 Color2 : COLOR2;
};
```
what do I need to do to affect the other two render targets too? | I finally have the answer now.
All I had to do was to set
```
ColorWriteEnable = red | green | blue;
```
in the effect file. Everything else was correct.
But I don't know why this made it work. | In your pixel shader, make sure you're returning the struct not a float4. Also don't beind the semantion COLOR0 to the function signature, that is don't do this:
```
PS_OUTPUT myPS(VS_OUTPUT): COLOR0
```
I duobt that will copmpile, but it might confuse the compiler. A simple MRT shader looks like this:
```
PS_OUTPUT myPS(VS_OUTPUT)
{
PS_OUTPUT out;
out.color0 = float4(0.5,0.5,0.5,1.0);
out.color1 = float4(0.2,0.5,0.8,1.0);
out.color2 = float4(0.8,0.5,0.2,1.0);
return out;
}
```
What are buffer0,1 & 2? Are they the result of a call to CreateTexture()? (or rather a surface from that texture). If they are, make sure the texture was created with the render target usage flag: D3DUSAGE\_RENDERTARGET.
Make sure your card can support rendering to more than one RT. (forgotten how to do this - but I doubt that it won't support them.)
If you've created the buffers correctly, set them correctly, and are writing the correct values out of the pixel shader correctly, then I don't see what could go wrong. What does PIX\* say about the MRTS? Are they benig written to, and it';s the displaying of them that's going wrong?
ps: You hopefully made a draw call, right? :)
\*PIX is an application in the DirectX SDK. If you've not used it before, you're really missing out :) | Multiple Rendertargets in DX9 | [
"",
"c++",
"directx",
"hlsl",
""
] |
How do I profile a MySQL database. I want to see all the SQL being run against a database.
I know you can do this:
* `set profiling=1;`
* Run your slow query (eg `SELECT * FROM messages WHERE fromaddress='xxx';`
* `SHOW PROFILES;`
But this seem to only apply to stuff run on the command line, I want to see the results from running a website. | You want the [query log](http://dev.mysql.com/doc/refman/5.1/en/query-log.html) - but obviously doing this on a heavy production server could be... unwise. | That worked for me on Ubuntu.
Find and open your MySQL configuration file, usually `/etc/mysql/my.cnf` on Ubuntu. Look for the section that says “Logging and Replication”
```
# * Logging and Replication
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
log = /var/log/mysql/mysql.log
```
or in newer versions of mysql, comment OUT this lines of codes
```
general_log_file = /var/log/mysql/mysql.log
general_log = 1
log_error = /var/log/mysql/error.log
```
Just uncomment the `log` variable to turn on logging. Restart MySQL with this command:
```
sudo /etc/init.d/mysql restart
```
Now we’re ready to start monitoring the queries as they come in. Open up a new terminal and run this command to scroll the log file, adjusting the path if necessary.
```
tail -f /var/log/mysql/mysql.log
``` | How to profile MySQL | [
"",
"mysql",
"sql",
"profiling",
"database-tuning",
""
] |
I have a QuerySet, let's call it `qs`, which is ordered by some attribute which is irrelevant to this problem. Then I have an object, let's call it `obj`. Now I'd like to know at what index `obj` has in `qs`, as *efficiently* as possible. I know that I could use `.index()` from Python or possibly loop through `qs` comparing each object to `obj`, but what is the best way to go about doing this? I'm looking for high performance and that's my only criteria.
Using Python 2.6.2 with Django 1.0.2 on Windows. | QuerySets in Django are actually generators, not lists (for further details, see [Django documentation on QuerySets](http://docs.djangoproject.com/en/dev/ref/models/querysets/#ref-models-querysets)).
As such, there is no shortcut to get the index of an element, and I think a plain iteration is the best way to do it.
For starter, I would implement your requirement in the simplest way possible (like iterating); if you really have performance issues, then I would use some different approach, like building a queryset with a smaller amount of fields, or whatever.
In any case, the idea is to leave such tricks as late as possible, when you definitely knows you need them.
**Update:** You may want to use directly some SQL statement to get the rownumber (something lie . However, Django's ORM does not support this natively and you have to use a raw SQL query (see [documentation](http://docs.djangoproject.com/en/dev/topics/db/sql/#topics-db-sql)). I think this could be the best option, but again - only if you really see a real performance issue. | If you're already iterating over the queryset and just want to know the index of the element you're currently on, the compact and probably the most efficient solution is:
```
for index, item in enumerate(your_queryset):
...
```
However, don't use this if you have a queryset and an object obtained by some unrelated means, and want to learn the position of this object in the queryset (if it's even there). | Get the index of an element in a queryset | [
"",
"python",
"django",
"indexing",
"django-queryset",
""
] |
In this code:
```
<?php
class Foo
{
var $value;
function foo($value)
{
$this->setValue($value);
}
function setValue($value)
{
$this->value=$value;
}
}
class Bar
{
var $foos=array();
function Bar()
{
for ($x=1; $x<=10; $x++)
{
$this->foos[$x]=new Foo("Foo # $x");
}
}
function getFoo($index)
{
return $this->foos[$index];
}
function test()
{
$testFoo=$this->getFoo(5);
$testFoo->setValue("My value has now changed");
}
}
?>
```
When the method `Bar::test()` is run and it changes the value of foo # 5 in the array of foo objects, will the actual foo # 5 in the array be affected, or will the `$testFoo` variable be only a local variable which would cease to exist at the end of the function? | Why not run the function and find out?
```
$b = new Bar;
echo $b->getFoo(5)->value;
$b->test();
echo $b->getFoo(5)->value;
```
For me the above code (along with your code) produced this output:
```
Foo #5
My value has now changed
```
This isn't due to "passing by reference", however, it is due to "assignment by reference". In PHP 5 assignment by reference is the default behaviour with objects. If you want to assign by value instead, use the [clone](https://www.php.net/manual/en/language.oop5.cloning.php) keyword. | You can refer to <https://www.php.net/manual/en/language.oop5.references.php> for the actual answer to your question.
> One of the key-points of PHP5 OOP that is often mentioned is that "objects are passed by references by default". This is not completely true.
>
> A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object. | Are objects in PHP assigned by value or reference? | [
"",
"php",
"oop",
""
] |
I am currently testing out using OSGi. I am running this through Eclipse. I want to have my DAO layer as part of an OSGi solution, but my first stumbling block is this error:
```
Jun 29, 2009 6:12:37 PM org.hibernate.cfg.annotations.Version <clinit>
INFO: Hibernate Annotations 3.3.0.GA
Jun 29, 2009 6:12:37 PM org.hibernate.ejb.Version <clinit>
INFO: Hibernate EntityManager 3.3.0.GA
Jun 29, 2009 6:12:37 PM org.hibernate.ejb.Ejb3Configuration configure
INFO: Could not find any META-INF/persistence.xml file in the classpath
```
I have tried putting the persistence.xml file in a lot of different places, to no avail. **Any ideas on what I am doing wrong?**
**Is there a way to manually load the persistence.xml?**
The **activator** looks like this:
```
package com.activator;
public class PersistenceActivator implements BundleActivator {
@Override
public void start(BundleContext arg0) throws Exception {
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("postgres");
EntityManager em = emf.createEntityManager();
SimpleDaoImpl dao = new SimpleDaoImpl();
dao.setEntityManager(em);
}
@Override
public void stop(BundleContext arg0) throws Exception {
// TODO Auto-generated method stub
}
}
```
Here is what my directory structure looks like:
[alt text http://www.freeimagehosting.net/uploads/7b7b7d2d30.jpg](http://www.freeimagehosting.net/uploads/7b7b7d2d30.jpg)
Here is my **Manifest.MF**
```
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Dao Plug-in
Bundle-SymbolicName: Dao
Bundle-Version: 1.0.0
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Import-Package: org.osgi.framework;version="1.4.0"
Bundle-Activator: com.activator.PersistenceActivator
Export-Package: com.dao.service
Require-Bundle: HibernateBundle;bundle-version="1.0.0"
```
**HibernateBundle** contains all of the Hibernate and Persistence Jars.
Here is my **Persistence.xml**
```
<?xml version="1.0" encoding="UTF-8"?>
<persistence>
<!-- Sample persistence using PostgreSQL. See postgres.txt. -->
<persistence-unit name="postgres" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.archive.autodetection" value="class" />
<!--
Comment out if schema exists & you don't want the tables dropped.
-->
<property name="hibernate.hbm2ddl.auto" value="create-drop" /> <!-- drop/create tables @startup, drop tables @shutdown -->
<!-- Database Connection Settings -->
<property name="hibernate.connection.autocommit">true</property>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="hibernate.connection.username" value="postgres" />
<property name="hibernate.connection.password" value="postgres" />
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/test" />
<!-- Not sure about these... -->
<property name="hibernate.max_fetch_depth">16</property>
<property name="hibernate.jdbc.batch_size">1000</property>
<property name="hibernate.use_outer_join">true</property>
<property name="hibernate.default_batch_fetch_size">500</property>
<!-- Hibernate Query Language (HQL) parser. -->
<property name="hibernate.query.factory_class">
org.hibernate.hql.ast.ASTQueryTranslatorFactory</property>
<!-- Echo all executed SQL to stdout -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">false</property>
<!-- Use c3p0 for the JDBC connection pool -->
<property name="hibernate.c3p0.min_size">3</property>
<property name="hibernate.c3p0.max_size">100</property>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider" />
</properties>
</persistence-unit>
</persistence>
```
Things I have tried in the Manifest's Classpath with no luck:
**Bundle-ClassPath: ., META-INF/persistence.xml**
**Bundle-ClassPath: ., ../META-INF/persistence.xml**
**Bundle-ClassPath: ., /META-INF/persistence.xml**
**Bundle-ClassPath: ., ./META-INF/persistence.xml**
**Bundle-ClassPath: ., META-INF**
**Bundle-ClassPath: ., ../META-INF**
**Bundle-ClassPath: ., /META-INF**
**Bundle-ClassPath: ., ./META-INF**
**Bundle-ClassPath: ., C:\Workspaces\OSGiJPA\Dao\META-INF\persistence.xml**
**Bundle-ClassPath: ., C:\Workspaces\OSGiJPA\Dao\META-INF** | I am not using persistence.xml but hibernate.cfg.xml which is similar:
```
src/main/resource/hibernate/hibernate.cfg.xml
```
In my Activator I am getting the file via the bundle context:
Here is some example code how I do it and also reference that file:>
```
private void initHibernate(BundleContext context) {
try {
final AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg.configure(context.getBundle().getEntry("/src/main/resource/hibernate/hibernate.cfg.xml"));
sessionFactory = cfg.buildSessionFactory();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
```
As you can see line which gets the config file is:
```
context.getBundle().getEntry("/src/main/resource/hibernate/hibernate.cfg.xml")
```
As you can see my hibernate.cfg.xml is NOT inside the META-INF folder. It is just in the root folder under /src/......
Hope that helps.
Christoph | Use [EclipseLink](http://www.eclipse.org/eclipselink/) and forget about Hibernate and other implementations, because :
* You'll have to play with the classloader too much...
*Thread.currentThread().setContextClassLoader*(...)
* You'll be tempted to set the bundle-classpath attribute and add dependencies manually instead of installing jar bundles.
* You'll get *provider not found* errors or you might not be able to find *persistence.xml*
All the above efforts might not work after many attempts.
However, with EclipseLink it's a no brainer, the implementation was designed to work out of the box in an OSGI environment and there aren't any class loading headaches. | Persistence.xml and OSGi (Equinox) | [
"",
"java",
"jpa",
"jakarta-ee",
"osgi",
"equinox",
""
] |
```
public class Options
{
public FolderOption FolderOption { set; get; }
public Options()
{
FolderOption = new FolderOption();
}
public void Save()
{
XmlSerializer serializer = new XmlSerializer(typeof(Options));
TextWriter textWriter = new StreamWriter(@"C:\Options.xml");
serializer.Serialize(textWriter, this);
textWriter.Close();
}
public void Read()
{
XmlSerializer deserializer = new XmlSerializer(typeof(Options));
TextReader textReader = new StreamReader(@"C:\Options.xml");
//this = (Options)deserializer.Deserialize(textReader);
textReader.Close();
}
}
}
```
I managed to Save without problem, all members of FolderOption are deserialized. But the problem is how to read it back? The line - //this = (Options)deserializer.Deserialize(textReader); won't work.
Edit: Any solution to this problem? Can we achieve the same purpose without assigning to this? That is deserialize Options object back into Option. I am lazy to do it property by property. Performing on the highest level would save of lot of effort. | This will work if your Options type is a struct, as you can a alter a struct itself.
If Options is a class (reference type), you can't assign to the current instance of a reference type with in that instance. Suggesting you to write a helper class, and put your Read and Save methods there, like this
```
public class XmlSerializerHelper<T>
{
public Type _type;
public XmlSerializerHelper()
{
_type = typeof(T);
}
public void Save(string path, object obj)
{
using (TextWriter textWriter = new StreamWriter(path))
{
XmlSerializer serializer = new XmlSerializer(_type);
serializer.Serialize(textWriter, obj);
}
}
public T Read(string path)
{
T result;
using (TextReader textReader = new StreamReader(path))
{
XmlSerializer deserializer = new XmlSerializer(_type);
result = (T)deserializer.Deserialize(textReader);
}
return result;
}
}
```
And then consume it from your caller, to read and save objects, instead of trying it from the class.
```
//In the caller
var helper=new XmlSerializerHelper<Options>();
var obj=new Options();
//Write and read
helper.Save("yourpath",obj);
obj=helper.Read("yourpath");
```
And put the XmlSerializerHelper in your Util's namespace, it is reusable and will work with any type. | Build your `.Read()` method as a static function that returns the read object:
```
public static Options Read(string path)
{
XmlSerializer deserializer = new XmlSerializer(typeof(Options));
using (TextReader textReader = new StreamReader(path))
{
return (Options)deserializer.Deserialize(textReader);
}
}
```
Then change your calling code so rather than something like this:
```
Options myOptions = new Options();
myOptions.Read(@"C:\Options.xml");
```
You do something like this:
```
Options myOptions = Options.Read(@"C:\Options.xml");
```
The nice difference is that it's impossible to ever have an Options object that doesn't have some data behind it. | C# - How to xml deserialize object itself? | [
"",
"c#",
"serialization",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.