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 post the below xml to <https://apps.quickbooks.com/j/AppGateway> and all I keep getting is the error: The remote server returned an error: (400) Bad Request. Does anyone have any ideas what I am doing wrong? See below for the C# code that I am using to post the xml. Thanks, -Jeff UPDATE: To add more to my question, I am thinking that the (400) Bad Request error is indicating that I have something grossly wrong with the xml or with the way I am posting the xml. So that is why I am asking this question... what am I missing here? ``` <?xml version="1.0" encoding="utf-8" ?> <?qbxml version="7.0"?> <QBXML> <SignonMsgsRq> <SignonDesktopRq> <ClientDateTime>7/20/2009 12:36PM</ClientDateTime> <ApplicationLogin>APP_LOGIN</ApplicationLogin> <ConnectionTicket>CONNECTION_TICKET</ConnectionTicket> <Language>English</Language> <AppID>APP_ID</AppID> <AppVer>1</AppVer> </SignonDesktopRq> </SignonMsgsRq> <QBXMLMsgsRq> <CustomerQueryRq requestID="2" /> </QBXMLMsgsRq> </QBXML> WebRequestObject = (HttpWebRequest)WebRequest.Create(requestUrl); WebRequestObject.Method = "POST"; WebRequestObject.ContentType = "application/x-qbxml"; WebRequestObject.AllowAutoRedirect = false; string post = XmlText.Text; WebRequestObject.ContentLength = post.Length; swr = new StreamWriter(WebRequestObject.GetRequestStream()); swr.Write(post); swr.Close(); WebResponseObject = (HttpWebResponse)WebRequestObject.GetResponse(); ```
As [Keith Palmer](https://stackoverflow.com/users/26133/keith-palmer) [mentioned in his answer](https://stackoverflow.com/questions/1154880/valid-xml-for-posting-to-quickbooks-online-edition-receiving-400-bad-request/1158910#1158910) the version number needs to be 6.0 but also need to include the onError attribute of the QBXMLMsgsRq tag. (I also corrected the time format too as recommend by [Keith Palmer](https://stackoverflow.com/users/26133/keith-palmer).) Complete/working xml is here: ``` <?xml version="1.0" encoding="utf-8" ?> <?qbxml version="6.0"?> <QBXML> <SignonMsgsRq> <SignonDesktopRq> <ClientDateTime>2009-07-21T10:10:00</ClientDateTime> <ApplicationLogin>APPLICATION_LOGIN</ApplicationLogin> <ConnectionTicket>CONNECTION_TICKET</ConnectionTicket> <Language>English</Language> <AppID>APP_ID</AppID> <AppVer>1</AppVer> </SignonDesktopRq> </SignonMsgsRq> <QBXMLMsgsRq onError="continueOnError"> <CustomerQueryRq requestID="2" /> </QBXMLMsgsRq> </QBXML> ```
Change your qbXML version to 6.0, QuickBooks Online Edition doesn't support 7.0 yet.
Valid XML for posting to QuickBooks Online Edition - Receiving (400) Bad Request Error
[ "", "c#", "quickbooks", "quickbooks-online", "" ]
Hacking on a Nvelocity C#/.NET view template (.cs file), I'm really missing the Python keyword "in" (as in, "foo in list"). What is the built-in for checking list/array membership? This is what my Python brain wants to do: ``` #set ( $ignore = ['a','b','c'] ) <ul> #foreach ( $f in $blah ) #if ( $f not in $ignore ) <li> $f </li> #end #end </ul> ``` But I am not sure what the right syntax is, if there is indeed any. I had a quick look at the [Velocity Template Guide](http://velocity.apache.org/engine/releases/velocity-1.5/user-guide.html) but didn't spot anything useful.
"Contains" is indeed what I was looking for. ...And in NVelocity template-speak: ``` #set( $ignorefeatures = ["a", "b"] ) #foreach( $f in $blah ) #if ( !$ignorefeatures.Contains($f.Key) ) <tr><td> $f.Key </td><td> $f.Value </td></tr> #end #end ```
You can use the Contains function in List, so it should be ``` List<int> list = new List<int>{1, 2, 3, 4, 5, 6, 7}; foreach(var f in blah) if(list.Contains(f)) ```
What's the nvelocity/C# equivalent of "if x in array"?
[ "", "c#", ".net", "nvelocity", "" ]
My question is almost exactly the same as [this post](https://stackoverflow.com/questions/623968/group-by-and-displaying-entries-under-date), except that I'm using Python and Django instead of PHP. The task is to take: ``` id date 1 2009-01-01 10:15:23 2 2009-01-01 13:21:29 3 2009-01-02 01:03:13 4 2009-01-03 12:20:19 5 2009-01-03 13:01:06 ``` And output: ``` 2009-01-01 1 2 2009-01-02 3 2009-01-03 4 5 ``` I can manually hack something together by looping through the sorted dates and outputting HTML into a string in my python view file, but I'm wondering: is there's a better way using a Django template or a nifty Python feature?
You can solve this with the *regroup* and *date* templatetags. ``` {% regroup object_list by start_date|date:"Y-m-d" as objects_by_day %} {% for d in objects_by_day %} ### DO SOMETHING HERE {% endfor %} ```
[`itertools.groupby`](http://docs.python.org/library/itertools.html#itertools.groupby) is your dear, dear friend: ``` import itertools dates = [ (1,'2009-01-01 10:15:23'), (2,'2009-01-01 13:21:29'), (3,'2009-01-02 01:03:13'), (4,'2009-01-03 12:20:19'), (5,'2009-01-03 13:01:06'), ] for key,group in itertools.groupby(dates, key=lambda x: x[1][:11]): print key for element in group: print ' ', element ``` The above code prints the following: ``` 2009-01-01 (1, '2009-01-01 10:15:23') (2, '2009-01-01 13:21:29') 2009-01-02 (3, '2009-01-02 01:03:13') 2009-01-03 (4, '2009-01-03 12:20:19') (5, '2009-01-03 13:01:06') ```
Grouping dates in Django
[ "", "python", "django", "django-forms", "" ]
Is there a way to create an uncompressed ZIP (level 0) from PHP? I can't find any info in the php documentation.
If the zip tool is installed on your server, you can always use the `shell_exec()` function to execute an external command. That way you can most likely create an uncompressed zip file.
According to php.net’s bugtracker (and [bug #41243](http://bugs.php.net/bug.php?id=41243)) this functionality is not available in the built-in zip utilities. For now you have to shell out.
Is there a way to create an uncompressed zip from PHP?
[ "", "php", "compression", "zip", "" ]
in the following indexer code block, why do we need: ``` public string this[int pos] { get { return myData[pos]; } set { myData[pos] = value; } } ``` what exactly does "this" in this[int pos] do? Thanks ``` /// Indexer Code Block starts here using System; /// <summary> /// A simple indexer example. /// </summary> class IntIndexer { private string[] myData; public IntIndexer(int size) { myData = new string[size]; for (int i = 0; i < size; i++) { myData[i] = "empty"; } } public string this[int pos] { get { return myData[pos]; } set { myData[pos] = value; } } static void Main(string[] args) { int size = 10; IntIndexer myInd = new IntIndexer(size); myInd[9] = "Some Value"; myInd[3] = "Another Value"; myInd[5] = "Any Value"; Console.WriteLine("\nIndexer Output\n"); for (int i = 0; i < size; i++) { Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]); } } } ```
**From a c# syntax perspective:** You need `this` because - how else would you declare it? Functionality on a class must have a name, or address, by which to reference it. A method signature is: ``` [modifiers] [type] [name] (parameters) public string GetString (Type myparam); ``` A property signature is: ``` [modifiers] [type] [name] public string MyString ``` A field signature is: ``` [modifiers] [type] [name] public string MyString ``` Since an indexer has no name, it would not make much sense to write: ``` public string [int pos] ``` So we use `this` to denote it's "name".
It means that you can use the indexer on the object itself (like an array). ``` class Foo { public string this[int i] { get { return someData[i]; } set { someData i = value; } } } // ... later in code Foo f = new Foo( ); string s = f[0]; ```
question on a simple indexer (c#)
[ "", "c#", ".net", "" ]
> **Possible Duplicate:** > [Calculate years from date](https://stackoverflow.com/questions/1112835/calculate-years-from-date) Hi, I have a table with a field representing the birthday. How do I find the age of the person from that date? This is what I have. ``` $qPersoonsgegevens = "SELECT * FROM alg_persoonsgegevens WHERE alg_persoonsgegevens_leerling_ID = $leerling_id"; $rPersoonsgegevens = mysql_query($qPersoonsgegevens); $aPersoonsgegevens = mysql_fetch_assoc( $rPersoonsgegevens ); $timeBirthdate = mktime($aPersoonsgegevens['alg_persoonsgegevens_geboortedatum']); ``` Unfortunately, I don't know how to proceed from that point to get the age. Any help is much appreciated. Matthy
[This has been asked before.](https://stackoverflow.com/questions/1112835/calculate-years-from-date) Try this: ``` function getAge($then) { $then = date('Ymd', strtotime($then)); $diff = date('Ymd') - $then; return substr($diff, 0, -4); } ``` Call it like so: ``` $age = getAge($aPersoonsgegevens['alg_persoonsgegevens_geboortedatum']); ```
### Birthdays and Ages are Culturally Dependent It may be useful to remember that some cultures start counting your age from conception or start counting at 1 year old at the time of birth. In particular, you will need to be careful of the Korean market when doing age calculation. I doubt that the author of the question needs this information, but I just wanted to shout it out since it might be useful to a programmer somewhere and at sometime.
How do I easily determine the age from an birthday? (php)
[ "", "php", "mysql", "date", "" ]
i have added this code ``` iTunes.OnPlayerPlayingTrackChangedEvent += new _IiTunesEvents_OnPlayerPlayingTrackChangedEventEventHandler(iTunes_OnPlayerPlayingTrackChangedEvent); ``` and this code ``` private void iTunes_OnPlayerPlayingTrackChangedEvent(object iTrack) { if (iTunes.CurrentTrack != null) { if (iTunes.CurrentTrack.Artist != null & iTunes.CurrentTrack.Album != null & iTunes.CurrentTrack.Name != null) { artist = iTunes.CurrentTrack.Artist; album = iTunes.CurrentTrack.Album; title = iTunes.CurrentTrack.Name; if (!NowPlaying.IsBusy) { NowPlaying.RunWorkerAsync(); } } } } ``` to my app thats programmed in c# but its not catching when the song changes. Am i Missing Something? is there any other way to catch iTunes track changed event?
I figured out a way to make it work. First of all I added a timer Then every 1 second it checks ``` try { if (iTunes.CurrentTrack.Artist != artist | iTunes.CurrentTrack.Album != album | iTunes.CurrentTrack.Name != title) { //Code to update UI here } } catch { //Nothing Here! this is just so your the app doesn't blow up if iTunes is busy. instead it will just try again in 1 second } ``` that's it :)
You're actually subscribing to the wrong event to capture this info. Here is a code snippet that will give you what you want: ``` iTunesApp app = new iTunesApp(); public Form1() { InitializeComponent(); app.OnPlayerPlayEvent += new _IiTunesEvents_OnPlayerPlayEventEventHandler(app_OnPlayerPlayEvent); } public void app_OnPlayerPlayEvent(object iTrack) { IITTrack currentTrack = (IITTrack)iTrack; string trackName = currentTrack.Name; string artist = currentTrack.Artist; string album = currentTrack.Album; } ```
how do i catch itunes events?
[ "", "c#", "events", "com", "itunes-sdk", "" ]
I have a JavaScript object that looks like the following: ``` venue = function(map, dataSet) { // set some constants this.VENUE_ID = 0; this.VENUE_NAME = 1; this.VENUE_CITY = 2; this.filterBy = function(field, value) { ... var filterValue = 'parent.VENUE_' + field; } } ``` Now, the problem is that I need the value of `filterValue` to contain the value of the constant on the parent object. Currently I have tried using the method shown above and then referencing the filterValue when trying to access the array item, but this simply returns undefined. How do I convert the `filterValue` variable into the value of the constant it represents?
This has nothing to do with the variable scope. ``` var filterValue = this['VENUE_' + field]; ``` would do.
JavaScript has no concept of 'parent'. And I think you're confusing scope and context. If that method was written as var filterBy() you'd have to access it in a different 'scope'. But by using 'this' you kept in in the same object as it was written. So everything you wrote is in 'this' context.
JavaScript: Convert string to value of predefined variable
[ "", "javascript", "scope", "javascript-objects", "" ]
I'm trying to run over the parameters space of a six-parameter function to study its numerical behavior before trying to do anything complex with it, so I'm searching for an efficient way to do this. My function takes float values given in a 6-dim NumPy array as input. What I tried to do initially was this: First, I created a function that takes two arrays and generate an array with all combinations of values from the two arrays: ``` from numpy import * def comb(a, b): c = [] for i in a: for j in b: c.append(r_[i,j]) return c ``` Then, I used `reduce()` to apply that to m copies of the same array: ``` def combs(a, m): return reduce(comb, [a]*m) ``` Finally, I evaluate my function like this: ``` values = combs(np.arange(0, 1, 0.1), 6) for val in values: print F(val) ``` This works, but it's *way* too slow. I know the space of parameters is huge, but this shouldn't be so slow. I have only sampled 106 (a million) points in this example and it took more than 15 seconds just to create the array `values`. Is there a more efficient way of doing this with NumPy? I can modify the way the function `F` takes its arguments if it's necessary.
In newer versions of NumPy (>1.8.x), [`numpy.meshgrid()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html) provides a much faster implementation: For [pv's solution](https://stackoverflow.com/questions/1208118/using-numpy-to-build-an-array-of-all-combinations-of-two-arrays/1235363#1235363): ``` In [113]: %timeit cartesian(([1, 2, 3], [4, 5], [6, 7])) 10000 loops, best of 3: 135 µs per loop In [114]: cartesian(([1, 2, 3], [4, 5], [6, 7])) Out[114]: array([[1, 4, 6], [1, 4, 7], [1, 5, 6], [1, 5, 7], [2, 4, 6], [2, 4, 7], [2, 5, 6], [2, 5, 7], [3, 4, 6], [3, 4, 7], [3, 5, 6], [3, 5, 7]]) ``` [`numpy.meshgrid()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html) used to be two-dimensional only, but now it is capable of being multidimensional. In this case, three-dimensional: ``` In [115]: %timeit np.array(np.meshgrid([1, 2, 3], [4, 5], [6, 7])).T.reshape(-1,3) 10000 loops, best of 3: 74.1 µs per loop In [116]: np.array(np.meshgrid([1, 2, 3], [4, 5], [6, 7])).T.reshape(-1,3) Out[116]: array([[1, 4, 6], [1, 5, 6], [2, 4, 6], [2, 5, 6], [3, 4, 6], [3, 5, 6], [1, 4, 7], [1, 5, 7], [2, 4, 7], [2, 5, 7], [3, 4, 7], [3, 5, 7]]) ``` Note that the order of the final result is slightly different.
Here's a pure-NumPy implementation. It's about 5 times faster than using [itertools](https://docs.python.org/3/library/itertools.html). ## Python 3: ``` import numpy as np def cartesian(arrays, out=None): """ Generate a Cartesian product of input arrays. Parameters ---------- arrays : list of array-like 1-D arrays to form the Cartesian product of. out : ndarray Array to place the Cartesian product in. Returns ------- out : ndarray 2-D array of shape (M, len(arrays)) containing Cartesian products formed of input arrays. Examples -------- >>> cartesian(([1, 2, 3], [4, 5], [6, 7])) array([[1, 4, 6], [1, 4, 7], [1, 5, 6], [1, 5, 7], [2, 4, 6], [2, 4, 7], [2, 5, 6], [2, 5, 7], [3, 4, 6], [3, 4, 7], [3, 5, 6], [3, 5, 7]]) """ arrays = [np.asarray(x) for x in arrays] dtype = arrays[0].dtype n = np.prod([x.size for x in arrays]) if out is None: out = np.zeros([n, len(arrays)], dtype=dtype) #m = n / arrays[0].size m = int(n / arrays[0].size) out[:,0] = np.repeat(arrays[0], m) if arrays[1:]: cartesian(arrays[1:], out=out[0:m, 1:]) for j in range(1, arrays[0].size): #for j in xrange(1, arrays[0].size): out[j*m:(j+1)*m, 1:] = out[0:m, 1:] return out ``` ## Python 2: ``` import numpy as np def cartesian(arrays, out=None): arrays = [np.asarray(x) for x in arrays] dtype = arrays[0].dtype n = np.prod([x.size for x in arrays]) if out is None: out = np.zeros([n, len(arrays)], dtype=dtype) m = n / arrays[0].size out[:,0] = np.repeat(arrays[0], m) if arrays[1:]: cartesian(arrays[1:], out=out[0:m, 1:]) for j in xrange(1, arrays[0].size): out[j*m:(j+1)*m, 1:] = out[0:m, 1:] return out ```
Using NumPy to build an array of all combinations of two arrays
[ "", "python", "arrays", "numpy", "multidimensional-array", "cartesian-product", "" ]
I have a flash upload script, that uses a .php file as the processor. I need the processor file to set a cookie with a gallery ID that was created by php script, and pass it on to the confirmation page. Except when Flash runs the php file... it doesnt set the cookie. It does set the session variable, which was good enough, but now Im using lighttpd for the site (including the confirmation page) and apache for the actual uploader processor script (because lighttps sucks at uploading large files), so the session vars don't get transferred between the 2 server software. How can I transfer a variable from the php processor (running on apache) to a confirmation page running lighttpd?
Well I would assume that it doesn't set a cookie as it was called by a flash script not a browser, and cookies are stored by the browser. The only ways I can think of are a mysql database, or simply a text file.
Just thought of a second solution which is probably less efficient than Nico's but may be better suited to you. If the cookie being sent to Flash isn't being sent to the browser also, you could use Flash's ExternalInterface class to pass the contents of the cookie to a javascript function which would set the cookie in the browser. Or you could call a javascript function which will make an AJAX call to fetch the contents of the cookie.
How to set a cookie with a php script thats executed by Flash?
[ "", "php", "flash", "apache", "lighttpd", "" ]
Very newbie (to Java) question: I opened an Rserve connection (<http://www.rforge.net/Rserve/>) on localhost, and I would like to use the REngine client (src/client/java-new in the Rserve package) to connect to it. What do I need to do to get the "RTest.java" (located in src/client/java-new/Rserve; pasted below) to compile? I gather that I need to compile the org.rosuda.\* libraries. How can I do this using Eclipse 3.5? I tried copying the "src/client/java-new" folder into my Java project's "src" directory, right clicking in Eclipse -> Build path -> Use as source folder. But I don't think this is enough to create the "org.rosuda" package, because I don't see an "org/rosuda" directory structure created anywhere (and those ominous red lines in Eclipse don't disappear). Anyone done this recently, care to offer a pointer? Thanks plenty. ``` import org.rosuda.REngine.*; import org.rosuda.REngine.Rserve.*; class TestException extends Exception { public TestException(String msg) { super(msg); } } public class test { public static void main(String[] args) { try { RConnection c = new RConnection(); System.out.println(">>"+c.eval("R.version$version.string").asString()+"<<"); { System.out.println("* Test string and list retrieval"); RList l = c.eval("{d=data.frame(\"huhu\",c(11:20)); lapply(d,as.character)}").asList(); int cols = l.size(); int rows = l.at(0).length(); String[][] s = new String[cols][]; for (int i=0; i<cols; i++) s[i]=l.at(i).asStrings(); System.out.println("PASSED"); } { System.out.println("* Test NA/NaN support in double vectors..."); double R_NA = Double.longBitsToDouble(0x7ff00000000007a2L); // int R_NA_int = -2147483648; // just for completeness double x[] = { 1.0, 0.5, R_NA, Double.NaN, 3.5 }; c.assign("x",x); String nas = c.eval("paste(capture.output(print(x)),collapse='\\n')").asString(); System.out.println(nas); if (!nas.equals("[1] 1.0 0.5 NA NaN 3.5")) throw new TestException("NA/NaN assign+retrieve test failed"); System.out.println("PASSED"); } { System.out.println("* Test assigning of lists and vectors ..."); RList l = new RList(); l.put("a",new REXPInteger(new int[] { 0,1,2,3})); l.put("b",new REXPDouble(new double[] { 0.5,1.2,2.3,3.0})); System.out.println(" assign x=pairlist"); c.assign("x", new REXPList(l)); System.out.println(" assign y=vector"); c.assign("y", new REXPGenericVector(l)); System.out.println(" assign z=data.frame"); c.assign("z", REXP.createDataFrame(l)); System.out.println(" pull all three back to Java"); REXP x = c.parseAndEval("x"); System.out.println(" x = "+x); x = c.eval("y"); System.out.println(" y = "+x); x = c.eval("z"); System.out.println(" z = "+x); System.out.println("PASSED"); } { System.out.println("* Test support for logicals ... "); System.out.println(" assign b={true,false,true}"); c.assign("b", new REXPLogical(new boolean[] { true, false, true })); REXP x = c.parseAndEval("b"); System.out.println(" " + ((x != null) ? x.toDebugString() : "NULL")); if (!x.isLogical() || x.length() != 3) throw new TestException("boolean array assign+retrieve test failed"); boolean q[] = ((REXPLogical)x).isTRUE(); if (q[0] != true || q[1] != false || q[2] != true) throw new TestException("boolean array assign+retrieve test failed (value mismatch)"); System.out.println(" get c(TRUE,FLASE,NA)"); x = c.parseAndEval("c(TRUE,FALSE,NA)"); System.out.println(" " + ((x != null) ? x.toDebugString() : "NULL")); if (!x.isLogical() || x.length() != 3) throw new TestException("boolean array NA test failed"); boolean q1[] = ((REXPLogical)x).isTRUE(); boolean q2[] = ((REXPLogical)x).isFALSE(); boolean q3[] = ((REXPLogical)x).isNA(); if (q1[0] != true || q1[1] != false || q1[2] != false || q2[0] != false || q2[1] != true || q2[2] != false || q3[0] != false || q3[1] != false || q3[2] != true) throw new TestException("boolean array NA test failed (value mismatch)"); } { // regression: object bit was not set for Java-side generated objects before 0.5-3 System.out.println("* Testing functionality of assembled S3 objects ..."); // we have already assigned the data.frame in previous test, so we jsut re-use it REXP x = c.parseAndEval("z[2,2]"); System.out.println(" z[2,2] = " + x); if (x == null || x.length() != 1 || x.asDouble() != 1.2) throw new TestException("S3 object bit regression test failed"); System.out.println("PASSED"); } { // this test does a pull and push of a data frame. It will fail when the S3 test above failed. System.out.println("* Testing pass-though capability for data.frames ..."); REXP df = c.parseAndEval("{data(iris); iris}"); c.assign("df", df); REXP x = c.eval("identical(df, iris)"); System.out.println(" identical(df, iris) = "+x); if (x == null || !x.isLogical() || x.length() != 1 || !((REXPLogical)x).isTrue()[0]) throw new TestException("Pass-through test for a data.frame failed"); System.out.println("PASSED"); } { // factors System.out.println("* Test support of factors"); REXP f = c.parseAndEval("factor(paste('F',as.integer(runif(20)*5),sep=''))"); System.out.println(" f="+f); System.out.println(" isFactor: "+f.isFactor()+", asFactor: "+f.asFactor()); if (!f.isFactor() || f.asFactor() == null) throw new TestException("factor test failed"); System.out.println(" singe-level factor used to degenerate:"); f = c.parseAndEval("factor('foo')"); System.out.println(" isFactor: "+f.isFactor()+", asFactor: "+f.asFactor()); if (!f.isFactor() || f.asFactor() == null) throw new TestException("single factor test failed (not a factor)"); if (!f.asFactor().at(0).equals("foo")) throw new TestException("single factor test failed (wrong value)"); System.out.println(" test factors with null elements contents:"); c.assign("f", new REXPFactor(new RFactor(new String[] { "foo", "bar", "foo", "foo", null, "bar" }))); f = c.parseAndEval("f"); if (!f.isFactor() || f.asFactor() == null) throw new TestException("factor assign-eval test failed (not a factor)"); System.out.println(" f = "+f.asFactor()); f = c.parseAndEval("as.factor(c(1,'a','b',1,'b'))"); System.out.println(" f = "+f); if (!f.isFactor() || f.asFactor() == null) throw new TestException("factor test failed (not a factor)"); System.out.println("PASSED"); } { System.out.println("* Lowess test"); double x[] = c.eval("rnorm(100)").asDoubles(); double y[] = c.eval("rnorm(100)").asDoubles(); c.assign("x", x); c.assign("y", y); RList l = c.parseAndEval("lowess(x,y)").asList(); System.out.println(" "+l); x = l.at("x").asDoubles(); y = l.at("y").asDoubles(); System.out.println("PASSED"); } { // multi-line expressions System.out.println("* Test multi-line expressions"); if (c.eval("{ a=1:10\nb=11:20\nmean(b-a) }\n").asInteger()!=10) throw new TestException("multi-line test failed."); System.out.println("PASSED"); } { System.out.println("* Matrix tests\n matrix: create a matrix"); int m=100, n=100; double[] mat=new double[m*n]; int i=0; while (i<m*n) mat[i++]=i/100; System.out.println(" matrix: assign a matrix"); c.assign("m", mat); c.voidEval("m<-matrix(m,"+m+","+n+")"); System.out.println("matrix: cross-product"); double[][] mr=c.parseAndEval("crossprod(m,m)").asDoubleMatrix(); System.out.println("PASSED"); } { System.out.println("* Test serialization and raw vectors"); byte[] b = c.eval("serialize(ls, NULL, ascii=FALSE)").asBytes(); System.out.println(" serialized ls is "+b.length+" bytes long"); c.assign("r", new REXPRaw(b)); String[] s = c.eval("unserialize(r)()").asStrings(); System.out.println(" we have "+s.length+" items in the workspace"); System.out.println("PASSED"); } { // string encoding test (will work with Rserve 0.5-3 and higher only) System.out.println("* Test string encoding support ..."); String t = "ひらがな"; // hiragana (literally, in hiragana ;)) c.setStringEncoding("utf8"); // -- Just in case the console is not UTF-8 don't display it //System.out.println(" unicode text: "+t); c.assign("s", t); REXP x = c.parseAndEval("nchar(s)"); System.out.println(" nchar = " + x); if (x == null || !x.isInteger() || x.asInteger() != 4) throw new TestException("UTF-8 encoding string length test failed"); // we cannot really test any other encoding .. System.out.println("PASSED"); } } catch (RserveException rse) { System.out.println(rse); } catch (REXPMismatchException mme) { System.out.println(mme); mme.printStackTrace(); } catch(TestException te) { System.err.println("** Test failed: "+te.getMessage()); te.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } ```
I cannot help you with the Java aspect, besides noting that on my Linux machine, simply calling `make` does the trick: ``` /tmp/java-new$ make javac -d . -source 1.4 -target 1.4 MutableREXP.java REngineException.java REngine.java REXPDouble.java REXPEnvironment.java REXPExpressionVector.java REXPFactor.java REXPGenericVector.java REXPInteger.java REXP.java REXPLanguage.java REXPList.java REXPLogical.java REXPMismatchException.java REXPNull.java REXPRaw.java REXPReference.javaREXPS4.java REXPString.java REXPSymbol.java REXPUnknown.java REXPVector.java RFactor.java RList.java jar fc REngine.jar org rm -rf org javac -d . -cp REngine.jar Rserve/RConnection.java Rserve/RFileInputStream.java Rserve/RFileOutputStream.java Rserve/RserveException.java Rserve/RSession.java Rserve/protocol/jcrypt.java Rserve/protocol/REXPFactory.java Rserve/protocol/RPacket.java Rserve/protocol/RTalk.java Note: Rserve/protocol/REXPFactory.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. jar fc Rserve.jar org rm -rf org ``` Likewise with the example directory you mentioned -- it builds fine on my Linux machine just saying 'make'. I do not use Eclipse and can't help with that aspect. The C++ examples also run fine as well (though I needed to adjust the Makefile to build them). You may need to ask to the Rosuda list for Rserv.
Yes, indeed. Compile the JAR just as Dirk indicated, then in Eclipse right click -> Add to Build Path, and the org.rosuda.\* package gets created and can be imported as in the examples.
How to connect to R with Java (using Eclipse)
[ "", "java", "eclipse", "r", "" ]
VS 2008 SP1 I have created a application that I have installed on the user computer. However, I want the application to be self-updating. But I am not sure if this would really update the application. The application will download all the files from the web server, and replace the files in the directory where the program as been installed to. The user will restart the application. I am just want to be sure, because I can't replace the installed files with the updated ones. As the application will be running. So really the application cannot delete/replace itself. So, I was thinking that I could download into another directory, if the program is installed in this directory 'program files/application/1.0.0' then I could download the files to 'program files/application/1.0.1'. However, when the program restarts, how can it know that it has to execute from the 1.0.1 directory? I can't use clickonce or the updater block for this. Many thanks for any advice,
You can wrap the application with a small loader program which will do a version check. If it's out of date, download the newer binaries and overwrite the old ones. If you want to maintain all version you might end up with: ``` c:\program files\mycompany\myapp\loader (the newer version will point to the latest directory) c:\program files\mycompany\myapp\v1.0 c:\program files\mycompany\myapp\v1.1 ``` If it's on a LAN, you might be able afford the bandwidth of just re-downloading the binaries on start up instead.
A good option is to make an independant Updater application. The updater will download the newest version and kill/replace the old. I think this is the best option, because you can execute the updater within the main appication (so you can say that it´s self-updating), or directly by the user with a shortcut. The updater can check if the application is running and ask the user to exit the application or kill it by itself. Forgive my english... Good luck
Creating a updater
[ "", "c#", "" ]
I need to translate a [Microsoft locale ID](http://msdn.microsoft.com/en-us/goglobal/bb964664.aspx), such as 1033 (for US English), into either an [ISO 639 language code](http://en.wikipedia.org/wiki/ISO_639) or directly into a Java [Locale](http://java.sun.com/javase/6/docs/api/java/util/Locale.html) instance. (Edit: or even simply into the "Language - Country/Region" in Microsoft's table.) Is this possible, and what's the easiest way? Preferably using only JDK standard libraries, of course, but if that's not possible, with a 3rd party library.
As it started to look like there is no ready Java solution to do this mapping, we took the ~20 minutes to roll something of our own, at least for now. We took the information from the horse's mouth, i.e. <http://msdn.microsoft.com/en-us/goglobal/bb964664.aspx>, and copy-pasted it (through Excel) into a .properties file like this: ``` 1078 = Afrikaans - South Africa 1052 = Albanian - Albania 1118 = Amharic - Ethiopia 1025 = Arabic - Saudi Arabia 5121 = Arabic - Algeria ... ``` (You can download the file [here](http://dl.dropbox.com/u/2896691/stack/lcid-codes.properties) if you have similar needs.) Then there's a very simple class that reads the information from the .properties file into a map, and has a method for doing the conversion. ``` Map<String, String> lcidToDescription; public String getDescription(String lcid) { ... } ``` And yes, this doesn't actually map to *language code* or *Locale object* (which is what I originally asked), but to Microsoft's "Language - Country/Region" description. It turned out this was sufficient for our current need. Disclaimer: this really is a minimalistic, "dummy" way of doing it yourself in Java, and obviously keeping (and maintaining) a copy of the LCID mapping information in your own codebase is not very elegant. (On the other hand, neither would I want to include a huge library jar or do anything overly complicated just for this simple mapping.) So despite this answer, **feel free to post more elegant solutions or existing libraries** if you know of anything like that.
You could use [GetLocaleInfo](http://msdn.microsoft.com/en-us/library/dd318101(VS.85).aspx) to do this (assuming you were running on Windows (win2k+)). This C++ code demonstrates how to use the function: ``` #include "windows.h" int main() { HANDLE stdout = GetStdHandle(STD_OUTPUT_HANDLE); if(INVALID_HANDLE_VALUE == stdout) return 1; LCID Locale = 0x0c01; //Arabic - Egypt int nchars = GetLocaleInfoW(Locale, LOCALE_SISO639LANGNAME, NULL, 0); wchar_t* LanguageCode = new wchar_t[nchars]; GetLocaleInfoW(Locale, LOCALE_SISO639LANGNAME, LanguageCode, nchars); WriteConsoleW(stdout, LanguageCode, nchars, NULL, NULL); delete[] LanguageCode; return 0; } ``` It would not take much work to turn this into a [JNA](https://github.com/twall/jna/) call. (Tip: emit constants as ints to find their values.) Sample JNA code: * [draw a Windows cursor](https://stackoverflow.com/questions/739870/extract-cursor-image-in-java/740528#740528) * [print Unicode on a Windows console](http://illegalargumentexception.blogspot.com/2009/04/java-unicode-on-windows-command-line.html) Using JNI is a bit more involved, but is manageable for a relatively trivial task. At the very least, I would look into using native calls to build your conversion database. I'm not sure if Windows has a way to enumerate the LCIDs, but there's bound to be something in .Net. As a build-level thing, this isn't a huge burden. I would want to avoid manual maintenance of the list.
How to convert Microsoft Locale ID (LCID) into language code or Locale object in Java
[ "", "java", "windows", "locale", "lcid", "" ]
I know why the post fails, but I'm not sure how to resolve it and I can't find any other references to this. I'm taking our references to jEditable to make this simpler, as it happens without the jEditable plugin. So how the heck do I "escape" the keyword so that it posts correctly? Here's relevant code: Test ``` <script type="text/javascript"> $(function() { $('#button').click(function() { $.ajax({ type : 'POST', url : 'ajax/post_cms.php', dataType : 'html', data : { id : '1', data : '<p>This is a test of the system that shows me an alert !</p>' }, success : function(data) { console.log(data); }, error : function(XMLHttpRequest, textStatus, errorThrown) { console.log('An Ajax error was thrown.'); console.log(XMLHttpRequest); console.log(textStatus); console.log(errorThrown); } }); }); }); </script> <input type="button" name="button" value="button" id="button" /> ``` When it errors out, it's throwing the "error:" callback function, and the "errorThrown" is logged as undefined. I'm positive it's the word "alert" because if I spell it "allert" in the one place it appears, everything posts just fine. If you take out the HTML (so it's just "data : 'This is a test of the system that shows me an alert !'") it works just fine. XMLHttpRequest = "XMLHttpRequest readyState=4 status=0 multipart=false" textStatus = "error" errorThrown = "undefined" GAH!! HELP!!
**UPDATE**: The problem was a firewall catching the AJAX request as a XSS attack. If you're experiencing problems similar to those exhibited below, make sure to check your environment. Symptoms: 1. Post data is failing with an error code of 0 2. Post data works in other places but not in your environment 3. Post data works as long as it doesn't contain any javascript functions 4. Your library doesn't seem like it should be at fault based on documentation 5. You can't find a bug in your library. I think there's something else wrong here other than jQuery. Your initial example works fine for me. See a working example here: <http://jsbin.com/ifami> *Note: I had to change your the ajax URL to a valid url but otherwise there were no other changes.* That being said, you could try encoding your values as URI components: ``` <script type="text/javascript"> $(function() { $('#button').click(function() { $.ajax({ type : 'POST', url : 'ajax/post_cms.php', dataType : 'html', data : { id : '1', data : encodeURIComponent('<p>This is a test of the system that shows me an alert !</p>') }, success : function(data) { console.log(data); }, error : function(XMLHttpRequest, textStatus, errorThrown) { console.log('An Ajax error was thrown.'); console.log(XMLHttpRequest); console.log(textStatus); console.log(errorThrown); } }); }); }); </script> ```
If it's only the word alert, you could simply change it to something else, like #1234# and then parse it back. It's hacky but a library that crash if you enter "alert" sounds pretty funky to me. You could also go in the lib code and fix it... or open a ticket and get them to fix it. It sounds to me it's a pretty important issue!
jQuery Ajax fails when posting data due to keyword in post data
[ "", "javascript", "jquery", "ajax", "" ]
I am using: ``` File.Exists(filepath) ``` I would like to swap this out for a pattern, because the first part of the filename changes. For example: the file could be ``` 01_peach.xml 02_peach.xml 03_peach.xml ``` How can I check if the file exists based on some kind of search pattern?
You can do a directory list with a pattern to check for files ``` string[] files = System.IO.Directory.GetFiles(path, "*_peach.xml", System.IO.SearchOption.TopDirectoryOnly); if (files.Length > 0) { //file exist } ```
If you're using .NET Framework 4 or above you could use [`Directory.EnumerateFiles`](http://msdn.microsoft.com/en-us/library/dd413233(v=vs.110).aspx) ``` bool exist = Directory.EnumerateFiles(path, "*_peach.xml").Any(); ``` This could be more efficient than using `Directory.GetFiles` since you avoid iterating trough the entire file list.
File exists by file name pattern
[ "", "c#", ".net-2.0", ".net", "" ]
Is there a [Cobertura](http://cobertura.sourceforge.net/) (or other code coverage tool) equivalent for C# .NET?
There's [NCover](http://www.ncover.com/), but's not free. There's an old, community edition somewhere on the site, maybe it will be sufficient for you.
You may try **[OpenCover](https://github.com/sawilde/opencover)** the successor of *PartCover*.
Cobertura equivalent available for C# .NET?
[ "", "c#", ".net", "code-coverage", "cobertura", "" ]
Is it possible to determine if a date is a **Saturday** or **Sunday** using JavaScript? Do you have the code for this?
Sure it is! The [`Date`](http://www.w3schools.com/jsref/jsref_obj_date.asp) class has a function called [`getDay()`](http://www.w3schools.com/jsref/jsref_getDay.asp) which returns a integer between 0 and 6 (0 being Sunday, 6 being Saturday). So, in order to see if today is during the weekend: ``` var today = new Date(); if(today.getDay() == 6 || today.getDay() == 0) alert('Weekend!'); ``` In order to see if an arbitrary date is a weekend day, you can use the following: ``` var myDate = new Date(); myDate.setFullYear(2009); myDate.setMonth(7); myDate.setDate(25); if(myDate.getDay() == 6 || myDate.getDay() == 0) alert('Weekend!'); ```
You can simplify @Andrew Moore 's test even further: ``` if(!(myDate.getDay() % 6)) alert('Weekend!'); ``` (Love that modulo function!)
Determine if a date is a Saturday or a Sunday using JavaScript
[ "", "javascript", "date", "" ]
I'm using jQuery. I need a div to fade in when the page loads. ``` <div id=monster></div> ``` How can I achieve this?
It cannot be simpler: ``` $(function(){ // $(document).ready shorthand $('#monster').fadeIn('slow'); }); ``` If your div is not initially hidden, you could hide it before the animation: ``` $('#monster').hide().fadeIn('slow'); ``` The speed parameter can be `'slow'`, `'normal'`, `'fast'` or the number of milliseconds to run the animation.
[jQuery/fadeIn](http://docs.jquery.com/Effects/fadeIn) ``` $(function() { $("#monster").fadeIn(); }); ```
How to fade in a div on page load?
[ "", "javascript", "jquery", "" ]
I'm writing a Windows console application in C++ and would like to return zero on success and a meaningful error code on failure (i.e., `S_OK` should return 0, and `E_OUTOFMEMORY` should return a different return value than `E_FAIL` and so on). Is the following an okay approach?: ``` int wmain(int argc, wchar_t *argv[]) { HRESULT hr = DoSomething(); return (int) hr; } ``` Or is there a better way? Maybe a standard Win32 API function or macro that I'm forgetting or failing to find?
`HRESULT` is just a 32-bit integer, with each code being a different value, so [what you are doing is what you want](http://msdn.microsoft.com/en-us/library/aa378137%28VS.85%29.aspx).
The OP wants a return value of zero to indicate success. There are success codes which are non-zero and so... ``` if ( SUCCEEDED( hr ) ) return 0; return hr; ```
How to convert Win32 HRESULT to int return value?
[ "", "c++", "windows", "winapi", "" ]
I'm having thread contention in an OLTP app. While reviewing the code involved, I found the following: ``` lock (_pendingTransactions) { transaction.EndPointRequest.Request.Key = (string)MessageComparer.GenerateKey(transaction.EndPointRequest.Request); if (!_pendingTransactions.ContainsKey(transaction.EndPointRequest.Request.Key)) { _pendingTransactions.Add(transaction.EndPointRequest.Request.Key, transaction); return true; } else { return false; } } ``` As you can see in the snippet, there is a lock on an object that is modified within the 'lock' block. Is there anything bad with that? Anyone had problems doing something like this?
Using locking in this way is often discouraged, with the recommendation being to use a dedicated lock field (class member variable). A dedicated lock field is of type `Object` and usually looks like this: ``` private object _pendingTransactionLock = new object(); ``` If the object itself has some threading awareness, this lock variable might belong in `_pendingTransaction`'s implementation class. Otherwise, it might belong alongside `_pendingTransaction` in the field's declaring class. You don't say what type `_pendingTransaction` is. If this is a built-in collection class that provides a `SyncRoot` property, that might be a good choice to lock on. See Jon Skeet's Choosing What to Lock On.
Generally speaking, one will take a lock on an object specifically because one is going to modify (or read) it, so there's nothing inherently wrong with this.
Modify locked object within lock block
[ "", "c#", "synchronization", "thread-safety", "" ]
So, I'm curious. How do you handle setting maximum execution time for threads? When running in a thread pool? I have several techniques but, I'm never quite satisfied with them. So, I figure I'd ask the community how they go about it.
Normally, I just poll regularly a control object from the threaded code. Something like: ``` interface ThreadControl { boolean shouldContinue(); } class Timer implements ThreadControl { public boolean shouldContinue() { // returns false if max_time has elapsed } } class MyTask implements Runnable { private tc; public MyTask(ThreadControl tc) { this.tc = tc; } public void run() { while (true) { // do stuff if (!tc.shouldContinue()) break; } } } ```
How about: Submit your `Callable` to the `ExecutorService` and keep a handle to the returned `Future`. ``` ExecutorService executorService = ... // Create ExecutorService. Callable<Result> callable = new MyCallable(); // Create work to be done. Future<Result> fut = executorService.submit(callable); ``` Wrap the `Future` in an implementation of `Delayed` whereby `Delayed`'s `getDelay(TimeUnit)` method returns the maximum execution time for the work in question. ``` public class DelayedImpl<T> implements Delayed { private final long maxExecTimeMillis; private final Future<T> future; public DelayedImpl(long maxExecTimeMillis, Future<T> future) { this.maxExecMillis = maxExecMillis; this.future = future; } public TimeUnit getDelay(TimeUnit timeUnit) { return timeUnit.convert(maxExecTimeMillis, TimeUnit.MILLISECONDS); } public Future<T> getFuture() { return future; } } DelayedImpl impl = new DelayedImpl(3000L, fut); // Max exec. time == 3000ms. Add the `DelayedImpl` to a `DelayQueue`. Queue<DelayedImpl> queue = new DelayQueue<DelayImpl>(); queue.add(impl); ``` Have a thread repeatedly `take()` from the queue and check whether each `DelayedImpl`'s `Future` is complete by calling `isDone()`; If not then cancel the task. ``` new Thread(new Runnable() { public void run() { while (!Thread.interrupted) { DelayedImpl impl = queue.take(); // Perform blocking take. if (!impl.getFuture().isDone()) { impl.getFuture().cancel(true); } } } }).start(); ``` The main advantage to this approach is that you can set a **different maximum execution time per task** and the delay queue will automatically return the task with the smallest amount of execution time remaining.
Best ways to handle maximum execution time for threads (in Java)
[ "", "java", "concurrency", "multithreading", "" ]
In a base class I have this property: ``` public virtual string Text { get { return text; } } ``` I want to override that and return a different text, but I would also like to be able to set the text, so I did this: ``` public override string Text { get { return differentText; } set { differentText = value; } } ``` This however does not work. I get a red squiggly under `set` saying that I can not override because it does not have a set accessor. Why is this aproblem? What should I do?
In your second block of code you are creating a public set method, but the word "override" in the declaration makes the compiler look for a method with the same signature in the base class. Since it can't find that method it will not allow you create your set. As ArsenMkrt says you could change your base declaration to contain a protected set. This will allow you to override it, but since you still won't be able to change the signature you can't promote this method to public in your subclass, so the code you posted still won't work. Instead you either need to add a public virtual set method to your base class that doesn't do anything (or even throws an exception if you try and call it) but this goes against what a user of the class would expect the behaviour to be so if you do this (and I won't recommend it) make sure it is so well documented that the user can't miss it: ``` ///<summary> ///Get the Text value of the object ///NOTE: Setting the value is not supported by this class but may be supported by child classes ///</summary> public virtual string Text { get { return text; } set { } } //using the class BaseClass.Text = "Wibble"; if (BaseClass.Text == "Wibble") { //Won't get here (unless the default value is "Wibble") } ``` Otherwise declare the set as a separate method in your child class: ``` public override string Text { get { return differentText; } } public void SetText(string value) { differentText = value; } ```
``` public virtual string Text { get { return text; } protected set {} } ``` change base class property like this, you are trying to override set method that doesn't exist
Why can I not add a set accessor to an overriden property?
[ "", "c#", "inheritance", "properties", "accessor", "" ]
When should I use: ``` Int32 myint = 0;//Framework data type ``` vs ``` int myint = 0;//C# language data type ``` What are the similarities/differences? I seem to recall being told that there are performance differences? Is this true?
In C# the language-defined keywords for data types are just aliases for their respective BCL types. So `int` is exactly the same as `Int32`, `long` is the same as `Int64`, etc. In general I'd think it's best to stick with the language-defined type names, though. There are definitely no performance differences as those aliases are resolved by the compiler.
`int` is an alias for `System.Int32`, `string` is an alias for `System.String`. There are no differences. That said, it's better practice to use `int` and `string`, not their System equivalent, mostly for readability. If you use a source style checker such as [StyleCop](https://web.archive.org/web/20101226140646/http://code.msdn.microsoft.com/sourceanalysis), it will enforce replacing all `System.String` and `System.Int32` declarations with their shorter equivalent.
When should I use .net Framework data types versus language datatypes?
[ "", "c#", ".net", "types", "" ]
PHP provides ways to get the number of the current day of the month (date('j')) as well as the number of the current day of the year (date('z')). Is there a way to get the number of the current day of the current quarter? So right now, August 5, it is day 36 of the third quarter. If there is no standard way of calculating this, does anyone have a (prefereably PHP-based) algorithm handy?
I wrote a class with the following methods. Enjoy. ``` public static function getQuarterByMonth($monthNumber) { return floor(($monthNumber - 1) / 3) + 1; } public static function getQuarterDay($monthNumber, $dayNumber, $yearNumber) { $quarterDayNumber = 0; $dayCountByMonth = array(); $startMonthNumber = ((self::getQuarterByMonth($monthNumber) - 1) * 3) + 1; // Calculate the number of days in each month. for ($i=1; $i<=12; $i++) { $dayCountByMonth[$i] = date("t", strtotime($yearNumber . "-" . $i . "-01")); } for ($i=$startMonthNumber; $i<=$monthNumber-1; $i++) { $quarterDayNumber += $dayCountByMonth[$i]; } $quarterDayNumber += $dayNumber; return $quarterDayNumber; } public static function getCurrentQuarterDay() { return self::getQuarterDay(date('n'), date('j'), date('Y')); } ```
How about: ``` $curMonth = date("m", time()); $curQuarter = ceil($curMonth/3); ```
Easy way to get day number of current quarter?
[ "", "php", "date", "date-arithmetic", "" ]
I have a database class, which an instance is declared in the main `index.php` as ``` $db = new Database(); ``` Is there a way for the `$db` variable to be globally recognized in all other classes without having to declare ``` global $db; ``` in the constructor of each class?
No. You have to declare Global $db in the constructor of every class. or you can use the Global array: $\_GLOBALS['vars']; The only way to get around this is to use a static class to wrap it, called the [Singleton Method](https://www.php.net/singleton) (See [Here](http://wiki.chacha102.com/Singleton) for an explanation). But this is very bad practice. ``` class myClass { static $class = false; static function get_connection() { if(self::$class == false) { self::$class = new myClass; } else { return self::$class; } } // Then create regular class functions. } ``` The singleton method was created to make sure there was only one instance of any class. But, because people use it as a way to shortcut globalling, it becomes known as lazy/bad programming. StackOverflow Knowledge [How to Avoid Using PHP Global Objects](https://stackoverflow.com/questions/1148068/how-to-avoid-using-php-global-objects/) [Share Variables Between Functions in PHP Without Using Globals](https://stackoverflow.com/questions/550753/share-variables-between-functions-in-php-without-using-globals) [Making a Global Variable Accessible For Every Function inside a Class](https://stackoverflow.com/questions/519078/making-a-global-variable-accessible-for-every-function-inside-a-class-php5) [Global or Singleton for Database Connection](https://stackoverflow.com/questions/130878/global-or-singleton-for-database-connection)
I do it a little different. I usually have a global application object (App). Within that object I do some basic initialization like creating my db objects, caching objects, etc. I also have a global function that returns the App object....thus (application object definition not shown): ``` define('APPLICATION_ID', 'myApplication'); ${APPLICATION_ID} = new App; function app() { return $GLOBALS[APPLICATION_ID]; } ``` So then I can use something like the following anywhere in any code to reference objects within the global object: ``` app()->db->read($statement); app()->cache->get($cacheKey); app()->debug->set($message); app()->user->getInfo(); ``` It's not perfect but I find it to make things easier in many circumstances.
Can I make a variable globally visible without having to declare it global in every single PHP class's constructor?
[ "", "php", "oop", "class", "variables", "global", "" ]
Just wonder. I have extended javascript Array object using its prototype as follows: ``` <html> <head> </head> <body> <script type="text/javascript"> function SomeMethod(){ alert('Hello'); } if(typeof Array.prototype.SomeMethod ==='undefined' ){ Array.prototype.SomeMethod = SomeMethod; } var ax=new Array("A","B","C"); for(var i in ax){ document.write(ax[i]); } </script> </body> </html> ``` The result will be: ``` ABCfunction SomeMethod() { alert("Hello"); } ``` EDIT: Although I have already found the answer I feel the necessity to add some more information so it would be clearer for others.
`for..in` iterates over the (non built-in) properties of an object. Do not use it to iterate through an array. Just use a regular `for` loop. Read this link <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/for...in#Description>
A question would be helpful ;-) I assume you don't want the prototype property to show up? JS doesn't allow you to set "DontEnum" on properties you add to the prototype, so you have to check to see if the array has the property, or if it's a property of its prototype: ``` for(var i in ax) { if (a.hasOwnProperty(i)) { document.write(ax[i]); } } ``` although to iterate over an array you shouldn't really be using `for...in` as that's for iterating over the properties of an object, rather than the elements of an array.
Javascript Array extension
[ "", "javascript", "" ]
I've been doing C++ for 3-4 months in a local college and I'm doing extra reading / learning using Accelerated C++ and so far, I've "finished" it. Now, I'm wondering which book to get next that'll help me code better in C++. I've looked around and found this: [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) I'm sorry if this question may seem stupid for most of you here but I'm a bit tight in cash and I would really want to invest in something that's "right" for me at this time. Right now, I only know the **basics** of stuff like (classes, templates, STL, iterators, dynamic memory management). Do you have any suggestions? Should I focus on STL or templates..? Or should I read something like The C++ Programming language?
If you haven't yet read Stroustrup's books, they are definitely a good read. There's nothing quite like reading about the language from the person who designed it. Whenever I learn a new language, I always try to find the canonical reference material written by the language designer or somebody very close to them.
In addition to reading Stroustrup's books (suggested by another answer here), I'd suggest his two FAQs as a great starting point: * [Bjarne Stroustrup's FAQ](http://www.research.att.com/~bs/bs_faq.html) * [C++ Style and Technique FAQ](http://www.research.att.com/~bs/bs_faq2.html) They both link to further reading material. These two, along with the [C++ FAQ Lite](http://www.parashift.com/c++-faq-lite/), are required reading for new programmers at my workplace. Once you're even a bit more comfortable, consider jumping in to the community: subscribe to something like the [boost mailinglists](http://www.boost.org/community/groups.html), watch the blogs of big name figures like [Herb Sutter](http://herbsutter.wordpress.com/), read Alexandrescu's [Guru of the Week](http://www.gotw.ca/gotw/) articles. You may feel like you're in over your head (I still do often after many years of reading the lists) but you'll learn a ton, *especially* watching the language grow and evolve. (And this stuff is free!) You can get more understanding from watching how a language changes over time, and how people *actually* use it, than you can from a million hours of memorizing the standard. (Not that shelling out a few bucks to have a copy of the ISO/IEC standard around is a bad idea, mind -- great for reference from time to time.) As for books: * after the Stroustrup books, * start with the [Meyers](http://www.aristeia.com/books.html) ("Effective") books. * I'd also recommend [C++ Coding Standards](http://www.gotw.ca/publications/c++cs.htm) -- a great amount of work went into gathering the "common sense" of the users of the language in this book. * Then if you want to blow your mind you can look at [Modern C++ Design](http://erdani.org/book/main.html) or some of the fun template metaprogramming resources... Above all, just stay connected and interested. Mailinglists, blogs, websites, academic papers, magazines, whatever -- choose what suits you best, don't expect to follow everything all the time, but keep your ears and eyes open; find aspects that interest you and follow them!
Which C++ material should I work on next?
[ "", "c++", "" ]
I wan't people to be able to register their own sections within my site, and have those sections be their own subdomain of my site. so someone can register 'test' and have 'test.example.com' refer to their site which would be at say /site.php?id=1 So how would i go about writing a mod\_rewrite rule for this?
`mod_rewrite` might not be the best tool for this. RewriteRules are great for mapping a file to something else, but it was not really meant for domain matching. The best you can do using `mod_rewrite` is the following: ``` RewriteEngine On # Skip www.domain.com RewriteCond %{HTTP_HOST} !^www\. RewriteCond %{HTTP_HOST} ^([^.]+)\.domain\.com RewriteRule ^/(.*)$ site.php?domain=%1&file=$1 [L] ``` Which is not really useful. What I would recommend to do instead if programmatically check the value of `HTTP_HOST` as such: ``` function get_subdomain() { if(preg_match('/^([^.]+)\.domain\.com/i', $_SERVER['HTTP_HOST'], $matches)) return $matches[1]; } ```
You can configure apache to claim the "special" domains in the apache configuration (e.g. www.mydomain.com, etc), in your virtual host containers and have the others default to your first virtual host. You can then rewrite the base url to a dispatch application that inspects the URL and sends the user off to their correct area. From Apache 2.0 docs: > Almost any Apache directive may go > into a VirtualHost container. The > first VirtualHost section is used for > requests without a known server name. Put the code to handle \*.mydomain.com in the first virtual host: ``` <VirtualHost *:80> Servername custom.mydomain.com DocumentRoot /var/www/html/custom RewriteEngine on RewriteRule ^/$ /var/www/cgi-bin/dispatch.cgi [R] # more configs here </VirtualHost> <VirtualHost *:80> Servername www.mydomain.com DocumentRoot /var/www/html/homepage # more configs here </VirtualHost> ``` In dispatch.cgi, inspect the calling url to determine where the user should go. Make sure you set up your DNS to accept all subdomains. Hope that helps!
Using mod_rewrite for subdomains
[ "", "php", "mod-rewrite", "subdomain", "" ]
I'm coming from a Linux background, but I'd like to provide a version of my software on Windows. For users to run my program, they will need the Visual C++ redistributable. I would like to provide it for them as part of the package. My worry is that there, in the future, will be an SP2 of the Visual Studio 2008 Redistributable. If I provide them SP1, or ask them to install it themselves, will it clobber later versions of the dll's that may be required by future tools? Is there any instruction to give users to make sure they do not do this? I'd certainly not want to screw up someone's machine or other applications by giving them incorrect instructions. Aside from the redistributable exe, I was going to provide my tool as a zip file which they can extract into any directory they please, so I was not planning on providing an installer.
With VS 2008 the runtimes are manifested and will install side-by-side. So if your application is linked to SP1's runtime, it will run only with the SP1 runtime (unless a manifest explicitly indicates that the Sp1 version should be overridden). So you're protected from that type of DLL hell, in exchange for another (the user **must** have the SP1 redistributable installed).
Why don't you statically link and avoid this problem altogether?
Visual c++ redistributable redistribution
[ "", "c++", "windows", "visual-c++", "package", "" ]
It has been a while since I have used regular expressions and I'm hoping what I'm trying to do is possible. I have a program that sends automated response regarding a particular file and I'd like to grab the text between two words I know will never change. In this example those words are "regarding" and "sent" ``` Dim subject As String = "Information regarding John Doe sent." Dim name As String = Regex.IsMatch(subject, "") ``` So in this case I'd like to be able to get just "John Doe". Every regexp I'm coming up with includes the words "regarding" and "sent". How can I use those words as the boundaries but not include them in the match?
Assuming `"Information regarding "` and `"sent."` never change, you can use a capturing group to get `"John Doe"`: ``` ^Information regarding (.+) sent.$ ``` And you use it this way: ``` Dim regex As New Regex("^Information regarding (.+) sent.$") Dim matches As MatchCollection = regex.Matches(subject) ``` Now, it should only match once, and you can get the group from the Groups property of the match: ``` For Each match As Match In matches Dim groups As GroupCollection = match.Groups Console.WriteLine(groups.Item(1).Value) // prints John Doe Next ```
Your regular expression should essentially look like this: ``` .*regarding (.+) sent.* ``` And the data you're looking for will be in the first capture variable ($1 in Perl).
Using regular expressions to get a word in between two Key words
[ "", "c#", ".net", "asp.net", "vb.net", "regex", "" ]
Is there any [Tree-Grid](http://www.componentsource.com/products/componentone-vsflexgrid-pro/index.html) component that is freely available for a C# project? A Tree-grid is a combination of a tree view and a datagrid. Every tree item represents a row in a table. Like this: [![enter image description here](https://i.stack.imgur.com/L4iQh.png)](https://i.stack.imgur.com/L4iQh.png)
[ObjectListView](http://objectlistview.sourceforge.net/) is great: [![alt text](https://i.stack.imgur.com/97DEk.png)](https://i.stack.imgur.com/97DEk.png) (source: [sourceforge.net](http://objectlistview.sourceforge.net/cs/_images/treelistview.png))
This one isn't bad : <http://www.codeproject.com/KB/tree/TreeWithColumns.aspx> The best one I used is DevExpress's XtraTreeList, but it's not free...
Free or open source Tree-grid for C#?
[ "", "c#", "user-interface", "gridview", "datagrid", "treeview", "" ]
This is a Java question. What is the fastest way to convert a `List<?>` to a `List<ObjectType>`? I am aware that this is possible through iteration please exclude that option. Example by iteration, ``` final List<ObjectType> targetList = new ArrayList<ObjectType>(); // API returns List<?> so I have no choice. List<?> resultList = resultSet.getResults(); // This is slow. Average list size is 500,000 elements. while (resultList != null && !resultList.isEmpty()) { for (final Object object : resultList) { final ObjectType objectType = (ObjectType) object; targetList.add(objectType); } resultSet = someService.getNext(resultSet); resultList = resultSet.getList(); } ``` Thanks.
It's a bit scary but depending on context you could possibly get away with just casting: ``` final List<ObjectType> targetList = (List<ObjectType>)problemSolver.getResults(); ```
As Tom said above, if you know for a fact that everything in the original `List<?>` is an `ObjectType` -- as implied by the iteration code -- casting to `List<ObjectType>` will work just fine. The only difference from the iteration code is that, if anything's *not* an `ObjectType`, in the iteration code the `ClassCastException` will happen when you're populating `targetList`, while with the straight cast, it'll happen when you're getting the values out. E.g.: ``` public static void main(String[] args) { List<?> list = Arrays.<Object> asList('I', "am", "not", "homogeneous"); List<Character> targetList = (List<Character>) list; int index = 0; try { for (Character c : targetList) { System.out.println(c); index++; } } finally { System.out.println("Reached " + index); } } ``` prints ``` I Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Character at Foo.main(Foo.java:100) Reached 1 ```
Fastest way to Convert List<?> to List<ObjectType>
[ "", "java", "generics", "optimization", "list", "" ]
I load dynamically PHP class files with autoload. And those files could be missing or corrupted by some reason. Autoload will successfully report missing files so application logic could handle that. But if those files are corrupted, then the whole processing halts with blank screen for the user and "PHP Parse error: syntax error" in error log. Is it possible to check syntax of PHP file from PHP code? I've looked here: <http://us.php.net/manual/en/function.php-check-syntax.php> - it's deprecated. And ``` exec("php -l $file"); ``` seems to be a wrong way (<http://bugs.php.net/bug.php?id=46339>) Thoughts?
You really shouldn't try to check for non-correct PHP files at execution time : it'll kill the response time of your application ! A "better way" would be to use php -l from command line when you're done modifying a PHP script ; or include it in your build process if you're using one ; or plug it as an SVN pre-commit hook if you're using SVN and can define [SVN hooks](http://svnbook.red-bean.com/nightly/en/svn.reposadmin.create.html). In my opinion, almost any given solution would be better than checking that yourself at execution time ! Considering errors like the ones you want to avoid will probably won't happen often, it is probably better to... just let them happen. ONly thing is : activate logs, and monitor them, the be able to detect quickly when tere is a problem :-) Of course, this doesn't prevent you from dealing with the case of missing files ; but that's a different matter...
Another way you can make one php file in your root directory called checkSyntax.php ``` <?php for($i=1; $i < count($argv); $i++){ $temp = "php -l " . $argv[$i]; $output = exec($temp); echo "\n$output"; } ?> ``` now, open your bashrc file to make a shortcut to run this file. add below line to run checkSyntax.php ``` alias checkSyntaxErrors='php /root/checkSyntax.php' ``` and now goto your source directory do svn st. it shows you list of files, now easily run the command. ``` checkSyntaxErrors file1.php file2.php ....... ``` this will check all your files passing as arguments. enjoy :)
Is it possible to check PHP file syntax from PHP?
[ "", "php", "parsing", "syntax-checking", "" ]
This is the **code-behind** of my view: ``` using System.Windows.Controls; namespace TestBoundTabControl.Views { public partial class SmartFormView : UserControl { public SmartFormView() { InitializeComponent(); } public void BeforeLoad() { MainTabControl.SelectedIndex = MainTabControl.Items.Count - 1; } } } ``` **But why can't I access the method "BeforeLoad()" from the view's presenter?** ``` using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using TestBoundTabControl.Views; namespace TestBoundTabControl.Presenters { public class SmartFormPresenter : PresenterBase { #region ViewModelProperty: SmartFormAreaPresenters private ObservableCollection<SmartFormAreaPresenter> _smartFormAreaPresenters = new ObservableCollection<SmartFormAreaPresenter>(); public ObservableCollection<SmartFormAreaPresenter> SmartFormAreaPresenters { get { return _smartFormAreaPresenters; } set { _smartFormAreaPresenters = value; OnPropertyChanged("SmartFormAreaPresenters"); } } #endregion public SmartFormPresenter() { View = new SmartFormView(); View.DataContext = this; for (int i = 0; i < 5; i++) { SmartFormAreaPresenters.Add(new SmartFormAreaPresenter()); } View.BeforeLoad(); //method not found } } } ```
My guess is that the property `View` has type `UserControl` and not `SmartFormView`. If that is true you will have to cast it (or change it's type): ``` ((SmartFormView) View).BeforeLoad(); ```
View is obviously of some base type, like FrameworkElement. Try this code: ``` SmartFormView myView = new SmartFormView(); View = myView; myView.BeforeLoad(); ```
Why can't I call a method in my View's code-behind from the view's presenter?
[ "", "c#", "wpf", "mvp", "" ]
I solved this question my own. The filename was wrong lolz. Hello everyone! I'm building a CMS like Drupal and Joomla. I'm working on the module feature (plugins), and I got the following error: ``` Fatal error: Class 'settings' not found in C:\wamp\www\SYSTEM\view.php on line 22 ``` Here is my code: start.php ``` <?php //First of all, start with some advertisement header("X-Powered-By:ZOMFG CMS, and ofcourse PHP, but that's less important"); //Then less impotant stuff lololol. session_start(); //Start a session mysql_connect($db_host, $db_user, $db_pass); //Connect to database mysql_select_db($db_name); //Select a database //Load core require_once("core.php"); //Load modules $res_modules = mysql_query("SELECT * FROM ".$_SERVER["db_prefix"]."modules WHERE enabled=1"); echo mysql_error(); $module_exists = array(); while($row_modules = mysql_fetch_array($res_modules)) { //Load module $name = $row_modules["name"]; modules::load_module($name); //and initialize it eval($name."::init();"); //Yes, it exists $module_exists[$name] = true; } //Check if the user wants shit from a module if(isset($_GET["m"]))//Yes the user want it { //Does the module exist and activated, and has it a function called view? if(isset($module_exists[$_GET["m"]]) && method_exists($_GET["m"], "view"))//Yep { //Load view (should be an array) eval("\$module_view = ".$_GET["m"]."::view();"); if(!is_array($module_view))//Not an array :( { error::e500module($_GET["m"], $_SERVER["REQUEST_URI"]); } else//The error would kill the entire script, m'kay { view::index(); } } else//Nope, so display error { error::e404($_SERVER['REQUEST_URI']); } } ``` settings.php ``` <?php class settings { function get($what) { $result_get = mysql_query("SELECT value FROM ".$_SERVER["db_prefix"]."settings WHERE key='$what'"); if(mysql_num_rows($result_get) > 0) { $row_get = mysql_fetch_array($result_get); return $result_get["value"]; } else { return -1; } } } ``` core.php ``` <?php //Load core classes require_once("settings.php"); require_once("error.php"); require_once("theme.php"); require_once("view.php"); require_once("modules.php"); ``` view.php ``` <?php class view { function head() { include("../THEMES/".settings::get("theme")."/head.php"); } function foot() { include("../THEMES/".settings::get("theme")."/foot.php"); } function left() { include("../THEMES/".settings::get("theme")."/left.php"); } function right() { include("../THEMES/".settings::get("theme")."/right.php"); } function index() { include("../THEMES/".settings::get("theme")."/index.php"); } } ``` Start.php is obviously executed first. Not other pages are executed before it, except customsettings.php that contains database information. If I used $\_SERVER["db\_prefix"] in my code above, it's because I needed a superglobal which is set in customsettings.php: customsettings.php ``` <?php $db_host = "localhost"; //Database host $db_user = "root"; //Database user $db_pass = "you may not know this"; //Database password $db_name = "zomfg"; //Database name $_SERVER["db_prefix"] = "zomfg_";//Prefix, needs to be superglobal ``` Can anybody help me? It seems that view.php's index function is called before settings.php is included. Sorry if this question is huge, I just want to be clear. Also don't say eval() is evil, I know. So I want to know why the settings class could not be found. If you need more source code, please comment to this question.
Though you would expect settings.php to be available to view.php because it was included in a script that includes them both, I have found that this usually isn't the case. You have a couple of choices: * [`require_once`](http://php.net/manual/en/function.require-once.php) all the files each class needs in each class file * write an [`__autoload()`](http://php.net/manual/en/language.oop5.autoload.php) function so that PHP can find all your classes whenever it thinks it needs one The 2nd option is more flexible. If you want to know classes are available from a particular place try outputting [`get_declared_classes()`](http://php.net/manual/en/function.get-declared-classes.php)
The following does not appy in OP's case but might help others. Check whether your code uses short tags `<?` instead of `<?php` and if yes, then check your php.ini for `short_open_tag` setting. By default it is off but if you inherit your php installation from someone else...
PHP class not found
[ "", "php", "class", "content-management-system", "module", "" ]
**Update:** As of jQuery 1.4, `$.live()` now supports *focusin* and *focusout* events. --- [jQuery](http://www.jquery.com) currently1 doesn't support "blur" or "focus" as arguments for the [$.live()](http://docs.jquery.com/Events/live) method. What type of work-around could I implement to achieve the following: ``` $("textarea") .live("focus", function() { foo = "bar"; }) .live("blur", function() { foo = "fizz"; }); ``` **1**. 07/29/2009, version 1.3.2
**Working solution:** ``` (function(){ var special = jQuery.event.special, uid1 = 'D' + (+new Date()), uid2 = 'D' + (+new Date() + 1); jQuery.event.special.focus = { setup: function() { var _self = this, handler = function(e) { e = jQuery.event.fix(e); e.type = 'focus'; if (_self === document) { jQuery.event.handle.call(_self, e); } }; jQuery(this).data(uid1, handler); if (_self === document) { /* Must be live() */ if (_self.addEventListener) { _self.addEventListener('focus', handler, true); } else { _self.attachEvent('onfocusin', handler); } } else { return false; } }, teardown: function() { var handler = jQuery(this).data(uid1); if (this === document) { if (this.removeEventListener) { this.removeEventListener('focus', handler, true); } else { this.detachEvent('onfocusin', handler); } } } }; jQuery.event.special.blur = { setup: function() { var _self = this, handler = function(e) { e = jQuery.event.fix(e); e.type = 'blur'; if (_self === document) { jQuery.event.handle.call(_self, e); } }; jQuery(this).data(uid2, handler); if (_self === document) { /* Must be live() */ if (_self.addEventListener) { _self.addEventListener('blur', handler, true); } else { _self.attachEvent('onfocusout', handler); } } else { return false; } }, teardown: function() { var handler = jQuery(this).data(uid2); if (this === document) { if (this.removeEventListener) { this.removeEventListener('blur', handler, true); } else { this.detachEvent('onfocusout', handler); } } } }; })(); ``` Tested in IE/FF/Chrome. Should work exactly as you intended. UPDATE: Teardowns now work.
This functionality is now included in jQuery core (as of 1.4.1).
Simulating "focus" and "blur" in jQuery .live() method
[ "", "javascript", "jquery", "" ]
Ok here is the situation (using PHP/MySQL) you are getting results from a large mysql table, lets say your mysql query returns 10,000 matching results and you have a paging script to show 20 results per page, your query might look like this **So page 1 query** ``` SELECT column FROM table_name WHERE userId=1 AND somethingelse=something else LIMIT 0,20 ``` **So page 2 query** ``` SELECT column FROM table_name WHERE userId=1 AND somethingelse=something else LIMIT 20,40 ``` Now you are grabbing 20 results at a time but there are a total of 10,000 rows that match your search criteria, **How can you only return 3,000 of the 10,000 results and still do your paging of 20 per page with a LIMIT 20 in your query?** I thought this was impossible but myspace does it on there browse page somehow, I know they aren't using php/mysql but how can it be achieved? **UPDATE** I see some people have replied with a couple of methods, it seems none of these would actually improve the performance by limiting the number to 3000?
Program your `PHP` so that when it finds itself ready to issue a query that ends with `LIMIT 3000, 20` or higher, it would just stop and don't issue the query. Or I am missing something? **Update:** `MySQL` treats `LIMIT` clause nicely. Unless you have `SQL_CALC_FOUND_ROWS` in your query, `MySQL` just stops parsing results, sorting etc. as soon as it finds enough records to satisfy your query. When you have something like that: ``` SELECT column FROM table_name WHERE userId=1 AND somethingelse='something else' LIMIT 0, 20 ``` , `MySQL` will fetch first `20` records that satisfy the criteria and stop. Doesn't matter how many records match the criteria: `50` or `1,000,000`, performance will be the same. If you add an `ORDER BY` to your query and don't have an index, then `MySQL` will of course need to browse all the records to find out the first `20`. However, even in this case it will not sort all `10,000`: it will have a "running window" of top `20` records and sort only within this window as soon as it finds a record with value large (or small) enough to get into the window. This is much faster than sorting the whole myriad. `MySQL`, however, is not good in pipelining recorsets. This means that this query: ``` SELECT column FROM ( SELECT column FROM table_name WHERE userId=1 AND somethingelse='something else' LIMIT 3000 ) LIMIT 0, 20 ``` is *worse* performance-wise than the first one. `MySQL` will fetch `3,000` records, cache them in a temporary table (or in memory) and apply the outer `LIMIT` only after that.
Firstly, the LIMIT paramters are Offset and number of records, so the second parameter should always be 20 - you don't need to increment this. Surely if you know the upper limit of rows you want to retrieve, you can just put this into your logic which runs the query, i.e. check that Offset + Limit <= 3000
Is it possible to have 2 limits in a MySQL query?
[ "", "php", "mysql", "" ]
How to count values of two drop down using ajax or php **Example Form** Base Price : $10 Color [drop-down] Size [drop-down] ``` Base Price : $10 <select name="color"> <option>Blue</option> <option>White</option> </select> <select name="size"> <option>8</option> <option>10</option> </select> ``` **Calculation** ``` example I change color to blue = $10 Price : $10 + $10 = $20 example I change Size to 8 = $5 Price : $10 + $5 = $15 ``` Where to start & any good sources for me to look in detail?. :)
All you need is a JavaScript function for this one that is fired on the `onchange` event: ``` <script lang="javascript"> function calcPrice (size, color) { var newprice = 0; // do the math depending on size and color document.getElementById('price').innerHTML = newprice; } </script> Base Price: $<div id="price">10<div> <select id="color" name="color" onchange="calcPrice (document.getElementById('size').value, this.value);"> <option>Blue</option> <option>White</option> </select> <select id="size" name="size" onchange="calcPrice (this.value, document.getElementById('color').value);"> <option>8</option> <option>10</option> </select> ``` The Base Price value will change dynamically based on a user's selection(s).
You should put values on your select options. Ideally, these values assigned to each item would match up to an ID in a database and then you retrieve prices from the database on the next page. You wouldn't be able to put a price in the value because multiple things might be the same price. ``` <select name="color"> <option value="1">Blue</option> <option value="2">White</option> </select> <select name="size"> <option value="1">8</option> <option value="2">10</option> </select> ``` Then when the form is submitted on the next page you'd get these IDs and query the database with these IDs for the total price. ``` $size_id = $_POST['size']; $color_id = $_POST['color']; ``` When generating the page you could also put the price in the value along with the ID, so that it could still be parsed with javascript to update the item price on the page when they make a selection. ``` <select name="color"> <option value="1-10">Blue</option> <option value="2-15">White</option> </select> <select name="size"> <option value="1-5">8</option> <option value="2-6">10</option> </select> ``` Then you could split by '-' in javascript and the second entry would be the price. When the form is submitted, you could again split by '-' in php and the first entry would be the option id in the database so you know what options they chose with their product. This is a simple explanation, but I hope it helps you a bit.
Count value from list/menu in ajax
[ "", "php", "jquery", "ajax", "" ]
I have a requirement to compare two XML documents and report differences. String comparison is not sufficient as I want to be able to say that: ``` <Foo/> ``` is the same as ``` <Foo></Foo> ``` Anyone used a library they would recommend?
There's the cunningly named [xmldiff](https://xmldiff.dev.java.net/) which I've used before with success. [XMLUnit](http://xmlunit.sourceforge.net/) also works well. It's primarily for use in unit tests (alongside JUnit).
or try [diffxml](http://diffxml.sourceforge.net/): > The standard Unix tools diff and patch > are used to find the differences > between text files and to apply the > differences. These tools operate on a > line by line basis using well-studied > methods for computing the longest > common subsequence (LCS). > > Using these tools on hierarchically > structured data (XML etc) leads to > sub-optimal results, as they are > incapable of recognizing the > tree-based structure of these files. > > This project aims to provide Open > Source XML diff and patch utilities > which operate on the hierarchical > structure of XML documents.
Recommend XML Difference open source Java libraries?
[ "", "java", "xml", "" ]
i got code like this: ``` swfobject.embedSWF("/Content/open-flash-chart.swf", "my_chart", "750", "300", "9.0.0", "expressInstall.swf", {"data-file":"http://localhost:8803/StatisticService/GetOpenFlashChartStatistic_Json?param1=123&param2=456"} ); ``` The outcome is, that a request is always made without any additional parameter, except for the first one.. so the request looks like this: ``` http://localhost:8803/StatisticService/GetOpenFlashChartStatistic_Json?param1=123 ``` Any ideas why all other parameters are not used? I would at least expect some damaged parameter in the call, but it's simply cut away. Thank you
You need to url-encode the flashvars that you pass to swfobject -- so url-encode the whole data-file url (after you url-encode any of the individual params in the url as necessary): ``` {"data-file": encodeURIComponent("/mydata?q=" + encodeURIComponent(x) + "&p=" + encodeURIComponent(y))} ``` See <http://teethgrinder.co.uk/open-flash-chart-2/tutorial-3.php>
As mentioned in the open flash chart [tutorial 3](http://teethgrinder.co.uk/open-flash-chart-2/tutorial-3.php "Tutorial 3") section entitled "Stop! And Read This..." you absolutely **must** url encode the parameters being passed into swfobject. You can do this as follows in your script: ``` swfobject.embedSWF("/Content/open-flash-chart.swf", "my_chart", "750", "300", "9.0.0", "expressInstall.swf", {"data-file": encodeURIComponent("http://localhost:8803/StatisticService/GetOpenFlashChartStatistic_Json?param1=123&param2=456")} ); ``` You need to make sure to encode *all* values you pass to swfobject, so make sure to add the encode to any you add in the future. Cheers.
JavaScript/Ajax/Flash HTTP Request
[ "", "javascript", "ajax", "flash", "http", "" ]
If I have a bunch of DAO's with a bunch of getXXX methods and I want all or some explicit list of the methods cached is there any way I can do this transparently with Spring? What I don't want is: * To change any source code / add anotations * Manually have to create a number of proxy beans for a number of DAO's and rewire them all. Ideally something with a regex to match the DAO's and the method's to cache and automatically wrap itself around the DAO's as needed. We are using OSCache so an example with that would be fantastic.
Spring AOP is what you want, I think. This will give you the ability to auto-create proxy objects for your DAOs without going through them all manually. It's a complex topic, though, so I suggest you [read the relevant section](http://static.springsource.org/spring/docs/2.5.x/reference/aop.html) of the Spring docs. As an idea to get you started, though, the BeanNameAutoProxyCreator might be useful to you. The AspextJK stuff is the full-blooded AOP approach, but it's quite scary. The Schema-based AOP approach is rather easier, but less flexible. > One of the central tenets of the > Spring Framework is that of > non-invasiveness; this is the idea > that you should not be forced to > introduce framework-specific classes > and interfaces into your > business/domain model. However, in > some places the Spring Framework does > give you the option to introduce > Spring Framework-specific dependencies > into your codebase: the rationale in > giving you such options is because in > certain scenarios it might be just > plain easier to read or code some > specific piece of functionality in > such a way. The Spring Framework > (almost) always offers you the choice > though: you have the freedom to make > an informed decision as to which > option best suits your particular use > case or scenario. > > One such choice that is relevant to > this chapter is that of which AOP > framework (and which AOP style) to > choose. You have the choice of AspectJ > and/or Spring AOP, and you also have > the choice of either the @AspectJ > annotation-style approach or the > Spring XML configuration-style > approach. The fact that this chapter > chooses to introduce the > @AspectJ-style approach first should > not be taken as an indication that the > Spring team favors the @AspectJ > annotation-style approach over the > Spring XML configuration-style. > > See the section entitled Section 6.4, > “Choosing which AOP declaration style > to use” for a fuller discussion of the > whys and wherefores of each style. As for the actual caching, you'll have to do that yourself, but that should be straightforward once the AOP hooks are integrated.
You can use [`@Cacheable`](http://www.jcabi.com/jcabi-aspects/annotation-cacheable.html) annotation and AOP aspects from [jcabi-aspects](http://www.jcabi.com/jcabi-aspects/): ``` @Cacheable(lifetime = 5, unit = TimeUnit.SECONDS) public String load(URL url) { return url.openConnection().getContent(); } ```
What is the easiest / most transparent way of caching methods in spring?
[ "", "java", "spring", "caching", "" ]
I have an anchor that doesn't go anywhere but has an onclick (e.g. `<a onclick="..."></a>`). My question pertains to the `href` attribute. What should I put for the value? If I simply omit `href`, the anchor doesn't have the appropriate decoration--the mouse pointer icon doesn't change when the mouse is put over it. If I use `href="#"`, then the window scrolls to the top of the page when the link is clicked. If I use `href="javascript:..."` and put the value of `onclick` proceeding `javascript:`, the page is left and the address bar contains the Javascript when the link is clicked. When I refer to browser behavior, I'm referring to Chrome, which I'm testing it in to start with. What should I be putting for `href` when the anchor isn't an actual link but exists only to have the `onclick` perform behavior?
In your onclick handler, add this to the end: ``` return false; ``` This will cancel the default processing (i.e. following the link) and you can put whatever you want in the href (the # is as good as any).
*Ideally* you would have an option for those with Javascript disabled: ``` <a href="degrade_option.html" onclick="return fancy_option();">do the option!</a> ``` If you're not into that sort of thing, although you really should be, the most common way is to use the pound but then cancel the event to prevent the default action from happening, like so: ``` <a href="#" onclick="return do_something();">do something</a> ``` But then you have to make sure `do_something` returns `false`. (or you can just add `return false;` at the end of the click handler, but this gets even more unsightly fast) Although, to be honest, you really shouldn't have inline Javascript attributes to begin with. They are bad practice, a nightmare to maintain, and there are much better alternatives out there. **EDIT**: In response to your comment, the alternative is [unobtrusive javascript](http://en.wikipedia.org/wiki/Unobtrusive_JavaScript): > "Unobtrusive JavaScript" is an emerging technique in the JavaScript programming language, as used on the World Wide Web. Though the term is not formally defined, its basic principles are generally understood to include: > > * Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation > * Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability) > * Progressive enhancement to support user agents that may not support advanced JavaScript functionality Read the page for some examples.
Empty-linked anchor
[ "", "javascript", "html", "anchor", "" ]
I'm trying to update a user's Twitter status from my C# application. I searched the web and found several possibilities, but I'm a bit confused by the recent (?) change in Twitter's authentication process. I also found what seems to be a [relevant StackOverflow post](https://stackoverflow.com/questions/751748/how-to-update-twitter-status-from-c), but it simply does not answer my question because it's ultra-specific regading a code snippet that does not work. I'm attempting to reach the REST API and not the Search API, which means I should live up to the stricter OAuth authentication. I looked at two solutions. The [Twitterizer Framework](http://code.google.com/p/twitterizer/) worked fine, but it's an external DLL and I would rather use source code. Just as an example, the code using it is very clear and looks like so: ``` Twitter twitter = new Twitter("username", "password"); twitter.Status.Update("Hello World!"); ``` I also examined [Yedda's Twitter library](http://devblog.yedda.com/index.php/twitter-c-library/), but this one failed on what I believe to be the authentication process, when trying basically the same code as above (Yedda expects the username and password in the status update itself but everything else is supposed to be the same). Since I could not find a clear cut answer on the web, I'm bringing it to StackOverflow. What's the simplest way to get a Twitter status update working in a C# application, without external DLL dependency? Thanks
If you like the Twitterizer Framework but just don't like not having the source, why not [download the source](http://code.google.com/p/twitterizer/source/checkout)? (Or [browse it](http://code.google.com/p/twitterizer/source/browse/) if you just want to see what it's doing...)
I'm not a fan of re-inventing the wheel, especially when it comes to products that already exist that provide 100% of the sought functionality. I actually have the source code for [Twitterizer](http://code.google.com/p/twitterizer/) running side by side my ASP.NET MVC application just so that I could make any necessary changes... If you really don't want the DLL reference to exist, here is an example on how to code the updates in C#. Check this out from [dreamincode](http://www.dreamincode.net/code/snippet2556.htm). ``` /* * A function to post an update to Twitter programmatically * Author: Danny Battison * Contact: gabehabe@hotmail.com */ /// <summary> /// Post an update to a Twitter acount /// </summary> /// <param name="username">The username of the account</param> /// <param name="password">The password of the account</param> /// <param name="tweet">The status to post</param> public static void PostTweet(string username, string password, string tweet) { try { // encode the username/password string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password)); // determine what we want to upload as a status byte[] bytes = System.Text.Encoding.ASCII.GetBytes("status=" + tweet); // connect with the update page HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml"); // set the method to POST request.Method="POST"; request.ServicePoint.Expect100Continue = false; // thanks to argodev for this recent change! // set the authorisation levels request.Headers.Add("Authorization", "Basic " + user); request.ContentType="application/x-www-form-urlencoded"; // set the length of the content request.ContentLength = bytes.Length; // set up the stream Stream reqStream = request.GetRequestStream(); // write to the stream reqStream.Write(bytes, 0, bytes.Length); // close the stream reqStream.Close(); } catch (Exception ex) {/* DO NOTHING */} } ```
Update Twitter Status in C#
[ "", "c#", "twitter", "" ]
I am loading several different classes from several different .jars from a custom class loader in Java. I create a custom `URLClassLoader`, add several .jars to it and pass it on to a `ServiceLoader` to find the classes I want. My question is: given a class, is there a way to discover which .jar it was loaded from?
You can call findResource on Classloader, and parse the URL that you get to figure out where it is coming from.
The following snippet should work: ``` obj.getClass().getProtectionDomain().getCodeSource().getLocation().toString() ``` Note that you should add checks for null when calling getProtectionDomain or getCodeSource and handle appropriately in any production code. (It depends on the class loader, security, etc.)
How do I discover which classpath entry provided a class?
[ "", "java", "reflection", "jar", "classloader", "" ]
I am trying to set the Authorize for my controllers can do the following: ``` [Authorize(Roles = "Approver")] ``` How ever the names of the roles are held in the database, and therefore I would like to try and do the following: ``` [Authorize(Roles = Settings.Instance.RoleEmployee)] ``` but I get the following error: > An attribute argument must be a constant expression, typeof expression > or array creation expression of an attribute parameter type Any way around this?
* [SO - C# Dynamic Attribute Arguments](https://stackoverflow.com/questions/1093466/c-dynamic-attribute-arguments) * [SO - use a global setting as an attribute argument](https://stackoverflow.com/questions/392083/use-a-global-setting-as-an-attribute-argument)
``` public class UniqueAttribute : ValidationAttribute { public string Identifier { get; set; } public override bool IsValid(object value) { // Get property value PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value); string identifierValue = properties.Find(this.Identifier, true).GetValue(value).ToString(); } } ``` You will get value of any property like this above ``` [UniqueAttribute(Identifier = "Id")] ```
Authorize attribute using a constant expression
[ "", "c#", "asp.net-mvc", "" ]
I've a var **example = "05-10-1983"** How I can get the "next day" of the string **example**? I've try to use Date object...but nothing...
This would do it for simple scenarios like the one you have: ``` var example = '05-10-1983'; var date = new Date(); var parts = example.split('-'); date.setFullYear(parts[2], parts[0]-1, parts[1]); // year, month (0-based), day date.setTime(date.getTime() + 86400000); alert(date); ``` Essentially, we create an empty [Date object](http://www.w3schools.com/jsref/jsref_obj_date.asp) and set the year, month, and date with the [`setFullYear()`](http://www.w3schools.com/jsref/jsref_setFullYear.asp) function. We then grab the timestamp from that date using [`getTime()`](http://www.w3schools.com/jsref/jsref_getTime.asp) and add 1 day (86400000 milliseconds) to it and set it back to the date using the [`setTime()`](http://www.w3schools.com/jsref/jsref_setTime.asp) function. If you need something more complicated than this, like support for different formats and stuff like that, you should take a look at the [datejs library](http://www.datejs.com/) which does quite a bit of work for you.
You can do the following: ``` var nextDay; var example = "05-10-1983"; nextDay = new Date(example); nextDay.setDate(nextDay.getDate() + 1); ``` `#getDate`/`#setDate` gets/sets the current day of the month (1-31). After the above is run, `nextDay` will be set to whatever tomorrow's date is. This will also rollover to the next month / year if it's the end of the month, and even handle leap years. :)
javascript - get next day of a string
[ "", "javascript", "date", "" ]
I am wondering which one of these would be considered the cleanest or best to use and why. One of them exposes the a list of passengers, which let the user add and remove etc. The other hides the list and only let the user enumerate them and add using a special method. Example 1 ``` class Bus { public IEnumerable<Person> Passengers { get { return passengers; } } private List<Passengers> passengers; public Bus() { passengers = new List<Passenger>(); } public void AddPassenger(Passenger passenger) { passengers.Add(passenger); } } var bus = new Bus1(); bus.AddPassenger(new Passenger()); foreach(var passenger in bus.Passengers) Console.WriteLine(passenger); ``` Example 2 ``` class Bus { public List<Person> Passengers { get; private set; } public Bus() { Passengers = new List<Passenger>(); } } var bus = new Bus(); bus.Passengers.Add(new Passenger()); foreach(var passenger in bus.Passengers) Console.WriteLine(passenger); ``` The first class I would say is better encapsulated. And in this exact case, that might be the better approach (since you should probably make sure it's space left on the bus, etc.). But I guess there might be cases where the second class may be useful as well? Like if the class doesn't really care what happens to that list as long as it has one. What do you think?
In example one, it is possible to mutate your collection. Consider the following: ``` var passengers = (List<Passenger>)bus.Passengers; // Now I have control of the list! passengers.Add(...); passengers.Remove(...); ``` To fix this, you might consider something like this: ``` class Bus { private List<Passenger> passengers; // Never expose the original collection public IEnumerable<Passenger> Passengers { get { return passengers.Select(p => p); } } // Or expose the original collection as read only public ReadOnlyCollection<Passenger> ReadOnlyPassengers { get { return passengers.AsReadOnly(); } } public void AddPassenger(Passenger passenger) { passengers.Add(passenger); } } ```
In most cases I would consider example 2 to be acceptable provided that the underlying type was extensible and/or exposed some form of onAdded/onRemoved events so that your internal class can respond to any changes to the collection. In this case List<T> isn't suitable as there is no way for the class to know if something has been added. Instead you should use a Collection because the Collection<T> class has several virtual members (Insert,Remove,Set,Clear) that can be overridden and event triggers added to notify the wrapping class. (You do also have to be aware that users of the class can modify the items in the list/collection without the parent class knowing about it, so make sure that you don't rely on the items being unchanged - unless they are immutable obviously - or you can provide onChanged style events if you need to.)
C#: Encapsulation of for example collections
[ "", "c#", "class", "encapsulation", "" ]
I'm trying to load an xml from a url in C#, but the problem is that, there is an xsl attached to the xml file, which means that I don't get the content of the xml file, but the html that it's transformed to using the xsl. Is there any way to load the xml without first transforming it, so I just get the content of the xml?
The fact that the URL has ".xml" in it doesn't mean that the server is going to give you XML. In the case of the URL you provided in your example, the server's emitting XHTML. (I also am not seeing the `xml-stylesheet` processing directive that you mention in your comment in that file, which makes me wonder if you're looking at two different things.) There's nothing you can do on the client side to change that. If there's a way of formulating the URL to get raw XML from the server, it's not documented on that site. They also seem to be serving up XHTML that isn't well-formed XML (judging on what happens when you try to parse it). That's not very nice of them. **Edit:** Okay, so the culprit here is that this site apparently checks the user agent to determine whether it should send XML or HTML. The answer [here](http://bytes.com/topic/net/answers/612065-reading-xml-webpage-without-xslt) (any why, pray, isn't Martin Honnen on StackOverflow?) shows how to do it: ``` string url = "http://eu.wowarmory.com/character-sheet.xml?r=Stormreaver&n=Sebassis"; HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url); httpRequest.UserAgent = @"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"; using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse()) { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(httpResponse.GetResponseStream()); Console.Write(xmlDocument.OuterXml); } ``` I wish I could tell you why they're doing that, and why this user agent works while others don't, but it's a little outside my area of expertise. Maybe someone else can shed some light on this.
If the server transforms the file prior to serving it, then no, you can only get the transformed version. However, if it only specifies a processing instruction that refers an XSL stylesheet and the browser transforms it, you get the XML by default.
Loading xml from url without styling it in C#
[ "", "c#", "xml", "xslt", "" ]
In Windows, how can I programmatically determine which user account last changed or deleted a file? I know that setting up object access auditing may be an option, but if I use that I then have the problem of trying to match up audit log entries to specific files... sounds complex and messy! I can't think of any other way, so does anyone either have any tips for this approach or any alternatives?
You can divide your problem into two parts: 1. Write to a log whenever a file is accessed. 2. Parse, filter and present the relevant information of the log. Of those two part 1, writing to the log is a built in function through auditing as you mention. Reinventing that would be hard and probably never get as good as the builtin functionality. I would use the built in functionality for logging by setting up an audit ACL on those files. Then I would focus my efforts on providing a good interface that reads the event log, filters out relevant events and presents them in a way that is suitable and relevant for your users.
You could always create a [file system filter](http://www.microsoft.com/whdc/driver/filterdrv/default.mspx). This might be overkill, but it depends on your purposes. You can have it load at boot and it sits behind pretty much every file access (its what virus scanners usually use to scan files as they are accessed). Simply need to log the "owner" of the application that is writing to the file. Also see the [MSDN documentation](http://msdn.microsoft.com/en-us/library/ms793580.aspx)
How to determine who changed a file?
[ "", "c#", "windows", "monitoring", "filesystems", "" ]
I have Mercurial 1.3 installed on my Windows 7 machine. I don't have python installed, but Mercurial seems to be OK with that. How does it work? Also, is it possible to force Mercurial run on IronPython and will it be compatible? Thank you.
The Mercurial windows installer is packaged using [py2exe](http://www.py2exe.org/). This places the python interpreter as a DLL inside of a file called "library.zip". On my machine, it is placed in "C:\Program Files\TortoiseHg\library.zip" This zip file also contains the python libraries that are required by mercurial. For a detailed description of how mercurial is packaged for windows, see the developer page describing [building windows installer](https://www.mercurial-scm.org/wiki/BuildingWindowsInstaller).
Since there is a "library.zip"(9MB), Mercurial's Windows binary package maybe made by [py2exe](http://www.py2exe.org/), py2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation.
How does mercurial work without Python installed?
[ "", "python", "mercurial", "ironpython", "" ]
Is it possible to use C# generics replace these 4 routines with one? ``` int memcmp (string a, string b){...} int memcmp (string a, byte[] b){...} int memcmp (byte[]a, string b){...} int memcmp (byte[]a, byte[] b){...} ``` I've tried a number of variations, but cannot determine exactly what to use... For example... ``` int memcmp<A, B>( A a, B b) { if ( a.Length < b.Length ) return 1; for ( int i = 0 ; i < a.Length ; i++ ) { if ( a[i] != b[i] ) return ( a[i] < b[i] ) ? -1 : 1; } } ``` gives the following errors: * 'A' does not contain a definition for 'Length' * Cannot apply indexing with [] to an expression of type 'A' Where is a good reference that discusses this? \*\*NOTE: \*\* I am not looking for a solution on how to compare strings and bytes, rather seeking an understanding of how generics work in C# using a "proof-of-concept" problem
Generic parameters without constraints are used as if they were of type `System.Object`, that's why the compiler argues about using `a.Length`. To get type specific syntax available on a generic parameter type you need to add constraints, e.g.: ``` public void Count<T>(T list) where T : IList ``` `String` and `byte[]` have only two seemingly common interfaces, `IEnumerable` and `IEnumerable<T>`, so it is the only usable thing here. However, `string` is `IEnumerable<char>` and `byte[]` is `IEnumerable<byte>`, so we need to fallback to `IEnumerable`: ``` public int MemCmp<TEn>(TEn obj1, TEn obj2) where TEn : IEnumerable { IEnumerator enumerator1 = obj1.GetEnumerator(); IEnumerator enumerator2 = obj2.GetEnumerator(); bool has1Next; bool has2Next; do { has1Next = enumerator1.MoveNext(); has2Next = enumerator2.MoveNext(); if(has1Next && has2Next) { if (enumerator1.Current is IComparable) { int comparison = ((IComparable) enumerator1.Current).CompareTo(enumerator2.Current); if (comparison != 0) return (comparison > 0) ? 1 : -1; } else if (enumerator2.Current is IComparable) { int comparison = ((IComparable) enumerator2.Current).CompareTo(enumerator1.Current); if (comparison != 0) return (comparison > 0) ? -1 : 1; } else { throw new ArgumentException("Not comparable types"); } } else { if(has1Next) { return 1; } else { return -1; } } } while (true); } ``` Usage: ``` MemCmp<IEnumerable>(a, b); ``` This is one possible solution to implementing your method. But, due to inherent type incomatibility here, and the static compilation of generics, we have lost strong typing. So, the answer to the question is yes, but at a considerable cost. Even chars and bytes will get boxed when cast to `IComparable`. Note also that in your code ``` if ( a[i] != b[i] ) ... ``` works because of built-in implicit conversions between `byte` and `char`, which cannot be mimicked with generics.
Your ideal solution would have a signature of: ``` int memcmp<T>( T a, T b ) where T : IHasLengthAndIndexer ``` where `IHasLengthAndIndexer` is defined as: ``` public interface IHasLengthAndIndexer { int Length { get; } byte this[ int index ] { get; } } ``` Then you could pass in any type assuming the type implements `IHasLengthAndIndexer` However you cannot change the interfaces of `byte[]` and `string` so this solution would not replace your four methods. You could, however, create your own class that has implicit operators from `byte[]` and `string` and create a method that compares instances of that class, but that isn't using generics.
How to use C# generics in place of string and byte[]
[ "", "c#", "generics", "" ]
Does Java SE (Standard Edition) offer a way to make its programs work online beside the Applets? Or is the applet the only way to do that?
You could use [Webstart](http://java.sun.com/javase/technologies/desktop/javawebstart/index.jsp) to allow users to launch your Java application from a website and have the application communicate back with a server. As with applets, Webstart applications run in a sandbox by default and hence you should look into signing your application jar to allow it to communicate over the network. You could also consider GWT or Servlets / JSP if your aim is to write a web application rather than deploy a standalone app. It all depends on what you're trying to achieve.
Java is trying to make a comeback on the client-side with a new technology called [JavaFX](http://javafx.com/). Not sure if that is not just an applet under the hood, though. And then there is [WebStart](http://java.sun.com/javase/technologies/desktop/javawebstart/index.jsp), which launches Java applications from a website (although they then run outside of the browser).
Is Java's applet the only way for the Java SE to work on a website?
[ "", "java", "applet", "standards", "" ]
I'm doing a Java EE application, and I'm at a point where I've concluded that I need a cache for my objects. My current requirements aren't much more complicated than some kind of key-value storage, possibly something that can handle a tree. It would be tempting to write a simple custom static/singleton class containing one or more maps. But, since there are several implementations that do more or less just like this (Memcached comes to mind), I began wondering that there must be some added value into using Memcached, instead of just my own implementation. So, I'm asking for thoughts about this: why should I pick up a ready-made cache, when I can do my own static data? And vice versa; why should I write a static class, when I can pick up a ready-made cache?
For many cases of complex object graphs I had good-enough performance with a one-liner ``` new MapMaker().weakKeys().makeMap(); ``` This creates a map using [Google collections](http://code.google.com/p/google-collections/), with can be used as a cache for complex objects. Since the keys are weak, and eventually go out of scope, it is unlikely that this will cause memory issues. So I'd say for simple cases - don't bother with the "cognitive load" of a distributed cache. Serialisation issues, latency etc.. you will not want to handle those.
There are many cache implementations, both open source and commercial. There are many issues regarding writing a correct cache - time to leave of the objects, eviction policies, persistence, memory management, and more, so I wouldn't start one of my own (why to reinvent the wheel?) Take a look at one of the following implementations: * [EHCache](http://ehcache.sourceforge.net/) * [OSCache](http://www.opensymphony.com/oscache/) * [JCS](http://jakarta.apache.org/jcs/) * [JBossCache](http://labs.jboss.com/jbosscache/) * [JCache](http://jcache.sourceforge.net/) See more at <http://java-source.net/open-source/cache-solutions>
Pick up a cache implementation, or roll your own?
[ "", "java", "caching", "" ]
I want to load an external XML file in a unit test to test some processing code on that XML. How do I get the path of the file? Usually in a web app I would do: ``` XDocument.Load(Server.MapPath("/myFile.xml")); ``` But obviously in my unit test I have no reference to Server or HttpContext so how can I map a path so that I don't have to specify the full path? **UPDATE:** I just want to make it clear that the code I'm actually testing is for an XML parser class, something like: ``` public static class CustomerXmlParser { public static Customer ParseXml(XDocument xdoc) { //... } } ``` So to test this I need to parse a valid XDocument. The method being tested does not access the file system itself. I could create the XDocument from a String directly in the test code but I thought it would be easier to just load it from a file.
Another idea would be to utilize dependency injection. ``` public interface IPathMapper { string MapPath(string relativePath); } ``` And then simply use 2 implementations ``` public class ServerPathMapper : IPathMapper { public string MapPath(string relativePath){ return HttpContext.Current.Server.MapPath(relativePath); } } ``` And then you also need your mock implementation ``` public class DummyPathMapper : IPathMapper { public string MapPath(string relativePath){ return "C:/Basedir/" + relativePath; } } ``` And then all your functions that needs to map path's would simply need to have access to an instance of IPathMapper - in your web app it needs to be the ServerPathMapper and in your unit tests the DummyPathMapper - basic DI (Dependency Injection).
Personally, I'd be very wary about having any code that relies on a back-end resource store, be that a file system or a database - you are introducing a dependency into your unit test that is likely to lead to false negatives i.e tests failing not because of your specific test code but because the file isn't there or the server is unavailable etc. See this [link](http://www.artima.com/weblogs/viewpost.jsp?thread=126923) for IMO a good definition of what a unit test is and more importantly is not Your unit test should be testing an atomic, well-defined piece of functionality not testing whether a file can load. One solution is to 'mock' the file load - there are various approaches to this however, I'd personally only mock the interface to the file system your are using and not try and do any full filesystem mocking - [here's](https://stackoverflow.com/questions/664277/needed-file-system-interfaces-and-implementation-in-net) a good SO post and [here's](https://stackoverflow.com/questions/1087351/how-do-you-mock-out-the-file-system-in-c-for-unit-testing) a good SO discussion on file system mocking Hope that helps
How to MapPath in a unit test in C#
[ "", "c#", "" ]
I can't seem to figure this one out. No matter what I do, I keep getting a "417 Expectation failed" error. Everywhere I've looked says that I need to get rid of the Expect header for the HttpWebRequest. Setting the static property `ServicePointManager.Expect100Continue = false` or the instance property on the web request `request.ServicePoint.Expect100Continue = false` never get's rid of the header. I have to manually set it to null to remove it. No matter what though, I STILL get the 417 error. What am I missing? ``` private static readonly MessageReceivingEndpoint UpdateStatusEndpoint = new MessageReceivingEndpoint("http://twitter.com/statuses/update.xml", HttpDeliveryMethods.PostRequest); public static XDocument UpdateStatus(ConsumerBase twitter, string accessToken, string message) { var data = new Dictionary<string, string>(); data.Add("status", message); ServicePointManager.Expect100Continue = false; //Doesn't work HttpWebRequest request = twitter.PrepareAuthorizedRequest(UpdateStatusEndpoint, accessToken, data); request.ServicePoint.Expect100Continue = false; //setting here doesn't work either //request.Expect is still set at this point unless I explicitly set it to null. request.Expect = null; var response = twitter.Channel.WebRequestHandler.GetResponse(request); //Throws exception return XDocument.Load(XmlReader.Create(response.GetResponseReader())); } ```
DotNetOpenAuth doesn't set or support Except100Continue directly. Would be nice if there is a property in the Channel class. Add this before your call to 'PrepareAuthorizedRequest': ``` ((HttpWebRequest)WebRequest.Create (UpdateStatusEndpoint.Location)).ServicePoint.Expect100Continue = false; ``` Except100Continue is set depending on the called URL. So you can set it before the connection is created. You may even set it globally in the config file. ``` <system.net> <settings> <servicePointManager expect100Continue="false" /> </settings> </system.net> ```
Set the Expectation to "expect:nothing" ..this is my code: var data = new Dictionary(); data.Add("status", status); HttpWebRequest request = twitter.PrepareAuthorizedRequest(UpdateStatusEndpoint, accessToken, data); request.Expect = "expect:nothing"; var response = twitter.Channel.WebRequestHandler.GetResponse(request); exception return XDocument.Load(XmlReader.Create(response.GetResponseReader())); it worked for me...
Expectation Failed when trying to update twitter status
[ "", "c#", ".net", "twitter", "oauth", "dotnetopenauth", "" ]
Let's say I have a `System.Xml.XmlDocument` whose `InnerXml` is: `<comedians><act id="1" type="single" name="Harold Lloyd"/><act id="2" type="duo" name="Laurel and Hardy"><member>Stan Laurel</member><member>Oliver Hardy</member></act></comedians>` I'd like to format it thusly, with newlines and whitespace added: ``` <comedians> <act id="1" type="single" name="Harold Lloyd"/> <act id="2" type="duo" name="Laurel and Hardy"> <member>Stan Laurel</member> <member>Oliver Hardy</member> </act> </comedians> ``` I looked in the `XmlDocument` class for some prettifying method, but couldn't find one.
Basically you can use `XmlDocument.Save(Stream)` and pass any Stream as target to receive the xml content. Including a "memory-only" `StringWriter` as below: ``` string xml = "<myXML>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); using(StringWriter sw = new StringWriter()) { doc.Save(sw); Console.Write(sw.GetStringBuilder().ToString()); } ``` Update: using block
Jon Galloway posted an answer and deleted it, but it was actually the best option for me. It went somewhat like this: ``` StringBuilder Prettify(XmlDocument xdoc) { StringBuilder myBuf = new StringBuilder(); XmlTextWriter myWriter = new XmlTextWriter(new StringWriter(myBuf)); myWriter.Formatting = Formatting.Indented; xdoc.Save(myWriter); return myBuf; } ``` No need to create a `XmlWriterSettings` object.
Best way to prettify an XmlDocument (.NET)?
[ "", "c#", ".net", "xml", "" ]
I am currently writing an IRC client and I've been trying to figure out a good way to store the server settings. Basically a big list of networks and their servers as most IRC clients have. I had decided on using SQLite but then I wanted to make the list freely available online in XML format (and perhaps definitive), for other IRC apps to use. So now I may just store the settings locally in the same format. I have very little experience with either ADO.NET or XML so I'm not sure how they would compare in a situation like this. Is one easier to work with programmatically? Is one faster? Does it matter?
It's a vaguer question than you realize. "Settings" can encompass an awful lot of things. There's a good .NET infrastructure for handling application settings in configuration files. These, generally, are exposed to your program as properties of a global Settings object; the classes in the `System.Configuration` namespace take care of reading and persisting them, and there are tools built into Visual Studio to auto-generate the code for dealing with them. One of the data types that this infrastructure supports is `StringCollection`, so you could use that to store a list of servers. But for a large list of servers, this wouldn't be my first choice, for a couple of reasons. I'd expect that the elements in your list are actually tuples (e.g. host name, port, description), not simple strings, in which case you'll end up having to format and parse the data to get it into a `StringCollection`, and that is generally a sign that you should be doing something else. Also, application settings are read-only (under Vista, at least), and while you can give a setting user scope to make it persistable, that leads you down a path that you probably want to understand before committing to. So, another thing I'd consider: Is your list of servers simply a list, or do you have an internal object model representing it? In the latter case, I might consider using XML serialization to store and retrieve the objects. (The only thing I'd keep in the application configuration file would be the path to the serialized object file.) I'd do this because serializing and deserializing simple objects into XML is really easy; you don't have to be concerned with designing and testing a proper serialization format because the tools do it for you. The primary reason I look at using a database is if my program performs a bunch of operations whose results need to be atomic and durable, or if for some reason I don't want all of my data in memory at once. If every time X happens, I want a permanent record of it, that's leading me in the direction of using a database. You don't want to use XML serialization for something like that, generally, because you can't realistically serialize just one object if you're saving all of your objects to a single physical file. (Though it's certainly not crazy to simply serialize your whole object model to save one change. In fact, that's exactly what my company's product does, and it points to another circumstance in which I wouldn't use a database: if the data's schema is changing frequently.)
I would personally use XML for settings - .NET is already built to do this and as such has many built-in facilities for storing your settings in XML configuration files. If you want to use a custom schema (be it XML or DB) for storing settings then I would say that either XML or SQLite will work just as well since you ought to be using a decent API around the data store.
Storing settings: XML vs. SQLite?
[ "", "c#", ".net", "xml", "sqlite", "ado.net", "" ]
We inherited some C# code as part of a project from another company which does URL redirects that modifies the existing query string, changing values of items, adding new params, etc as needed. The issue however is that the code is buggy at best, and ends up duplicating items in the query string instead of updating them properly. The code works on the first pass but on additional calls the duplication issues become apparent. Ex: MyPage.aspx?startdate=08/22/09&startdate=09/22/09 Instead of duplicating the item it needs to be either updated with the new value if it already exists, or added if not there already. Is there a C# class or set of functions for handling query strings, allowing a simple means to access and update/add parameters that gets around these issues instead of the blind add approach that seems to be in use now with the code? This needs to be able to handle multiple parameters that may or may not exists at all times and be added and updated on subsequent calls. We would sooner use existing logic than recreate something if possible so as to get this resolved quickly in a semi standard way for future maintainability and reuse.
Yes I would suggest converting the querystring to a collection by using [`HttpUtility.ParseQueryString()`](http://msdn.microsoft.com/en-us/library/system.web.httputility.parsequerystring.aspx) You can then find/add/update/replace values directly in the collection, before re-creating the querystring from this collection. This should make it easier to spot duplicates.
You can access and manipulate all values of your Querystring through the Request.QueryString collection. Here's a [link](http://msdn.microsoft.com/en-us/library/ms524784.aspx).
URL Querystring - Find, replace, add, update values?
[ "", "c#", "url", "query-string", "" ]
Why does the the RegExp `/^\w+$/` match `undefined`? Example code: ``` alert(/^\w+$/.test(undefined)); ``` This will display true in Firefox 3 (only browser I tested it on).
When `undefined` is cast to a string (which the regex does), it produces the string `"undefined"`, which is then matched.
``` /(\w)(\w)(\w)(\w)(\w)/.exec(undefined); ``` returns: `["undef", "u", "n", "d", "e", "f"]` It is treating undefined as the string `"undefined"`.
Why does the JavaScript RegExp /^\w+$/ match undefined?
[ "", "javascript", "regex", "firefox", "" ]
I'm trying to set tooltips on a `JEditorPane`. The method which I use to determine what tooltip text to show is fairly CPU intensive - and so I would like to only show it after the mouse has stopped for a short amount of time - say 1 second. I know I can use `ToolTipManager.sharedInstance().setInitialDelay()`, however this will set the delay time for tooltips on all swing components at once and I don't want this.
Well, I would recommend doing the CPU intensive task on another thread so it doesn't interrupt normal GUI tasks. That would be a better solution. (instead of trying to circumvent the problem) **\*Edit\*** You could possibly calculate the tootips for every word in the `JEditorPane` and store them in a `Map`. Then all you would have to do is access the tootip out of the `Map` if it changes. Ideally people won't be moving the mouse and typing at the same time. So, you can calculate the tootlips when the text changes, and just pull them from the `Map` on `mouseMoved()`.
If what you want is to make the tooltip dismiss delay much longer for a specific component, then this is a nice hack: (kudos to tech at <http://tech.chitgoks.com/2010/05/31/disable-tooltip-delay-in-java-swing/>) ``` private final int defaultDismissTimeout = ToolTipManager.sharedInstance().getDismissDelay(); addMouseListener(new MouseAdapter() { public void mouseEntered(MouseEvent me) { ToolTipManager.sharedInstance().setDismissDelay(60000); } public void mouseExited(MouseEvent me) { ToolTipManager.sharedInstance().setDismissDelay(defaultDismissTimeout); } }); ```
Set the Tooltip Delay Time for a Particular Component in Java Swing
[ "", "java", "performance", "swing", "user-interface", "tooltip", "" ]
I'm trying to use an installer for a Windows service, and would like to avoid using InstallUtil.exe. The installer appears to work correctly (the executable and dlls are in the correct directory), but the service doesn't appear under Computer Management. Here's what I've done so far: The service class name is the default - Service1. In the Project installer, the ServiceName of the service installer matches the class name - Service1. Under the Custom Actions, the primary output of the service was added to Install, Commit, Rollback, and Uninstall. I'm using <http://support.microsoft.com/kb/816169> as a reference. Any ideas?
Does your service project have an Installer class? You should have one that looks something like this: ``` [RunInstaller(true)] public partial class Service1Installer : Installer { public Service1Installer() { InitializeComponent(); ServiceProcessInstaller process = new ServiceProcessInstaller(); process.Account = ServiceAccount.LocalSystem; ServiceInstaller serviceAdmin = new ServiceInstaller(); serviceAdmin.StartType = ServiceStartMode.Manual; serviceAdmin.ServiceName = "Service1"; serviceAdmin.DisplayName = "Service1"; serviceAdmin.Description = "Service1"; Installers.Add(serviceAdmin); } } ```
Make sure you've created a ServiceInstaller and ServiceProcessInstaller class in your service project. (Check [this link](http://msdn.microsoft.com/en-us/library/system.serviceprocess.serviceinstaller.aspx) for more info). Close computer management and the Services window, run your installer again, and reopen the Services window. If that doesn't work, restart your computer. You might have some files locked. It goes without saying that you probably need administrative privileges on the machine for this to work properly.
C# - windows service installer not registering service
[ "", "c#", "windows-services", "windows-installer", "setup-deployment", "" ]
If I use the maven-dependency-plugin plugin, than I can't use a version range. Also it seems the version of a there defined artifact doesn't get updated though a newer version is in the remote repository. Why is that so? Uses the maven-dependency-plugin some other mechanism than the rest of maven to resolve dependencies? And if that is the case, why? **Here a example:** I have created a project *org.example:org.example.simple.project1:jar* and put it in the repository using the versions *1.0.0-SNAPSHOT, 1.0.0, 1.0.1* and *1.1.0-SNAPSHOT* I have now configured the dependency plugin in the following way: ``` <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>unpack-stuff<id> <phase>initialize</phase> <goals> <goal>unpack</goal> </goals> <configuration> <artifactItems> <artifactItem> <groupId>org.example</groupId> <artifactId>org.example.simple.project1.</artifactId> <version>[1.0,1.1)</version> <type>jar</type> <overWrite>true</overWrite> <outputDirectory>target/stuff</outputDirectory> <includes>**/*.*</includes> </artifactItem> </artifactItems> </configuration> </execution> </executions> </plugin> ``` If the dependency resolution would be the same as in the other dependencies, the version shoud resolve (at least in my opinion) to **1.0.1**. Instead I get the following exception: ``` [ERROR] FATAL ERROR [INFO] ------------------------------------------------------------------------ [INFO] version was null for org.example:org.example.simple.project1. [INFO] ------------------------------------------------------------------------ [INFO] Trace java.lang.NullPointerException: version was null for org.example:org.example.simple.project1. at org.apache.maven.artifact.DefaultArtifact.getBaseVersion(DefaultArtifact.java:362) at org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout.pathOf(DefaultRepositoryLayout.java:47) at org.apache.maven.artifact.repository.DefaultArtifactRepository.pathOf(DefaultArtifactRepository.java:110) at org.apache.maven.artifact.resolver.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:125) at org.apache.maven.artifact.resolver.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:74) at org.apache.maven.plugin.dependency.fromConfiguration.AbstractFromConfigurationMojo.getArtifact(AbstractFromConfigurationMojo.java:242) at org.apache.maven.plugin.dependency.fromConfiguration.AbstractFromConfigurationMojo.getProcessedArtifactItems(AbstractFromConfigurationMojo.java:143) at org.apache.maven.plugin.dependency.fromConfiguration.UnpackMojo.getProcessedArtifactItems(UnpackMojo.java:138) at org.apache.maven.plugin.dependency.fromConfiguration.UnpackMojo.execute(UnpackMojo.java:88) at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:453) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:559) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:500) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:479) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:331) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:292) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:142) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:336) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:129) at org.apache.maven.cli.MavenCli.main(MavenCli.java:301) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315) at org.codehaus.classworlds.Launcher.launch(Launcher.java:255) at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430) at org.codehaus.classworlds.Launcher.main(Launcher.java:375) [INFO] ------------------------------------------------------------------------ [INFO] Total time: 4 seconds [INFO] Finished at: Mon Aug 03 17:21:41 CEST 2009 [INFO] Final Memory: 13M/133M [INFO] ------------------------------------------------------------------------ ```
Ok here's the real answer (I wrote the dependency plugin): The unpack and copy goals have to replicate some of the core resolution code. Unfortunately that resolution code was not really in a useable form api-wise. Because of this, those goals do not handle version ranges, and also don't resolve artifacts directly from the reactor (I frankly just never implemented them because it broke too many of the existing use cases, yeah core the resolution code was that bad) A much better approach is to use the xxx-dependencies forms of these goals. These goals ask Maven to do the resolution before they are invoked and so it's 100% compatible. You can use the filters like the groupId and artifactId filter to effectively get the list of artifacts you want and the end result will be the same. The copy and unpack are definately more flexible and were intended for a much simpler use case I had at the time. Knowing what I know now, I probably would have implemented it more like the xxx-dependencies forms to start with. All that said, in Maven 3, the resolution code is finally completely decoupled...the dependency plugin driving most of the use cases needed for this. I'll be starting to work on a new version of the plugin to fully leverage this soon...and while it will require maven 3, it will finally work 100% with all the goals.
The dependency plugin uses the same resolution mechanism as everything else. It may be that your repositories are not updating the metadata because the is set to *never* or *weekly* or something. You can force Maven to refresh all the remote repository metadata by running with a -U. The dependency plugin also doesn't overwrite downloaded dependencies by default if they already exist in the target. You can do a clean or configure the goal to force overwrites. There are three parameters you can set to true: *overWriteIfNewer*, *overWriteReleases*, and *overWriteSnapshots*. See [the documentation](http://maven.apache.org/plugins/maven-dependency-plugin/copy-mojo.html) for more details. Edit: based on your updated question, the problem is that you are using a dependency range. Ranges are fine as long as there is something to resolve the version (for example you have the version defined in the parent project or in your dependencies section). If you change the range to an exact version, or use one of the [LATEST or RELEASE keywords](http://www.sonatype.com/books/maven-book/reference/pom-relationships-sect-pom-syntax.html#pom-relationships-sect-latest-release), Maven will be able to resolve the version number (though be aware that those keywords carry their own risks. I'd recommend defining a dependencyManagement section in your parent with the versions you use, then your projects can inherit those versions. I answered another question about this recently, I'll post a link if I find it
Does the maven-dependency-plugin use some other kind of artifact resolution than the rest of maven?
[ "", "java", "maven-2", "build", "" ]
What's the difference between these two methods of initializing the observers ArrayList. Or any other type for that matter. Is one faster than the other? Or am I missing some other benefit here. ``` class Publisher implements Observerable { private ArrayList observers = new ArrayList(); } class Publisher implements Observerable { private ArrayList observers; public Publisher() { observers = new ArrayList(); } } ```
They're equivalent. In fact, if you compile the two you'll see that they generate exactly the same byte code: ``` Publisher(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."<init>":()V 4: aload_0 5: new #2; //class java/util/ArrayList 8: dup 9: invokespecial #3; //Method java/util/ArrayList."<init>":()V 12: putfield #4; //Field observers:Ljava/util/ArrayList; 15: return } ``` Given that they're the same code, there clearly can't be any speed difference :) Note that in C# they're not quite equivalent - in C# the initializer for `observers` would run *before* the base constructor call; in Java they really are the same. Which you use is a matter of taste. If you have several different constructors which all initialize a variable in the same way it would make sense to use the first form. On the other hand, it's generally a good idea if you have several constructors to try to make most of them call one "core" constructor which does the actual work.
They are equal, but: the difference is that in the last example, you gain the benefit of being able to do more advanced initialization logic: error handling etc.
Java: What is the difference between these methods of construction
[ "", "java", "constructor", "initialization", "" ]
I have a C program to check whether the machine stack is growing up or down in memory in. It goes like that : ``` #include <stdio .h> void sub(int *a) { int b; if (&b > a) { printf("Stack grows up."); } else { printf("Stack grows down."); } } main () { int a; sub(&a); } ``` Now i want to do the same in Java. :-) Any one knows a solution without writing any native code ??? Thanks
If you're not doing any native code, then I can't imagine a situation where it could possibly matter in pure Java code. After all, the Java stack might be allocated in any direction at all instead of being a strictly contiguous block of memory (like the machine stack).
This cannot be done in Java code. It cannot be done in C code either. The code you posted invokes undefined behavior `(&b > a)`. According to the standard, the result of comparing two pointers is undefined unless the pointers point to elements within the same array. The standard says nothing about the direction of stack growth or whether a stack even exists.
How would you find out if a machine’s stack grows up or down in memory? (JAVA)
[ "", "java", "c", "" ]
As I understand it, Spring MVC application has two distinct contexts, the application context and the web context, which are controlled by applicationContext.xml and dispatcher-servlet.xml, respectively. Inside my controllers, **how do I go about loading a bean into either of these contexts?** Note that I am aware of [Getting Spring Application Context](https://stackoverflow.com/questions/129207/getting-spring-application-context). That would answer my question for a stand alone application. Where I would use a factory to load the application context from the xml file, but this seems like the wrong way to go about loading beans in Spring MVC.
[Matt](https://stackoverflow.com/a/1190472/20774) is absolutely correct. You should not need with any kind of bean-loading/instantiating code in your MVC application, otherwise you're doing something wrong. You define your beans inside the according spring XML configuration files. ``` <bean id="pinboardServiceTarget" class="com.lifepin.services.PinboardService"> <property name="pinboardEntryDao" ref="pinboardEntryDAO"/> </bean> ... <bean id="pinboardEntryDAO" class="com.lifepin.daos.PinboardEntryDAO"> <property name="sessionFactory" ref="sessionFactory"/> </bean> ``` Your PinboardService class (this is just from an application I wrote recently) will have a property `IPinboardEntryDAO` like ``` public class PinboardService implements IPinboardService{ private IPinboardEntryDAO pinboardEntryDao; ... public void setPinboardEntryDAO(IPinboardEntryDAO dao){ this.pinboardEntryDao = dao; } public IPinboardEntryDAO getPinboardEntryDAO(){ ... } ... } public class PinboardEntryDAO implements IPinboardEntryDAO{ ... } ``` Note that inside the the `PinboardService` class I'm using the DAO interface, not the implementation itself, while in the configuration I'm then injecting the real implementation `PinboardEntryDAO`. This is a very good practice for separating the different layers (presentation, service and data layer).
Although a Spring MVC application has two distinct contexts, the web context has access to all the beans loaded in the application context. The application context however cannot access beans in the web context. This is used to enforce separation of concerns, e.g. business rules class does not need to know about the HTTP session. So if you have a bean you need access to from both contexts it will have to be declared within the application context.
How do you load a bean into Spring MVC's application context?
[ "", "java", "spring", "spring-mvc", "" ]
I have a **BindingList(T)** that I am displaying in a **DataGrid**. I'm watching for **ListChanged** events and performing different actions when the **ListChanged** event is evoked. I'm checking the **ListChangeType** argument of the event to check how the list was changed, and then responding accordingly. However, I noticed that there is a **ListChanged** event type **ItemMoved**. I have buttons for "Move Up" and "Move Down" to move items up and down the list. But these are actually removing the selected item, and then reinserting it at a higher or lower position. However, I don't see any method of **BindingList(T)** that looks like it would move an item in the list. So am I missing something or is there just no way to move an item in a BindingList that would also evoke a ItemMoved type ListChanged event? ``` void FloorCollection_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { //DO STUFF } else if (e.ListChangedType == ListChangedType.ItemDeleted) { //DO STUFF } else if (e.ListChangedType == ListChangedType.ItemMoved) { //HOW DO I GET THIS CODE TO RUN? } else if (e.ListChangedType == ListChangedType.ItemChanged) { //DO STUFF } } ```
Unfortunately, nothing in BindingList will raise a ListChanged event with ListChangedType set to ListChangedType.ItemMoved. BindingList inherits from Collection which does not provide any kind of support for "moving" items in the list. BindingList does not add any support for this type of behavior either. If you really need/want to respond the ListChangedType.ItemMoved events your best option is to derive your own class from BindingList and provide your own Move methods. Inside those methods you need to temporarily suspend raising ListChanged events, perform the move by removing/adding, raise the ListChanged event yourself with the appropriate ItemMoved ListChangedType, and then revert the suspension of raising ListChanged events. It would look something like this\*: ``` public class CustomBindingList<T> : BindingList<T> { public void Move(T item, int index) { bool raiseListChangedEvents = this.RaiseListChangedEvents; try { this.RaiseListChangedEvents = false; int oldIndex = this.IndexOf(item); this.Remove(item); this.InsertItem(index, item); this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemMoved, index, oldIndex)); } finally { this.RaiseListChangedEvents = raiseListChangedEvents; } } } ``` \*Totally untested code, but it should illustrate the main points.
It triggers if the binding source has a sort applied to it, if you change and data that is held in the sort field and it then changes the position of the record then the event triggers.
What causes a ListChangedType.ItemMoved ListChange Event in a BindingList<T>?
[ "", "c#", "list", "events", "bindinglist", "" ]
I would like to monitor remote glassfish server. I have enabled JMX Connection in domain.xml: ``` <jmx-connector accept-all="true" address="0.0.0.0" auth-realm-name="admin-realm" enabled="true" name="system" port="8686" protocol="rmi_jrmp" security-enabled="false"> ``` But this didn't help. I still can't connect to server with JConsole. Then I've found solution - I need to specify JVM properties in domain.xml to open 8686 port for remote connection. So I added this lines into **java-config** section: ``` <jvm-options>-Dcom.sun.management.jmxremote</jvm-options> <jvm-options>-Dcom.sun.management.jmxremote.port=8686</jvm-options> <jvm-options>-Dcom.sun.management.jmxremote.local.only=false</jvm-options> <jvm-options>-Dcom.sun.management.jmxremote.authenticate=false</jvm-options> ``` But now when I'm starting server, I'm getting following errors: > Could not load Logmanager > "com.sun.enterprise.server.logging.ServerLogManager" > java.lang.ClassNotFoundException: > com.sun.enterprise.server.logging.ServerLogManager > at java.net.URLClassLoader$1.run(URLClassLoader.java:200) > at java.security.AccessController.doPrivileged(Native > Method) > at java.net.URLClassLoader.findClass(URLClassLoader.java:188) > at java.lang.ClassLoader.loadClass(ClassLoader.java:307) > at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) > at java.lang.ClassLoader.loadClass(ClassLoader.java:252) > at java.util.logging.LogManager$1.run(LogManager.java:166) > at java.security.AccessController.doPrivileged(Native > Method) > at java.util.logging.LogManager.(LogManager.java:156) > at java.util.logging.Logger.getLogger(Logger.java:273) > at sun.management.snmp.util.MibLogger.(MibLogger.java:57) > at sun.management.snmp.util.MibLogger.(MibLogger.java:42) > at sun.management.jmxremote.ConnectorBootstrap.(ConnectorBootstrap.java:760) > at sun.management.Agent.startAgent(Agent.java:127) > at sun.management.Agent.startAgent(Agent.java:239) > javax.management.JMRuntimeException: > Failed to load MBeanServerBuilder > class > com.sun.enterprise.admin.server.core.jmx.AppServerMBeanServerBuilder: > java.lang.ClassNotFoundException: > com.sun.enterprise.admin.server.core.jmx.AppServerMBeanServerBuilder > at javax.management.MBeanServerFactory.checkMBeanServerBuilder(MBeanServerFactory.java:480) > at javax.management.MBeanServerFactory.getNewMBeanServerBuilder(MBeanServerFactory.java:511) > at javax.management.MBeanServerFactory.newMBeanServer(MBeanServerFactory.java:298) > at javax.management.MBeanServerFactory.createMBeanServer(MBeanServerFactory.java:213) > at javax.management.MBeanServerFactory.createMBeanServer(MBeanServerFactory.java:174) > at sun.management.ManagementFactory.createPlatformMBeanServer(ManagementFactory.java:302) > at java.lang.management.ManagementFactory.getPlatformMBeanServer(ManagementFactory.java:504) > at sun.management.jmxremote.ConnectorBootstrap.initialize(ConnectorBootstrap.java:392) > at sun.management.Agent.startAgent(Agent.java:127) > at sun.management.Agent.startAgent(Agent.java:239) > Caused by: > java.lang.ClassNotFoundException: > com.sun.enterprise.admin.server.core.jmx.AppServerMBeanServerBuilder > at java.net.URLClassLoader$1.run(URLClassLoader.java:200) > at java.security.AccessController.doPrivileged(Native > Method) > at java.net.URLClassLoader.findClass(URLClassLoader.java:188) > at java.lang.ClassLoader.loadClass(ClassLoader.java:307) > at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) > at java.lang.ClassLoader.loadClass(ClassLoader.java:252) > at javax.management.MBeanServerFactory.loadBuilderClass(MBeanServerFactory.java:423) > at javax.management.MBeanServerFactory.checkMBeanServerBuilder(MBeanServerFactory.java:465) > ... 9 more Exception thrown by the agent : > javax.management.JMRuntimeException: > Failed to load MBeanServerBuilder > class > com.sun.enterprise.admin.server.core.jmx.AppServerMBeanServerBuilder: > java.lang.ClassNotFoundException: > com.sun.enterprise.admin.server.core.jmx.AppServerMBeanServerBuilder How can I fix the problem? Thanks in advance.
Steps to solve the problem are: 1. use default settings 2. add -Djava.rmi.server.hostname= in the JVM Options of the instance of GlassFish.
Still mystical behavior, but with these 4 settings you can connect to the JVM running Glassfish (add to domain.xml in admin console, restart required) ``` -Djava.rmi.server.hostname=yourhost -Dcom.sun.management.jmxremote.port=8686 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false ``` **Beware** ! This is not safe, as anyone now can connect a jconsole to it ! IMO this is not the Glassfish way, which is using the JMX connector. (Above works in GF 3.1)
How to activate JMX on remote Glassfish server for access with jconsole?
[ "", "java", "glassfish", "jmx", "jconsole", "" ]
I want to hide a file in c#. I know the file path and can create a FileInfo object. How can I hide it?
The previously accepted answer: ``` File.SetAttributes(path, FileAttributes.Hidden); ``` will result in certain other attributes it may have being lost, so you should: ``` File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden); ```
``` File.SetAttributes("pathToFile",FileAttributes.Hidden) ```
How to hide file in C#?
[ "", "c#", ".net", "" ]
I've been using [FreeMarker](http://freemarker.sourceforge.net/) for a little while now, but there's one glaring piece of functionality that is either missing or I just can't figure out (I hope the latter!). If you pass cfg.getTemplate() an absolute path, it just doesn't work. I know you can specify a template directory, but I can't afford to do that, my use case could deal with files in any directory. Is there any way to set FreeMarker to render absolute paths the way any user would expect?
I had to use the absolute path because the templating is happening in an Ant script and the templates are on the file system and discovered with an Ant fileset. I guess these are quite some unique requirements... Anyway,for the posterity (as long as SO is up), here's a solution that works: ``` public class TemplateAbsolutePathLoader implements TemplateLoader { public Object findTemplateSource(String name) throws IOException { File source = new File(name); return source.isFile() ? source : null; } public long getLastModified(Object templateSource) { return ((File) templateSource).lastModified(); } public Reader getReader(Object templateSource, String encoding) throws IOException { if (!(templateSource instanceof File)) { throw new IllegalArgumentException("templateSource is a: " + templateSource.getClass().getName()); } return new InputStreamReader(new FileInputStream((File) templateSource), encoding); } public void closeTemplateSource(Object templateSource) throws IOException { // Do nothing. } } ``` and the initialization is: ``` public String generate(File template) { Configuration cfg = new Configuration(); cfg.setTemplateLoader(new TemplateAbsolutePathLoader()); Template tpl = cfg.getTemplate(template.getAbsolutePath()); // ... } ```
Actually it remove the beginning "/" so you need to add it back in ``` public Object findTemplateSource(String name) throws IOException { File source = new File("/" + name); return source.isFile() ? source : null; } ```
Using An Absolute Path With FreeMarker
[ "", "java", "linux", "freemarker", "" ]
I need to store some statistics using JavaScript in a way like I'd do it in C#: ``` Dictionary<string, int> statistics; statistics["Foo"] = 10; statistics["Goo"] = statistics["Goo"] + 1; statistics.Add("Zoo", 1); ``` Is there an `Hashtable` or something like `Dictionary<TKey, TValue>` in JavaScript? How could I store values in such a way?
Use [JavaScript objects as associative arrays](http://blog.xkoder.com/2008/07/10/javascript-associative-arrays-demystified/). > Associative Array: In simple words associative arrays use Strings instead of Integer numbers as index. Create an object with ``` var dictionary = {}; ``` > JavaScript allows you to add properties to objects by using the following syntax: ``` Object.yourProperty = value; ``` An alternate syntax for the same is: ``` Object["yourProperty"] = value; ``` If you can, also create key-to-value object maps with the following syntax: ``` var point = { x:3, y:2 }; point["x"] // returns 3 point.y // returns 2 ``` > You can iterate through an associative array using the for..in loop construct as follows ``` for(var key in Object.keys(dict)){ var value = dict[key]; /* use key/value for intended purpose */ } ```
``` var associativeArray = {}; associativeArray["one"] = "First"; associativeArray["two"] = "Second"; associativeArray["three"] = "Third"; ``` If you are coming from an object-oriented language you should check [this article](http://javascript.info/tutorial/objects).
How to do associative array/hashing in JavaScript
[ "", "javascript", "dictionary", "hashtable", "" ]
Some **DO** facts: * two developers in a team * we write unit tests (auto run with every build) * we use source versioning control system (SVN) * we (the two developers) are product managers as well (a classic situation with high risk of product over-engineering) Some **DON'T** facts * we don't have nightly builds * we don't have continuous integration * we don't have integration tests * we don't have regression tests * we don't have acceptance/customer tests * we don't have a dedicated tester yet I read a lot about all these different kinds of tests, but I don't see a reason to write them at the moment. Right now it looks like a *plain overhead without any value* (**edit**: *work that doesn't seem to add much value at the moment*). **Question:** What causes will *force* us to decide to implement any of the don'ts and which ones can/should be automated with which tools/libs?
"What causes will force us to decide to implement any of the don'ts " Nothing. Nothing forces you to improve your quality. Many people write code that mostly works most of the time, requires a lot of careful maintenance and their users are mostly satisfied. That's fine. Some people like it like that. Clearly, since you've characterized practices that lead to high quality as "plain overhead without any value" then you don't need that level of quality and can't foresee ever needing that level of quality. That's fine. I don't know how you deliver without doing acceptance testing, but you've stated clearly that you don't. I can't understand how this works, but you seem to be happy with it. "which ones can/should be automated" None. This is pretty trivial stuff. You're already using C#'s unit testing. Unit testing, essentially *is* regression testing. To a degree you can use the same tools and framework for integration and elements of acceptance testing. There are numerous make-like (ant-like, maven-like, scons-like) tools to do nightly builds. You don't need any more automation than you have. "continuous integration" doesn't require tools, just the "plain overhead without any value" of checking stuff in often enough that the build is never broken. As far as I care, every developer is a tester, so you are all dedicated testers. Many people debate the "dedicated tester" role. I no longer know what this means. It seems to be a person who doesn't produce deliverable code. Don't know why you'd hire someone like that. It makes more sense to simply make everyone responsible for all the testing at all times. A "dedicated tester" -- who acts as surrogate for the user -- always turns out to be working closely with the business analyst. Since this is how it usually shakes out, they're usually junior business analysts with a focus on the acceptance test. This is a good thing because they have a deliverable: a solved business problem. I'm never sure what testers deliver. More tests? More bugs? How about making them answerable to the users for assuring that the business problem is *solved*? Nothing *forces* you to do any of this.
I'm not entirely sure this is answer-worthy, but here are a few things to consider: * If your unit tests are good and up-to-date (a bug report leads to unit tests that confirm the bug), unit tests can act as regression tests. * If your unit tests run with every check-in, that sounds very close to my understanding of nightly builds, but with a different frequency. * If you don't have acceptance tests, how do you know that what you build meets the needs of your customer? An acceptance test can be as simple as making sure that the requirements are fulfilled as documented.
Which tests beside unit tests and continuous integration decision?
[ "", "c#", ".net", "testing", "" ]
I was reading [Pro WPF in C# 2008](https://rads.stackoverflow.com/amzn/click/com/1590599551) yesterday (in anonymous bookstore) and in chapter 2 they mention that XAML allows for the graphic design and the programmer to be completely independent. It got me wondering if most companies are moving toward having dedicated design specialists for implementing there UI’s? I know at our company we have had less than encouraging comments about our displays/UI's and we have even considered bringing in [consultants](http://www.construx.com/Page.aspx?nid=272). All of our UI development is done by the developer. Should we have/hire a graphic design specialist, or hire a consultant to look at our work, or will WPF be the savior for our lack luster UI’s?
We've started using WPF, but we have no UI designers - and it shows. Some of our user interfaces here (99% in Windows Forms, rough guesstimate) could be filed under "crime against humanity." I've done something relatively pleasing to the eyes with my first WPF application, but it still could use some [TLC](http://en.wiktionary.org/wiki/tender_loving_care). I must say that even though WPF drove me nuts at first, now I hope I won't have to go back to Windows Forms for future projects. WPF offers the potential, but it's very likely that the majority of companies who don't use UI designers now won't start just because they're using WPF. Hell, most don't have dedicated test teams, so don't even dare mentioning the idea of dedicated UI designers. The mentality here is: "As long as it works, it doesn't matter how it looks." It drives me mad every time. Stephan mentioned laziness. That's not un-true (we have people who display actual cryptic database field names on screen rather than user-friendly names, for instance), but as Mario pointed out, UI skills are a different beast from programming skills. We have some excellent programmers who should never be allowed to go near the interface.
The one you need is not graphics designer, but rather a UI/UX designer. Generally speaking, developers are notoriously bad at two things for sure: finding bottlenecks in applications (profilers should be used to do so) and creating interfaces: [![alt text](https://i.stack.imgur.com/QM3a2.gif)](https://i.stack.imgur.com/QM3a2.gif) (source: [mac.com](http://homepage.mac.com/bradster/iarchitect/images/ibm.gif)) The thing with WPF is that it separates UI layout from actual UI code thus allowing developers and designers to work on these two parts separately, each using proper tools: Visual Studio for developers and [Expression](http://expression.microsoft.com/) suite for designers. And yes, if you want to have a nice-looking UI, you should hire a designer.
Will WPF be the savior for our lack luster UI’s?
[ "", "c#", "wpf", "user-interface", "" ]
I have a mssql stored procedure question for you experts: I have two tables [table1] which retrieves new entries all the time. I then have another table [table2] which I need to copy the content of [table1] into. I need to check if some of the the rows already exists in [table2], if it do, just update the Update-timestamp of [table2], otherwise insert it into [table2]. The tables can be rather big, about 100k entries, so which is the fastest way to do this? It should be noticed that this is a simplified idea, since there is some more datahandling happening when copying new content from [Table1] -> [Table2]. So to sum up: If a row exist both [Table1] and [Table2] update the timestamp of the row in [Table2] otherwise just insert a new record with the content into [Table1].
This works across all versions of SQL Server. MERGE does the same in SQL Server 2008. ``` UPDATE table2 SET timestampcolumn = whatever WHERE EXISTS (SELECT * FROM table1 WHERE table1.key = table2.key) INSERT table2 (col1, col2, col3...) SELECT col1, col2, col3... FROM table1 WHERE NOT EXISTS (SELECT * FROM table2 WHERE table2.key = table1.key) ```
If you have SQL Server 2008, it has a [MERGE](http://technet.microsoft.com/en-us/library/bb510625.aspx) command that can do an insert or update as appropriate.
Sql exists copy
[ "", "sql", "sql-server", "stored-procedures", "" ]
How do I mirror text just like [iTunes](http://en.wikipedia.org/wiki/ITunes) in [Firefox](http://en.wikipedia.org/wiki/Mozilla_Firefox)? Is there [JavaScript](http://en.wikipedia.org/wiki/JavaScript) that can do this or is it possible with [CSS](http://en.wikipedia.org/wiki/Cascading_Style_Sheets)? I'm looking for a true mirror image that I can then manipulate not backwards text.
There's a jQuery plugin that can create that effect: [FontEffect](http://www.iofo.it/jquery/fonteffect/) **Edit:** The original links does not work any more but this seems to be the same plugin (untested...): <https://code.google.com/p/clapee-shuffle/source/browse/trunk/Test1/js/jquery-fonteffect-1.0.0.js?r=4>
Christian Effenberger's [Reflex](http://www.netzgesta.de/reflex/) library provides a nice degradable reflection effect for images, but not for text. Depending on the height of the area you wish to reflect you can use the old technique of creating multiple single-pixel-tall divs with with negative top offsets and copies of the original text. Clunky, but effective.
How do I mirror text in Firefox?
[ "", "javascript", "css", "mirror", "" ]
See title. Using either javascript or pure HTML.
``` window.open('url.htm','mywindow','width=400,height=200,left=0,top=100,screenX=0,screenY=100'); ```
To make it non-resizable, just add a 'resizable=0' as one of the parameters. ``` window.open('url.htm','mywindow','width=400,height=200, left=0,top=100,screenX=0,screenY=100,resizable=0'); ```
How can I open a non-resizable popup at a fixed position?
[ "", "javascript", "html", "popup", "" ]
Consider a SQL Server table defined with a `varchar(1) NULL` field. It's being used to store a gender character. Some rows have data, some not: either null or blank. Granted the blanks SHOULD be nulls, but consider that blank is a valid value here. I'd much prefer the value to be null. ``` ID Gender 1 'M' 4 'M' 3 '' 4 'F' ``` An exception is raised when running a Linq To Sql query where the value of `someID` is 3. ``` var emp = (from e in db.Employees where e.ID == someID select e); ``` **Exception**: > String must be exactly one character long. **Question**: What is the cause of this exception? What can be done to prevent or eliminate this problem?
Check the `Employee` type that was created for you by the LINQ to SQL designer. Most likely the type for the `Gender` property is `System.Char` (which is the type that the LINQ to SQL designer uses for `varchar(1)`) and should be changed to a `System.String` to properly match your database schema. The fact that the LINQ to SQL designer interprets a `varchar(1)` as a `System.Char` is foolish considering that this is valid T-SQL: ``` declare @foo varchar(1); set @foo = ''; ``` and this is *invalid* C#: ``` Char foo = ''; ``` Since the type of the property that was generated is too restrictive you need to change it to be a `System.String`. **Note:** *You may want to consider adding some validation inside the setter of the property to throw an exception if the length of the string is greater than one.*
Is it possible that the blank data like '' doesn't meet the current constraints of the table? E.g. perhaps the table doesn't permit empty strings (even though there is one in there). Then, maybe LINQ is applying those constraints for you, or expecting those constraints to be met and complaining that they are not. If this is what is going on, you might change the constraints/design of the table to allow blank values, or just update all the blank values to NULL (assuming NULLs are allowed)
Linq To Sql: Exception "String must be exactly one character long"
[ "", "c#", "sql-server", "linq-to-sql", "" ]
I was wondering about C# Enumerations and what happens with duplicate values. I created the following small program to test things out: ``` namespace ConsoleTest { enum TestEnum { FirstElement = -1, SecondElement, ThirdElement, Duplicate = FirstElement } /// <summary> /// Summary description for MainConsole. /// </summary> public class MainConsole { /// <summary> /// Constructor for the class. /// </summary> public MainConsole() { // // TODO: Add constructor logic here // } /// <summary> /// Entry point for the application. /// </summary> /// <param name="args">Arguments to the application</param> public static void Main(string[] args) { TestEnum first = TestEnum.FirstElement; TestEnum second = TestEnum.SecondElement; TestEnum duplicate = TestEnum.Duplicate; foreach (string str in Enum.GetNames(typeof(TestEnum))) { Console.WriteLine("Name is: " + str); } Console.WriteLine("first string is: " + first.ToString()); Console.WriteLine("value is: " + ((int)first).ToString()); Console.WriteLine("second string is: " + second.ToString()); Console.WriteLine("value is: " + ((int)second).ToString()); Console.WriteLine("duplicate string is: " + duplicate.ToString()); Console.WriteLine("value is: " + ((int)duplicate).ToString()); TestEnum fromStr = (TestEnum)Enum.Parse(typeof(TestEnum), "duplicate", true); Console.WriteLine("fromstr string is: " + fromStr.ToString()); Console.WriteLine("value is: " + ((int)fromStr).ToString()); if (fromStr == TestEnum.Duplicate) { Console.WriteLine("Duplicate compares the same as FirstElement"); } else { Console.WriteLine("Duplicate does NOT compare the same as FirstElement"); } } } } ``` Which produces the following output: ``` Name is: SecondElement Name is: ThirdElement Name is: FirstElement Name is: Duplicate first string is: FirstElement value is: -1 second string is: SecondElement value is: 0 duplicate string is: FirstElement value is: -1 fromstr string is: FirstElement value is: -1 Duplicate compares the same as FirstElement Press any key to continue . . . ``` This seems to be EXACTLY what I want and expect since I'm constructing something that a version tag will increment every so often, so I want something that I can "assign" to the current version, and even compare to it. Here's the question though: what's the pitfalls of this approach? Is there one? Is it just bad style (I don't want to end up on thedailywtf)? Is there a lot better way of doing something like this? I'm on .NET 2.0 and do NOT have the option to go to 3.5 or 4.0. Opinions are welcome.
Its not clear what you're trying to achieve, but it doesn't look great to me. Adding another entry to the enum after 'Duplicate' for example will take the value 0 unless you explicitly set the value again.
Providing alias enum values can be useful if you have a flags enum. E.g. ``` [Flags] enum Rows { Even = 0x01, Odd = = 0x02, All = Even | Odd } ``` However, if you read the guidelines for enums in *Framework Design Guidelines* by Cwalina and Abrams you will find the following advice: > **DO NOT** use an enum for open sets (such as the operating system version, names of your friends etc.). and > **DO NOT** include sentinel values in enums. Having a *current version* is a sentinel value. These guidelines are for framework design and if you simply want to use the enum internally in your application it may not matter if you break these guidelines. However, Microsoft created these guidelines to avoid common pitfalls when other developers have to use your code.
C# Enumerations and Duplicate Values - dangers?
[ "", "c#", ".net-2.0", "enums", "" ]
I'm developing a simple 2D game in Java, everything works fine. To find the correct FPS refresh/redraw/update, I used currentTimeMillis to find the difference. The problem is that currentTimeMillis sometimes returns negative values, and the Thread.sleep will throw exception (java.lang.IllegalArgumentException: timeout value is negative) What I did was to put a while in my game and while currentTimeMillis <= -1 check again until its over, then sleep. Code sample: ``` private void gameLoop(){ // Find FPS long FPS = 40; long beginTime = System.currentTimeMillis(); while(beginTime < -1){ beginTime = System.currentTimeMillis(); } while(!done){ // Sleep try{ beginTime += FPS; long currTime = System.currentTimeMillis(); while(currTime < -1){ currTime = System.currentTimeMillis(); } difference = (beginTime - currTime); // Should be (currTime - beginTime) Thread.sleep(difference); }catch (Exception e){ e.printStackTrace(); } // RENDER GAME renderGame(); } JOptionPane.showMessageDialog(null, "Game Over\nYou Died."); System.exit(0); }// end gameLoop() ``` When the game starts, this works fine, but sometimes I still get the Exception. Is there a better way? I still think it´s strange that it´s returning a negative value.
Isn't the real problem that `beginTime-currTime` is negative ? ``` difference = (beginTime - currTime); Thread.sleep(difference); ``` I note that you add `FPS` (40) to `beginTime`. But if `currentTime` is greater than `beginTime+FPS`, you're going to have problems. If you're trying to schedule something at regular intervals (which I think you are), check out [Timer](http://java.sun.com/j2se/1.4.2/docs/api/java/util/Timer.html), which will allow you to do this more simply/reliably.
imho the following instruction: ``` difference = (beginTime - currTime); ``` should be: ``` difference = (currTime - beginTime); ``` currTime is always greater than beginTime, so difference is always negative or at least 0.
Java's currentTimeMillis returns negative value(s)
[ "", "java", "time", "" ]
Currently my GUI is Freezing when I try to display data I read from my socket. It's not freezing when i display one, or two messages, only when I receive many messages(2-3 per sec). I am using async socket(non blocking). I guess it's related to how I display the data to the gui. Code: ``` public class Globals { public static MainDialog myDialog; } public partial class MainDialog : Form { public MainDialog() { InitializeComponent(); Globals.myDialog = this; } public void sendText(string text) { logBox.AppendText(text); logBox.AppendText("\n"); } } ``` Then I simply call Globals.myDialog.sendText(..) from my network class. As I said it works fine, but not when I receive many messages at once. Anyone have an Idea?
Also remember to check for InvokeRequired when calling updates to gui controls from other threads.
Looking at the code, my guess is that your network class that reads the data from the socket is not on a seperate thread. I would use the [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) class to run the socket data on, then call ProgressChanged to bring data back to your GUI. [Here](http://msdn.microsoft.com/en-us/library/cc221403(VS.95).aspx) is a good example how to setup the BackgroundWorker to run a job and upate a GUI.
Windows Forms GUI Freezing while Using Socket
[ "", "c#", "winforms", "sockets", "" ]
I have a class whose constructor is defined as internal, which means I cannot instantiate it. While that may make sense, I would still like to do it once for debugging and research purposes. Is it possible to do so with Reflection? I know I can access Private/Internal Members, but can I call an internal constructor? Or, as the constructor does nothing important, can I use reflection to say "Look, just give me an instance of the class without calling the constructor, I'll do it's work manually"? Performance and "Stability" is not an issue here, as it's not production code. **Edit:** Just as clarification: Sadly, I don't control the other assembly and don't have it's source code, I merely try to understand how it works as it's documentation is next to non-existent, but I am supposed to interface with it.
A [FormatterServices.GetUninitializedObject](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatterservices.getuninitializedobject.aspx) method exists (Namespace: System.Runtime.Serialization), it supposedly calls no constructors, if you really want to try out that approach.
An alternative would be to nominate the calling assembly as a "friend" assembly. Simply add this to AssemblyInfo.cs file of the assembly containing the internal constructor: ``` [assembly: InternalsVisibleTo("Calling.Assembly")] ``` --- If you don't have access to the assembly, you can also call the constructor directly (using Reflection): ``` MyClass obj = (MyClass) typeof(MyClass).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null).Invoke(null); ```
Instancing a class with an internal constructor
[ "", "c#", ".net", "reflection", "" ]
*Updating by `@Cesar`'s request. Hope I understood what you want, if not, please revert. Quassnoi.* If I make an `SQL` query like this: `SELECT * FROM TABLE_NAME WHERE b IN (2, 7) AND c IN (3, 9)`, can I assume that `MySQL` will match only pairs from elements with same number in each list? That is, `(2, 3)`, `(7, 9)`, ...? For example, suppose we have a table like this: ``` +----------+----------+----------+ | PK | b | c | +----------+----------+----------+ | 1 | 2 | 3 | +----------+----------+----------+ | 2 | 5 | 4 | +----------+----------+----------+ | 3 | 7 | 9 | +----------+----------+----------+ | 4 | 7 | 4 | +----------+----------+----------+ | 5 | 2 | 9 | +----------+----------+----------+ ``` Is it correct to assume that the *only* rows returned are `1` and `3` (and not `5`)?
> ``` > SELECT * FROM TABLE_NAME WHERE b IN(5,7) AND c IN(4,4) > ``` This query will return rows, where `b` is either `5` or `7`, AND `c` is `4`. What do you mean by "evaluation in pairs?" **Update:** I'll add one more row to the sample: ``` +----------+----------+----------+ | PK | b | c | +----------+----------+----------+ | 1 | 2 | 3 | +----------+----------+----------+ | 2 | 5 | 4 | +----------+----------+----------+ | 3 | 7 | 9 | +----------+----------+----------+ | 4 | 7 | 4 | +----------+----------+----------+ | 5 | 2 | 9 | +----------+----------+----------+ ``` If you want to match the whole sets, you can use this syntax: ``` SELECT * FROM table_name WHERE (b, c) IN ((2, 3), (7, 9)) ``` This means: "return all rows where `b` is `2` and `c` is `3` at the same time, OR `b` is `7` and `с` is `9` at the same time." In the example above, this query will return rows `1` and `3` But if you rewrite this query the other way around, like this: ``` SELECT * FROM table_name WHERE b IN (2, 7) AND c IN (3, 9) ``` , this will mean "return all rows where `b` is either `2` or `7`, AND `c` is either `3` or `9`). This will return rows `1`, `3` and `5`, since row `5` satisfies the condition for the second query but not for the first one.
The return of rows 2 & 4 is correct, though your choice of (4,4) can make it a little more confusing, as it is redundant. The AND means that the row must satisfy both your conditions to be true. If the query had `WHERE b IN(5,7) AND c IN(4,9)`, you would get rows 2, 3, and 4 returned. If you think of it in pairs, you need to have all the combinations. e.g., `b IN(5,7) AND c IN(4,9)` would yield (5,4), (5,9), (7,4), and (7,9) as possible combinations that would work, and NOT just (5,4) and (7,9)
Evaluation of multiples 'IN' Expressions in 'WHERE' clauses in mysql
[ "", "sql", "mysql", "where-clause", "evaluation", "" ]
In the absence of a BOM is there a quick and dirty way in which I can check if a char\* buffer contains UTF8 characters?
Not reliably. See Raymond Chen's [series](https://devblogs.microsoft.com/oldnewthing/20040324-00/?p=40093) of [posts](https://devblogs.microsoft.com/oldnewthing/20070417-00/?p=27223) on the subject. The problem is that UTF-8 without a BOM is all too often indistinguishable from equally valid ANSI encoding. I think most solutions (like the win32 API [`IsTextUnicode`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-istextunicode)) use various heuristics to give a best guess to the format of the text.
You can test the hypothesis that it could, but I believe you can only end up knowing that it does not with certainty. In other words, you can examine the buffer to see if all byte sequences are legal UTF-8, that the code points are represented with the least number of bytes, that no 16-bit surrogate codes are present, and so forth. A buffer that passes all of those criteria might seem to be text, but you could be fooled. In addition to the Raymond Chen discussion at Old New Thing cited by Mark Pim's answer, the buffer could actually contain x86 machine code that just happens to be restricted to the subset that seems to be 7-bit printable ASCII. Amazingly you actually can write meaningful programs in that subset, one example of which is the [EICAR](http://www.eicar.org/anti_virus_test_file.htm) anti-virus test virus. Of course, a buffer that contains byte sequences that are malformed UTF-8 is probably not UTF-8 text at all. In that case, you have a high degree of confidence. Then the trick is to figure out what encoding it might actually be. If you know (or can assume) something about the semantic content of the buffer, then you could also use that to support your determination. For example, if the buffer is supposed to contain English text, then it is highly unlikely to have codepoints from Korean in it, and it should generally be spelled correctly, follow English grammar, and so forth. This can get expensive to test, of course...
Check if a char* buffer contains UTF8 characters?
[ "", "c++", "c", "utf-8", "" ]
I'm using the PHP [NumberFormatter](http://us.php.net/manual/en/class.numberformatter.php) class to print currency values. Eg: ``` $cFormatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY); $cFormatter->formatCurrency(123, 'USD'); $cFormatter->formatCurrency(123, 'BRL'); $cFormatter->formatCurrency(123, 'GBP'); ``` That works fine, and returns `"$123.00`", `"R$123.00`", `"£123.00`" respectively as expected. But negative numbers are printed "accountancy style", surrounded by brackets, instead of a leading minus "-". eg: ``` $cFormatter->formatCurrency(-456, 'USD'); ``` Returns `"($456.00)"`, whereas I want `"-$456.00"`. Surely there's a simple way of doing this? I can remove the brackets by override the prefix and postfix as follows: ``` $cFormatter->setTextAttribute(NumberFormatter::NEGATIVE_PREFIX, "-"); $cFormatter->setTextAttribute(NumberFormatter::NEGATIVE_SUFFIX, ""); ``` But then I get no currency symbol eg `"-456.00"`. Is there some escape code for the currency symbol that I need to use when setting the NEGATIVE\_PREFIX attribute? **Edit:** I'm happy to set a different locale if that gives me the result I'm looking for. **Edit 2:** Looking at the [Intl library docs](http://icu-project.org/apiref/icu4j/com/ibm/icu/text/DecimalFormat.html) (which is the library used to implement NumberFormatter), the following looked promising: > ¤ (\u00A4) : Prefix or suffix : No Currency sign, replaced by currency symbol. If doubled, replaced by international currency symbol. If tripled, replaced by currency plural names, for example, "US dollar" or "US dollars" for America. If present in a pattern, the monetary decimal separator is used instead of the decimal separator. But this: ``` $cFormatter->setTextAttribute(NumberFormatter::NEGATIVE_PREFIX, "-¤"); ``` Just prints "-¤123", so no joy. **Edit 3:** I think I found the answer, see below.
I've found a slightly less hacky way to bend the en\_US locale behaviour to what I'm looking for - the [getPattern()](https://www.php.net/manual/en/numberformatter.getpattern.php) / [setPattern()](https://www.php.net/manual/en/numberformatter.setpattern.php) functions. ``` $cFormatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY); $sPattern = $cFormatter->getPattern(); // returns "¤#,##0.00;(¤#,##0.00)"; $sMyPattern = "¤#,##0.00;-¤#,##0.00"; $cFormatter->setPattern($sMyPattern); $cFormatter->formatCurrency(-456, 'USD'); // returns -$456.00 ```
By doing so, you are kinda ruining the point of the localization. Since the ¤ represent the dollar sign and your are telling that your pattern always puts the sign in the beginning of the number, which is not the case for every currency. If you want to remove the parenthesis, I would go something more like, ``` $locale = 'en_US'; $nf = new \NumberFormatter($locale, \NumberFormatter::CURRENCY); $nf->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, $decimals); $pattern = str_replace(array('(',')'),'',$nf->getPattern()); $nf->setPattern($pattern); echo $nf->format($number); ```
How do I get NumberFormatter to print negative currency values with a minus sign?
[ "", "php", "currency", "numberformatter", "intl", "" ]
How to print an XML file to the screen in PHP? This is not working: ``` $curl = curl_init(); curl_setopt ($curl, CURLOPT_URL, 'http://rss.news.yahoo.com/rss/topstories'); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec ($curl); curl_close ($curl); $xml = simplexml_load_string($result); echo $xml; ``` Is there a simple solution? Maybe without SimpleXML?
You can use HTTP URLs as if they were local files, thanks to [PHP's wrappers](http://docs.php.net/manual/en/wrappers.php) You can get the contents from an URL via file\_get\_contents() and then echo it, or even read it directly using readfile() ``` $file = file_get_contents('http://example.com/rss'); echo $file; ``` or ``` readfile('http://example.com/rss'); ``` Don't forget to set the correct MIME type before outputing anything, though. ``` header('Content-type: text/xml'); ```
Here's what worked for me: ``` <pre class="prettyprint linenums"> <code class="language-xml"><?php echo htmlspecialchars(file_get_contents("example.xml"), ENT_QUOTES); ?></code> </pre> ``` Using [htmlspecialchars](http://php.net/manual/en/function.htmlentities.php) will prevent tags from being displayed as html and won't break anything. Note that I'm using [Prettyprint](http://code.google.com/p/google-code-prettify/) to highlight the code ;)
How to echo XML file in PHP
[ "", "php", "xml", "" ]
If I want to sort a vector of a UDT by one of two types of variables it holds, is it possible for the standard library sort to do this or do I need to write my own sort function. For example if you had ``` struct MyType{ int a; int b; }; vector<MyType> moo; // do stuff that pushes data back into moo sort(moo.begin(), moo.end()) // but sort it by lowest to highest for a, not b ``` So is this possible using the stdlib sort? Thanks.
It is possible to use standard function if your type implements `"bool operator < (...) const"` and a copy constructor (compiler-generated or custom). ``` struct MyType { int a; int b; bool operator < (const MyType& other) const { ... // a meaningful implementation for your type } // Copy constructor (unless it's a POD type). MyType(const MyType &other) : a(other.a), b(other.b) { } // Some other form of construction apart from copy constructor. MyType() : a(0), b(0) { } }; ``` Alternatively, you can pass an ordering function (or a functor) as a third argument to `sort()` instead of implementing operator `"<"`. ``` bool type_is_less(const MyType& t1, const MyType& t2) { ... } ... std::sort(c.begin(), c.end(), type_is_less); ``` This is useful in the following situations: 1. you don't want to implement operator `"<"` for whatever reason, 2. you need to sort a container of built-in or pointer types for which you can't overload operators. 3. you wish to sort the sequence using *different* orderings. ex: sometimes you want a struct with first/last name members sorted by first name, other times by last name. two different functions (or functors) make such options trivial.
There's three ways to do this: You could overload `operator<` for your class: ``` bool operator<(const MyType& lhs, const MyType& rhs) {return lhs.a<rhs.a;} ``` This has the disadvantage that, if you ever want to sort them according to `b`, you're out of luck. You could also specialize `std::less` for your type. That makes `std::sort` working (and other things, like using the type as a key in a map) without hijacking `operator<` for this meaning. It does, however, still hijack a general-purpose comparison syntax for `a`, while you might, at other places in your code, compare your type according to `b`. Or you could write your own comparator like this: ``` struct compare_by_a { bool operator()(const MyType& lhs, const MyType& rhs) const {return lhs.a<rhs.a;} }; ``` (Note: The `const` after the operator isn't strictly necessary. I still consider it good style, though.) This leaves the general-purpose means of comparison undefined; so if some code wants to use them without you being aware, the compile emits an error and makes you aware of it. You can use this or other comparators selectively and explicitly where ever you need comparison.
Standard library sort and user defined types
[ "", "c++", "" ]
I can currently place static points in the map window: ``` var latlng = new GLatLng(lat, lng); map.addOverlay(new GMarker(latlng, markerOptions)); ``` And I know how to get the bounds of the window. I can also code a page that will take the bounds and return the points that are inside them in any format. The problems I have now: 1. Does the `moveend` event capture all moves, including zoom changes? Or do I need to watch for that event separately? 2. How should I call my external datasource? (should I just do a JQuery `$.get` request?) 3. What should that datasource return? 4. How do I display that data on the map?
I'm using [this](http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/) in one of my sites. I think it's exactly what you are looking for. But be warned "gmaps-utility-library" plugins have some buggy/bad code so it's a good idea to go over it and double check if everything is working as it should (I haven't encountered any bugs in marker manager but in some other plugins from that library). Here's [reference](http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/1.1/docs/reference.html) and [examples](http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/1.1/docs/examples.html). Even if you want to code your own this one is probably a good starting point. EDIT My answer for 3-4: It really depends on situation. If it's static (you just need to manage a lot points on map > 300) then you could serve all points together with the page where the map is located in (as JavaScript array for example). If user interacts with data then probably it's better to use AJAX. If you use jQuery (or any other JS library) in your site then use ajax function from that library if not then go with the one which comes from gmaps. It's because it's nice to use same AJAX function in whole site instead of using 2 which does the same job. If you are taking AJAX path you have 2 options: 1. Load all markers for whole map in one request. 2. Load markers that shows up on user screen + small margin. If you expect that user wants to see the big picture or that he will want to see all/most of the points then go for option 1 + marker manager (like the one I recommended or your own similar). If there's really a lot of points and user will never be interested in most of them then go for option 2 + manager or just this simple algorithm: Clear map -> Request points for map window bounds + magin / (Cache) -> Draw points -> Repeat for each move/zoom. From personal experience (I've used both AJAX options) marker manager does quite nice job, can handle a lot points and overall user experience is a lot smoother then loading points for just viewport. Requesting new points and drawing them on map is quite laggy/choppy. Of course it depends on amount of points.
I'm currently doing something very similar to this, along with clustering on the server. 1. Yes, `moveend` will capture zoom changes. 2. If you're already using jQuery, a `$.get` request would work great. 3. I have tried returning both XML and JSON. These worked fine, but I discovered that parsing through these data formats caused the application to get significantly slower as more points were added to the database. I now return plain Javascript which I execute with eval(). I don't have a problem with this since I completely trust the source of the Javascript (me). 4. The Javascript function which adds a marker contains only the latitude, longitude, and id of the marker. The page already contains a Javascript array with all of the data for each marker, which can be accessed when the marker is clicked on. That's how I'm doing it, but you could certainly accompish what you want to do with a number of methods.
How do I dynamically add points to a Google Map when the bounds change?
[ "", "javascript", "jquery", "google-maps", "mapping", "dynamic-data", "" ]
I'm in the process of developing a simple 2d grid based sim game, and have fully functional path finding. I used the answer found in my previous question as my basis for implementing A\* path finding. ([Pathfinding 2D Java game?](https://stackoverflow.com/questions/735523/pathfinding-2d-java-game)). To show you really what I'm asking, I need to show you this video screen capture that I made. I was just testing to see how the person would move to a location and back again, and this was the result... <http://www.screenjelly.com/watch/Bd7d7pObyFo> Different choice of path depending on the direction, an unexpected result. Any ideas?
If you're looking for a simple-ish solution, may I suggest a bit of randomization? What I mean is this: in the cokeandcode code example, there is the nested-for-loops that generate the "successor states" (to use the AI term). I refer to the point where it loops over the 3x3 square around the "current" state, adding new locations on the pile to consider. A relatively simple fix would (should :)) be isolate that code a bit, and have it, say, generated a linkedlist of nodes before the rest of the processing step. Then Containers.Shuffle (or is it Generics.Shuffle?) that linked list, and continue the processing there. Basically, have a routine say, "createNaiveNeighbors(node)" that returns a LinkedList = {(node.x-1,node.y), (node.x, node.y-1)... } (please pardon the pidgin Java, I'm trying (and always failing) to be brief. Once you build the linked list, however, you should just be able to do a "for (Node n : myNewLinkedList)" instead of the ``` for (int x=-1;x<2;x++) { for (int y=-1;y<2;y++) { ``` And still use the exact same body code! What this would do, ideally, is sort of "shake up" the order of nodes considered, and create paths closer to the diagonal, but without having to change the heuristic. The paths will still be the most efficient, but *usually* closer to the diagonal. The downside is, of course, if you go from A to B multiple times, a different path may be taken. If that is unnacceptable, you may need to consider a more drastic modification. Hope this helps! -Agor
Both of the paths are of the same length, so the algorithm is doing its job just fine - it's finding a shortest path. However the A\* algorithm doesn't specify WHICH shortest path it will take. Implementations normally take the "first" shortest path. Without seeing yours, it's impossible to know exactly why, but if you want the same results each time you're going to have to add priority rules of some sort (so that you're desired path comes up first in the search).
Why does A* path finding sometimes go in straight lines and sometimes diagonals? (Java)
[ "", "java", "artificial-intelligence", "a-star", "path-finding", "" ]
Suppose I have this (outrageously) simplified XML schema: ``` <xsd:complexType name="Person"> <xsd:sequence> <xsd:element ref="FirstName"/> <xsd:element ref="FamilyName"/> </xsd:sequence> </xsd:complexType> ``` If I generate a Java class from it I get something like this: ``` public class Person { protected FirstName firstName; protected FamilyName familyName; // and the usual getters and setters } ``` This class smells awfully like a [Data Class](http://wiki.java.net/bin/view/People/SmellsToRefactorings) and I'd like to add behavior to it. Extending it appears to me as the most obvious solution, but can I always count on such Java classes to be safely extensible? Will it always be safe to do? A related question: how would you name the augmented class? Would you give it the same name as the original class but in another package? Would you call it something like `MyPerson`?
Mixing auto-generated with hand-crafted code always smells for trouble. If the schema is altered and the class re-generated, your own custom class will break. I would avoid extending the auto-generated class. If you do need to add functionality to it, prefer composition over inheritance. That means create a MyPerson class that includes a Person as a field object. If the xml schema is modified and the Person class re-generated, then MyPerson class will again break, but: * With carefully design the breaking changes won't affect code outside the MyPerson class. If you opt for inheritance and a method changes its name, you would need to make changes in all the callers of your class. * It will be easier to fix the breaking changes. The compiler will give you clear descriptions of the missing methods.
If you want to do this kind of thing, I suggest that you take a good look at the [Eclipse Modelling Framework (EMF)](http://eclipse.org/modeling/emf/). The EMF toolset can take an XSD and use it to extract an EMF model and then generate Java classes. **You can modify the generated classes** and provided you follow a simple rule, your modifications will not be lost when you change the XSD / Model and regenerate the classes. Each modifiable member declaration in the generated code is preceded by a Java comment which marks the member as generated. If you want to modify a member, you remove this comment and make your changes. Next time you regenerate, the generator performs a member by member comparison of the old and new versions of each class, looking for members whose signatures match, and updating them depending on the presence of the "generated" marker comments in the "old" version. This works surprisingly well. You occasionally have to do a bit of manual tidyup (e.g. to remove imports that are no longer required) but provided you remembered to delete the marker comments you won't lose your changes. (But it is a good idea to check in the generated code anyway ... if only to version control your changes!) If you don't like the code that EMF generates, you there are many code generation options you can tweak in your Model's associated GenModel, or you can modify or replace the JET templates that comprise the EMF source code generator. In addition to generating the classes that represent your XML in memory, EMF gives you an XML serializer / deserializer and an extensible / tailorable GUI based editor for your data structures. Related EMF projects include facilities for persisting your data into databases, augmenting your Model with validation rules, transactions, queries and comparisons. And there much more in the related Eclipse Modelling projects. There is a whole stack of white-papers, tutorials and other documentation on the [EMF documents](http://www.eclipse.org/modeling/emf/docs/) page
Is it safe to extend classes generated from an XML schema?
[ "", "java", "oop", "schema", "" ]
Is there any event in Internet Explorer, that is fired whenever DOM is changed? For example: ``` document.attachEvent("ondocumentchange", function () { alert("you've just changed DOM!"); }); ``` And when I execute: ``` document.appendChild(document.createElement("img")); ``` Window with text "you've just changed DOM!" appears. I try to emulate "advanced" CSS selectors (e.g. +, >, [attr]) in IE6 using Javascript. However to work properly with dynamic content, they would have to be recalculated after each change in document.
Brute-force "solution": ``` (function (previousInnerHTML) { return function () { if (document.body.innerHTML !== previousInnerHTML) { alert("you've just (at max 33ms ago) changed DOM"); } setTimout(arguments.callee, 33); }; })(document.body.innerHTML)(); ```
You want to look at dom mutation events - see <http://en.wikipedia.org/wiki/DOM_Events>, and scroll down to the section on mutation events. Only problem is that support for these events is pretty sketchy, so be careful using them. Notably, a lack of support at all in IE or Opera. Firefox, Safari and Chrome seem to be the only ones. Something like: ``` document.addEventListener("DOMSubtreeModified", function () { alert("you've just changed DOM!"); }); ``` According to <http://www.quirksmode.org/dom/events/index.html> for these kind of events you need to use addEventListener, not attachEvent. The event apparently bubbles, so that should be fine.
Is there any onDocumentChange event?
[ "", "javascript", "internet-explorer", "events", "" ]
Which Operating System is the best for PHP development or Development in General? 1) Linux Mint? 2) Ubuntu? 3) Windows 7? 4) OS?
There are four possibilities for the best operating system to develop on: 1. The one you're most familiar with. Familiarity breeds productivity; 2. The one everyone else on your team uses. You can create problems by being different; 3. The one your tools are available on. Sometimes you don't have a choice; and 4. The one your production environment is on. I've seen problems caused before because the dev environment was on Windows and the production environment was Linux. This was with Java. As similar as they can be there can be subtle differences that can bite you badly. PHP is another good example of being quite different on Windows vs Linux. The one thing I'll add to this is that, of any OS-specific features I can think of, the one that can really matter is filesystem. Once I went a 20 minute subversion checkout on WinXP/NTFS with putty (svn+ssh) to 40 seconds on Ubuntu/ext3. Build time also dropped from 15 minutes to ~3 minutes. In both cases that was nearly all filesystem.
Whatever your most familiar with and like the best. It is really a personal decision about how you like to work and the tools you like to work with. It can also depend on the team that your working with. If you have a specific IDE that the team uses, it may help to use the same IDE they are using. One of the great things about PHP is that you can develop almost anywhere with a large variety of tools.
Which Operating System is the best for PHP development or Development in General?
[ "", "php", "development-environment", "" ]
In multi-thread environment, in order to have thread safe array element swapping, we will perform synchronized locking. ``` // a is char array. synchronized(a) { char tmp = a[1]; a[1] = a[0]; a[0] = tmp; } ``` Is it possible that we can make use of the following API in the above situation, so that we can have a lock free array element swapping? If yes, how? <http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.html#compareAndSet%28T,%20V,%20V%29>
Regardless of API used you won't be able to achieve both thread-safe and lock-free array element swapping in Java. The element swapping requires multiple read and update operations that need to be performed atomically. To simulate the atomicity you need a lock. EDIT: An alternative to lock-free algorithm might be micro-locking: instead of locking the entire array it’s possible to lock only elements that are being swapped. The value of this approach fully is questionable. That is to say if the algorithm that requires swapping elements can guarantee that different threads are going to work on different parts of the array then no synchronisation required. In the opposite case, when different threads can actually attempt swapping overlapping elements then thread execution order will matter. For example if one thread tries to swap elements 0 and 1 of the array and the other simultaneously attempts to swap 1 and 2 then the result will depend entirely on the order of execution, for initial {‘a’,’b’,’c’} you can end up either with {‘b’,’c’,’a’} or {‘c’,’a’,’b’}. Hence you’d require a more sophisticated synchronisation. Here is a quick and dirty class for character arrays that implements micro locking: ``` import java.util.concurrent.atomic.AtomicIntegerArray; class SyncCharArray { final private char array []; final private AtomicIntegerArray locktable; SyncCharArray (char array[]) { this.array = array; // create a lock table the size of the array // to track currently locked elements this.locktable = new AtomicIntegerArray(array.length); for (int i = 0;i<array.length;i++) unlock(i); } void swap (int idx1, int idx2) { // return if the same element if (idx1==idx2) return; // lock element with the smaller index first to avoid possible deadlock lock(Math.min(idx1,idx2)); lock(Math.max(idx1,idx2)); char tmp = array[idx1]; array [idx1] = array[idx2]; unlock(idx1); array[idx2] = tmp; unlock(idx2); } private void lock (int idx) { // if required element is locked when wait ... while (!locktable.compareAndSet(idx,0,1)) Thread.yield(); } private void unlock (int idx) { locktable.set(idx,0); } } ``` You’d need to create the SyncCharArray and then pass it to all threads that require swapping: ``` char array [] = {'a','b','c','d','e','f'}; SyncCharArray sca = new SyncCharArray(array); // then pass sca to any threads that require swapping // then within a thread sca.swap(15,3); ``` Hope that makes some sense. UPDATE: Some testing demonstrated that unless you have a great number of threads accessing the array simulteniously (100+ on run-of-the-mill hardware) a simple synchronise (array) {} works much faster than the elaborate synchronisation.
``` // lock-free swap array[i] and array[j] (assumes array contains not null elements only) static <T> void swap(AtomicReferenceArray<T> array, int i, int j) { while (true) { T ai = array.getAndSet(i, null); if (ai == null) continue; T aj = array.getAndSet(j, null); if (aj == null) { array.set(i, ai); continue; } array.set(i, aj); array.set(j, ai); break; } } ```
Lock Free Array Element Swapping
[ "", "java", "multithreading", "concurrency", "locking", "deadlock", "" ]
I have a tomcat 6.20 instance running, and would like to send an email via a background thread to prevent the email sending function from blocking the request. Is there any way I can execute the thread in the background, while still allowing normal page flow to occur. The application is written in ICEfaces. Thanks.
1. Create an `Executor` using `java.util.concurrent.Executors.newCachedThreadPool` (or one of the other factory methods) in your controller/servlet's initialization method. 2. When a request comes in, wrap the mail-sending logic in a `java.lang.Runnable` 3. Submit the `Runnable` to the `Executor` This will perform the sending in the background. Remember to create a single Executor at startup, and share across all the requests; don't create a new Executor every time (you could, but it would be a bit slow and wasteful).
Put your email sending in place of `Thread.sleep()`. Put your output in place of `sendRedirect()`. ``` public void doUrlRequest(HttpServletRequest request, HttpServletResponse response) { try { response.sendRedirect("/home"); } catch (IOException e) { CustomLogger.info(TAG, "doUrlRequest", "doUrlRequest(): "+e.getMessage()); } (new Thread() { public void run() { try { Thread.sleep(9000); System.out.println("Awoken!"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); ```
tomcat background threads
[ "", "java", "tomcat", "tomcat6", "background-process", "" ]
Im not proficient in JS myself very much, so it would probably take me a few hours to figure this out myself, so I figured I'd ask you guys. I have Delete/Ban links on my site, that are used by admins to moderate the users and what they post. Since these links have such drastic consequences on the site's content I would want to have some sort of confirmation that would popup when one of the links is clicked. It should have some extra text explaining what's about to happen, and OK/Cancel buttons. So I have a link, for example like this: ``` <a href="ban.php?id=123" class="confirm_ban">Ban John</a> <a href="delete.php?id=123" class="confirm_delete">Delete Post</a> ``` When this link is clicked, the code needs to be triggered. If OK is pressed, it goes to ban.php?id=123, if Cancel is pressed, it doesn't go anywhere. A simple JS dialog box, will do. Or if you have a link for a fancy jquery powered box, you can point me towards that also. Thanks!
Easiest way to achieve this is to use the `confirm()` function: ``` var confirmed = confirm('Do you really want to do this?'); if(confirmed) { //Do dangerous action } ``` It basically displays a box with the text you provide and ok and cancel buttons. With a link you can do something like this: ``` <a href="someurl" onclick="return confirm('Are you sure?');"> ``` It's not best possible practices to put the action in the onclick like that, but it works and is simple to understand even if you're not a pro javascripter
I think you're looking for something like "confirm delete". The Confirm function takes as an input a string parameter. It displays a dialog box whose message is that parameter, with OK and Cancel buttons. If the user clicks OK, the confirm function returns True; if the user clicks Cancel False is returned. Here's an example of using it: ``` function fConfirmDelete() { if(confirm("Delete Field?")) { document.forms[0].lblFieldSelect.value="DELETE"; document.forms[0].submit(); } else { document.forms[0].lblFieldSelect.value=""; } return; } ```
How can I implement a confirmation dialog for critical action?
[ "", "javascript", "" ]
I have a foreach block where I want to plot out for trace-debug purposes the index of the step inside the foreach. As a C# newbie I do it as follows: ``` int i = 1; foreach (x in y) { ... do something ... WriteDebug("Step: "+i.ToString()); i++; } ``` I wondered if there's any way to get the value of the current step's index without explicitly creating a variable for that purpose. EDIT: To clarify, I'm obviously familiar with the option of a for loop, however it's not an array I'm going through but rather an unordered collection. The reason for the numbering is just for the purpose of showing progress in the debug level and nothing else.
No, there is not. This is an instance where you're better off using a basic for loop ``` for(int i = 0; i < y.Count; i++) { } ``` rather than a for each loop **EDIT**: In response to askers clarification. If you're iterating through an enumerator with no size property (such as length or count), then your approach is about as clear as you can get. **Second Edit** Given me druthers I'd take Marc's answer using select to do this these days.
Contrary to a few other answers, I would be perfectly happy to mix `foreach` with a counter (as per the code in the question). This retains your ability to use `IEnumerable[<T>]` rather than requiring an indexer. But if you want, in LINQ: ``` foreach (var pair in y.Select((x,i) => new {Index = i,Value=x})) { Console.WriteLine(pair.Index + ": " + pair.Value); } ``` (the counter approach in the question is a lot simpler and more effecient, but the above should map better to a few scenarios like Parallel.ForEach).
C# newbie: find out the index in a foreach block
[ "", "c#", "foreach", "" ]
While updating for loops to for-each loops in our application, I came across a lot of these "patterns": ``` for (int i = 0, n = a.length; i < n; i++) { ... } ``` instead of ``` for (int i = 0; i < a.length; i++) { ... } ``` I can see that you gain performance for collections because you don't need to call the *size()* method with each loop. But with arrays?? So the question arose: is `array.length` more expensive than a regular variable?
No, a call to `array.length` is `O(1)` or constant time operation. Since the `.length` is(acts like) a `public` `final` member of `array`, it is no slower to access than a local variable. (It is very different from a call to a method like `size()`) A modern JIT compiler is likely to optimize the call to `.length` right out anyway. You can confirm this by either looking at the source code of the JIT compiler in OpenJDK, or by getting the JVM to dump out the JIT compiled native code and examining the code. Note that there may be cases where the JIT compiler can't do this; e.g. 1. if you are debugging the enclosing method, or 2. if the loop body has enough local variables to force register spilling.
I had a bit of time over lunch: ``` public static void main(String[] args) { final int[] a = new int[250000000]; long t; for (int j = 0; j < 10; j++) { t = System.currentTimeMillis(); for (int i = 0, n = a.length; i < n; i++) { int x = a[i]; } System.out.println("n = a.length: " + (System.currentTimeMillis() - t)); t = System.currentTimeMillis(); for (int i = 0; i < a.length; i++) { int x = a[i]; } System.out.println("i < a.length: " + (System.currentTimeMillis() - t)); } } ``` The results: ``` n = a.length: 672 i < a.length: 516 n = a.length: 640 i < a.length: 516 n = a.length: 656 i < a.length: 516 n = a.length: 656 i < a.length: 516 n = a.length: 640 i < a.length: 532 n = a.length: 640 i < a.length: 531 n = a.length: 641 i < a.length: 516 n = a.length: 656 i < a.length: 531 n = a.length: 656 i < a.length: 516 n = a.length: 656 i < a.length: 516 ``` Notes: 1. If you reverse the tests, then `n = a.length` shows as being faster than `i < a.length` by about half, probably due to garbage collection(?). 2. I couldn't make `250000000` much larger because I got `OutOfMemoryError` at `270000000`. The point is, and it is the one everyone else has been making, you have to run Java out of memory and you still don't see a significant difference in speed between the two alternatives. Spend your development time on things that actually matter.
What is the Cost of Calling array.length
[ "", "java", "arrays", "premature-optimization", "" ]
I am building a C# application that exports a CSV file to be used with the Visio org chart wizard. How can I check that an installation of Visio exists, and what path? The most obvious method is checking if `C:\Program Files\Office12\ORGWIZ.EXE` exists, but that is fairly dependant on having Visio 2007 installed.. My other thought is checking the registry, but what is the most reliable source? I've looked under `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\` where there are version numbers, but underneath them is a `Visio\InstallRoot` which would be perfect except for checking each versions.. I read elsewhere that I could check Uninstall information under `Software\Microsoft\Windows\CurrentVersion\Uninstall\`, but that looks fairly complicated for Windows components...
I would do a lookup for HKEY\_CLASSES\_ROOT\Visio.Application in the registry. If it doesn't exist, no install. If it does exist, the CurVer sub key will give you something like Visio.Application.12 That tells you the DEFAULT version that is installed (might be others) HKEY\_CLASSES\_ROOT\Visio.Application.12 Sub Key CLSID will give you a guid: {00021A20-0000-0000-C000-000000000046} HKEY\_CLASSES\_ROOT\CLSID{00021A20-0000-0000-C000-000000000046} in turn will give you Sub Key "LocalServer32" Which will contain the path to the EXE. C:\PROGRA~1\MICROS~4\Office12\VISIO.EXE /Automation As you can see, in my case it has the short path form.
Here is my solution, based on [Roger's](https://stackoverflow.com/questions/1085214/how-do-i-programatically-check-if-visio-is-installed-and-where/1085252#1085252 "Roger's") answer: ``` RegistryKey regVersionString = Registry.ClassesRoot.OpenSubKey("Visio.Drawing\\CurVer"); Console.WriteLine("VERSION: " + regVersionString.GetValue("")); RegistryKey regClassId = Registry.ClassesRoot.OpenSubKey(regVersionString.GetValue("") + "\\CLSID"); Console.WriteLine("CLSID: " + regClassId.GetValue("")); RegistryKey regInstallPath = Registry.ClassesRoot.OpenSubKey("CLSID\\" + regClassId.GetValue("") + "\\LocalServer32"); Console.WriteLine("PATH: " + regInstallPath.GetValue("")); ```
How do I programatically check if Visio is installed, and where?
[ "", "c#", "registry", "ms-office", "visio", "" ]
I have a page that is inherited from WebPage and is protected by class below: ``` public final class WiaAuthorizationStrategy implements IAuthorizationStrategy, IUnauthorizedComponentInstantiationListener { private RealmPolicy roleManager; private static WiaAuthorizationStrategy instance; private WiaAuthorizationStrategy() { roleManager = RealmPolicy.getInstance(); } public static WiaAuthorizationStrategy getInstance() { if(instance == null) instance = new WiaAuthorizationStrategy(); return instance; } public boolean isInstantiationAuthorized(Class componentClass) { if (ProtectedPage.class.isAssignableFrom(componentClass)) { if (WiaSession.get().getUser() == null) { return false; } if(!roleManager.isAuthorized(WiaSession.get().getUser().getRole(), componentClass.getName()))//WiaSession.get().isAuthenticated(); { WiaSession.get().setAccess(false); return false; } else return true; } return true; } public void onUnauthorizedInstantiation(Component component) { throw new RestartResponseAtInterceptPageException( Login.class); } public boolean isActionAuthorized(Component component, Action action) { //System.out.println("Name:" + component.getClass().getName() + "\n Action:" + action.getName() + "\nUser:" + WiaSession.get().getUser()); if (action.equals(Component.RENDER)) { if (roleManager.containClass(component.getClass().getName())) { if (WiaSession.get().getUser() != null) { if(!roleManager.isAuthorized(WiaSession.get().getUser().getRole(), component.getClass().getName())) { WiaSession.get().setAccess(false); return false; } return true; } return false; } } return true; } } ``` when I enter that page it is ok and everything works but when I press Ctrl+F5 the page redirect to Login Page which is default for entring protected pages. I tried to debug the code and I found that the super() function in ProtectedPage class do this and in debugging I cannot enter this part of code. this class exists below: ``` public abstract class ProtectedPage extends WebPage { public ProtectedPage() { ``` ---->>> super(); verifyAccess(); } ``` protected void verifyAccess() { // Redirect to Login page on invalid access. if (!isUserLoggedIn()) { throw new RestartResponseAtInterceptPageException(Login.class); } } protected boolean isUserLoggedIn() { return ((WiaSession) getSession()).isAuthenticated(); } } ``` I have signed that by ---->>> sign in the code. Can anyone help me with this problem?
Don't use something like verifyAccess when you have a IAuthorizationStrategy installed; the latter should do the whole job for you.
what is ctrl+F5 supposed to do? do you have some keybinding issues? You can't do a redirect? What's your problem exactly?
Redirection problem in Java(Wicket)
[ "", "java", "frameworks", "wicket", "" ]
I'm using this REST web service, which returns various templated strings as urls, for example: ``` "http://api.app.com/{foo}" ``` In Ruby, I can then use ``` url = Addressable::Template.new("http://api.app.com/{foo}").expand('foo' => 'bar') ``` to get ``` "http://api.app.com/bar" ``` Is there any way to do this in Python? I know about %() templates, but obviously they're not working here.
Don't use a quick hack. What is used there (and implemented by Addressable) are [URI Templates](http://bitworking.org/projects/URI-Templates/spec/draft-gregorio-uritemplate-03.html). There seem to be several libs for this in python, for example: [uri-templates](http://code.google.com/p/uri-templates/). [described\_routes\_py](http://github.com/asplake/described_routes-py/tree/master) also has a parser for them.
In python 2.6 you can do this if you need exactly that syntax ``` from string import Formatter f = Formatter() f.format("http://api.app.com/{foo}", foo="bar") ``` If you need to use an earlier python version then you can either copy the 2.6 formatter class or hand roll a parser/regex to do it.
Python string templater
[ "", "python", "ruby", "templates", "string", "" ]
I have the classic problem of a thread pushing events to the incoming queue of a second thread. Only this time, I am very interested about performance. What I want to achieve is: * I want concurrent access to the queue, the producer pushing, the receiver poping. * When the queue is empty, I want the consumer to block to the queue, waiting for the producer. My first idea was to use a `LinkedBlockingQueue`, but I soon realized that it is not concurrent and the performance suffered. On the other hand, I now use a `ConcurrentLinkedQueue`, but still I am paying the cost of `wait()` / `notify()` on each publication. Since the consumer, upon finding an empty queue, does not block, I have to synchronize and `wait()` on a lock. On the other part, the producer has to get that lock and `notify()` upon every single publication. The overall result is that I am paying the cost of `sycnhronized (lock) {lock.notify()}` in every single publication, even when not needed. What I guess is needed here, is a queue that is both blocking and concurrent. I imagine a `push()` operation to work as in `ConcurrentLinkedQueue`, with an extra `notify()` to the object when the pushed element is the first in the list. Such a check I consider to already exist in the `ConcurrentLinkedQueue`, as pushing requires connecting with the next element. Thus, this would be much faster than synchronizing every time on the external lock. Is something like this available/reasonable?
I think you can stick to `java.util.concurrent.LinkedBlockingQueue` regardless of your doubts. It is concurrent. Though, I have no idea about its performance. Probably, other implementation of `BlockingQueue` will suit you better. There's not too many of them, so make performance tests and measure.
Similar to this answer <https://stackoverflow.com/a/1212515/1102730> but a bit different.. I ended up using an `ExecutorService`. You can instantiate one by using `Executors.newSingleThreadExecutor()`. I needed a concurrent queue for reading/writing BufferedImages to files, as well as atomicity with reads and writes. I only need a single thread because the file IO is orders of magnitude faster than the source, net IO. Also, I was more concerned about atomicity of actions and correctness than performance, but this approach can also be done with multiple threads in the pool to speed things up. To get an image (Try-Catch-Finally omitted): ``` Future<BufferedImage> futureImage = executorService.submit(new Callable<BufferedImage>() { @Override public BufferedImage call() throws Exception { ImageInputStream is = new FileImageInputStream(file); return ImageIO.read(is); } }) image = futureImage.get(); ``` To save an image (Try-Catch-Finally omitted): ``` Future<Boolean> futureWrite = executorService.submit(new Callable<Boolean>() { @Override public Boolean call() { FileOutputStream os = new FileOutputStream(file); return ImageIO.write(image, getFileFormat(), os); } }); boolean wasWritten = futureWrite.get(); ``` It's important to note that you should flush and close your streams in a finally block. I don't know about how it performs compared to other solutions, but it is pretty versatile.
Concurrent and Blocking Queue in Java
[ "", "java", "queue", "blocking", "concurrency", "" ]
I'm linking a C++ source with a C source and a C++ source. I create a thread with pthread, a cancellation point and then I call pthread\_exit either through the C or the C++ source file. If the pthread\_exit call comes from the C source, the cancellation handler does not fire! What may be the reason for this? b.cc: ``` #include <cstdio> #include <cstdlib> #include <stdbool.h> #include <pthread.h> extern "C" void V(); extern "C" void Vpp(); extern "C" void Vs(); #define PTHREAD_EXIT Vs void cleanup(void*v) { fprintf(stderr, "Aadsfasdf\n"); exit(0); } void* f(void*p) { pthread_cleanup_push(cleanup, NULL); PTHREAD_EXIT(); pthread_cleanup_pop(true); return NULL; } int main() { pthread_t p; if (pthread_create(&p, NULL, f, NULL)) abort(); for(;;); } ``` vpp.cc: ``` #include <pthread.h> extern "C" void Vpp(); void Vpp() { pthread_exit(0); } ``` v.c: ``` #include <pthread.h> void V() { pthread_exit(0); } ``` vs.s: ``` .text Vs: .global Vs call pthread_exit spin: jmp spin ``` compilation with ``` g++ -c vpp.cc -g -o vpp.o -Wall gcc -c v.c -g -o v.o -Wall as vs.s -o vs.o g++ b.cc vpp.o v.o vs.o -o b -lpthread -g -Wall ``` If PTHREAD\_EXIT is Vpp the program displays a message and terminates, if it is V or Vs it doesn't. the disassembly for V and Vpp is identical, and changing the definition of PTHREAD\_EXIT between V and Vpp merely changes between `call V` and `call Vpp` in the disassembly. EDIT: Not reproducible on another computer, so I guess I hit an error in the library or something.
Inspired by Ch. Vu-Brugier I took a look at `pthread.h` and found out that I have to add ``` #undef __EXCEPTIONS ``` before including `pthread.h`. This is a satisfactory workaround for my current needs.
In the "pthread.h" header file installed on my machine, the pthread\_cleanup\_push() function is not defined the same way for C and C++ (search for \_\_cplusplus). Could you try to give C linkage for both f() and cleanup()? You may find the above link interesting: <http://www.cs.rit.edu/~afb/20012/cs4/slides/threads-05.html>
cancellation handler won't run if pthread_exit called from C source instead of C++ source
[ "", "c++", "c", "pthreads", "" ]