qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
100,860
<p>As most of you would know, if I drop a file named app_offline.htm in the root of an asp.net application, it takes the application offline <a href="http://asp-net-whidbey.blogspot.com/2006/04/aspnet-20-features-appofflinehtm.html" rel="nofollow noreferrer">as detailed here</a>.</p> <p>You would also know, that while this is great, IIS actually returns a 404 code when this is in process and Microsoft is not going to do anything about it <a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=319986" rel="nofollow noreferrer">as mentioned here</a>.</p> <p>Now, since Asp.Net in general is so extensible, I am thinking that shouldn't there be a way to over ride this status code to return a 503 instead? The problem is, I don't know where to start looking to make this change.</p> <p>HELP!</p>
[ { "answer_id": 100881, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 1, "selected": false, "text": "<p>You can try turning it off in the web.config.</p>\n\n<pre><code>&lt;httpRuntime enable = \"False\"/&gt;\n</code></pre>\n...
2008/09/19
[ "https://Stackoverflow.com/questions/100860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380/" ]
As most of you would know, if I drop a file named app\_offline.htm in the root of an asp.net application, it takes the application offline [as detailed here](http://asp-net-whidbey.blogspot.com/2006/04/aspnet-20-features-appofflinehtm.html). You would also know, that while this is great, IIS actually returns a 404 code when this is in process and Microsoft is not going to do anything about it [as mentioned here](https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=319986). Now, since Asp.Net in general is so extensible, I am thinking that shouldn't there be a way to over ride this status code to return a 503 instead? The problem is, I don't know where to start looking to make this change. HELP!
The handling of app\_offline.htm is hardcoded in the ASP.NET pipeline, and can't be modified: see `CheckApplicationEnabled()` in `HttpRuntime.cs`, where it throws a very non-configurable 404 error if the application is deemed to be offline. However, [creating your own HTTP module](http://support.microsoft.com/kb/307996) to do something similar is of course trivial -- the OnBeginRequest handler could look as follows in this case (implementation for a HttpHandler shown, but in a HttpModule the idea is exactly the same): ``` Public Sub ProcessRequest(ByVal ctx As System.Web.HttpContext) Implements IHttpHandler.ProcessRequest If IO.File.Exists(ctx.Server.MapPath("/app_unavailable.htm")) Then ctx.Response.Status = "503 Unavailable (in Maintenance Mode)" ctx.Response.Write(String.Format("<html><h1>{0}</h1></html>", ctx.Response.Status)) ctx.Response.End() End If End Sub ``` This is just a starting point, of course: by making the returned HTML a bit friendlier, you can display a nice "we'll be right back" page to your users as well.
100,898
<p>What's the best / simplest / most accurate way to detect the browser of a user?</p> <p>Ease of extendability and implementation is a plus.</p> <p>The less technologies used, the better.</p> <p>The solution can be server side, client side, or both. The results should eventually end up at the server, though.</p> <p>The solution can be framework agnostic.</p> <p>The solution will only be used for reporting purposes.</p>
[ { "answer_id": 100908, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"http://jquery.thewikies.com/browser/\" rel=\"noreferrer\">JQuery Browser Plugin</a> will do it client-side ...
2008/09/19
[ "https://Stackoverflow.com/questions/100898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681/" ]
What's the best / simplest / most accurate way to detect the browser of a user? Ease of extendability and implementation is a plus. The less technologies used, the better. The solution can be server side, client side, or both. The results should eventually end up at the server, though. The solution can be framework agnostic. The solution will only be used for reporting purposes.
On the server you're pretty much limited to the UserAgent string the browser provides (which is fraught with problems, have a read about the [UserAgent string's history](http://www.webaim.org/blog/user-agent-string-history/)). On the client (ie in Javascript), you have more options. But the best option is to not actually worry about working out which browser it is. Simply check to make sure whatever feature you want to use actually exists. For example, you might want to use setCapture, which only MSIE provides: ``` if (element.setCapture) element.setCapture() ``` Rather than working out what the browser is, and then inferring its capabilities, we're simply seeing if it supports something before using it - who knows what browsers will support what in the future, do you really want to have to go back and update your scripts if Safari decides to support setCapture?
100,904
<p>Per man pages, snprintf is returning number of bytes written from glibc version 2.2 onwards. But on lower versions of libc2.2 and HP-UX, it returns a positive integer, which could lead to a buffer overflow.</p> <p>How can one overcome this and write portable code?</p> <p>Edit : For want of more clarity</p> <p>This code is working perfectly in lib 2.3</p> <pre><code> if ( snprintf( cmd, cmdLen + 1, ". %s%s", myVar1, myVar2 ) != cmdLen ) { fprintf( stderr, "\nError: Unable to copy bmake command!!!"); returnCode = ERR_COPY_FILENAME_FAILED; } </code></pre> <p>It returns the length of the string (10) on Linux. But the same code is returning a positive number that is greater than the number of characters printed on HP-UX machine. Hope this explanation is fine.</p>
[ { "answer_id": 100936, "author": "finnw", "author_id": 12048, "author_profile": "https://Stackoverflow.com/users/12048", "pm_score": 0, "selected": false, "text": "<p>I have found one portable way to predict and/or limit the number of characters returned by sprintf and related functions,...
2008/09/19
[ "https://Stackoverflow.com/questions/100904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18657/" ]
Per man pages, snprintf is returning number of bytes written from glibc version 2.2 onwards. But on lower versions of libc2.2 and HP-UX, it returns a positive integer, which could lead to a buffer overflow. How can one overcome this and write portable code? Edit : For want of more clarity This code is working perfectly in lib 2.3 ``` if ( snprintf( cmd, cmdLen + 1, ". %s%s", myVar1, myVar2 ) != cmdLen ) { fprintf( stderr, "\nError: Unable to copy bmake command!!!"); returnCode = ERR_COPY_FILENAME_FAILED; } ``` It returns the length of the string (10) on Linux. But the same code is returning a positive number that is greater than the number of characters printed on HP-UX machine. Hope this explanation is fine.
you could create a snprintf wrapper that returns -1 for each case when there is not enough space in the buffer. See the [man page](http://linux.die.net/man/3/snprintf) for more docs. It has also an example which threats all the cases. ``` while (1) { /* Try to print in the allocated space. */ va_start(ap, fmt); n = vsnprintf (p, size, fmt, ap); va_end(ap); /* If that worked, return the string. */ if (n > -1 && n < size) return p; /* Else try again with more space. */ if (n > -1) /* glibc 2.1 */ size = n+1; /* precisely what is needed */ else /* glibc 2.0 */ size *= 2; /* twice the old size */ if ((np = realloc (p, size)) == NULL) { free(p); return NULL; } else { p = np; } } ```
100,917
<p>I'm trying to read data from a Delphi DBIV database, every time I access the database it creates a Paradox.lck and a Pdoxusrs.lck file. I'm using only a TQuery Object to do this (nothing else). can I access a Delphi DBIV database without it creating these lock files?</p>
[ { "answer_id": 100936, "author": "finnw", "author_id": 12048, "author_profile": "https://Stackoverflow.com/users/12048", "pm_score": 0, "selected": false, "text": "<p>I have found one portable way to predict and/or limit the number of characters returned by sprintf and related functions,...
2008/09/19
[ "https://Stackoverflow.com/questions/100917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to read data from a Delphi DBIV database, every time I access the database it creates a Paradox.lck and a Pdoxusrs.lck file. I'm using only a TQuery Object to do this (nothing else). can I access a Delphi DBIV database without it creating these lock files?
you could create a snprintf wrapper that returns -1 for each case when there is not enough space in the buffer. See the [man page](http://linux.die.net/man/3/snprintf) for more docs. It has also an example which threats all the cases. ``` while (1) { /* Try to print in the allocated space. */ va_start(ap, fmt); n = vsnprintf (p, size, fmt, ap); va_end(ap); /* If that worked, return the string. */ if (n > -1 && n < size) return p; /* Else try again with more space. */ if (n > -1) /* glibc 2.1 */ size = n+1; /* precisely what is needed */ else /* glibc 2.0 */ size *= 2; /* twice the old size */ if ((np = realloc (p, size)) == NULL) { free(p); return NULL; } else { p = np; } } ```
100,922
<p>Can someone explain to me the advantages of using an IOC container over simply hardcoding the default implementation into a default constructor?</p> <p>In other words, what is wrong about this code?</p> <pre><code>public class MyClass { private IMyInterface _myInterface; public MyClass() { _myInterface = new DefaultMyInterface(); } public MyClass(IMyInterface myInterface) { _myInterface = myInterface; } } </code></pre> <p>As far as I can tell, this class supports constructor injection enough so unit testing and mocking is easily done. In addition to which, the default constructor removes the computational overhead of the IOC container (not to mention the whole process is a lot more transparent).</p> <p>The only benefits i can see to using an IOC container is if you need to switch out the implementation of your interfaces frequently. Am I missing something?</p>
[ { "answer_id": 100951, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 5, "selected": true, "text": "<p>The idea of IoC is to delegate part of your component's functionality to another part of the system. In IoC world, you have co...
2008/09/19
[ "https://Stackoverflow.com/questions/100922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ]
Can someone explain to me the advantages of using an IOC container over simply hardcoding the default implementation into a default constructor? In other words, what is wrong about this code? ``` public class MyClass { private IMyInterface _myInterface; public MyClass() { _myInterface = new DefaultMyInterface(); } public MyClass(IMyInterface myInterface) { _myInterface = myInterface; } } ``` As far as I can tell, this class supports constructor injection enough so unit testing and mocking is easily done. In addition to which, the default constructor removes the computational overhead of the IOC container (not to mention the whole process is a lot more transparent). The only benefits i can see to using an IOC container is if you need to switch out the implementation of your interfaces frequently. Am I missing something?
The idea of IoC is to delegate part of your component's functionality to another part of the system. In IoC world, you have components that don't know about each other. Your example violates this, as you're creating tight coupling between MyClass and some implementation of IMyInterface. **The main idea** is that your component **has no knowledge** about how it will be used. In your example, your component **makes some assumptions** about its use. Actually this approach can work, but mixing IoC and explicit object initialization is not a good practice IMO. IoC gives you loose coupling by performing late binding for the price of code clarity. When you add additional behavior to this process, it makes things even more complicated and can lead to bugs when some components can potentially receive object with unwanted or unpredicted behavior.
100,948
<p>I installed MySQL via <a href="http://en.wikipedia.org/wiki/MacPorts" rel="noreferrer">MacPorts</a>. What is the command I need to stop the server (I need to test how my application behave when MySQL is dead)?</p>
[ { "answer_id": 100953, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 4, "selected": false, "text": "<p>Apparently you want:</p>\n\n<pre><code>sudo /Library/StartupItems/MySQLCOM/MySQLCOM stop\n</code></pre>\n\n<p>Have a furthe...
2008/09/19
[ "https://Stackoverflow.com/questions/100948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7473/" ]
I installed MySQL via [MacPorts](http://en.wikipedia.org/wiki/MacPorts). What is the command I need to stop the server (I need to test how my application behave when MySQL is dead)?
There are different cases depending on whether you installed [MySQL](http://en.wikipedia.org/wiki/MySQL) with the official binary installer, using [MacPorts](http://en.wikipedia.org/wiki/MacPorts), or using [Homebrew](http://brew.sh/): Homebrew -------- ``` brew services start mysql brew services stop mysql brew services restart mysql ``` MacPorts -------- ``` sudo port load mysql57-server sudo port unload mysql57-server ``` Note: this is persistent after a reboot. Binary installer ---------------- ``` sudo /Library/StartupItems/MySQLCOM/MySQLCOM stop sudo /Library/StartupItems/MySQLCOM/MySQLCOM start sudo /Library/StartupItems/MySQLCOM/MySQLCOM restart ```
100,990
<p>How could I get the Fault Detail sent by a SoapFaultClientException ? I use a WebServiceTemplate as shown below :</p> <pre><code>WebServiceTemplate ws = new WebServiceTemplate(); ws.setMarshaller(client.getMarshaller()); ws.setUnmarshaller(client.getUnMarshaller()); try { MyResponse resp = (MyResponse) = ws.marshalSendAndReceive(WS_URI, req); } catch (SoapFaultClientException e) { SoapFault fault = e.getSoapFault(); SoapFaultDetail details = e.getSoapFault().getFaultDetail(); //details always NULL ? Bug? } </code></pre> <p>The Web Service Fault sent seems correct :</p> <pre><code>&lt;soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;soapenv:Body&gt; &lt;soapenv:Fault&gt; &lt;faultcode&gt;soapenv:Client&lt;/faultcode&gt; &lt;faultstring&gt;Validation error&lt;/faultstring&gt; &lt;faultactor/&gt; &lt;detail&gt; &lt;ws:ValidationError xmlns:ws="http://ws.x.y.com"&gt;ERR_UNKNOWN&lt;/ws:ValidationError&gt; &lt;/detail&gt; &lt;/soapenv:Fault&gt; &lt;/soapenv:Body&gt; </code></pre> <p></p> <p>Thanks</p> <p>Willome</p>
[ { "answer_id": 105872, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 1, "selected": false, "text": "<p>From the Javadocs for the <a href=\"http://static.springframework.org/spring-ws/sites/1.5/apidocs/org/springframewor...
2008/09/19
[ "https://Stackoverflow.com/questions/100990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18714/" ]
How could I get the Fault Detail sent by a SoapFaultClientException ? I use a WebServiceTemplate as shown below : ``` WebServiceTemplate ws = new WebServiceTemplate(); ws.setMarshaller(client.getMarshaller()); ws.setUnmarshaller(client.getUnMarshaller()); try { MyResponse resp = (MyResponse) = ws.marshalSendAndReceive(WS_URI, req); } catch (SoapFaultClientException e) { SoapFault fault = e.getSoapFault(); SoapFaultDetail details = e.getSoapFault().getFaultDetail(); //details always NULL ? Bug? } ``` The Web Service Fault sent seems correct : ``` <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Body> <soapenv:Fault> <faultcode>soapenv:Client</faultcode> <faultstring>Validation error</faultstring> <faultactor/> <detail> <ws:ValidationError xmlns:ws="http://ws.x.y.com">ERR_UNKNOWN</ws:ValidationError> </detail> </soapenv:Fault> </soapenv:Body> ``` Thanks Willome
I also had the problem that getFaultDetail() returned null (for a SharePoint web service). I could get the detail element out by using a method similar to this: ``` private Element getDetail(SoapFaultClientException e) throws TransformerException { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMResult result = new DOMResult(); transformer.transform(e.getSoapFault().getSource(), result); NodeList nl = ((Document)result.getNode()).getElementsByTagName("detail"); return (Element)nl.item(0); } ``` After that, you can call getTextContent() on the returned Element or whatever you want.
101,012
<p>Our rails app is designed as a single code base linking to multiple client databases. Based on the subdomain the app determines which db to connect to.</p> <p>We use liquid templates to customise the presentation for each client. We are unable to customise the generic 'We're Sorry, somethign went wrong..' message for each client.</p> <p>Can anyone recommend an approach that would allow us to do this.</p> <p>Thanks</p> <p>DOm</p>
[ { "answer_id": 101027, "author": "mislav", "author_id": 11687, "author_profile": "https://Stackoverflow.com/users/11687", "pm_score": 4, "selected": true, "text": "<p>For catching exceptions in Rails 2, <code>rescue_from</code> controller method is a great way to specify actions which ha...
2008/09/19
[ "https://Stackoverflow.com/questions/101012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Our rails app is designed as a single code base linking to multiple client databases. Based on the subdomain the app determines which db to connect to. We use liquid templates to customise the presentation for each client. We are unable to customise the generic 'We're Sorry, somethign went wrong..' message for each client. Can anyone recommend an approach that would allow us to do this. Thanks DOm
For catching exceptions in Rails 2, `rescue_from` controller method is a great way to specify actions which handle various cases. ``` class ApplicationController < ActionController::Base rescue_from MyAppError, :with => :show_errors def show_errors render :action => "..." end end ``` This way you can make dynamic error pages to replace the static "public/500.html" page.
101,033
<p>I want to create a stored procedure with one argument which will return different sets of records depending on the argument. What is the way to do this? Can I call it from plain SQL?</p>
[ { "answer_id": 101064, "author": "Thilo", "author_id": 14955, "author_profile": "https://Stackoverflow.com/users/14955", "pm_score": 5, "selected": false, "text": "<p>I think you want to return a REFCURSOR:</p>\n\n<pre><code>create function test_cursor \n return sys_refcursor\...
2008/09/19
[ "https://Stackoverflow.com/questions/101033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to create a stored procedure with one argument which will return different sets of records depending on the argument. What is the way to do this? Can I call it from plain SQL?
Here is how to build a function that returns a result set that can be queried as if it were a table: ``` SQL> create type emp_obj is object (empno number, ename varchar2(10)); 2 / Type created. SQL> create type emp_tab is table of emp_obj; 2 / Type created. SQL> create or replace function all_emps return emp_tab 2 is 3 l_emp_tab emp_tab := emp_tab(); 4 n integer := 0; 5 begin 6 for r in (select empno, ename from emp) 7 loop 8 l_emp_tab.extend; 9 n := n + 1; 10 l_emp_tab(n) := emp_obj(r.empno, r.ename); 11 end loop; 12 return l_emp_tab; 13 end; 14 / Function created. SQL> select * from table (all_emps); EMPNO ENAME ---------- ---------- 7369 SMITH 7499 ALLEN 7521 WARD 7566 JONES 7654 MARTIN 7698 BLAKE 7782 CLARK 7788 SCOTT 7839 KING 7844 TURNER 7902 FORD 7934 MILLER ```
101,070
<p>If you are writing a <em>simple</em> little loop, what <em>should</em> you name the counter?</p> <p><em>Provide example loops!</em></p>
[ { "answer_id": 101071, "author": "just mike", "author_id": 12293, "author_profile": "https://Stackoverflow.com/users/12293", "pm_score": 4, "selected": false, "text": "<p>My experience is that most people use single letters, e.g.:\n<code>i</code>,\n<code>j</code>,\n<code>k</code>,\n...\n...
2008/09/19
[ "https://Stackoverflow.com/questions/101070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12293/" ]
If you are writing a *simple* little loop, what *should* you name the counter? *Provide example loops!*
I always use a **meaningful name** unless it's a single-level loop and the variable has no meaning other than "the number of times I've been through this loop", in which case I use `i`. When using meaningful names: * the code is more understandable to colleagues reading your code, * it's easier to find bugs in the loop logic, and * text searches for the variable name to return relevant pieces of code operating on the same data are more reliable. Example - spot the bug ---------------------- It can be tricky to find the bug in this nested loop using single letters: ``` int values[MAX_ROWS][MAX_COLS]; int sum_of_all_values() { int i, j, total; total = 0; for (i = 0; i < MAX_COLS; i++) for (j = 0; j < MAX_ROWS; j++) total += values[i][j]; return total; } ``` whereas it is easier when using meaningful names: ``` int values[MAX_ROWS][MAX_COLS]; int sum_of_all_values() { int row_num, col_num, total; total = 0; for (row_num = 0; row_num < MAX_COLS; row_num++) for (col_num = 0; col_num < MAX_ROWS; col_num++) total += values[row_num][col_num]; return total; } ``` ### Why `row_num`? - rejected alternatives In response to some other answers and comments, these are some alternative suggestions to using `row_num` and `col_num` and why I choose not to use them: * **`r`** and **`c`**: This is slightly better than `i` and `j`. I would only consider using them if my organisation's standard were for single-letter variables to be integers, and also always to be the first letter of the equivalent descriptive name. The system would fall down if I had two variables in the function whose name began with "r", and readability would suffer even if other objects beginning with "r" appeared anywhere in the code. * **`rr`** and **`cc`**: This looks weird to me, but I'm not used to a double-letter loop variable style. If it were the standard in my organisation then I imagine it would be slightly better than `r` and `c`. * **`row`** and **`col`**: At first glance this seems more succinct than `row_num` and `col_num`, and just as descriptive. However, I would expect bare nouns like "row" and "column" to refer to structures, objects or pointers to these. If `row` could mean *either* the row structure itself, *or* a row number, then confusion will result. * **`iRow`** and **`iCol`**: This conveys extra information, since `i` can mean it's a loop counter while `Row` and `Col` tell you what it's counting. However, I prefer to be able to read the code almost in English: + `row_num < MAX_COLS` reads as "the **row num**ber is **less than** the **max**imum (number of) **col**umn**s**"; + `iRow < MAX_COLS` at best reads as "the **integer loop counter** for the **row** is **less than** the **max**imum (number of) **col**umn**s**". + It may be a personal thing but I prefer the first reading. An alternative to `row_num` I would accept is `row_idx`: the word "index" uniquely refers to an array position, unless the application's domain is in database engine design, financial markets or similar. My example above is as small as I could make it, and as such some people might not see the point in naming the variables descriptively since they can hold the whole function in their head in one go. In real code, however, the functions would be larger, and the logic more complex, so decent names become more important to aid readability and to avoid bugs. In summary, my aim with all variable naming (not just loops) is to be **completely unambiguous**. If *anybody* reads any portion of my code and can't work out what a variable is for immediately, then I have failed.
101,072
<p>Was this an oversight? Or is it to do with the JVM?</p>
[ { "answer_id": 101084, "author": "Confusion", "author_id": 16784, "author_profile": "https://Stackoverflow.com/users/16784", "pm_score": 1, "selected": false, "text": "<p>I guess it has to do with the fact that the JVM is coded in C++. Apart from that, pointers and references are nearly ...
2008/09/19
[ "https://Stackoverflow.com/questions/101072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4857/" ]
Was this an oversight? Or is it to do with the JVM?
Java does indeed have pointers--pointers on which you cannot perform pointer arithmetic. From the venerable [JLS](http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.1): > > There are two kinds of types in the Java programming language: primitive types (§4.2) and reference types (§4.3). There are, correspondingly, two kinds of data values that can be stored in variables, passed as arguments, returned by methods, and operated on: primitive values (§4.2) and reference values (§4.3). > > > And [later](http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.3.1): > > An *object* is a *class instance* or an *array*. > > > The reference values (often just *references*) are *pointers* to these objects, and a special null reference, which refers to no object. > > > (emphasis theirs) So, to interpret, if you write: ``` Object myObj = new Object(); ``` then `myObj` is a *reference type* which contains a *reference value* that is itself a *pointer* to the newly-created `Object`. Thus if you set `myObj` to `null` you are setting the *reference value* (aka *pointer*) to `null`. Hence a NullPointerException is reasonably thrown when the variable is dereferenced. Don't worry: this topic has been [heartily debated](http://groups.google.com/group/comp.lang.java.programmer/browse_thread/thread/65bf7e9d6bffb1b9/) before.
101,096
<p>I have an Exchange mailbox linked as a table in an MS Access app. This is primarily used for reading, but I would also like to be able to "move" messages to another folder. </p> <p>Unfortunately this is not as simple as writing in a second linked mailbox, because apparently I can not edit some fields. Some critical fields like the To: field are unavailable, as I get the following error </p> <p><em>"Field 'To' is based on an expression and cannot be edited".</em> </p> <p>Using <em>CreateObject("Outlook.Application")</em> instead is not an option here, because as far as I know, this gives a security dialog when called from Access.</p> <p>Any solutions?*</p>
[ { "answer_id": 102406, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 1, "selected": false, "text": "<p>Is this two problems? Mail can be moved using the Move method. Here is a snippet:</p>\n\n<pre><code> Set oApp = CreateO...
2008/09/19
[ "https://Stackoverflow.com/questions/101096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have an Exchange mailbox linked as a table in an MS Access app. This is primarily used for reading, but I would also like to be able to "move" messages to another folder. Unfortunately this is not as simple as writing in a second linked mailbox, because apparently I can not edit some fields. Some critical fields like the To: field are unavailable, as I get the following error *"Field 'To' is based on an expression and cannot be edited".* Using *CreateObject("Outlook.Application")* instead is not an option here, because as far as I know, this gives a security dialog when called from Access. Any solutions?\*
Is this two problems? Mail can be moved using the Move method. Here is a snippet: ``` Set oApp = CreateObject("Outlook.Application") Set oNS = oApp.GetNamespace("MAPI") Set oMailItems = oNS.GetDefaultFolder(olFolderInbox) Set itm = oMailItems.Items(6) itm.Move oNS.GetDefaultFolder(olFolderDeletedItems) ``` However, Recipients (To) is read only, even, I believe, with Outlook Redemtion.
101,125
<p>Is there a way to check if the user has a different version of the CSS cached by their browser and if so force their browser to pull the new version?</p>
[ { "answer_id": 101131, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 0, "selected": false, "text": "<p>You should possibly just share a common ancestor class, then you can flick it with a single js command if need be....
2008/09/19
[ "https://Stackoverflow.com/questions/101125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is there a way to check if the user has a different version of the CSS cached by their browser and if so force their browser to pull the new version?
I don´t know if it is correct usage, but I think you can force a reload of the css file using a query string: ``` <link href="mystyle.css?SOME_UNIQUE_TEXT" type="text/css" rel="stylesheet" /> ``` I remember I used this method years ago to force a reload of a web-cam image, but time has probably moved on...
101,128
<p>How do I read text from the (windows) clipboard with python?</p>
[ { "answer_id": 101143, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 2, "selected": false, "text": "<p>Try win32clipboard from the win32all package (that's probably installed if you're on ActiveState Python).</p>\n\n<p...
2008/09/19
[ "https://Stackoverflow.com/questions/101128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17493/" ]
How do I read text from the (windows) clipboard with python?
You can use the module called [win32clipboard](http://docs.activestate.com/activepython/2.5/pywin32/win32clipboard.html), which is part of [pywin32](https://github.com/mhammond/pywin32). Here is an example that first sets the clipboard data then gets it: ``` import win32clipboard # set clipboard data win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardText('testing 123') win32clipboard.CloseClipboard() # get clipboard data win32clipboard.OpenClipboard() data = win32clipboard.GetClipboardData() win32clipboard.CloseClipboard() print data ``` An important reminder from the documentation: > > When the window has finished examining or changing the clipboard, > close the clipboard by calling CloseClipboard. This enables other > windows to access the clipboard. Do not place an object on the > clipboard after calling CloseClipboard. > > >
101,145
<p>How can someone validate that a specific element exists in an XML file? Say I have an ever changing XML file and I need to verify every element exists before reading/parsing it. </p>
[ { "answer_id": 101160, "author": "Chris James", "author_id": 3193, "author_profile": "https://Stackoverflow.com/users/3193", "pm_score": 6, "selected": false, "text": "<pre><code>if(doc.SelectSingleNode(\"//mynode\")==null)....\n</code></pre>\n\n<p>Should do it (where doc is your XmlDocu...
2008/09/19
[ "https://Stackoverflow.com/questions/101145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How can someone validate that a specific element exists in an XML file? Say I have an ever changing XML file and I need to verify every element exists before reading/parsing it.
``` if(doc.SelectSingleNode("//mynode")==null).... ``` Should do it (where doc is your XmlDocument object, obviously) Alternatively you could use an XSD and validate against that
101,151
<p>I have the following scenario:</p> <pre> public class CarManager { .. public long AddCar(Car car) { try { string username = _authorizationManager.GetUsername(); ... long id = _carAccessor.AddCar(username, car.Id, car.Name, ....); if(id == 0) { throw new Exception("Car was not added"); } return id; } catch (Exception ex) { throw new AddCarException(ex); } } public List AddCars(List cars) { List ids = new List(); foreach(Car car in cars) { ids.Add(AddCar(car)); } return ids; } } </pre> <p>I am mocking out _reportAccessor, _authorizationManager etc.</p> <p>Now I want to unittest the CarManager class. Should I have multiple tests for AddCar() such as </p> <pre> AddCarTest() AddCarTestAuthorizationManagerException() AddCarTestCarAccessorNoId() AddCarTestCarAccessorException() </pre> <p>For AddCars() should I repeat all previous tests as AddCars() calls AddCar() - it seems like repeating oneself? Should I perhaps not be calling AddCar() from AddCars()? &lt; p/></p> <p>Please help.</p>
[ { "answer_id": 101190, "author": "Andreas Bakurov", "author_id": 7400, "author_profile": "https://Stackoverflow.com/users/7400", "pm_score": 1, "selected": false, "text": "<p>Unit Test should focus only to its corresponding class under testing. All attributes of class that are not of sam...
2008/09/19
[ "https://Stackoverflow.com/questions/101151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15771/" ]
I have the following scenario: ``` public class CarManager { .. public long AddCar(Car car) { try { string username = _authorizationManager.GetUsername(); ... long id = _carAccessor.AddCar(username, car.Id, car.Name, ....); if(id == 0) { throw new Exception("Car was not added"); } return id; } catch (Exception ex) { throw new AddCarException(ex); } } public List AddCars(List cars) { List ids = new List(); foreach(Car car in cars) { ids.Add(AddCar(car)); } return ids; } } ``` I am mocking out \_reportAccessor, \_authorizationManager etc. Now I want to unittest the CarManager class. Should I have multiple tests for AddCar() such as ``` AddCarTest() AddCarTestAuthorizationManagerException() AddCarTestCarAccessorNoId() AddCarTestCarAccessorException() ``` For AddCars() should I repeat all previous tests as AddCars() calls AddCar() - it seems like repeating oneself? Should I perhaps not be calling AddCar() from AddCars()? < p/> Please help.
There are two issues here: * Unit tests should do more than test methods one at a time. They should be designed to prove that your class can do the job it was designed for when integrated with the rest of the system. So you should mock out the dependencies and then write a test for each way in which you class will actually be used. For each (non-trivial) class you write there will be scenarios that involve the client code calling methods in a particular pattern. * There is nothing wrong with AddCars calling AddCar. You should repeat tests for error handling but only when it serves a purpose. One of the unofficial rules of unit testing is 'test to the point of boredom' or (as I like to think of it) 'test till the fear goes away'. Otherwise you would be writing tests forever. So if you are confident a test will add no value them don't write it. You may be wrong of course, in which case you can come back later and add it in. You don't have to produce a perfect test first time round, just a firm basis on which you can build as you better understand what your class needs to do.
101,156
<p>I need to count and check how much of some images is placed in folder od web server. Example- images get names from <code>user_id</code>, and on example I have <code>user_id 27</code>, and my images are:</p> <pre><code>27_1.jpg, 27_2.jpg, 27_3.jpg, ... </code></pre> <p>How to check and write to database this thing?</p> <p>Thanks</p>
[ { "answer_id": 101230, "author": "hometoast", "author_id": 2009, "author_profile": "https://Stackoverflow.com/users/2009", "pm_score": 2, "selected": false, "text": "<p>Once you know your path you can use IO.Directory.GetFiles() method.</p>\n\n<pre><code>IO.Directory.GetFiles(\"\\transla...
2008/09/19
[ "https://Stackoverflow.com/questions/101156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/205368/" ]
I need to count and check how much of some images is placed in folder od web server. Example- images get names from `user_id`, and on example I have `user_id 27`, and my images are: ``` 27_1.jpg, 27_2.jpg, 27_3.jpg, ... ``` How to check and write to database this thing? Thanks
Once you know your path you can use IO.Directory.GetFiles() method. ``` IO.Directory.GetFiles("\translated\path","27_*.jpg").Count() ``` will give you what you're looking for.
101,162
<p>How do you return a serialized JSON object to the client side using ASP.NET MVC via an AJAX call?</p>
[ { "answer_id": 101256, "author": "David Bick", "author_id": 4914, "author_profile": "https://Stackoverflow.com/users/4914", "pm_score": 6, "selected": true, "text": "<p>From the controller you can just return a JsonResult:</p>\n\n<pre><code>public ActionResult MyAction()\n{\n ... // P...
2008/09/19
[ "https://Stackoverflow.com/questions/101162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do you return a serialized JSON object to the client side using ASP.NET MVC via an AJAX call?
From the controller you can just return a JsonResult: ``` public ActionResult MyAction() { ... // Populate myObject return new JsonResult{ Data = myObject }; } ``` The form of the Ajax call will depend on which library you're using, of course. Using jQuery it would be something like: ``` $.getJSON("/controllerName/MyAction", callbackFunction); ``` where the `callbackFunction` takes a parameter which is the data from the XHR request.
101,174
<p>In Python there is a really neat function called <code>zip</code> which can be used to iterate through two lists at the same time:</p> <pre><code>list1 = [1, 2, 3] list2 = ["a", "b", "c"] for v1, v2 in zip(list1, list2): print v1 + " " + v2 </code></pre> <p>The above code should produce the following:</p> <pre>1 a 2 b 3 c</pre> <p>I wonder if there is a method like it available in .Net? I'm thinking about writing it myself, but there is no point if it's already available.</p>
[ { "answer_id": 101207, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 3, "selected": false, "text": "<p>Nope, there is no such function in .NET. You have roll out your own. Note that C# doesn't support tuples, so python-like synt...
2008/09/19
[ "https://Stackoverflow.com/questions/101174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16047/" ]
In Python there is a really neat function called `zip` which can be used to iterate through two lists at the same time: ``` list1 = [1, 2, 3] list2 = ["a", "b", "c"] for v1, v2 in zip(list1, list2): print v1 + " " + v2 ``` The above code should produce the following: ``` 1 a 2 b 3 c ``` I wonder if there is a method like it available in .Net? I'm thinking about writing it myself, but there is no point if it's already available.
Update: It is built-in in C# 4 as [System.Linq.Enumerable.Zip Method](https://msdn.microsoft.com/en-us/library/vstudio/dd267698(v=vs.110).aspx) Here is a C# 3 version: ``` IEnumerable<TResult> Zip<TResult,T1,T2> (IEnumerable<T1> a, IEnumerable<T2> b, Func<T1,T2,TResult> combine) { using (var f = a.GetEnumerator()) using (var s = b.GetEnumerator()) { while (f.MoveNext() && s.MoveNext()) yield return combine(f.Current, s.Current); } } ``` Dropped the C# 2 version as it was showing its age.
101,180
<p>I need to communicate with an XML-RPC server from a .NET 2.0 client. Can you recommend any libraries?</p> <p>EDIT: Having tried XML-RPC.Net, I like the way it generates dynamic proxies, it is very neat. Unfortunately, as always, things are not so simple. I am accessing an XML-RPC service which uses the unorthodox technique of having object names in the names of the methods, like so:</p> <pre><code>object1.object2.someMethod(string1) </code></pre> <p>This means I can't use the attributes to set the names of my methods, as they are not known until run-time. If you start trying to get closer to the raw calls, XML-RPC.Net starts to get pretty messy.</p> <p>So, anyone know of a simple and straightforward XML-RPC library that'll just let me do (pseudocode):</p> <pre><code>x = new xmlrpc(host, port) x.makeCall("methodName", "arg1"); </code></pre> <p>I had a look at a thing by Michael somebody on Codeproject, but there are no unit tests and the code looks pretty dire.</p> <p>Unless someone has a better idea looks like I am going to have to start an open source project myself!</p>
[ { "answer_id": 101204, "author": "Matthias Kestenholz", "author_id": 317346, "author_profile": "https://Stackoverflow.com/users/317346", "pm_score": 2, "selected": false, "text": "<p>I've used the library from <a href=\"http://www.xml-rpc.net/\" rel=\"nofollow noreferrer\">www.xml-rpc.ne...
2008/09/19
[ "https://Stackoverflow.com/questions/101180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16881/" ]
I need to communicate with an XML-RPC server from a .NET 2.0 client. Can you recommend any libraries? EDIT: Having tried XML-RPC.Net, I like the way it generates dynamic proxies, it is very neat. Unfortunately, as always, things are not so simple. I am accessing an XML-RPC service which uses the unorthodox technique of having object names in the names of the methods, like so: ``` object1.object2.someMethod(string1) ``` This means I can't use the attributes to set the names of my methods, as they are not known until run-time. If you start trying to get closer to the raw calls, XML-RPC.Net starts to get pretty messy. So, anyone know of a simple and straightforward XML-RPC library that'll just let me do (pseudocode): ``` x = new xmlrpc(host, port) x.makeCall("methodName", "arg1"); ``` I had a look at a thing by Michael somebody on Codeproject, but there are no unit tests and the code looks pretty dire. Unless someone has a better idea looks like I am going to have to start an open source project myself!
If the method name is all that is changing (i.e., the method signature is static) XML-RPC.NET can handle this for you. This is addressed [in the FAQ](http://xml-rpc.net/faq/xmlrpcnetfaq.html#2.23), noting "However, there are some XML-RPC APIs which require the method name to be generated dynamically at runtime..." From the FAQ: ``` ISumAndDiff proxy = (ISumAndDiff)XmlRpcProxyGen.Create(typeof(ISumAndDiff)); proxy.XmlRpcMethod = "Id1234_SumAndDifference" proxy.SumAndDifference(3, 4); ``` This generates an XmlRpcProxy which implementes the specified interface. Setting the XmlRpcMethod attribute causes methodCalls to use the new method name.
101,184
<p>I'm building an installer for an application. The user gets to select a datasource they have configured and nominate what type of database it is. I want to confirm that the database type is indeed Oracle, and if possible, what version of Oracle they are running by sending a SQL statement to the datasource.</p>
[ { "answer_id": 101197, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 9, "selected": true, "text": "<p>Run this SQL:</p>\n\n<pre><code>select * from v$version;\n</code></pre>\n\n<p>And you'll get a result like: </p>...
2008/09/19
[ "https://Stackoverflow.com/questions/101184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10750/" ]
I'm building an installer for an application. The user gets to select a datasource they have configured and nominate what type of database it is. I want to confirm that the database type is indeed Oracle, and if possible, what version of Oracle they are running by sending a SQL statement to the datasource.
Run this SQL: ``` select * from v$version; ``` And you'll get a result like: ``` BANNER ---------------------------------------------------------------- Oracle Database 10g Release 10.2.0.3.0 - 64bit Production PL/SQL Release 10.2.0.3.0 - Production CORE 10.2.0.3.0 Production TNS for Solaris: Version 10.2.0.3.0 - Production NLSRTL Version 10.2.0.3.0 - Production ```
101,198
<p>I'm building an installer for an application. The user gets to select a datasource they have configured and nominate what type of database it is. I want to confirm that the database type is indeed Postgres, and if possible, what version of Postgres they are running by sending a SQL statement to the datasource.</p>
[ { "answer_id": 101210, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 2, "selected": false, "text": "<pre><code>SELECT version();\n</code></pre>\n" }, { "answer_id": 101214, "author": "Matthias Kestenholz", ...
2008/09/19
[ "https://Stackoverflow.com/questions/101198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10750/" ]
I'm building an installer for an application. The user gets to select a datasource they have configured and nominate what type of database it is. I want to confirm that the database type is indeed Postgres, and if possible, what version of Postgres they are running by sending a SQL statement to the datasource.
Try this: ``` mk=# SELECT version(); version ----------------------------------------------------------------------------------------------- PostgreSQL 8.3.3 on i486-pc-linux-gnu, compiled by GCC cc (GCC) 4.2.3 (Ubuntu 4.2.3-2ubuntu7) (1 row) ``` The command works too in MySQL: ``` mysql> select version(); +--------------------------------+ | version() | +--------------------------------+ | 5.0.32-Debian_7etch1~bpo.1-log | +--------------------------------+ 1 row in set (0.01 sec) ``` There is no version command in sqlite as far as I can see.
101,212
<p>Net::HTTP can be rather cumbersome for the standard use case!</p>
[ { "answer_id": 101289, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This is what I use: <a href=\"http://rubyforge.org/projects/restful-rails/\" rel=\"nofollow noreferrer\">http://rubyforge.o...
2008/09/19
[ "https://Stackoverflow.com/questions/101212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18751/" ]
Net::HTTP can be rather cumbersome for the standard use case!
If you only have to deal with REST, the [rest-client](https://github.com/rest-client/rest-client) library is fantastic. If the APIs you're using aren't completely RESTful - or even if they are - [HTTParty](http://railstips.org/2008/7/29/it-s-an-httparty-and-everyone-is-invited) is really worth checking out. It simplifies using REST APIs, as well as non-RESTful web APIs. Check out this code (copied from the above link): ``` require 'rubygems' require 'httparty' class Representative include HTTParty format :xml def self.find_by_zip(zip) get('http://whoismyrepresentative.com/whoismyrep.php', :query => {:zip => zip}) end end puts Representative.find_by_zip(46544).inspect # {"result"=>{"n"=>"1", "rep"=>{"name"=>"Joe Donnelly", "district"=>"2", "office"=>"1218 Longworth", "phone"=>"(202) 225-3915", "link"=>"http://donnelly.house.gov/", "state"=>"IN"}}} ```
101,244
<pre><code>/etc/init.d/* /etc/rc{1-5}.d/* </code></pre>
[ { "answer_id": 101246, "author": "px.", "author_id": 18769, "author_profile": "https://Stackoverflow.com/users/18769", "pm_score": 2, "selected": false, "text": "<p><code>/sbin/chkconfig</code> — The <code>/sbin/chkconfig</code> utility is a simple command line tool for maintaining the <...
2008/09/19
[ "https://Stackoverflow.com/questions/101244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18769/" ]
``` /etc/init.d/* /etc/rc{1-5}.d/* ```
in one word: `init`. This process always has pid of 1 and controls (spawns) all other processes in your unix according to the rules in `/etc/init.d`. init is usually called with a number as an argument, e.g. `init 3` This will make it run the contents of the `rc3.d` folder. For more information: [Wikipedia article for init](http://en.wikipedia.org/wiki/Init). Edit: Forgot to mention, what actually controls what rc level you start off in is your bootloader.
101,258
<p>I want to search for <code>$maximumTotalAllowedAfterFinish</code> and replace it with <code>$minimumTotalAllowedAfterFinish</code>. Instead of typing the long text:</p> <pre><code>:%s/$maximumTotalAllowedAfterFinish/$minimumTotalAllowedAfterFinish/g </code></pre> <p>Is there a way to COPY these long variable names down into the search line, since, on the command line I can't type "<code>p</code>" to paste?</p>
[ { "answer_id": 101281, "author": "Johannes Hoff", "author_id": 3102, "author_profile": "https://Stackoverflow.com/users/3102", "pm_score": 4, "selected": false, "text": "<p>Type <code>q:</code> to get into history editing mode in a new buffer. Then edit the last line of the buffer and pr...
2008/09/19
[ "https://Stackoverflow.com/questions/101258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ]
I want to search for `$maximumTotalAllowedAfterFinish` and replace it with `$minimumTotalAllowedAfterFinish`. Instead of typing the long text: ``` :%s/$maximumTotalAllowedAfterFinish/$minimumTotalAllowedAfterFinish/g ``` Is there a way to COPY these long variable names down into the search line, since, on the command line I can't type "`p`" to paste?
You can insert the contents of a numbered or named register by typing `CTRL``R` ``{0-9a-z"%#:-=.}``. By typing `CTRL-R` `CTRL-W` you can paste the current word under the cursor. See: ``` :he cmdline-editing ``` for more information.
101,265
<p>Inspired by another question asking about the missing <code>Zip</code> function:</p> <p>Why is there no <code>ForEach</code> extension method on the <code>IEnumerable</code> interface? Or anywhere? The only class that gets a <code>ForEach</code> method is <code>List&lt;&gt;</code>. Is there a reason why it's missing, maybe performance?</p>
[ { "answer_id": 101274, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 2, "selected": false, "text": "<p>Most of the LINQ extension methods return results. ForEach does not fit into this pattern as it returns nothing.</p>\n" ...
2008/09/19
[ "https://Stackoverflow.com/questions/101265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3820/" ]
Inspired by another question asking about the missing `Zip` function: Why is there no `ForEach` extension method on the `IEnumerable` interface? Or anywhere? The only class that gets a `ForEach` method is `List<>`. Is there a reason why it's missing, maybe performance?
There is already a `foreach` statement included in the language that does the job most of the time. I'd hate to see the following: ``` list.ForEach( item => { item.DoSomething(); } ); ``` Instead of: ``` foreach(Item item in list) { item.DoSomething(); } ``` The latter is clearer and easier to read **in most situations**, although maybe a bit longer to type. However, I must admit I changed my stance on that issue; a `ForEach()` extension method would indeed be useful in some situations. Here are the major differences between the statement and the method: * Type checking: foreach is done at runtime, `ForEach()` is at compile time (Big Plus!) * The syntax to call a delegate is indeed much simpler: objects.ForEach(DoSomething); * ForEach() could be chained: although evilness/usefulness of such a feature is open to discussion. Those are all great points made by many people here and I can see why people are missing the function. I wouldn't mind Microsoft adding a standard ForEach method in the next framework iteration.
101,267
<p>When I used to write libraries in C/C++ I got into the habit of having a method to return the compile date/time. This was always a compiled into the library so would differentiate builds of the library. I got this by returning a #define in the code:</p> <p>C++:</p> <pre><code>#ifdef _BuildDateTime_ char* SomeClass::getBuildDateTime() { return _BuildDateTime_; } #else char* SomeClass::getBuildDateTime() { return "Undefined"; } #endif </code></pre> <p>Then on the compile I had a '-D_BuildDateTime_=<code>Date</code>' in the build script.</p> <p>Is there any way to achieve this or similar in Java without needing to remember to edit any files manually or distributing any seperate files.</p> <p>One suggestion I got from a co-worker was to get the ant file to create a file on the classpath and to package that into the JAR and have it read by the method. </p> <p>Something like (assuming the file created was called 'DateTime.dat'):</p> <pre><code>// I know Exceptions and proper open/closing // of the file are not done. This is just // to explain the point! String getBuildDateTime() { return new BufferedReader(getClass() .getResourceAsStream("DateTime.dat")).readLine(); } </code></pre> <p>To my mind that's a hack and could be circumvented/broken by someone having a similarly named file <em>outside</em> the JAR, but on the classpath.</p> <p>Anyway, my question is whether there is any way to inject a constant into a class at compile time</p> <p>EDIT</p> <p>The reason I consider using an externally generated file in the JAR a hack is because this <em>is</em>) a library and will be embedded in client apps. These client apps may define their own classloaders meaning I can't rely on the standard JVM class loading rules.</p> <p>My personal preference would be to go with using the date from the JAR file as suggested by serg10.</p>
[ { "answer_id": 101293, "author": "basszero", "author_id": 287, "author_profile": "https://Stackoverflow.com/users/287", "pm_score": 1, "selected": false, "text": "<p>Unless you want to run your Java source through a C/C++ Preprocessor (which is a BIG NO-NO), use the jar method. There are...
2008/09/19
[ "https://Stackoverflow.com/questions/101267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18744/" ]
When I used to write libraries in C/C++ I got into the habit of having a method to return the compile date/time. This was always a compiled into the library so would differentiate builds of the library. I got this by returning a #define in the code: C++: ``` #ifdef _BuildDateTime_ char* SomeClass::getBuildDateTime() { return _BuildDateTime_; } #else char* SomeClass::getBuildDateTime() { return "Undefined"; } #endif ``` Then on the compile I had a '-D\_BuildDateTime\_=`Date`' in the build script. Is there any way to achieve this or similar in Java without needing to remember to edit any files manually or distributing any seperate files. One suggestion I got from a co-worker was to get the ant file to create a file on the classpath and to package that into the JAR and have it read by the method. Something like (assuming the file created was called 'DateTime.dat'): ``` // I know Exceptions and proper open/closing // of the file are not done. This is just // to explain the point! String getBuildDateTime() { return new BufferedReader(getClass() .getResourceAsStream("DateTime.dat")).readLine(); } ``` To my mind that's a hack and could be circumvented/broken by someone having a similarly named file *outside* the JAR, but on the classpath. Anyway, my question is whether there is any way to inject a constant into a class at compile time EDIT The reason I consider using an externally generated file in the JAR a hack is because this *is*) a library and will be embedded in client apps. These client apps may define their own classloaders meaning I can't rely on the standard JVM class loading rules. My personal preference would be to go with using the date from the JAR file as suggested by serg10.
**I would favour the standards based approach.** Put your version information (along with other useful publisher stuff such as build number, subversion revision number, author, company details, etc) in the jar's [Manifest File](http://java.sun.com/developer/Books/javaprogramming/JAR/basics/manifest.html). **This is a well documented and understood Java specification.** Strong tool support exists for creating manifest files (a [core Ant task](http://ant.apache.org/manual/Tasks/manifest.html) for example, or the [maven jar plugin](http://maven.apache.org/plugins/maven-jar-plugin/)). These can help with setting some of the attributes automatically - I have maven configured to put the jar's maven version number, Subversion revision and timestamp into the manifest for me at build time. You can read the contents of the manifest at runtime with standard java api calls - something like: ``` import java.util.jar.*; ... JarFile myJar = new JarFile("nameOfJar.jar"); // various constructors available Manifest manifest = myJar.getManifest(); Map<String,Attributes> manifestContents = manifest.getAttributes(); ``` To me, that feels like a more Java standard approach, so will probably prove more easy for subsequent code maintainers to follow.
101,268
<p>What are the lesser-known but useful features of the Python programming language?</p> <ul> <li>Try to limit answers to Python core.</li> <li>One feature per answer.</li> <li>Give an example and short description of the feature, not just a link to documentation.</li> <li>Label the feature using a title as the first line.</li> </ul> <h2>Quick links to answers:</h2> <ul> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#111176">Argument Unpacking</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#112303">Braces</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#101945">Chaining Comparison Operators</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#101447">Decorators</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#113198">Default Argument Gotchas / Dangers of Mutable Default arguments</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#102062">Descriptors</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#111970">Dictionary default <code>.get</code> value</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#102065">Docstring Tests</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python/112316#112316">Ellipsis Slicing Syntax</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#117116">Enumeration</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#114420">For/else</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#102202">Function as iter() argument</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#101310">Generator expressions</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#101276"><code>import this</code></a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#102037">In Place Value Swapping</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#101840">List stepping</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#112286"><code>__missing__</code> items</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#101537">Multi-line Regex</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#113164">Named string formatting</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#101549">Nested list/generator comprehensions</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#108297">New types at runtime</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#113833"><code>.pth</code> files</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#1024693">ROT13 Encoding</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#143636">Regex Debugging</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#101739">Sending to Generators</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#168270">Tab Completion in Interactive Interpreter</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#116480">Ternary Expression</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#114157"><code>try/except/else</code></a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#3267903">Unpacking+<code>print()</code> function</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#109182"><code>with</code> statement</a></li> </ul>
[ { "answer_id": 101276, "author": "cleg", "author_id": 29503, "author_profile": "https://Stackoverflow.com/users/29503", "pm_score": 7, "selected": false, "text": "<p><strong>Main messages :)</strong></p>\n\n<pre><code>import this\n# btw look at this module's source :)\n</code></pre>\n\n<...
2008/09/19
[ "https://Stackoverflow.com/questions/101268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2679/" ]
What are the lesser-known but useful features of the Python programming language? * Try to limit answers to Python core. * One feature per answer. * Give an example and short description of the feature, not just a link to documentation. * Label the feature using a title as the first line. Quick links to answers: ----------------------- * [Argument Unpacking](https://stackoverflow.com/questions/101268/hidden-features-of-python#111176) * [Braces](https://stackoverflow.com/questions/101268/hidden-features-of-python#112303) * [Chaining Comparison Operators](https://stackoverflow.com/questions/101268/hidden-features-of-python#101945) * [Decorators](https://stackoverflow.com/questions/101268/hidden-features-of-python#101447) * [Default Argument Gotchas / Dangers of Mutable Default arguments](https://stackoverflow.com/questions/101268/hidden-features-of-python#113198) * [Descriptors](https://stackoverflow.com/questions/101268/hidden-features-of-python#102062) * [Dictionary default `.get` value](https://stackoverflow.com/questions/101268/hidden-features-of-python#111970) * [Docstring Tests](https://stackoverflow.com/questions/101268/hidden-features-of-python#102065) * [Ellipsis Slicing Syntax](https://stackoverflow.com/questions/101268/hidden-features-of-python/112316#112316) * [Enumeration](https://stackoverflow.com/questions/101268/hidden-features-of-python#117116) * [For/else](https://stackoverflow.com/questions/101268/hidden-features-of-python#114420) * [Function as iter() argument](https://stackoverflow.com/questions/101268/hidden-features-of-python#102202) * [Generator expressions](https://stackoverflow.com/questions/101268/hidden-features-of-python#101310) * [`import this`](https://stackoverflow.com/questions/101268/hidden-features-of-python#101276) * [In Place Value Swapping](https://stackoverflow.com/questions/101268/hidden-features-of-python#102037) * [List stepping](https://stackoverflow.com/questions/101268/hidden-features-of-python#101840) * [`__missing__` items](https://stackoverflow.com/questions/101268/hidden-features-of-python#112286) * [Multi-line Regex](https://stackoverflow.com/questions/101268/hidden-features-of-python#101537) * [Named string formatting](https://stackoverflow.com/questions/101268/hidden-features-of-python#113164) * [Nested list/generator comprehensions](https://stackoverflow.com/questions/101268/hidden-features-of-python#101549) * [New types at runtime](https://stackoverflow.com/questions/101268/hidden-features-of-python#108297) * [`.pth` files](https://stackoverflow.com/questions/101268/hidden-features-of-python#113833) * [ROT13 Encoding](https://stackoverflow.com/questions/101268/hidden-features-of-python#1024693) * [Regex Debugging](https://stackoverflow.com/questions/101268/hidden-features-of-python#143636) * [Sending to Generators](https://stackoverflow.com/questions/101268/hidden-features-of-python#101739) * [Tab Completion in Interactive Interpreter](https://stackoverflow.com/questions/101268/hidden-features-of-python#168270) * [Ternary Expression](https://stackoverflow.com/questions/101268/hidden-features-of-python#116480) * [`try/except/else`](https://stackoverflow.com/questions/101268/hidden-features-of-python#114157) * [Unpacking+`print()` function](https://stackoverflow.com/questions/101268/hidden-features-of-python#3267903) * [`with` statement](https://stackoverflow.com/questions/101268/hidden-features-of-python#109182)
Chaining comparison operators: ------------------------------ ``` >>> x = 5 >>> 1 < x < 10 True >>> 10 < x < 20 False >>> x < 10 < x*10 < 100 True >>> 10 > x <= 9 True >>> 5 == x > 4 True ``` In case you're thinking it's doing `1 < x`, which comes out as `True`, and then comparing `True < 10`, which is also `True`, then no, that's really not what happens (see the last example.) It's really translating into `1 < x and x < 10`, and `x < 10 and 10 < x * 10 and x*10 < 100`, but with less typing and each term is only evaluated once.
101,270
<p>I want to use Vim's quickfix features with the output from Visual Studio's devenv build process or msbuild.</p> <p>I've created a batch file called build.bat which executes the devenv build like this:</p> <pre><code>devenv MySln.sln /Build Debug </code></pre> <p>In vim I've pointed the :make command to that batch file:</p> <pre><code>:set makeprg=build.bat </code></pre> <p>When I now run :make, the build executes successfully, however the errors don't get parsed out. So if I run :cl or :cn I just end up seeing all the output from devenv /Build. I should see only the errors.</p> <p>I've tried a number of different errorformat settings that I've found on various sites around the net, but none of them have parsed out the errors correctly. Here's a few I've tried:</p> <pre><code>set errorformat=%*\\d&gt;%f(%l)\ :\ %t%[A-z]%#\ %m set errorformat=\ %#%f(%l)\ :\ %#%t%[A-z]%#\ %m set errorformat=%f(%l,%c):\ error\ %n:\ %f </code></pre> <p>And of course I've tried Vim's default.</p> <p>Here's some example output from the build.bat:</p> <pre><code>C:\TFS\KwB Projects\Thingy&gt;devenv Thingy.sln /Build Debug Microsoft (R) Visual Studio Version 9.0.30729.1. Copyright (C) Microsoft Corp. All rights reserved. ------ Build started: Project: Thingy, Configuration: Debug Any CPU ------ c:\WINDOWS\Microsoft.NET\Framework\v3.5\Csc.exe /noconfig /nowarn:1701,1702 /errorreport:prompt /warn:4 /define:DEBUG;TRACE /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\PresentationCore.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\PresentationFramework.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Core.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.DataSetExtensions.dll" /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.Linq.dll" /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Xml.Linq.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\UIAutomationProvider.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\WindowsBase.dll" /debug+ /debug:full /filealign:512 /optimize- /out:obj\Debug\Thingy.exe /resource:obj\Debug\Thingy.g.resources /resource:obj\Debug\Thingy.Properties.Resources.resources /target:winexe App.xaml.cs Controller\FieldFactory.cs Controller\UserInfo.cs Data\ThingGatewaySqlDirect.cs Data\ThingListFetcher.cs Data\UserListFetcher.cs Gui\FieldList.xaml.cs Interfaces\IList.cs Interfaces\IListFetcher.cs Model\ComboBoxField.cs Model\ListValue.cs Model\ThingType.cs Interfaces\IThingGateway.cs Model\Field.cs Model\TextBoxField.cs Model\Thing.cs Gui\MainWindow.xaml.cs Gui\ThingWindow.xaml.cs Interfaces\IField.cs Properties\AssemblyInfo.cs Properties\Resources.Designer.cs Properties\Settings.Designer.cs RequiredValidation.cs "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\Gui\FieldList.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\Gui\MainWindow.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\Gui\ThingWindow.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\App.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\GeneratedInternalTypeHelper.g.cs" C:\TFS\KwB Projects\Thingy\Thingy\Controller\FieldFactory.cs(14,19): error CS0246: The type or namespace name 'IFieldNothing' could not be found (are you missing a using directive or an assembly reference?) Compile complete -- 1 errors, 0 warnings ========== Build: 0 succeeded or up-to-date, 1 failed, 0 skipped ========== </code></pre> <p><strong>UPDATE:</strong> It looks like using msbuild instead of devenv is probably the right way to go (as per Jay's comment).</p> <p>Using msbuild the makeprg would be:</p> <pre><code>:set makeprg=msbuild\ /nologo\ /v:q </code></pre> <p>Sample output whould be:</p> <pre><code>Controller\FieldFactory.cs(14,19): error CS0246: The type or namespace name 'IFieldNothing' could not be found (are you missing a using directive or an assembly reference?) </code></pre> <p>It looks like the tricky part here may lie in the fact that the path is relative to the .csproj file, not the .sln file which is the current directory in Vim and lies one directory above the .csproj file.</p> <p><strong>ANSWER:</strong> I figured it out...</p> <pre><code>set errorformat=\ %#%f(%l\\\,%c):\ %m </code></pre> <p>This will capture the output for both devenv /Build and msbuild. However, msbuild has one catch. By default, it's output doesn't include full paths. To fix this you have to add the following line to your csproj file's main PropertyGroup:</p> <pre><code>&lt;GenerateFullPaths&gt;True&lt;/GenerateFullPaths&gt; </code></pre>
[ { "answer_id": 102454, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 1, "selected": false, "text": "<p>Try running msbuild instead of devenv. This will open up a ton of power in how the build runs.</p>\n\n<p>Open a Visua...
2008/09/19
[ "https://Stackoverflow.com/questions/101270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4407/" ]
I want to use Vim's quickfix features with the output from Visual Studio's devenv build process or msbuild. I've created a batch file called build.bat which executes the devenv build like this: ``` devenv MySln.sln /Build Debug ``` In vim I've pointed the :make command to that batch file: ``` :set makeprg=build.bat ``` When I now run :make, the build executes successfully, however the errors don't get parsed out. So if I run :cl or :cn I just end up seeing all the output from devenv /Build. I should see only the errors. I've tried a number of different errorformat settings that I've found on various sites around the net, but none of them have parsed out the errors correctly. Here's a few I've tried: ``` set errorformat=%*\\d>%f(%l)\ :\ %t%[A-z]%#\ %m set errorformat=\ %#%f(%l)\ :\ %#%t%[A-z]%#\ %m set errorformat=%f(%l,%c):\ error\ %n:\ %f ``` And of course I've tried Vim's default. Here's some example output from the build.bat: ``` C:\TFS\KwB Projects\Thingy>devenv Thingy.sln /Build Debug Microsoft (R) Visual Studio Version 9.0.30729.1. Copyright (C) Microsoft Corp. All rights reserved. ------ Build started: Project: Thingy, Configuration: Debug Any CPU ------ c:\WINDOWS\Microsoft.NET\Framework\v3.5\Csc.exe /noconfig /nowarn:1701,1702 /errorreport:prompt /warn:4 /define:DEBUG;TRACE /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\PresentationCore.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\PresentationFramework.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Core.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.DataSetExtensions.dll" /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.Linq.dll" /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Xml.Linq.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\UIAutomationProvider.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\WindowsBase.dll" /debug+ /debug:full /filealign:512 /optimize- /out:obj\Debug\Thingy.exe /resource:obj\Debug\Thingy.g.resources /resource:obj\Debug\Thingy.Properties.Resources.resources /target:winexe App.xaml.cs Controller\FieldFactory.cs Controller\UserInfo.cs Data\ThingGatewaySqlDirect.cs Data\ThingListFetcher.cs Data\UserListFetcher.cs Gui\FieldList.xaml.cs Interfaces\IList.cs Interfaces\IListFetcher.cs Model\ComboBoxField.cs Model\ListValue.cs Model\ThingType.cs Interfaces\IThingGateway.cs Model\Field.cs Model\TextBoxField.cs Model\Thing.cs Gui\MainWindow.xaml.cs Gui\ThingWindow.xaml.cs Interfaces\IField.cs Properties\AssemblyInfo.cs Properties\Resources.Designer.cs Properties\Settings.Designer.cs RequiredValidation.cs "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\Gui\FieldList.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\Gui\MainWindow.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\Gui\ThingWindow.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\App.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\GeneratedInternalTypeHelper.g.cs" C:\TFS\KwB Projects\Thingy\Thingy\Controller\FieldFactory.cs(14,19): error CS0246: The type or namespace name 'IFieldNothing' could not be found (are you missing a using directive or an assembly reference?) Compile complete -- 1 errors, 0 warnings ========== Build: 0 succeeded or up-to-date, 1 failed, 0 skipped ========== ``` **UPDATE:** It looks like using msbuild instead of devenv is probably the right way to go (as per Jay's comment). Using msbuild the makeprg would be: ``` :set makeprg=msbuild\ /nologo\ /v:q ``` Sample output whould be: ``` Controller\FieldFactory.cs(14,19): error CS0246: The type or namespace name 'IFieldNothing' could not be found (are you missing a using directive or an assembly reference?) ``` It looks like the tricky part here may lie in the fact that the path is relative to the .csproj file, not the .sln file which is the current directory in Vim and lies one directory above the .csproj file. **ANSWER:** I figured it out... ``` set errorformat=\ %#%f(%l\\\,%c):\ %m ``` This will capture the output for both devenv /Build and msbuild. However, msbuild has one catch. By default, it's output doesn't include full paths. To fix this you have to add the following line to your csproj file's main PropertyGroup: ``` <GenerateFullPaths>True</GenerateFullPaths> ```
I have a blog post which walks through all the details of getting C# projects building in Vim, including the error format. You can find it here: <http://kevin-berridge.blogspot.com/2008/09/vim-c-compiling.html> In short you need the following: ``` :set errorformat=\ %#%f(%l\\\,%c):\ %m :set makeprg=msbuild\ /nologo\ /v:q\ /property:GenerateFullPaths=true ```
101,326
<p>I've set up wildcard mapping on IIS 6, by adding "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll", and ensured "Verify that file exists" is not checked :</p> <ul> <li>on the "websites" directory in IIS</li> <li>on the website</li> </ul> <p>However, after a iisreset, when I go to <a href="http://myserver/something.gif" rel="nofollow noreferrer">http://myserver/something.gif</a>, I still get IIS 404 error, not asp.net one.</p> <p>Is there something I missed ?</p> <p>Precisions:</p> <ul> <li>this is not for using ASP.NET MVC</li> <li>i'd rather not use iis 404 custom error pages, as I have a httpmodule for logging errors (this is a low traffic internal site, so wildcard mapping performance penalty is not a problem ;))</li> </ul>
[ { "answer_id": 101408, "author": "WebDude", "author_id": 15360, "author_profile": "https://Stackoverflow.com/users/15360", "pm_score": 0, "selected": false, "text": "<p>You can try use custom errors to do this.\nGo into Custom Errors in you Website properties and set the 404 to point to ...
2008/09/19
[ "https://Stackoverflow.com/questions/101326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971/" ]
I've set up wildcard mapping on IIS 6, by adding "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet\_isapi.dll", and ensured "Verify that file exists" is not checked : * on the "websites" directory in IIS * on the website However, after a iisreset, when I go to <http://myserver/something.gif>, I still get IIS 404 error, not asp.net one. Is there something I missed ? Precisions: * this is not for using ASP.NET MVC * i'd rather not use iis 404 custom error pages, as I have a httpmodule for logging errors (this is a low traffic internal site, so wildcard mapping performance penalty is not a problem ;))
You need to add an HTTP Handler in your web config for gif files: ``` <system.web> <httpHandlers> <add path="*.gif" verb="GET,HEAD" type="System.Web.StaticFileHandler" validate="true"/> </httpHandlers> </system.web> ``` That forces .Net to handle the file, then you'll get the .Net error. Server Error in '/' Application. -------------------------------- The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly. Requested URL: /test.gif --- Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433
101,329
<p>In particular, wouldn't there have to be some kind of function pointer in place anyway? </p>
[ { "answer_id": 101341, "author": "yrp", "author_id": 7228, "author_profile": "https://Stackoverflow.com/users/7228", "pm_score": 0, "selected": false, "text": "<p>There's no need for function pointers as it cant change during the runtime.</p>\n" }, { "answer_id": 101342, "aut...
2008/09/19
[ "https://Stackoverflow.com/questions/101329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
In particular, wouldn't there have to be some kind of function pointer in place anyway?
Non virtual member functions are really just a syntactic sugar as they are almost like an ordinary function but with access checking and an implicit object parameter. ``` struct A { void foo (); void bar () const; }; ``` is basically the same as: ``` struct A { }; void foo (A * this); void bar (A const * this); ``` The vtable is needed so that we call the right function for our specific object instance. For example, if we have: ``` struct A { virtual void foo (); }; ``` The implementation of 'foo' might approximate to something like: ``` void foo (A * this) { void (*realFoo)(A *) = lookupVtable (this->vtable, "foo"); (realFoo)(this); // Make the call to the most derived version of 'foo' } ```
101,338
<p>Is it valid to have a 'choice' of 'group' elements when defining an XML Schema (XSD)</p> <p>i.e. is the following valid</p> <pre><code>&lt;xs:complexType name=&quot;HeaderType&quot;&gt; &lt;xs:sequence&gt; &lt;xs:element name=&quot;reservation-number&quot; type=&quot;ReservationNumberType&quot; minOccurs=&quot;1&quot; maxOccurs=&quot;1&quot; nillable=&quot;false&quot; /&gt; &lt;xs:choice minOccurs=&quot;1&quot; maxOccurs=&quot;1&quot;&gt; &lt;xs:group ref=&quot;ReservationGroup&quot; /&gt; &lt;xs:group ref=&quot;CancellationGroup&quot;/&gt; &lt;/xs:choice&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; </code></pre> <p>Where an XML message can represent, for example, either a new reservation or a cancellation of an existing reservation.</p> <p>If the message is for a reservation, then it must include all the elements defined in the ReservationGroup group.</p> <p>If it is a cancellation, then it must include all the elements defined in the CancellationGroup group.</p> <p>For some reason, my XML editor (Eclipse) does not like this, but does not indicate why. It shows there being an error on the line &lt;xs:complexType name=&quot;HeaderType&quot;&gt; but does not say what the error is</p>
[ { "answer_id": 101410, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 1, "selected": false, "text": "<p>Whether this is valid depends on the content of the groups: if they're 'sequence' or 'choice' model groups, it's perfectly le...
2008/09/19
[ "https://Stackoverflow.com/questions/101338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15452/" ]
Is it valid to have a 'choice' of 'group' elements when defining an XML Schema (XSD) i.e. is the following valid ``` <xs:complexType name="HeaderType"> <xs:sequence> <xs:element name="reservation-number" type="ReservationNumberType" minOccurs="1" maxOccurs="1" nillable="false" /> <xs:choice minOccurs="1" maxOccurs="1"> <xs:group ref="ReservationGroup" /> <xs:group ref="CancellationGroup"/> </xs:choice> </xs:sequence> </xs:complexType> ``` Where an XML message can represent, for example, either a new reservation or a cancellation of an existing reservation. If the message is for a reservation, then it must include all the elements defined in the ReservationGroup group. If it is a cancellation, then it must include all the elements defined in the CancellationGroup group. For some reason, my XML editor (Eclipse) does not like this, but does not indicate why. It shows there being an error on the line <xs:complexType name="HeaderType"> but does not say what the error is
I'm no XML expert, although I use it quite a lot. This isn't the way I'd generally do this sort of structure. I would prefer a separate complex types rather than a choice of two groups (see the very end of this answer). I suspect that the problem is that ReservationGroup and CancellationGroup start with the same element, in which case you will violate the Schema Component Constraint: Unique Particle Attribution (below). [http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/#cos-nonambig](http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/#cos-nonambig "http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/#cos-nonambig") > > **Schema Component Constraint: Unique > Particle Attribution** > > > A content model > must be formed such that during > ·validation· of an element information > item sequence, the particle component > contained directly, indirectly or > ·implicitly· therein with which to > attempt to ·validate· each item in the > sequence in turn can be uniquely > determined without examining the > content or attributes of that item, > and without any information about the > items in the remainder of the > sequence. > > > **Note:** This constraint > reconstructs for XML Schema the > equivalent constraints of [XML 1.0 > (Second Edition)] and SGML. Given the > presence of element substitution > groups and wildcards, the concise > expression of this constraint is > difficult, see Analysis of the Unique > Particle Attribution Constraint > (non-normative) (§H) for further > discussion. > > > For example, the two groups below are illegal in the same choice, because each of their first element is "name" which means that you cannot identify which group you are looking at. However is the first element of ReservationGroup is different from Cancellation group (resDate and cancDate maybe), then the that is valid. **Edit:** I'd never come across this sort of problem before, and I think its fascinating that the definitions of the groups are totally legal, but if you put them together in a choice, that choice becomes illegal because of the definition of each group. **Groups that cannot form a legal choice** ``` <xs:group name="ReservationGroup"> <xs:sequence> <xs:element name="date"/> <xs:element name="name"/> <xs:element name="address"/> </xs:sequence> </xs:group> <xs:group name="CancellationGroup"> <xs:sequence> <xs:element name="date"/> <xs:element name="name"/> <xs:element name="address"/> </xs:sequence> </xs:group> ``` **Groups that can form a legal choice** ``` <xs:group name="ReservationGroup"> <xs:sequence> <xs:element name="resDate"/> <xs:element name="name"/> <xs:element name="address"/> </xs:sequence> </xs:group> <xs:group name="CancellationGroup"> <xs:sequence> <xs:element name="cancDate"/> <xs:element name="name"/> <xs:element name="address"/> </xs:sequence> </xs:group> ``` As I mentioned above, I'd do this sort of thing with complex types. Yes, it adds another element, but it seems the obvious way and I like obviousness. ``` <xs:complexType name="HeaderType"> <xs:sequence> <xs:element name="reservation-number" type="ReservationNumberType" minOccurs="1" maxOccurs="1" nillable="false" /> <xs:choice minOccurs="1" maxOccurs="1"> <xs:element name="reservation" type="ReservationType" /> <xs:element name="cancellation" type="CancellationType" /> </xs:choice> </xs:sequence> </xs:complexType> ```
101,362
<p>How do you generate passwords?</p> <ul> <li>Random Characters?</li> <li>Passphrases?</li> <li>High Ascii?</li> </ul> <p>Something like this?</p> <pre><code>cat /dev/urandom | strings </code></pre>
[ { "answer_id": 101368, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 4, "selected": false, "text": "<p>A short python script to generate passwords, originally from the python cookbook.</p>\n\n<pre><code>#!/usr/bin/env...
2008/09/19
[ "https://Stackoverflow.com/questions/101362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18769/" ]
How do you generate passwords? * Random Characters? * Passphrases? * High Ascii? Something like this? ``` cat /dev/urandom | strings ```
Mac OS X's "Keychain Access" application gives you access to the nice OS X password generator. Hit command-N and click the key icon. You get to choose password style (memorable, numeric, alphanumeric, random, FIPS-181) and choose the length. It also warns you about weak passwords.
101,363
<p>I'm using Castle Windsor for dependency injection in my test project. I'm trying to create an instance one of my 'Repository' classes. "It works fine on my machine", but when I run a nightly build in TFS, my tests are not able to load said classes.</p> <pre><code>private static readonly WindsorContainer _container = new WindsorContainer(new XmlInterpreter()); public void MyTestInitialize() { var testRepository = (IBogusRepository)_container[typeof(IBogusRepository)]; } </code></pre> <p>xml configuration:</p> <pre><code>&lt;castle&gt; &lt;components&gt; &lt;component id="primaryBogusRepository" type="Example2008.Repository.LALALALALA, Example2008.Repository" service="Example2008.Domain.Repository.IBogusRepository, Example2008.Domain" /&gt; &lt;component id="primaryProductRepository" type="Example2008.Repository.ProductRepository, Example2008.Repository" service="Example2008.Domain.Repository.IProductRepository, Example2008.Domain" /&gt; &lt;/components&gt; &lt;/castle&gt; </code></pre> <p>When I queue a new build it produces the following message:</p> <blockquote> <p>Unable to create instance of class Example2008.Test.ActiveProductRepositoryTest. Error: System.Configuration.ConfigurationException: The type name Example2008.Repository.LALALALALA, Example2008.Repository could not be located.</p> <p>Castle.Windsor.Installer.DefaultComponentInstaller.ObtainType(String typeName) Castle.Windsor.Installer.DefaultComponentInstaller.SetUpComponents(IConfiguration[] configurations, IWindsorContainer container) Castle.Windsor.Installer.DefaultComponentInstaller.SetUp(IWindsorContainer container, IConfigurationStore store) Castle.Windsor.WindsorContainer.RunInstaller() Castle.Windsor.WindsorContainer..ctor(IConfigurationInterpreter interpreter) Example2008.Test.ActiveProductRepositoryTest..cctor() in d:\Code_Temp\Example Project Nightly\Sources\Example2008.Test\ProductRepositoryTest.cs: line 19</p> </blockquote> <p>From this message, it seems that my configuration is correct (it can see that I want to instantiate the concrete class 'LALALALALA', so the xml configuration has obviously been red correctly)</p> <p>I think I have my dependencies set up correctly as well (because it works locally, even if I clean the solution and rebuild).</p> <p>Any thoughts?</p> <p>(using VS2008, TFS 2008.Net 3.5, Castle 1.03, by the way) </p>
[ { "answer_id": 101368, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 4, "selected": false, "text": "<p>A short python script to generate passwords, originally from the python cookbook.</p>\n\n<pre><code>#!/usr/bin/env...
2008/09/19
[ "https://Stackoverflow.com/questions/101363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12756/" ]
I'm using Castle Windsor for dependency injection in my test project. I'm trying to create an instance one of my 'Repository' classes. "It works fine on my machine", but when I run a nightly build in TFS, my tests are not able to load said classes. ``` private static readonly WindsorContainer _container = new WindsorContainer(new XmlInterpreter()); public void MyTestInitialize() { var testRepository = (IBogusRepository)_container[typeof(IBogusRepository)]; } ``` xml configuration: ``` <castle> <components> <component id="primaryBogusRepository" type="Example2008.Repository.LALALALALA, Example2008.Repository" service="Example2008.Domain.Repository.IBogusRepository, Example2008.Domain" /> <component id="primaryProductRepository" type="Example2008.Repository.ProductRepository, Example2008.Repository" service="Example2008.Domain.Repository.IProductRepository, Example2008.Domain" /> </components> </castle> ``` When I queue a new build it produces the following message: > > Unable to create instance of class > Example2008.Test.ActiveProductRepositoryTest. Error: > System.Configuration.ConfigurationException: > The type name > Example2008.Repository.LALALALALA, > Example2008.Repository could not be > located. > > > Castle.Windsor.Installer.DefaultComponentInstaller.ObtainType(String > typeName) > Castle.Windsor.Installer.DefaultComponentInstaller.SetUpComponents(IConfiguration[] > configurations, IWindsorContainer > container) > Castle.Windsor.Installer.DefaultComponentInstaller.SetUp(IWindsorContainer > container, IConfigurationStore store) > Castle.Windsor.WindsorContainer.RunInstaller() > Castle.Windsor.WindsorContainer..ctor(IConfigurationInterpreter > interpreter) > Example2008.Test.ActiveProductRepositoryTest..cctor() > in d:\Code\_Temp\Example Project > Nightly\Sources\Example2008.Test\ProductRepositoryTest.cs: > line 19 > > > From this message, it seems that my configuration is correct (it can see that I want to instantiate the concrete class 'LALALALALA', so the xml configuration has obviously been red correctly) I think I have my dependencies set up correctly as well (because it works locally, even if I clean the solution and rebuild). Any thoughts? (using VS2008, TFS 2008.Net 3.5, Castle 1.03, by the way)
Mac OS X's "Keychain Access" application gives you access to the nice OS X password generator. Hit command-N and click the key icon. You get to choose password style (memorable, numeric, alphanumeric, random, FIPS-181) and choose the length. It also warns you about weak passwords.
101,386
<p>Does PHP have a method of having auto-generated class variables? I <em>think</em> I've seen something like this before but I'm not certain.</p> <pre><code>public class TestClass { private $data = array(); public function TestClass() { $this-&gt;data['firstValue'] = "cheese"; } } </code></pre> <p>The <code>$this-&gt;data</code> array is always an associative array but they keys change from class to class. Is there any viable way to access <code>$this-&gt;data['firstValue']</code> from <code>$this-&gt;firstValue</code> without having to define the link?</p> <p>And if it is, are there any downsides to it?</p> <p>Or is there a static method of defining the link in a way which won't explode if the <code>$this-&gt;data</code> array doesn't contain that key?</p>
[ { "answer_id": 101404, "author": "Jan Hančič", "author_id": 185527, "author_profile": "https://Stackoverflow.com/users/185527", "pm_score": 5, "selected": true, "text": "<p>See here: <a href=\"http://www.php.net/manual/en/language.oop5.overloading.php\" rel=\"noreferrer\">http://www.php....
2008/09/19
[ "https://Stackoverflow.com/questions/101386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12870/" ]
Does PHP have a method of having auto-generated class variables? I *think* I've seen something like this before but I'm not certain. ``` public class TestClass { private $data = array(); public function TestClass() { $this->data['firstValue'] = "cheese"; } } ``` The `$this->data` array is always an associative array but they keys change from class to class. Is there any viable way to access `$this->data['firstValue']` from `$this->firstValue` without having to define the link? And if it is, are there any downsides to it? Or is there a static method of defining the link in a way which won't explode if the `$this->data` array doesn't contain that key?
See here: <http://www.php.net/manual/en/language.oop5.overloading.php> What you want is the "\_\_get" method. There is an example for what you need on the link.
101,439
<p>What is the most efficient way given to raise an integer to the power of another integer in C?</p> <pre><code>// 2^3 pow(2,3) == 8 // 5^5 pow(5,5) == 3125 </code></pre>
[ { "answer_id": 101473, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 3, "selected": false, "text": "<p>An extremely specialized case is, when you need say 2^(-x to the y), where x, is of course is negative and y is too large...
2008/09/19
[ "https://Stackoverflow.com/questions/101439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8123/" ]
What is the most efficient way given to raise an integer to the power of another integer in C? ``` // 2^3 pow(2,3) == 8 // 5^5 pow(5,5) == 3125 ```
Exponentiation by squaring. ``` int ipow(int base, int exp) { int result = 1; for (;;) { if (exp & 1) result *= base; exp >>= 1; if (!exp) break; base *= base; } return result; } ``` This is the standard method for doing modular exponentiation for huge numbers in asymmetric cryptography.
101,449
<p>I'm guessing I need to implement an <code>NVelocityViewEngine</code> and <code>NVelocityView</code> - but before I do I wanted to check to see if anyone has already done this.</p> <p>I can't see anything in the <a href="http://mvccontrib.googlecode.com/svn/trunk/" rel="nofollow noreferrer">trunk</a> for <a href="http://www.codeplex.com/MVCContrib" rel="nofollow noreferrer">MVCContrib</a>.</p> <p>I've already seen the post below - I'm looking specifically for something which works with Preview 5:</p> <ul> <li><a href="http://www.chadmyers.com/Blog/archive/2007/11/28/testing-scottgu-alternate-view-engines-with-asp.net-mvc-nvelocity.aspx" rel="nofollow noreferrer">Testing ScottGu: Alternate View Engines with ASP.NET MVC (NVelocity)</a></li> </ul> <p>Otherwise I'll start writing one :)</p>
[ { "answer_id": 101473, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 3, "selected": false, "text": "<p>An extremely specialized case is, when you need say 2^(-x to the y), where x, is of course is negative and y is too large...
2008/09/19
[ "https://Stackoverflow.com/questions/101449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8542/" ]
I'm guessing I need to implement an `NVelocityViewEngine` and `NVelocityView` - but before I do I wanted to check to see if anyone has already done this. I can't see anything in the [trunk](http://mvccontrib.googlecode.com/svn/trunk/) for [MVCContrib](http://www.codeplex.com/MVCContrib). I've already seen the post below - I'm looking specifically for something which works with Preview 5: * [Testing ScottGu: Alternate View Engines with ASP.NET MVC (NVelocity)](http://www.chadmyers.com/Blog/archive/2007/11/28/testing-scottgu-alternate-view-engines-with-asp.net-mvc-nvelocity.aspx) Otherwise I'll start writing one :)
Exponentiation by squaring. ``` int ipow(int base, int exp) { int result = 1; for (;;) { if (exp & 1) result *= base; exp >>= 1; if (!exp) break; base *= base; } return result; } ``` This is the standard method for doing modular exponentiation for huge numbers in asymmetric cryptography.
101,461
<p>Most languages (Ruby included) allow number literals to be written in at least three bases: decimal, octal and hexadecimal. Numbers in decimal base is the usual thing and are written as (most) people naturally write numbers, 96 is written as <code>96</code>. Numbers prefixed by a zero are usually interpreted as octal based: 96 would be written as <code>0140</code>. Hexadecimal based numbers are usually prefixed by <code>0x</code>: 96 would be written as <code>0x60</code>.</p> <p>The question is: can I write numbers as binary literals in Ruby? How?</p>
[ { "answer_id": 101479, "author": "Thelema", "author_id": 12874, "author_profile": "https://Stackoverflow.com/users/12874", "pm_score": 3, "selected": false, "text": "<p>From <a href=\"http://docs.huihoo.com/ruby/ruby-man-1.4/syntax.html#numeric\" rel=\"noreferrer\">this manual</a></p>\n\...
2008/09/19
[ "https://Stackoverflow.com/questions/101461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17801/" ]
Most languages (Ruby included) allow number literals to be written in at least three bases: decimal, octal and hexadecimal. Numbers in decimal base is the usual thing and are written as (most) people naturally write numbers, 96 is written as `96`. Numbers prefixed by a zero are usually interpreted as octal based: 96 would be written as `0140`. Hexadecimal based numbers are usually prefixed by `0x`: 96 would be written as `0x60`. The question is: can I write numbers as binary literals in Ruby? How?
use 0b prefix ``` >> 0b100 => 4 ```
101,463
<p>I know how to change the schema of a table in SQL server 2005:</p> <pre><code>ALTER SCHEMA NewSchama TRANSFER dbo.Table1 </code></pre> <p>But how can i check and/or alter stored procedures that use the old schema name?</p> <p>Sorry: I mean: There are stored procedures that have the old schema name of the table in the sql of the stored procedure... How can i edit all the stored procedures that have the dbo.Table1 in the body of the procedure...</p>
[ { "answer_id": 101509, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 1, "selected": true, "text": "<p>Get a list of dependent objects by right-clicking on the table before you change the schema and then look at what is depende...
2008/09/19
[ "https://Stackoverflow.com/questions/101463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13262/" ]
I know how to change the schema of a table in SQL server 2005: ``` ALTER SCHEMA NewSchama TRANSFER dbo.Table1 ``` But how can i check and/or alter stored procedures that use the old schema name? Sorry: I mean: There are stored procedures that have the old schema name of the table in the sql of the stored procedure... How can i edit all the stored procedures that have the dbo.Table1 in the body of the procedure...
Get a list of dependent objects by right-clicking on the table before you change the schema and then look at what is dependent on the table, make a list and then change those. There is, however, always a possibility that you'll miss something because it is possible to break the dependencies SQL server tracks. But the best way would be to script the database out into a file and then do a search for the table name, make a list of all of the sprocs where it needs to be changed and then add those to the script to change the schema of the table.
101,470
<p>Does anybody know if there is a feasible way on Windows XP to programmatically create and configure a user account so that after logging in from the console (no terminal services) a specific app is launched and the user is "locked" to that app ?</p> <p>The user should be prevented from doing anything else with the system (e.g.: no ctrl+alt+canc, no ctrl+shift+esc, no win+e, no nothing).</p> <p>As an added optional bonus the user should be logged off when the launched app is closed and/or crashes.</p> <p>Any existing free tool, language or any mixture of them that gets the job done would be fine (batch, VB-script, C, C++, whatever)</p>
[ { "answer_id": 104220, "author": "kervin", "author_id": 16549, "author_profile": "https://Stackoverflow.com/users/16549", "pm_score": 0, "selected": false, "text": "<p>I guess you're building a windows kiosk?</p>\n\n<p>Here's some background in replacing the windows login shell - <a href...
2008/09/19
[ "https://Stackoverflow.com/questions/101470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18780/" ]
Does anybody know if there is a feasible way on Windows XP to programmatically create and configure a user account so that after logging in from the console (no terminal services) a specific app is launched and the user is "locked" to that app ? The user should be prevented from doing anything else with the system (e.g.: no ctrl+alt+canc, no ctrl+shift+esc, no win+e, no nothing). As an added optional bonus the user should be logged off when the launched app is closed and/or crashes. Any existing free tool, language or any mixture of them that gets the job done would be fine (batch, VB-script, C, C++, whatever)
SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon has two values UserInit points to the application that is executed upon successful logon. The default app there, userinit.exe processes domain logon scripts (if any) and then launches the specified Shell= application. By creating or replacing those entries in HKEY\_CURRENT\_USER or in a HKEY\_USERS hive you can replace the shell for a specific user. Once you ahve your own shell in place, you have very little to worry about, unless the "kiosk user" has access to a keyboard and can press ctrl-alt-del. This seems to be hardcoded to launch taskmgr.exe - rather than replacing the exe, you can set the following registry key ``` [SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\taskmgr.exe] Debugger="A path to an exe file that will be run instead of taskmgr.exe" ```
101,487
<p>I have some code which collects points (consed integers) from a loop which looks something like this:</p> <pre><code>(loop for x from 1 to 100 for y from 100 downto 1 collect `(,x . ,y)) </code></pre> <p>My question is, is it correct to use <code>`(,x . ,y)</code> in this situation?</p> <p>Edit: This sample is not about generating a table of 100x100 items, the code here just illustrate the use of two loop variables and the consing of their values. I have edited the loop to make this clear. The actual loop I use depends on several other functions (and is part of one itself) so it made more sense to replace the calls with literal integers and to pull the loop out of the function.</p>
[ { "answer_id": 101503, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 1, "selected": false, "text": "<p>Why not just</p>\n\n<pre><code>(cons x y)\n</code></pre>\n\n<p>By the way, I tried to run your code in CLISP and it did...
2008/09/19
[ "https://Stackoverflow.com/questions/101487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7780/" ]
I have some code which collects points (consed integers) from a loop which looks something like this: ``` (loop for x from 1 to 100 for y from 100 downto 1 collect `(,x . ,y)) ``` My question is, is it correct to use ``(,x . ,y)` in this situation? Edit: This sample is not about generating a table of 100x100 items, the code here just illustrate the use of two loop variables and the consing of their values. I have edited the loop to make this clear. The actual loop I use depends on several other functions (and is part of one itself) so it made more sense to replace the calls with literal integers and to pull the loop out of the function.
It would be much 'better' to just do (cons x y). But to **answer the question**, there is nothing wrong with doing that :) (except making it a tad slower).
101,532
<p>When I run a Flex application in the debug flash player I get an exception pop up as soon as something unexpected happened. However when a customer uses the application he does not use the debug flash player. In this case he does not get an exception pop up, but he UI is not working.</p> <p>So for supportability reasons, I would like to catch any exception that can happen anywhere in the Flex UI and present an error message in a Flex internal popup. By using Java I would just encapsulate the whole UI code in a try/catch block, but with MXML applications in Flex I do not know, where I could perform such a general try/catch.</p>
[ { "answer_id": 101953, "author": "Richard Szalay", "author_id": 3603, "author_profile": "https://Stackoverflow.com/users/3603", "pm_score": 7, "selected": true, "text": "<p>There is no way to be notified on uncaught exceptions in Flex 3. Adobe are aware of the problem but I don't know if...
2008/09/19
[ "https://Stackoverflow.com/questions/101532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7524/" ]
When I run a Flex application in the debug flash player I get an exception pop up as soon as something unexpected happened. However when a customer uses the application he does not use the debug flash player. In this case he does not get an exception pop up, but he UI is not working. So for supportability reasons, I would like to catch any exception that can happen anywhere in the Flex UI and present an error message in a Flex internal popup. By using Java I would just encapsulate the whole UI code in a try/catch block, but with MXML applications in Flex I do not know, where I could perform such a general try/catch.
There is no way to be notified on uncaught exceptions in Flex 3. Adobe are aware of the problem but I don't know if they plan on creating a workaround. The only solution as it stands is to put try/catch in logical places and make sure you are listening to the ERROR (or FAULT for webservices) event for anything that dispatches them. **Edit:** Furthermore, it's actually impossible to catch an error thrown from an event handler. I have logged a [bug](http://bugs.adobe.com/jira/browse/FP-1619) on the Adobe Bug System. **Update 2010-01-12:** Global error handling is now supported in [Flash 10.1](http://labs.adobe.com/technologies/flashplayer10/) and [AIR 2.0](http://labs.adobe.com/technologies/air2) (both in beta), and is achieved by subscribing the [UNCAUGHT\_ERROR](http://help.adobe.com/en_US/FlashPlatform/beta/reference/actionscript/3/flash/events/UncaughtErrorEvent.html) event of [LoaderInfo.uncaughtErrorEvents](http://help.adobe.com/en_US/FlashPlatform/beta/reference/actionscript/3/flash/display/LoaderInfo.html#uncaughtErrorEvents). The following code is taken from the [code sample on livedocs](http://help.adobe.com/en_US/FlashPlatform/beta/reference/actionscript/3/flash/display/LoaderInfo.html#uncaughtErrorEvents): ``` public class UncaughtErrorEventExample extends Sprite { public function UncaughtErrorEventExample() { loaderInfo.uncaughtErrorEvents.addEventListener( UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler); } private function uncaughtErrorHandler(event:UncaughtErrorEvent):void { if (event.error is Error) { var error:Error = event.error as Error; // do something with the error } else if (event.error is ErrorEvent) { var errorEvent:ErrorEvent = event.error as ErrorEvent; // do something with the error } else { // a non-Error, non-ErrorEvent type was thrown and uncaught } } ```
101,533
<p>I have created a C# class file by using a XSD-file as an input. One of my properties look like this:</p> <pre><code> private System.DateTime timeField; [System.Xml.Serialization.XmlElementAttribute(DataType="time")] public System.DateTime Time { get { return this.timeField; } set { this.timeField = value; } } </code></pre> <p>When serialized, the contents of the file now looks like this:</p> <pre><code>&lt;Time&gt;14:04:02.1661975+02:00&lt;/Time&gt; </code></pre> <p>Is it possible, with XmlAttributes on the property, to have it render without the milliseconds and the GMT-value like this?</p> <pre><code>&lt;Time&gt;14:04:02&lt;/Time&gt; </code></pre> <p>Is this possible, or do i need to hack together some sort of xsl/xpath-replace-magic after the class has been serialized?</p> <p>It is not a solution to changing the object to String, because it is used like a DateTime in the rest of the application and allows us to create an xml-representation from an object by using the XmlSerializer.Serialize() method.</p> <p>The reason I need to remove the extra info from the field is that the receiving system does not conform to the w3c-standards for the time datatype.</p>
[ { "answer_id": 101598, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 5, "selected": true, "text": "<p>You could create a string property that does the translation to/from your timeField field and put the serial...
2008/09/19
[ "https://Stackoverflow.com/questions/101533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2257/" ]
I have created a C# class file by using a XSD-file as an input. One of my properties look like this: ``` private System.DateTime timeField; [System.Xml.Serialization.XmlElementAttribute(DataType="time")] public System.DateTime Time { get { return this.timeField; } set { this.timeField = value; } } ``` When serialized, the contents of the file now looks like this: ``` <Time>14:04:02.1661975+02:00</Time> ``` Is it possible, with XmlAttributes on the property, to have it render without the milliseconds and the GMT-value like this? ``` <Time>14:04:02</Time> ``` Is this possible, or do i need to hack together some sort of xsl/xpath-replace-magic after the class has been serialized? It is not a solution to changing the object to String, because it is used like a DateTime in the rest of the application and allows us to create an xml-representation from an object by using the XmlSerializer.Serialize() method. The reason I need to remove the extra info from the field is that the receiving system does not conform to the w3c-standards for the time datatype.
You could create a string property that does the translation to/from your timeField field and put the serialization attribute on that instead the the real DateTime property that the rest of the application uses.
101,569
<p>I need to write a module to detect similar documents. I have read many papers of fingerprints of documents techniques and others, but I do not know how to write code or implement such a solution. The algorithm should work for Chinese, Japanese, English and German language or be language independent. How can I accomplish this?</p>
[ { "answer_id": 101605, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 3, "selected": false, "text": "<p>You can use or at last study <a href=\"http://docs.python.org/lib/module-difflib.html\" rel=\"noreferrer\" title=\"diffl...
2008/09/19
[ "https://Stackoverflow.com/questions/101569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17451/" ]
I need to write a module to detect similar documents. I have read many papers of fingerprints of documents techniques and others, but I do not know how to write code or implement such a solution. The algorithm should work for Chinese, Japanese, English and German language or be language independent. How can I accomplish this?
Bayesian filters have exactly this purpose. That's the techno you'll find in most tools that identify spam. Example, to detect a language (from <http://sebsauvage.net/python/snyppets/#bayesian>) : ``` from reverend.thomas import Bayes guesser = Bayes() guesser.train('french','La souris est rentrée dans son trou.') guesser.train('english','my tailor is rich.') guesser.train('french','Je ne sais pas si je viendrai demain.') guesser.train('english','I do not plan to update my website soon.') >>> print guesser.guess('Jumping out of cliffs it not a good idea.') [('english', 0.99990000000000001), ('french', 9.9999999999988987e-005)] >>> print guesser.guess('Demain il fera très probablement chaud.') [('french', 0.99990000000000001), ('english', 9.9999999999988987e-005)] ``` But it works to detect any type you will train it for : technical text, songs, jokes, etc. As long as you can provide enought material to let the tool learn what does you document looks like.
101,574
<p>I want a list of hyperlinks on a basic html page, which point to files on our corporate intranet.</p> <p>When a user clicks the link, I want the file to open. They are excel spreadsheets, and this is an intranet environment, so I can count on everyone having Excel installed.</p> <p>I've tried two things:</p> <ol> <li>The obvious and simple thing:</li> </ol> <pre class="lang-html prettyprint-override"><code>&lt;a href="file://server/directory/file.xlsx"&gt;Click me!&lt;/a&gt; </code></pre> <ol start="2"> <li>A <a href="/questions/tagged/vbscript" class="post-tag" title="show questions tagged &#39;vbscript&#39;" rel="tag">vbscript</a> option that I found in a Google search:</li> </ol> <pre class="lang-html prettyprint-override"><code>&lt;HTML&gt; &lt;HEAD&gt; &lt;SCRIPT LANGUAGE=VBScript&gt; Dim objExcel Sub Btn1_onclick() call OpenWorkbook("\\server\directory\file.xlsx") End Sub Sub OpenWorkbook(strLocation) Set objExcel = CreateObject("Excel.Application") objExcel.Visible = true objExcel.Workbooks.Open strLocation objExcel.UserControl = true End Sub &lt;/SCRIPT&gt; &lt;TITLE&gt;Launch Excel&lt;/Title&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;INPUT TYPE=BUTTON NAME=Btn1 VALUE="Open Excel File"&gt; &lt;/BODY&gt; &lt;/HTML&gt; </code></pre> <p>I know this is a very basic question, but I would appreciate any help I can get.</p> <p><strong><em>Edit: Any suggestions that work in both IE and Firefox?</em></strong></p>
[ { "answer_id": 101586, "author": "diciu", "author_id": 2811, "author_profile": "https://Stackoverflow.com/users/2811", "pm_score": 2, "selected": false, "text": "<p><code>&lt;a href=\"file://server/directory/file.xlsx\" target=\"_blank\"&gt;</code> if I remember correctly.</p>\n" }, ...
2008/09/19
[ "https://Stackoverflow.com/questions/101574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
I want a list of hyperlinks on a basic html page, which point to files on our corporate intranet. When a user clicks the link, I want the file to open. They are excel spreadsheets, and this is an intranet environment, so I can count on everyone having Excel installed. I've tried two things: 1. The obvious and simple thing: ```html <a href="file://server/directory/file.xlsx">Click me!</a> ``` 2. A [vbscript](/questions/tagged/vbscript "show questions tagged 'vbscript'") option that I found in a Google search: ```html <HTML> <HEAD> <SCRIPT LANGUAGE=VBScript> Dim objExcel Sub Btn1_onclick() call OpenWorkbook("\\server\directory\file.xlsx") End Sub Sub OpenWorkbook(strLocation) Set objExcel = CreateObject("Excel.Application") objExcel.Visible = true objExcel.Workbooks.Open strLocation objExcel.UserControl = true End Sub </SCRIPT> <TITLE>Launch Excel</Title> </HEAD> <BODY> <INPUT TYPE=BUTTON NAME=Btn1 VALUE="Open Excel File"> </BODY> </HTML> ``` I know this is a very basic question, but I would appreciate any help I can get. ***Edit: Any suggestions that work in both IE and Firefox?***
Try formatting the link like this (looks hellish, but it works in Firefox 3 under Vista for me) : ``` <a href="file://///SERVER/directory/file.ext">file.ext</a> ```
101,597
<p>Let's say I have the following HTML:</p> <pre><code>&lt;table id="foo"&gt; &lt;th class="sortasc"&gt;Header&lt;/th&gt; &lt;/table&gt; &lt;table id="bar"&gt; &lt;th class="sortasc"&gt;Header&lt;/th&gt; &lt;/table&gt; </code></pre> <p>I know that I can do the following to get all of the <strong>th</strong> elements that have class="sortasc"</p> <pre><code>$$('th.sortasc').each() </code></pre> <p>However that gives me the <strong>th</strong> elements from both table <em>foo</em> and table <em>bar</em>.</p> <p>How can I tell it to give me just the th elements from table <em>foo</em>?</p>
[ { "answer_id": 101611, "author": "Fuzzy76", "author_id": 15932, "author_profile": "https://Stackoverflow.com/users/15932", "pm_score": 4, "selected": true, "text": "<p>table#foo th.sortasc</p>\n" }, { "answer_id": 101616, "author": "pjesi", "author_id": 1296737, "auth...
2008/09/19
[ "https://Stackoverflow.com/questions/101597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
Let's say I have the following HTML: ``` <table id="foo"> <th class="sortasc">Header</th> </table> <table id="bar"> <th class="sortasc">Header</th> </table> ``` I know that I can do the following to get all of the **th** elements that have class="sortasc" ``` $$('th.sortasc').each() ``` However that gives me the **th** elements from both table *foo* and table *bar*. How can I tell it to give me just the th elements from table *foo*?
table#foo th.sortasc
101,693
<p>I get an error everytime I upload my webapp to the provider. Because of the customErrors mode, all I see is the default "Runtime error" message, instructing me to turn off customErrors to view more about the error.</p> <p>Exasperated, I've set my web.config to look like this:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;configuration&gt; &lt;system.web&gt; &lt;customErrors mode="Off"/&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre> <p>And still, all I get is the stupid remote errors page with no useful info on it. What else can I do to turn customErrors OFF ?!</p>
[ { "answer_id": 101707, "author": "Nick Craver", "author_id": 13249, "author_profile": "https://Stackoverflow.com/users/13249", "pm_score": 3, "selected": false, "text": "<p>If you're still getting that page, it's likely that it's blowing up before getting past the Web.Config</p>\n\n<p>Ma...
2008/09/19
[ "https://Stackoverflow.com/questions/101693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3263/" ]
I get an error everytime I upload my webapp to the provider. Because of the customErrors mode, all I see is the default "Runtime error" message, instructing me to turn off customErrors to view more about the error. Exasperated, I've set my web.config to look like this: ``` <?xml version="1.0"?> <configuration> <system.web> <customErrors mode="Off"/> </system.web> </configuration> ``` And still, all I get is the stupid remote errors page with no useful info on it. What else can I do to turn customErrors OFF ?!
This has been driving me insane for the past few days and couldn't get around it but have finally figured it out: In my machine.config file I had an entry under `<system.web>`: ``` <deployment retail="true" /> ``` This seems to override any other customError settings that you have specified in a web.config file, so setting the above entry to: ``` <deployment retail="false" /> ``` now means that I can once again see the detailed error messages that I need to. The `machine.config` is located at **32-bit** ``` %windir%\Microsoft.NET\Framework\[version]\config\machine.config ``` **64-bit** ``` %windir%\Microsoft.NET\Framework64\[version]\config\machine.config ``` Hope that helps someone out there and saves a few hours of hair-pulling.
101,708
<p>In VB.net I'm using the TcpClient to retrieve a string of data. I'm constantly checking the .Connected property to verify if the client is connected but even if the client disconnects this still returns true. What can I use as a workaround for this?</p> <p>This is a stripped down version of my current code:</p> <pre><code>Dim client as TcpClient = Nothing client = listener.AcceptTcpClient do while client.connected = true dim stream as networkStream = client.GetStream() dim bytes(1024) as byte dim numCharRead as integer = stream.Read(bytes,0,bytes.length) dim strRead as string = System.Text.Encoding.ASCII.GetString(bytes,0,i) loop </code></pre> <p>I would have figured at least the GetStream() call would throw an exception if the client was disconnected but I've closed the other app and it still doesn't... </p> <p>Thanks. </p> <p><strong>EDIT</strong> Polling the Client.Available was suggested but that doesn't solve the issue. If the client is not 'acutally' connected available just returns 0.</p> <p>The key is that I'm trying to allow the connection to stay open and allow me to receive data multiple times over the same socket connection. </p>
[ { "answer_id": 101759, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": -1, "selected": false, "text": "<p>Instead of polling client.connected, maybe use of the NetworkStream's properties to see if there's no more data ...
2008/09/19
[ "https://Stackoverflow.com/questions/101708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77830/" ]
In VB.net I'm using the TcpClient to retrieve a string of data. I'm constantly checking the .Connected property to verify if the client is connected but even if the client disconnects this still returns true. What can I use as a workaround for this? This is a stripped down version of my current code: ``` Dim client as TcpClient = Nothing client = listener.AcceptTcpClient do while client.connected = true dim stream as networkStream = client.GetStream() dim bytes(1024) as byte dim numCharRead as integer = stream.Read(bytes,0,bytes.length) dim strRead as string = System.Text.Encoding.ASCII.GetString(bytes,0,i) loop ``` I would have figured at least the GetStream() call would throw an exception if the client was disconnected but I've closed the other app and it still doesn't... Thanks. **EDIT** Polling the Client.Available was suggested but that doesn't solve the issue. If the client is not 'acutally' connected available just returns 0. The key is that I'm trying to allow the connection to stay open and allow me to receive data multiple times over the same socket connection.
When NetworkStream.Read returns 0, then the connection has been closed. [Reference](http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.read(VS.71).aspx): > > If no data is available for reading, the NetworkStream.Read method will block until data is available. To avoid blocking, you can use the DataAvailable property to determine if data is queued in the incoming network buffer for reading. If DataAvailable returns true, the Read operation will complete immediately. The Read operation will read as much data as is available, up to the number of bytes specified by the size parameter. **If the remote host shuts down the connection, and all available data has been received, the Read method will complete immediately and return zero bytes.** > > >
101,742
<p>I have a Google App Engine app - <a href="http://mylovelyapp.appspot.com/" rel="noreferrer">http://mylovelyapp.appspot.com/</a> It has a page - mylovelypage</p> <p>For the moment, the page just does <code>self.response.out.write('OK')</code></p> <p>If I run the following Python at my computer:</p> <pre><code>import urllib2 f = urllib2.urlopen("http://mylovelyapp.appspot.com/mylovelypage") s = f.read() print s f.close() </code></pre> <p>it prints "OK"</p> <p>the problem is if I add <code>login:required</code> to this page in the app's yaml</p> <p>then this prints out the HTML of the Google Accounts login page</p> <p>I've tried "normal" authentication approaches. e.g.</p> <pre><code>passman = urllib2.HTTPPasswordMgrWithDefaultRealm() auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(None, uri='http://mylovelyapp.appspot.com/mylovelypage', user='billy.bob@gmail.com', passwd='billybobspasswd') opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) </code></pre> <p>But it makes no difference - I still get the login page's HTML back.</p> <p>I've tried <a href="http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html" rel="noreferrer">Google's ClientLogin auth API</a>, but I can't get it to work.</p> <pre><code>h = httplib2.Http() auth_uri = 'https://www.google.com/accounts/ClientLogin' headers = {'Content-Type': 'application/x-www-form-urlencoded'} myrequest = "Email=%s&amp;Passwd=%s&amp;service=ah&amp;source=DALELANE-0.0" % ("billy.bob@gmail.com", "billybobspassword") response, content = h.request(auth_uri, 'POST', body=myrequest, headers=headers) if response['status'] == '200': authtok = re.search('Auth=(\S*)', content).group(1) headers = {} headers['Authorization'] = 'GoogleLogin auth=%s' % authtok.strip() headers['Content-Length'] = '0' response, content = h.request("http://mylovelyapp.appspot.com/mylovelypage", 'POST', body="", headers=headers) while response['status'] == "302": response, content = h.request(response['location'], 'POST', body="", headers=headers) print content </code></pre> <p>I do seem to be able to get some token correctly, but attempts to use it in the header when I call 'mylovelypage' still just return me the login page's HTML. :-( </p> <p>Can anyone help, please?</p> <p>Could I use the <a href="http://code.google.com/p/gdata-python-client/" rel="noreferrer">GData client library</a> to do this sort of thing? From what I've read, I think it should be able to access App Engine apps, but I haven't been any more successful at getting the authentication working for App Engine stuff there either </p> <p>Any pointers to samples, articles, or even just keywords I should be searching for to get me started, would be very much appreciated.</p> <p>Thanks!</p>
[ { "answer_id": 102158, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>I'm not a python expert or a app engine expert. But did you try following the sample appl at <a href=\"http://code.google....
2008/09/19
[ "https://Stackoverflow.com/questions/101742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/477/" ]
I have a Google App Engine app - <http://mylovelyapp.appspot.com/> It has a page - mylovelypage For the moment, the page just does `self.response.out.write('OK')` If I run the following Python at my computer: ``` import urllib2 f = urllib2.urlopen("http://mylovelyapp.appspot.com/mylovelypage") s = f.read() print s f.close() ``` it prints "OK" the problem is if I add `login:required` to this page in the app's yaml then this prints out the HTML of the Google Accounts login page I've tried "normal" authentication approaches. e.g. ``` passman = urllib2.HTTPPasswordMgrWithDefaultRealm() auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(None, uri='http://mylovelyapp.appspot.com/mylovelypage', user='billy.bob@gmail.com', passwd='billybobspasswd') opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) ``` But it makes no difference - I still get the login page's HTML back. I've tried [Google's ClientLogin auth API](http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html), but I can't get it to work. ``` h = httplib2.Http() auth_uri = 'https://www.google.com/accounts/ClientLogin' headers = {'Content-Type': 'application/x-www-form-urlencoded'} myrequest = "Email=%s&Passwd=%s&service=ah&source=DALELANE-0.0" % ("billy.bob@gmail.com", "billybobspassword") response, content = h.request(auth_uri, 'POST', body=myrequest, headers=headers) if response['status'] == '200': authtok = re.search('Auth=(\S*)', content).group(1) headers = {} headers['Authorization'] = 'GoogleLogin auth=%s' % authtok.strip() headers['Content-Length'] = '0' response, content = h.request("http://mylovelyapp.appspot.com/mylovelypage", 'POST', body="", headers=headers) while response['status'] == "302": response, content = h.request(response['location'], 'POST', body="", headers=headers) print content ``` I do seem to be able to get some token correctly, but attempts to use it in the header when I call 'mylovelypage' still just return me the login page's HTML. :-( Can anyone help, please? Could I use the [GData client library](http://code.google.com/p/gdata-python-client/) to do this sort of thing? From what I've read, I think it should be able to access App Engine apps, but I haven't been any more successful at getting the authentication working for App Engine stuff there either Any pointers to samples, articles, or even just keywords I should be searching for to get me started, would be very much appreciated. Thanks!
appcfg.py, the tool that uploads data to App Engine has to do exactly this to authenticate itself with the App Engine server. The relevant functionality is abstracted into appengine\_rpc.py. In a nutshell, the solution is: 1. Use the [Google ClientLogin API](http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html) to obtain an authentication token. appengine\_rpc.py does this in [\_GetAuthToken](http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/tools/appengine_rpc.py#180) 2. Send the auth token to a special URL on your App Engine app. That page then returns a cookie and a 302 redirect. Ignore the redirect and store the cookie. appcfg.py does this in [\_GetAuthCookie](http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/tools/appengine_rpc.py#228) 3. Use the returned cookie in all future requests. You may also want to look at [\_Authenticate](http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/tools/appengine_rpc.py#253), to see how appcfg handles the various return codes from ClientLogin, and [\_GetOpener](http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/tools/appengine_rpc.py#397), to see how appcfg creates a urllib2 OpenerDirector that doesn't follow HTTP redirects. Or you could, in fact, just use the AbstractRpcServer and HttpRpcServer classes wholesale, since they do pretty much everything you need.
101,752
<p>I used <code>git pull</code> and had a merge conflict:</p> <pre><code>unmerged: some_file.txt You are in the middle of a conflicted merge. </code></pre> <p>How do I abandon my changes to the file and keep only the pulled changes?</p>
[ { "answer_id": 101773, "author": "David Precious", "author_id": 4040, "author_profile": "https://Stackoverflow.com/users/4040", "pm_score": 7, "selected": false, "text": "<p>I think it's <code>git reset</code> you need.</p>\n\n<p>Beware that <code>git revert</code> means something very d...
2008/09/19
[ "https://Stackoverflow.com/questions/101752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18666/" ]
I used `git pull` and had a merge conflict: ``` unmerged: some_file.txt You are in the middle of a conflicted merge. ``` How do I abandon my changes to the file and keep only the pulled changes?
Since your `pull` was unsuccessful then `HEAD` (not `HEAD^`) is the last "valid" commit on your branch: ``` git reset --hard HEAD ``` The other piece you want is to let their changes over-ride your changes. Older versions of git allowed you to use the "theirs" merge strategy: ``` git pull --strategy=theirs remote_branch ``` But this has since been removed, as explained in [this message by Junio Hamano](http://marc.info/?l=git&m=121637513604413&w=2) (the Git maintainer). As noted in [the link](http://marc.info/?l=git&m=121637513604413&w=2), instead you would do this: ``` git fetch origin git reset --hard origin ```
101,767
<p>I'm trying to use cygwin as a build environment under Windows. I have some dependencies on 3rd party packages, for example, GTK+. </p> <p>Normally when I build under Linux, in my Makefile I can add a call to pkg-config as an argument to gcc, so it comes out like so:</p> <pre> gcc example.c `pkg-config --libs --cflags gtk+-2.0` </pre> <p>This works fine under Linux, but in cygwin I get:</p> <pre> :Invalid argument make: *** [example] Error 1 </pre> <p>Right now, I am just manually running pkg-config and pasting the output into the Makefile, which is truly terrible. Is there a good way to workaround or fix for this issue?</p> <p>Make isn't the culprit. I can copy and paste the command line that make uses to call gcc, and that by itself will run gcc, which halts with ": Invalid argument". </p> <p>I wrote a small test program to print out command line arguments:</p> <pre><code>for (i = 0; i &lt; argc; i++) printf("'%s'\n", argv[i]); </code></pre> <p>Notice the single quotes.</p> <pre> $ pkg-config --libs gtk+-2.0 -Lc:/mingw/lib -lgtk-win32-2.0 -lgdk-win32-2.0 -latk-1.0 -lgdk_pixbuf-2.0 -lpang owin32-1.0 -lgdi32 -lpangocairo-1.0 -lpango-1.0 -lcairo -lgobject-2.0 -lgmodule- 2.0 -lglib-2.0 -lintl </pre> <p>Running through the test program:</p> <pre> $ ./t `pkg-config --libs gtk+-2.0` 'C:\cygwin\home\smo\pvm\src\t.exe' '-Lc:/mingw/lib' '-lgtk-win32-2.0' '-lgdk-win32-2.0' '-latk-1.0' '-lgdk_pixbuf-2.0' '-lpangowin32-1.0' '-lgdi32' '-lpangocairo-1.0' '-lpango-1.0' '-lcairo' '-lgobject-2.0' '-lgmodule-2.0' '-lglib-2.0' '-lintl' ' </pre> <p>Notice the one single quote on the last line. It looks like argc is one greater than it should be, and argv[argc - 1] is null. Running the same test on Linux does not have this result.</p> <p>That said, is there, say, some way I could have the Makefile store the result of pkg-config into a variable, and then use that variable, rather than using the back-tick operator?</p>
[ { "answer_id": 102136, "author": "Tobias Kunze", "author_id": 6070, "author_profile": "https://Stackoverflow.com/users/6070", "pm_score": 2, "selected": false, "text": "<p>Are you sure that you're using the make provided by Cygwin? Use</p>\n\n<pre><code>which make\nmake --version\n</code...
2008/09/19
[ "https://Stackoverflow.com/questions/101767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16080/" ]
I'm trying to use cygwin as a build environment under Windows. I have some dependencies on 3rd party packages, for example, GTK+. Normally when I build under Linux, in my Makefile I can add a call to pkg-config as an argument to gcc, so it comes out like so: ``` gcc example.c `pkg-config --libs --cflags gtk+-2.0` ``` This works fine under Linux, but in cygwin I get: ``` :Invalid argument make: *** [example] Error 1 ``` Right now, I am just manually running pkg-config and pasting the output into the Makefile, which is truly terrible. Is there a good way to workaround or fix for this issue? Make isn't the culprit. I can copy and paste the command line that make uses to call gcc, and that by itself will run gcc, which halts with ": Invalid argument". I wrote a small test program to print out command line arguments: ``` for (i = 0; i < argc; i++) printf("'%s'\n", argv[i]); ``` Notice the single quotes. ``` $ pkg-config --libs gtk+-2.0 -Lc:/mingw/lib -lgtk-win32-2.0 -lgdk-win32-2.0 -latk-1.0 -lgdk_pixbuf-2.0 -lpang owin32-1.0 -lgdi32 -lpangocairo-1.0 -lpango-1.0 -lcairo -lgobject-2.0 -lgmodule- 2.0 -lglib-2.0 -lintl ``` Running through the test program: ``` $ ./t `pkg-config --libs gtk+-2.0` 'C:\cygwin\home\smo\pvm\src\t.exe' '-Lc:/mingw/lib' '-lgtk-win32-2.0' '-lgdk-win32-2.0' '-latk-1.0' '-lgdk_pixbuf-2.0' '-lpangowin32-1.0' '-lgdi32' '-lpangocairo-1.0' '-lpango-1.0' '-lcairo' '-lgobject-2.0' '-lgmodule-2.0' '-lglib-2.0' '-lintl' ' ``` Notice the one single quote on the last line. It looks like argc is one greater than it should be, and argv[argc - 1] is null. Running the same test on Linux does not have this result. That said, is there, say, some way I could have the Makefile store the result of pkg-config into a variable, and then use that variable, rather than using the back-tick operator?
> > That said, is there, say, some way I could have the Makefile store the result of pkg-config into a variable, and then use that variable, rather than using the back-tick operator? > > > GTK\_LIBS = $(shell pkg-config --libs gtk+-2.0)
101,777
<p>Let's say I have this code:</p> <pre><code>if (md5($_POST[$foo['bar']]) == $somemd5) { doSomethingWith(md5($_POST[$foo['bar']]); } </code></pre> <p>I could shorten that down by doing:</p> <pre><code>$value = md5($_POST[$foo['bar']]; if ($value == $somemd5) { doSomethingWith($value); } </code></pre> <p>But is there any pre-set variable that contains the first or second condition of the current if? Like for instance:</p> <pre><code>if (md5($_POST[$foo['bar']]) == $somemd5) { doSomethingWith($if1); } </code></pre> <p>May be a unnecessary way of doing it, but I'm just wondering.</p>
[ { "answer_id": 101805, "author": "smo", "author_id": 16080, "author_profile": "https://Stackoverflow.com/users/16080", "pm_score": 4, "selected": true, "text": "<p>No, but since the assignment itself is an expression, you can use the assignment as the conditional expression for the if st...
2008/09/19
[ "https://Stackoverflow.com/questions/101777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15214/" ]
Let's say I have this code: ``` if (md5($_POST[$foo['bar']]) == $somemd5) { doSomethingWith(md5($_POST[$foo['bar']]); } ``` I could shorten that down by doing: ``` $value = md5($_POST[$foo['bar']]; if ($value == $somemd5) { doSomethingWith($value); } ``` But is there any pre-set variable that contains the first or second condition of the current if? Like for instance: ``` if (md5($_POST[$foo['bar']]) == $somemd5) { doSomethingWith($if1); } ``` May be a unnecessary way of doing it, but I'm just wondering.
No, but since the assignment itself is an expression, you can use the assignment as the conditional expression for the if statement. ``` if (($value = md5(..)) == $somemd5) { ... } ``` In general, though, you'll want to avoid embedding assignments into conditional expressions: * The code is denser and therefore harder to read, with more nested parentheses. * Mixing = and == in the same expression is just asking for them to get mixed up.
101,783
<p>Anyone happen to have a sample script for recursing a given directory in a filesystem with Powershell? Ultimately what I'm wanting to do is create a script that will generate NSIS file lists for me given a directory. Something very similar to what was done <a href="http://blogs.oracle.com/duffblog/2006/12/dynamic_file_list_with_nsis.html" rel="nofollow noreferrer">here</a> with a BASH script.</p>
[ { "answer_id": 106413, "author": "halr9000", "author_id": 6637, "author_profile": "https://Stackoverflow.com/users/6637", "pm_score": 2, "selected": false, "text": "<p>This is a \"paraphrase\" port of that bash script.</p>\n\n<pre><code>$path = \"c:\\path\\to\\program\"\n$installFiles = ...
2008/09/19
[ "https://Stackoverflow.com/questions/101783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18831/" ]
Anyone happen to have a sample script for recursing a given directory in a filesystem with Powershell? Ultimately what I'm wanting to do is create a script that will generate NSIS file lists for me given a directory. Something very similar to what was done [here](http://blogs.oracle.com/duffblog/2006/12/dynamic_file_list_with_nsis.html) with a BASH script.
As [halr9000](https://stackoverflow.com/questions/101783/recursing-the-file-system-with-powershell#106413) demonstrated, you can use the `-recurse` switch parameter of the `Get-ChildItem` cmdlet to retrieve all files and directories under a specified path. It looks like the bash script you linked to in your question saves out the directories as well, so here is a simple function to return both the files and directories in a single result object: ``` function Get-InstallFiles { param( [string]$path ) $allItems = Get-ChildItem -path $path -recurse $directories = $allItems | ? { $_.PSIsContainer } | % { $_.FullName } $installFiles = $allItems | ? { -not $_.PSIsContainer } | % { $_.FullName } $uninstallFiles = $installFiles[-1..-$installFiles.Length] $result = New-Object PSObject $result | Add-Member NoteProperty Directories $directories $result | Add-Member NoteProperty InstallFiles $installFiles $result | Add-Member NoteProperty UninstallFiles $uninstallFiles return $result } ``` Here is how you could use it to create the same install/uninstall text files from halr9000's example, including uninstall directories: ``` $files = Get-InstallFiles 'C:\some\directory' $files.InstallFiles | Set-Content 'installfiles.txt' $files.UninstallFiles + $files.Directories | Set-Content 'uninstallfiles.txt' ```
101,806
<p>I am working on an application that installs a system wide keyboard hook. I do not want to install this hook when I am running a debug build from inside the visual studio (or else it would hang the studio and eventually the system), and I can avoid this by checking if the DEBUG symbol is defined.</p> <p>However, when I debug the <em>release</em> version of the application, is there a way to detect that it has been started from inside visual studio to avoid the same problem? It is very annoying to have to restart the studio/the computer, just because I had been working on the release build, and want to fix some bugs using the debugger having forgotten to switch back to the debug build. </p> <p>Currently I use something like this to check for this scenario:</p> <pre><code>System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess(); string moduleName = currentProcess.MainModule.ModuleName; bool launchedFromStudio = moduleName.Contains(".vshost"); </code></pre> <p>I would call this the "brute force way", which works in my setting, but I would like to know whether there's another (better) way of detecting this scenario.</p>
[ { "answer_id": 101812, "author": "TraumaPony", "author_id": 18658, "author_profile": "https://Stackoverflow.com/users/18658", "pm_score": 7, "selected": true, "text": "<p>Try: <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.isattached.aspx\" rel=\"noreferrer...
2008/09/19
[ "https://Stackoverflow.com/questions/101806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17378/" ]
I am working on an application that installs a system wide keyboard hook. I do not want to install this hook when I am running a debug build from inside the visual studio (or else it would hang the studio and eventually the system), and I can avoid this by checking if the DEBUG symbol is defined. However, when I debug the *release* version of the application, is there a way to detect that it has been started from inside visual studio to avoid the same problem? It is very annoying to have to restart the studio/the computer, just because I had been working on the release build, and want to fix some bugs using the debugger having forgotten to switch back to the debug build. Currently I use something like this to check for this scenario: ``` System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess(); string moduleName = currentProcess.MainModule.ModuleName; bool launchedFromStudio = moduleName.Contains(".vshost"); ``` I would call this the "brute force way", which works in my setting, but I would like to know whether there's another (better) way of detecting this scenario.
Try: [`System.Diagnostics.Debugger.IsAttached`](http://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.isattached.aspx)
101,818
<p>When I run indent with various options I want against my source, it does what I want but also messes with the placement of *s in pointer types:</p> <pre><code> -int send_pkt(tpkt_t* pkt, void* opt_data); -void dump(tpkt_t* bp); +int send_pkt(tpkt_t * pkt, void *opt_data); +void dump(tpkt * bp); </code></pre> <p>I know my placement of *s next to the type not the variable is unconventional but how can I get indent to just leave them alone? Or is there another tool that will do what I want? I've looked in the man page, the info page, and visited a half a dozen pages that Google suggested and I can't find an option to do this. </p> <p>I tried Artistic Style (a.k.a. AStyle) but can't seem to figure out how to make it indent in multiples of 4 but make every 8 a tab. That is:</p> <pre><code>if ( ... ) { &lt;4spaces&gt;if ( ... ) { &lt;tab&gt;...some code here... &lt;4spaces&gt;} } </code></pre>
[ { "answer_id": 101835, "author": "Chris M.", "author_id": 6747, "author_profile": "https://Stackoverflow.com/users/6747", "pm_score": 4, "selected": false, "text": "<p><strong>Uncrustify</strong> </p>\n\n<p>Uncrustify has several options on how to indent your files. </p>\n\n<p>From the...
2008/09/19
[ "https://Stackoverflow.com/questions/101818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7685/" ]
When I run indent with various options I want against my source, it does what I want but also messes with the placement of \*s in pointer types: ``` -int send_pkt(tpkt_t* pkt, void* opt_data); -void dump(tpkt_t* bp); +int send_pkt(tpkt_t * pkt, void *opt_data); +void dump(tpkt * bp); ``` I know my placement of \*s next to the type not the variable is unconventional but how can I get indent to just leave them alone? Or is there another tool that will do what I want? I've looked in the man page, the info page, and visited a half a dozen pages that Google suggested and I can't find an option to do this. I tried Artistic Style (a.k.a. AStyle) but can't seem to figure out how to make it indent in multiples of 4 but make every 8 a tab. That is: ``` if ( ... ) { <4spaces>if ( ... ) { <tab>...some code here... <4spaces>} } ```
**Uncrustify** Uncrustify has several options on how to indent your files. From the config file: ``` indent_with_tabs How to use tabs when indenting code 0=spaces only 1=indent with tabs, align with spaces 2=indent and align with tabs ``` You can find it [here](http://uncrustify.sourceforge.net/). **BCPP** From the website: *"bcpp indents C/C++ source programs, replacing tabs with spaces or the reverse. Unlike indent, it does (by design) not attempt to wrap long statements."* Find it [here](http://invisible-island.net/bcpp/). **UniversalIndentGUI** It's a tool which supports several beautifiers / formatters. It could lead you to even more alternatives. Find it [here](http://universalindent.sourceforge.net/). **Artistic Style** You could try [Artistic Style aka AStyle](http://astyle.sourceforge.net/) instead (even though it doesn't do what you need it to do, I'll leave it here in case someone else finds it useful).
101,825
<p>That is, I'd like to have a tuple of values.</p> <p>The use case on my mind:</p> <pre><code>Dictionary&lt;Pair&lt;string, int&gt;, object&gt; </code></pre> <p>or</p> <pre><code>Dictionary&lt;Triple&lt;string, int, int&gt;, object&gt; </code></pre> <p>Are there built-in types like Pair or Triple? Or what's the best way of implementing it?</p> <p><strong>Update</strong> There are some general-purpose tuples implementations described in the answers, but for tuples used as keys in dictionaries you should additionaly verify correct calculation of the hash code. Some more info on that in another <a href="https://stackoverflow.com/questions/102690/how-does-c-figure-out-the-hash-code-for-an-object">question</a>.</p> <p><strong>Update 2</strong> I guess it is also worth reminding, that when you use some value as a key in dictionary, it should be immutable.</p>
[ { "answer_id": 101841, "author": "Grad van Horck", "author_id": 12569, "author_profile": "https://Stackoverflow.com/users/12569", "pm_score": 2, "selected": false, "text": "<p>I usually just create my own struct, containing the values. It's often a bit more readable ;)</p>\n" }, { ...
2008/09/19
[ "https://Stackoverflow.com/questions/101825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2351099/" ]
That is, I'd like to have a tuple of values. The use case on my mind: ``` Dictionary<Pair<string, int>, object> ``` or ``` Dictionary<Triple<string, int, int>, object> ``` Are there built-in types like Pair or Triple? Or what's the best way of implementing it? **Update** There are some general-purpose tuples implementations described in the answers, but for tuples used as keys in dictionaries you should additionaly verify correct calculation of the hash code. Some more info on that in another [question](https://stackoverflow.com/questions/102690/how-does-c-figure-out-the-hash-code-for-an-object). **Update 2** I guess it is also worth reminding, that when you use some value as a key in dictionary, it should be immutable.
I have implemented a tuple library in C#. Visit <http://www.adventuresinsoftware.com/generics/> and click on the "tuples" link.
101,850
<p>Take this code:</p> <pre><code>&lt;?php if (isset($_POST['action']) &amp;&amp; !empty($_POST['action'])) { $action = $_POST['action']; } if ($action) { echo $action; } else { echo 'No variable'; } ?&gt; </code></pre> <p>And then access the file with ?action=test Is there any way of preventing $action from automatically being declared by the GET? Other than of course adding</p> <pre><code>&amp;&amp; !isset($_GET['action']) </code></pre> <p>Why would I want the variable to be declared for me?</p>
[ { "answer_id": 101879, "author": "owenmarshall", "author_id": 9806, "author_profile": "https://Stackoverflow.com/users/9806", "pm_score": 6, "selected": true, "text": "<p>Check your php.ini for the <code>register_globals</code> setting. It is probably on, you want it off.</p>\n\n<blockqu...
2008/09/19
[ "https://Stackoverflow.com/questions/101850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15214/" ]
Take this code: ``` <?php if (isset($_POST['action']) && !empty($_POST['action'])) { $action = $_POST['action']; } if ($action) { echo $action; } else { echo 'No variable'; } ?> ``` And then access the file with ?action=test Is there any way of preventing $action from automatically being declared by the GET? Other than of course adding ``` && !isset($_GET['action']) ``` Why would I want the variable to be declared for me?
Check your php.ini for the `register_globals` setting. It is probably on, you want it off. > > Why would I want the variable to be declared for me? > > > [You don't.](http://us3.php.net/manual/en/security.globals.php) It's a horrible security risk. It makes the Environment, GET, POST, Cookie and Server variables global [(PHP manual)](http://us3.php.net/manual/en/ini.core.php#ini.register-globals). These are a handful of [reserved variables](http://us.php.net/manual/en/reserved.variables.php) in PHP.
101,868
<p>Is there any easy to install/use (on unix) database migration tools like Rails Migrations? I really like the idea, but installing ruby/rails purely to manage my database migrations seems overkill.</p>
[ { "answer_id": 102353, "author": "Otto", "author_id": 9594, "author_profile": "https://Stackoverflow.com/users/9594", "pm_score": 1, "selected": false, "text": "<p>I haven't personally done it, but it should be possible to use ActiveRecord::Migration without any of the other Rails stuff....
2008/09/19
[ "https://Stackoverflow.com/questions/101868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3839/" ]
Is there any easy to install/use (on unix) database migration tools like Rails Migrations? I really like the idea, but installing ruby/rails purely to manage my database migrations seems overkill.
Just use ActiveRecord and a simple Rakefile. For example, if you put your migrations in a `db/migrate` directory and have a `database.yml` file that has your db config, this simple Rakefile should work: **Rakefile:** ``` require 'active_record' require 'yaml' desc "Migrate the database through scripts in db/migrate. Target specific version with VERSION=x" task :migrate => :environment do ActiveRecord::Migrator.migrate('db/migrate', ENV["VERSION"] ? ENV["VERSION"].to_i : nil) end task :environment do ActiveRecord::Base.establish_connection(YAML::load(File.open('database.yml'))) ActiveRecord::Base.logger = Logger.new(STDOUT) end ``` **database.yml**: ``` adapter: mysql encoding: utf8 database: test_database username: root password: host: localhost ``` Afterwards, you'll be able to run `rake migrate` and have all the migration goodness without a surrounding rails app. Alternatively, I have a set of bash scripts that perform a very similar function to ActiveRecord migrations, but they only work with Oracle. I used to use them before switching to Ruby and Rails. They are somewhat complicated and I provide no support for them, but if you are interested, feel free to contact me.
101,877
<p>How can I add Page transitions effects like IE in Safari for web pages?</p>
[ { "answer_id": 101961, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 3, "selected": true, "text": "<p>You could check out this example: <a href=\"http://sachiniscool.blogspot.com/2006/01/implementing-page-transitions...
2008/09/19
[ "https://Stackoverflow.com/questions/101877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191/" ]
How can I add Page transitions effects like IE in Safari for web pages?
You could check out this example: <http://sachiniscool.blogspot.com/2006/01/implementing-page-transitions-in.html>. It describes how to emulate page transitions in Firefox using AJAX and CSS. The same method works for Safari as well. The code below is taken from that page and slightly formatted: ``` var xmlhttp; var timerId = 0; var op = 1; function getPageFx() { url = "/transpage2.html"; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest() xmlhttp.onreadystatechange=xmlhttpChange xmlhttp.open("GET",url,true) xmlhttp.send(null) } else getPageIE(); } function xmlhttpChange() { // if xmlhttp shows "loaded" if (xmlhttp.readyState == 4) { // if "OK" if (xmlhttp.status == 200) { if (timerId != 0) window.clearTimeout(timerId); timerId = window.setTimeout("trans();",100); } else { alert(xmlhttp.status) } } } function trans() { op -= .1; document.body.style.opacity = op; if(op < .4) { window.clearTimeout(timerId); timerId = 0; document.body.style.opacity = 1; document.open(); document.write(xmlhttp.responseText); document.close(); return; } timerId = window.setTimeout("trans();",100); } function getPageIE() { window.location.href = "transpage2.html"; } ```
101,880
<ul> <li>I start up my application which uses a Jetty server, using port 9000.</li> <li>I then shut down my application with Ctrl-C</li> <li>I check with "netstat -a" and see that the port 9000 is no longer being used.</li> <li>I restart my application and get:</li> </ul> <blockquote> <pre><code>[ERROR,9/19 15:31:08] java.net.BindException: Only one usage of each socket address (protocol/network address/port) is normally permitted [TRACE,9/19 15:31:08] java.net.BindException: Only one usage of each socket address (protocol/network address/port) is normally permitted [TRACE,9/19 15:31:08] at java.net.PlainSocketImpl.convertSocketExceptionToIOException(PlainSocketImpl.java:75) [TRACE,9/19 15:31:08] at sun.nio.ch.Net.bind(Net.java:101) [TRACE,9/19 15:31:08] at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:126) [TRACE,9/19 15:31:08] at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:77) [TRACE,9/19 15:31:08] at org.mortbay.jetty.nio.BlockingChannelConnector.open(BlockingChannelConnector.java:73) [TRACE,9/19 15:31:08] at org.mortbay.jetty.AbstractConnector.doStart(AbstractConnector.java:285) [TRACE,9/19 15:31:08] at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) [TRACE,9/19 15:31:08] at org.mortbay.jetty.Server.doStart(Server.java:233) [TRACE,9/19 15:31:08] at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) [TRACE,9/19 15:31:08] at ... </code></pre> </blockquote> <p>Is this a Java bug? Can I avoid it somehow before starting the Jetty server?</p> <p><strong>Edit #1</strong> Here is our code for creating our BlockingChannelConnector, note the "setReuseAddress(true)":</p> <blockquote> <pre><code> connector.setReuseAddress( true ); connector.setPort( port ); connector.setStatsOn( true ); connector.setMaxIdleTime( 30000 ); connector.setLowResourceMaxIdleTime( 30000 ); connector.setAcceptQueueSize( maxRequests ); connector.setName( "Blocking-IO Connector, bound to host " + connector.getHost() ); </code></pre> </blockquote> <p>Could it have something to do with the idle time?</p> <p><strong>Edit #2</strong> Next piece of the puzzle that may or may not help: when running the application in Debug Mode (Eclipse) the server starts up without a problem!!! But the problem described above occurs reproducibly when running the application in Run Mode or as a built jar file. Whiskey Tango Foxtrot?</p> <p><strong>Edit #3 (4 days later)</strong> - still have the issue. Any thoughts?</p>
[ { "answer_id": 101906, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 1, "selected": false, "text": "<p>You might want call <code>setReuseAddress(true)</code> before calling <code>bind()</code> on your socket object. This i...
2008/09/19
[ "https://Stackoverflow.com/questions/101880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
* I start up my application which uses a Jetty server, using port 9000. * I then shut down my application with Ctrl-C * I check with "netstat -a" and see that the port 9000 is no longer being used. * I restart my application and get: > > > ``` > [ERROR,9/19 15:31:08] java.net.BindException: Only one usage of each socket address (protocol/network address/port) is normally permitted > [TRACE,9/19 15:31:08] java.net.BindException: Only one usage of each socket address (protocol/network address/port) is normally permitted > [TRACE,9/19 15:31:08] at java.net.PlainSocketImpl.convertSocketExceptionToIOException(PlainSocketImpl.java:75) > > [TRACE,9/19 15:31:08] at sun.nio.ch.Net.bind(Net.java:101) > [TRACE,9/19 15:31:08] at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:126) > [TRACE,9/19 15:31:08] at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:77) > [TRACE,9/19 15:31:08] at org.mortbay.jetty.nio.BlockingChannelConnector.open(BlockingChannelConnector.java:73) > > [TRACE,9/19 15:31:08] at org.mortbay.jetty.AbstractConnector.doStart(AbstractConnector.java:285) > [TRACE,9/19 15:31:08] at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) > [TRACE,9/19 15:31:08] at org.mortbay.jetty.Server.doStart(Server.java:233) > [TRACE,9/19 15:31:08] at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) > [TRACE,9/19 15:31:08] at ... > > ``` > > Is this a Java bug? Can I avoid it somehow before starting the Jetty server? **Edit #1** Here is our code for creating our BlockingChannelConnector, note the "setReuseAddress(true)": > > > ``` > connector.setReuseAddress( true ); > connector.setPort( port ); > connector.setStatsOn( true ); > connector.setMaxIdleTime( 30000 ); > connector.setLowResourceMaxIdleTime( 30000 ); > connector.setAcceptQueueSize( maxRequests ); > connector.setName( "Blocking-IO Connector, bound to host " + connector.getHost() ); > > ``` > > Could it have something to do with the idle time? **Edit #2** Next piece of the puzzle that may or may not help: when running the application in Debug Mode (Eclipse) the server starts up without a problem!!! But the problem described above occurs reproducibly when running the application in Run Mode or as a built jar file. Whiskey Tango Foxtrot? **Edit #3 (4 days later)** - still have the issue. Any thoughts?
During your first invocation of your program, did it accept at least one incoming connection? If so then what you are most likely seeing is the socket linger in effect. For the best explanation dig up a copy of TCP/IP Illustrated by Stevens [![alt text](https://i.stack.imgur.com/DNDVu.gif)](https://i.stack.imgur.com/DNDVu.gif) (source: [kohala.com](http://www.kohala.com/start/gifs/tcpipiv1.gif)) But, as I understand it, because the application did not properly close the connection (that is BOTH client and server sent their FIN/ACK sequences) the socket you were listening on cannot be reused until the connection is considered dead, the so called 2MSL timeout. The value of 1 MSL can vary by operating system, but its usually a least a minute, and usually more like 5. The best advice I have heard to avoid this condition (apart from always closing all sockets properly on exit) is to set the SO\_LINGER tcp option to 0 on your server socket during the listen() phase. As freespace pointed out, in java this is the setReuseAddress(true) method.
101,893
<p>This concept is a new one for me -- I first came across it at the <a href="http://developer.yahoo.com/yui/articles/hosting/#configure" rel="nofollow noreferrer">YUI dependency configurator</a>. Basically, instead of having multiple requests for many files, the files are chained into one http request to cut down on page load time.</p> <p>Anyone know how to implement this on a LAMP stack? (I saw a similar question was asked already, but it <a href="https://stackoverflow.com/questions/47937/combining-and-caching-multiple-javascript-files-in-aspnet">seems to be ASP specific</a>.</p> <p>Thanks!</p> <p>Update: Both answers are helpful...(my rep isn't high enough to comment yet so I'm adding some parting thoughts here). I also came <a href="http://www.artzstudio.com/2008/08/using-modconcat-to-speed-up-render-start/" rel="nofollow noreferrer">across another blog post</a> with PHP-specific examples that might be useful. David's build answer, though, is making me consider a different approach. Thanks, David!</p>
[ { "answer_id": 101941, "author": "David McLaughlin", "author_id": 3404, "author_profile": "https://Stackoverflow.com/users/3404", "pm_score": 4, "selected": true, "text": "<p>There are various ways, the two most obvious would be:</p>\n\n<ol>\n<li>Build a tool like YUI which builds a besp...
2008/09/19
[ "https://Stackoverflow.com/questions/101893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13243/" ]
This concept is a new one for me -- I first came across it at the [YUI dependency configurator](http://developer.yahoo.com/yui/articles/hosting/#configure). Basically, instead of having multiple requests for many files, the files are chained into one http request to cut down on page load time. Anyone know how to implement this on a LAMP stack? (I saw a similar question was asked already, but it [seems to be ASP specific](https://stackoverflow.com/questions/47937/combining-and-caching-multiple-javascript-files-in-aspnet). Thanks! Update: Both answers are helpful...(my rep isn't high enough to comment yet so I'm adding some parting thoughts here). I also came [across another blog post](http://www.artzstudio.com/2008/08/using-modconcat-to-speed-up-render-start/) with PHP-specific examples that might be useful. David's build answer, though, is making me consider a different approach. Thanks, David!
There are various ways, the two most obvious would be: 1. Build a tool like YUI which builds a bespoke, unique version based on the components you ticked as required so that you can still serve the file as static. MooTools and jQuery UI all provide package-builders like this when you download their package to give you the most streamlined and effecient library possible. I'm sure a generic all purpose tool exists out there. 2. Create a simple Perl/PHP/Python/Ruby script that serves a bunch of JavaScript files based on the request. So "onerequest.js?load=ui&load=effects" would go to a PHP script that loads in the files and serves them with the correct content-type. There are many examples of this but personally I'm not a fan. I prefer not to serve static files through any sort of script, but I also like to develop my code with 10 or so seperate small class files without the cost of 10 HTTP requests. So I came up with a custom build process that combines all the most common classes and functions and then minifies them into a single file like project.min.js and have a condition in all my views/templates that includes this file on production. Edit - The "custom build process" is actually an extremely simple perl script. It reads in each of the files that I've passed as arguments and writes them to a new file, optionally passing the entire thing through [JSMIN](http://www.crockford.com/javascript/jsmin.html) (available in all your favourite languages) automatically. At the command like it looks like: ``` perl build-project-master.pl core.js class1.js etc.js /path/to/live/js/file.js ```
101,935
<p>Is there a way (without installing any libraries) of validating XML using a custom DTD in PHP?</p>
[ { "answer_id": 101962, "author": "owenmarshall", "author_id": 9806, "author_profile": "https://Stackoverflow.com/users/9806", "pm_score": 4, "selected": true, "text": "<p>Take a look at <a href=\"http://us3.php.net/dom\" rel=\"noreferrer\">PHP's DOM</a>, especially <a href=\"http://us3.p...
2008/09/19
[ "https://Stackoverflow.com/questions/101935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18856/" ]
Is there a way (without installing any libraries) of validating XML using a custom DTD in PHP?
Take a look at [PHP's DOM](http://us3.php.net/dom), especially [DOMDocument::schemaValidate](http://us3.php.net/manual/en/domdocument.schemavalidate.php) and [DOMDocument::validate](http://us3.php.net/manual/en/domdocument.validate.php). The example for DOMDocument::validate is fairly simple: ``` <?php $dom = new DOMDocument; $dom->Load('book.xml'); if ($dom->validate()) { echo "This document is valid!\n"; } ?> ```
101,958
<p>I recently discovered that our company has a set of coding guidelines (hidden away in a document management system where no one can find it). It generally seems pretty sensible, and keeps away from the usual religious wars about where to put '{'s and whether to use hard tabs. However, it does suggest that "lines SHOULD NOT contain embedded multiple spaces". By which it means don't do this sort of thing:</p> <pre><code>foo = 1; foobar = 2; bar = 3; </code></pre> <p>Or this:</p> <pre><code>if ( test_one ) return 1; else if ( longer_test ) return 2; else if ( shorter ) return 3; else return 4; </code></pre> <p>Or this:</p> <pre><code>thing foo_table[] = { { "aaaaa", 0 }, { "aa", 1 }, // ... } </code></pre> <p>The justification for this is that changes to one line often require every line to be edited. That makes it more effort to change, and harder to understand diffs.</p> <p>I'm torn. On the one hand, lining up like this can make repetitive code much easier to read. On the other hand, it does make diffs harder to read.</p> <p>What's your view on this?</p>
[ { "answer_id": 101970, "author": "Sarien", "author_id": 1994377, "author_profile": "https://Stackoverflow.com/users/1994377", "pm_score": 2, "selected": false, "text": "<p>With a good editor their point is just not true. :)</p>\n\n<p>(See \"visual block\" mode for vim.)</p>\n\n<p>P.S.: O...
2008/09/19
[ "https://Stackoverflow.com/questions/101958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1105/" ]
I recently discovered that our company has a set of coding guidelines (hidden away in a document management system where no one can find it). It generally seems pretty sensible, and keeps away from the usual religious wars about where to put '{'s and whether to use hard tabs. However, it does suggest that "lines SHOULD NOT contain embedded multiple spaces". By which it means don't do this sort of thing: ``` foo = 1; foobar = 2; bar = 3; ``` Or this: ``` if ( test_one ) return 1; else if ( longer_test ) return 2; else if ( shorter ) return 3; else return 4; ``` Or this: ``` thing foo_table[] = { { "aaaaa", 0 }, { "aa", 1 }, // ... } ``` The justification for this is that changes to one line often require every line to be edited. That makes it more effort to change, and harder to understand diffs. I'm torn. On the one hand, lining up like this can make repetitive code much easier to read. On the other hand, it does make diffs harder to read. What's your view on this?
> > I'm torn. On the one hand, lining up > like this can make repetitive code > much easier to read. On the other > hand, it does make diffs harder to > read. > > > Well, since making code understandable is more important than making diffs understandable, you should not be torn. IMHO lining up similar lines does greatly improve readability. Moreover, it allows easier cut-n-pasting with editors that permit vertical selection.
102,019
<p>We've got a product which utilizes multiple SQL Server 2005 databases with triggers. We're looking for a sustainable solution for deploying and upgrading the database schemas on customer servers.</p> <p>Currently, we're using Red Gate's SQL Packager, which appears to be the wrong tool for this particular job. Not only does SQL Packager appear to be geared toward individual databases, but the particular (old) version we own has some issues with SQL Server 2005. (Our version of SQL Packager worked fine with SQL Server 2000, even though we had to do a lot of workarounds to make it handle multiple databases with triggers.) </p> <p>Can someone suggest a product which can create an EXE or a .NET project to do the following things?</p> <pre><code>* Create a main database with some default data. * Create an audit trail database. * Put triggers on the main database so audit data will automatically be inserted into the audit trail database. * Create a secondary database that has nothing to do with the main database and audit trail database. </code></pre> <p>And then, when a customer needs to update their database schema, the product can look at the changes between the original set of databases and the updated set of databases on our server. Then the product can create an EXE or .NET project which can, on the customer's server...</p> <pre><code>* Temporarily drop triggers on the main database so alterations can be made. * Alter database schemas, triggers, stored procedures, etc. on any of the original databases, while leaving the customer's data alone. * Put the triggers back on the main database. </code></pre> <p>Basically, we're looking for a product similar to SQL Packager, but one which will handle multiple databases easily. If no such product exists, we'll have to make our own.</p> <p>Thanks in advance for your suggestions!</p>
[ { "answer_id": 102816, "author": "Martin Marconcini", "author_id": 2684, "author_profile": "https://Stackoverflow.com/users/2684", "pm_score": 1, "selected": false, "text": "<p>I was looking for this product myself, knowing that RedGate solution worked fine for \"one\" DB; unfortunately ...
2008/09/19
[ "https://Stackoverflow.com/questions/102019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18871/" ]
We've got a product which utilizes multiple SQL Server 2005 databases with triggers. We're looking for a sustainable solution for deploying and upgrading the database schemas on customer servers. Currently, we're using Red Gate's SQL Packager, which appears to be the wrong tool for this particular job. Not only does SQL Packager appear to be geared toward individual databases, but the particular (old) version we own has some issues with SQL Server 2005. (Our version of SQL Packager worked fine with SQL Server 2000, even though we had to do a lot of workarounds to make it handle multiple databases with triggers.) Can someone suggest a product which can create an EXE or a .NET project to do the following things? ``` * Create a main database with some default data. * Create an audit trail database. * Put triggers on the main database so audit data will automatically be inserted into the audit trail database. * Create a secondary database that has nothing to do with the main database and audit trail database. ``` And then, when a customer needs to update their database schema, the product can look at the changes between the original set of databases and the updated set of databases on our server. Then the product can create an EXE or .NET project which can, on the customer's server... ``` * Temporarily drop triggers on the main database so alterations can be made. * Alter database schemas, triggers, stored procedures, etc. on any of the original databases, while leaving the customer's data alone. * Put the triggers back on the main database. ``` Basically, we're looking for a product similar to SQL Packager, but one which will handle multiple databases easily. If no such product exists, we'll have to make our own. Thanks in advance for your suggestions!
I was looking for this product myself, knowing that RedGate solution worked fine for "one" DB; unfortunately I have been unable to find such tool :( In the end, I had to roll my own solution to do something "similar". It was a *pain in the…* but it worked. My scenario was way simpler than yours, as we didn't have triggers and T-SQL. Later, I decided to take a different approach: Every DB change had a SCRIPT. Numbered. 001\_Create\_Table\_xXX.SQL, 002\_AlterTable\_whatever.SQL, etc. No matter how small the change is, there's got to be a script. The new version of the updater does this: 1. Makes a BKP of the customerDB (just in case) 2. Starts executing scripts in Alphabetical order. (001, 002...) 3. If a script fails, it drops the BD. Logs the Script error, Script Number, etc. and restores the customer's DB. 4. If it finishes, it makes another backup of the customer's DB (after the "migration") and updates a table where we store the DB version; this table is checked by the app to make sure that the DB and the app are in sync. 5. Shows a nice success msg. This turned out to be a little bit more "manual" but it has been really working with little effort for three years now. The secret lies in keeping a few testing DBs to test the "upgrade" before deploying. But apart from a few isolated Dbs where some scripts failed because of data inconsistency, this worked fine. Since your scenario is a bit more complex, I don't know if this kind of approach can be ok with you.
102,049
<p>For example:</p> <pre><code>me$ FOO="BAR * BAR" me$ echo $FOO BAR file1 file2 file3 file4 BAR </code></pre> <p>and using the <code>\</code> escape character:</p> <pre><code>me$ FOO="BAR \* BAR" me$ echo $FOO BAR \* BAR </code></pre> <p>I'm obviously doing something stupid.</p> <p>How do I get the output <code>BAR * BAR</code>?</p>
[ { "answer_id": 102073, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 3, "selected": false, "text": "<pre><code>FOO='BAR * BAR'\necho \"$FOO\"\n</code></pre>\n" }, { "answer_id": 102074, "author": "Rafał Dowgird", ...
2008/09/19
[ "https://Stackoverflow.com/questions/102049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2108/" ]
For example: ``` me$ FOO="BAR * BAR" me$ echo $FOO BAR file1 file2 file3 file4 BAR ``` and using the `\` escape character: ``` me$ FOO="BAR \* BAR" me$ echo $FOO BAR \* BAR ``` I'm obviously doing something stupid. How do I get the output `BAR * BAR`?
Quoting when setting `$FOO` is not enough. You need to quote the variable reference as well: ``` me$ FOO="BAR * BAR" me$ echo "$FOO" BAR * BAR ```
102,055
<p>I am trying to make a div, that when you click it turns into an input box, and focuses it. I am using prototype to achieve this. This works in both Chrome and Firefox, but not in IE. IE refuses to focus the newly added input field, even if I set a 1 second timeout.</p> <p>Basically the code works like this:</p> <pre><code>var viewElement = new Element("div").update("text"); var editElement = new Element("input", {"type":"text"}); root.update(viewElement); // pseudo shortcut for the sake of information: viewElementOnClick = function(event) { root.update(editElement); editElement.focus(); } </code></pre> <p>The above example is a shortened version of the actual code, the actual code works fine except the focus bit in IE.</p> <p>Are there limitations on the focus function in IE? Do I need to place the input in a form?</p>
[ { "answer_id": 102097, "author": "x0n", "author_id": 6920, "author_profile": "https://Stackoverflow.com/users/6920", "pm_score": 0, "selected": false, "text": "<p>What version IE? What's your DocType set to? is it strict, standards or quirks mode? Any javascript errors appearing (check t...
2008/09/19
[ "https://Stackoverflow.com/questions/102055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355/" ]
I am trying to make a div, that when you click it turns into an input box, and focuses it. I am using prototype to achieve this. This works in both Chrome and Firefox, but not in IE. IE refuses to focus the newly added input field, even if I set a 1 second timeout. Basically the code works like this: ``` var viewElement = new Element("div").update("text"); var editElement = new Element("input", {"type":"text"}); root.update(viewElement); // pseudo shortcut for the sake of information: viewElementOnClick = function(event) { root.update(editElement); editElement.focus(); } ``` The above example is a shortened version of the actual code, the actual code works fine except the focus bit in IE. Are there limitations on the focus function in IE? Do I need to place the input in a form?
My guess is that IE hasn't updated the DOM yet when you make the call to focus(). Sometimes browsers will wait until a script has finished executing before updating the DOM. I would try doing the update, then doing ``` setTimeout("setFocus", 0); function setFocus() { editElement.focus(); } ``` Your other option would be to have both items present in the DOM at all times and just swap the style.display on them depending on what you need hidden/shown at a given time.
102,057
<p>I've got a Fitnesse RowFixture that returns a list of business objects. The object has a field which is a float representing a percentage between 0 and 1. The <em>consumer</em> of the business object will be a web page or report that comes from a designer, so the formatting of the percentage will be up to the designer rather than the business object. </p> <p>It would be nicer if the page could emulate the designer when converting the number to a percentage, i.e. instead of displaying 0.5, it should display 50%. But I'd rather not pollute the business object with the display code. Is there a way to specify a format string in the RowFixture?</p>
[ { "answer_id": 105012, "author": "Tom Carr", "author_id": 14954, "author_profile": "https://Stackoverflow.com/users/14954", "pm_score": 0, "selected": false, "text": "<p>I'm not sure what the \"polution\" is. Either the requirement is that your Business Object returns a value expressed ...
2008/09/19
[ "https://Stackoverflow.com/questions/102057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6902/" ]
I've got a Fitnesse RowFixture that returns a list of business objects. The object has a field which is a float representing a percentage between 0 and 1. The *consumer* of the business object will be a web page or report that comes from a designer, so the formatting of the percentage will be up to the designer rather than the business object. It would be nicer if the page could emulate the designer when converting the number to a percentage, i.e. instead of displaying 0.5, it should display 50%. But I'd rather not pollute the business object with the display code. Is there a way to specify a format string in the RowFixture?
You certainly don't want to modify your Business Logic just to make your tests look better. Good news however, there is a way to accomplish this that is not difficult, but not as easy as passing in a format specifier. Try to think of your Fit Fixture as a service boundary between FitNesse and your application code. You want to define a contract that doesn't necessarily have to change if the implementation details of your **SUT** (**S**ystem **U**nder **T**est) change. Lets look at a simplified version of your Business Object: ``` public class BusinessObject { public float Percent { get; private set; } } ``` Becuase of the way that a RowFixture works we need to define a simple object that will work as the contract. Ordinarily we would use an interface, but that isn't going to serve our purpose here so a simple **DTO** (**D**ata **T**ransfer **O**bject) will suffice. Something Like This: ``` public class ReturnRowDTO { public String Percent { get; set; } } ``` Now we can define a RowFixture that will return a list of our custom DTO objects. We also need to create a way to convert BusinessObjects to ReturnRowDTOs. We end up with a Fixture that looks something like this. ``` public class ExampleRowFixture: fit.RowFixture { private ISomeService _someService; public override object[] Query() { BusinessObject[] list = _someService.GetBusinessObjects(); return Array.ConvertAll(list, new Converter<BusinessObject, ReturnRowDTO>(ConvertBusinessObjectToDTO)); } public override Type GetTargetClass() { return typeof (ReturnRowDTO); } public ReturnRowDTO ConvertBusinessObjectToDTO(BusinessObject businessObject) { return new ReturnRowDTO() {Percent = businessObject.Percent.ToString("%")}; } } ``` You can now change your underlying BusinessObjects around without breaking your actual Fit Tests. Hope this helps.
102,058
<p>The server.xml which controls the startup of Apache Tomcat's servlet container contains a debug attribute for nearly every major component. The debug attribute is more or less verbose depending upon the number you give it, zero being least and 99 being most verbose. How does the debug level affect Tomcat's speed when servicing large numbers of users? I assume zero is fast and 99 is relatively slower, but is this true. If there are no errors being thrown, does it matter?</p>
[ { "answer_id": 105012, "author": "Tom Carr", "author_id": 14954, "author_profile": "https://Stackoverflow.com/users/14954", "pm_score": 0, "selected": false, "text": "<p>I'm not sure what the \"polution\" is. Either the requirement is that your Business Object returns a value expressed ...
2008/09/19
[ "https://Stackoverflow.com/questions/102058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13930/" ]
The server.xml which controls the startup of Apache Tomcat's servlet container contains a debug attribute for nearly every major component. The debug attribute is more or less verbose depending upon the number you give it, zero being least and 99 being most verbose. How does the debug level affect Tomcat's speed when servicing large numbers of users? I assume zero is fast and 99 is relatively slower, but is this true. If there are no errors being thrown, does it matter?
You certainly don't want to modify your Business Logic just to make your tests look better. Good news however, there is a way to accomplish this that is not difficult, but not as easy as passing in a format specifier. Try to think of your Fit Fixture as a service boundary between FitNesse and your application code. You want to define a contract that doesn't necessarily have to change if the implementation details of your **SUT** (**S**ystem **U**nder **T**est) change. Lets look at a simplified version of your Business Object: ``` public class BusinessObject { public float Percent { get; private set; } } ``` Becuase of the way that a RowFixture works we need to define a simple object that will work as the contract. Ordinarily we would use an interface, but that isn't going to serve our purpose here so a simple **DTO** (**D**ata **T**ransfer **O**bject) will suffice. Something Like This: ``` public class ReturnRowDTO { public String Percent { get; set; } } ``` Now we can define a RowFixture that will return a list of our custom DTO objects. We also need to create a way to convert BusinessObjects to ReturnRowDTOs. We end up with a Fixture that looks something like this. ``` public class ExampleRowFixture: fit.RowFixture { private ISomeService _someService; public override object[] Query() { BusinessObject[] list = _someService.GetBusinessObjects(); return Array.ConvertAll(list, new Converter<BusinessObject, ReturnRowDTO>(ConvertBusinessObjectToDTO)); } public override Type GetTargetClass() { return typeof (ReturnRowDTO); } public ReturnRowDTO ConvertBusinessObjectToDTO(BusinessObject businessObject) { return new ReturnRowDTO() {Percent = businessObject.Percent.ToString("%")}; } } ``` You can now change your underlying BusinessObjects around without breaking your actual Fit Tests. Hope this helps.
102,059
<p>With previous versions of flash, entering the full screen mode increased the height and width of the stage to the dimensions of the screen. Now that hardware scaling has arrived, the height and width are set to the dimensions of the video (plus borders if the aspect ratio is different).</p> <p>That's fine, unless you have controls placed over the video. Before, you could control their size; but now they're blown up by the same scale as the video, and pixellated horribly. Controls are ugly and subtitles are unreadable.</p> <p>It's possible for the user to turn off hardware scaling, but all that achieves is to turn off anti-aliasing. The controls are still blown up to ugliness.</p> <p>Is there a way to get the old scaling behaviour back?</p>
[ { "answer_id": 106667, "author": "Brent", "author_id": 10680, "author_profile": "https://Stackoverflow.com/users/10680", "pm_score": -1, "selected": false, "text": "<pre><code>stage.align = StageAlign.TOP_LEFT; \nstage.scaleMode = StageScaleMode.NO_SCALE;\nstage.addEventListener(Even...
2008/09/19
[ "https://Stackoverflow.com/questions/102059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
With previous versions of flash, entering the full screen mode increased the height and width of the stage to the dimensions of the screen. Now that hardware scaling has arrived, the height and width are set to the dimensions of the video (plus borders if the aspect ratio is different). That's fine, unless you have controls placed over the video. Before, you could control their size; but now they're blown up by the same scale as the video, and pixellated horribly. Controls are ugly and subtitles are unreadable. It's possible for the user to turn off hardware scaling, but all that achieves is to turn off anti-aliasing. The controls are still blown up to ugliness. Is there a way to get the old scaling behaviour back?
I've eventually found the answer to this. The problem is that the FLVPlayback component is now using the stage.fullScreenSourceRect property to enter a hardware-scaled full screen mode. When it does that, it stretches the rendered area given by stage.fullScreenSourceRect to fill the screen, rather than increasing the size of the stage or any components. To stop it, you have to create a subclass of FLVPlayback that uses a subclass of UIManager, and override the function that's setting stage.fullScreenSourceRect. On the down side, you lose hardware scaling; but on the up side, your player doesn't look like it's been drawn by a three-year-old in crayons. CustomFLVPlayback.as: ``` import fl.video.*; use namespace flvplayback_internal; public class CustomFLVPlayback { public function CustomFLVPlayback() { super(); uiMgr = new CustomUIManager(this); } } ``` CustomUIManager.as: ``` import fl.video.*; import flash.display.StageDisplayState; public class CustomUIManager { public function CustomUIManager(vc:FLVPlayback) { super(vc); } public override function enterFullScreenDisplayState():void { if (!_fullScreen && _vc.stage != null) { try { _vc.stage.displayState = StageDisplayState.FULL_SCREEN; } catch (se:SecurityError) { } } } } ``` We add the FLVPlayback to our movie using actionscript, so we just have to replace ``` var myFLVPLayback:FLVPlayback = new FLVPlayback(); ``` with ``` var myFLVPLayback:CustomFLVPlayback = new CustomFLVPlayback(); ``` I don't know whether there's a way to make the custom class available in the component library.
102,072
<p>A friend of mine was explaining how they do ping-pong pairing with TDD at his workplace and he said that they take an "adversarial" approach. That is, when the test writing person hands the keyboard over to the implementer, the implementer tries to do the bare simplest (and sometimes wrong thing) to make the test pass.</p> <p>For example, if they're testing a GetName() method and the test checks for "Sally", the implementation of the GetName method would simply be:</p> <pre><code>public string GetName(){ return "Sally"; } </code></pre> <p>Which would, of course, pass the test (naively).</p> <p>He explains that this helps eliminate naive tests that check for specific canned values rather than testing the actual behavior or expected state of components. It also helps drive the creation of more tests and ultimately better design and fewer bugs.</p> <p>It sounded good, but in a short session with him, it seemed like it took a lot longer to get through a single round of tests than otherwise and I didn't feel that a lot of extra value was gained.</p> <p>Do you use this approach, and if so, have you seen it pay off?</p>
[ { "answer_id": 102236, "author": "Heath Borders", "author_id": 9636, "author_profile": "https://Stackoverflow.com/users/9636", "pm_score": 1, "selected": false, "text": "<p>I've used this approach. It doesn't work with all pairs; some people are just naturally resistant and won't give i...
2008/09/19
[ "https://Stackoverflow.com/questions/102072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10862/" ]
A friend of mine was explaining how they do ping-pong pairing with TDD at his workplace and he said that they take an "adversarial" approach. That is, when the test writing person hands the keyboard over to the implementer, the implementer tries to do the bare simplest (and sometimes wrong thing) to make the test pass. For example, if they're testing a GetName() method and the test checks for "Sally", the implementation of the GetName method would simply be: ``` public string GetName(){ return "Sally"; } ``` Which would, of course, pass the test (naively). He explains that this helps eliminate naive tests that check for specific canned values rather than testing the actual behavior or expected state of components. It also helps drive the creation of more tests and ultimately better design and fewer bugs. It sounded good, but in a short session with him, it seemed like it took a lot longer to get through a single round of tests than otherwise and I didn't feel that a lot of extra value was gained. Do you use this approach, and if so, have you seen it pay off?
It is based on the team's personality. Every team has a personality that is the sum of its members. You have to be careful not to practice passive-aggressive implementations done with an air of superiority. Some developers are frustrated by implementations like > > `return "Sally";` > > > This frustration will lead to an unsuccessful team. I was among the frustrated and did not see it pay off. I think a better approach is more oral communication making suggestions about how a test might be better implemented.
102,083
<p>Preferably free tools if possible.</p> <p>Also, the option of searching for multiple regular expressions and each replacing with different strings would be a bonus.</p>
[ { "answer_id": 102110, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 2, "selected": false, "text": "<p>Under Windows, I used to like <a href=\"http://www.wingrep.com\" rel=\"nofollow noreferrer\">WinGrep</a></p>\n\n<p>Under Ub...
2008/09/19
[ "https://Stackoverflow.com/questions/102083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13967/" ]
Preferably free tools if possible. Also, the option of searching for multiple regular expressions and each replacing with different strings would be a bonus.
Perl. Seriously, it makes sysadmin stuff so much easier. Here's an example: ``` perl -pi -e 's/something/somethingelse/g' *.log ```
102,084
<p>I have learned quite a bit browsing through <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c">Hidden Features of C#</a> and was surprised when I couldn't find something similar for VB.NET.</p> <p>So what are some of its hidden or lesser known features?</p>
[ { "answer_id": 102111, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 5, "selected": false, "text": "<ul>\n<li>AndAlso/OrElse logical operators</li>\n</ul>\n\n<p>(EDIT: Learn more here: <a href=\"https://stackoverflow.c...
2008/09/19
[ "https://Stackoverflow.com/questions/102084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12842/" ]
I have learned quite a bit browsing through [Hidden Features of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c) and was surprised when I couldn't find something similar for VB.NET. So what are some of its hidden or lesser known features?
The `Exception When` clause is largely unknown. Consider this: ``` Public Sub Login(host as string, user as String, password as string, _ Optional bRetry as Boolean = False) Try ssh.Connect(host, user, password) Catch ex as TimeoutException When Not bRetry ''//Try again, but only once. Login(host, user, password, True) Catch ex as TimeoutException ''//Log exception End Try End Sub ```
102,093
<p>I wrote a small <code>PHP</code> application several months ago that uses the <code>WordPress XMLRPC library</code> to synchronize two separate WordPress blogs. I have a general "RPCRequest" function that packages the request, sends it, and returns the server response, and I have several more specific functions that customize the type of request that is sent.</p> <p>In this particular case, I am calling "getPostIDs" to retrieve the number of posts on the remote server and their respective postids. Here is the code:</p> <pre><code>$rpc = new WordRPC('http://mywordpressurl.com/xmlrpc.php', 'username', 'password'); $rpc-&gt;getPostIDs(); </code></pre> <p>I'm receiving the following error message:</p> <pre><code>expat reports error code 5 description: Invalid document end line: 1 column: 1 byte index: 0 total bytes: 0 data beginning 0 before byte index: </code></pre> <p>Kind of a cliffhanger ending, which is also strange. But since the error message isn't formatted in XML, my intuition is that it's the local XMLRPC library that is generating the error, not the remote server.</p> <p>Even stranger, if I change the "getPostIDs()" call to "getPostIDs(1)" or any other integer, it works just fine.</p> <p>Here is the code for the WordRPC class:</p> <pre><code>public function __construct($url, $user, $pass) { $this-&gt;url = $url; $this-&gt;username = $user; $this-&gt;password = $pass; $id = $this-&gt;RPCRequest("blogger.getUserInfo", array("null", $this-&gt;username, $this-&gt;password)); $this-&gt;blogID = $id['userid']; } public function RPCRequest($method, $params) { $request = xmlrpc_encode_request($method, $params); $context = stream_context_create(array('http' =&gt; array( 'method' =&gt; "POST", 'header' =&gt; "Content-Type: text/xml", 'content' =&gt; $request ))); $file = file_get_contents($this-&gt;url, false, $context); return xmlrpc_decode($file); } public function getPostIDs($num_posts = 0) { return $this-&gt;RPCRequest("mt.getRecentPostTitles", array($this-&gt;blogID, $this-&gt;username, $this-&gt;password, $num_posts)); } </code></pre> <p>As I mentioned, it works fine if "getPostIDs" is given a positive integer argument. Furthermore, this used to work perfectly well as is; the default parameter of 0 simply indicates to the RPC server that it should retrieve <em>all</em> posts, not just the most recent <code>$num_posts</code> posts. Only recently has this error started showing up.</p> <p>I've tried googling the error without much luck. My question, then, is <strong>what exactly does "expat reports error code 5" mean, and who is generating the error?</strong> Any details/suggestions/insights beyond that are welcome, too!</p>
[ { "answer_id": 104047, "author": "Novaktually", "author_id": 13243, "author_profile": "https://Stackoverflow.com/users/13243", "pm_score": 0, "selected": false, "text": "<p>Expat is the XML parser in PHP. Error code 5 is one of many expat error constants, in this case: <code>XML_ERROR_UN...
2008/09/19
[ "https://Stackoverflow.com/questions/102093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13604/" ]
I wrote a small `PHP` application several months ago that uses the `WordPress XMLRPC library` to synchronize two separate WordPress blogs. I have a general "RPCRequest" function that packages the request, sends it, and returns the server response, and I have several more specific functions that customize the type of request that is sent. In this particular case, I am calling "getPostIDs" to retrieve the number of posts on the remote server and their respective postids. Here is the code: ``` $rpc = new WordRPC('http://mywordpressurl.com/xmlrpc.php', 'username', 'password'); $rpc->getPostIDs(); ``` I'm receiving the following error message: ``` expat reports error code 5 description: Invalid document end line: 1 column: 1 byte index: 0 total bytes: 0 data beginning 0 before byte index: ``` Kind of a cliffhanger ending, which is also strange. But since the error message isn't formatted in XML, my intuition is that it's the local XMLRPC library that is generating the error, not the remote server. Even stranger, if I change the "getPostIDs()" call to "getPostIDs(1)" or any other integer, it works just fine. Here is the code for the WordRPC class: ``` public function __construct($url, $user, $pass) { $this->url = $url; $this->username = $user; $this->password = $pass; $id = $this->RPCRequest("blogger.getUserInfo", array("null", $this->username, $this->password)); $this->blogID = $id['userid']; } public function RPCRequest($method, $params) { $request = xmlrpc_encode_request($method, $params); $context = stream_context_create(array('http' => array( 'method' => "POST", 'header' => "Content-Type: text/xml", 'content' => $request ))); $file = file_get_contents($this->url, false, $context); return xmlrpc_decode($file); } public function getPostIDs($num_posts = 0) { return $this->RPCRequest("mt.getRecentPostTitles", array($this->blogID, $this->username, $this->password, $num_posts)); } ``` As I mentioned, it works fine if "getPostIDs" is given a positive integer argument. Furthermore, this used to work perfectly well as is; the default parameter of 0 simply indicates to the RPC server that it should retrieve *all* posts, not just the most recent `$num_posts` posts. Only recently has this error started showing up. I've tried googling the error without much luck. My question, then, is **what exactly does "expat reports error code 5" mean, and who is generating the error?** Any details/suggestions/insights beyond that are welcome, too!
@Novak: Thanks for your suggestion. The problem turned out to be a memory issue; by retrieving all the posts from the remote location, the response exceeded the amount of memory PHP was allowed to utilize, hence the unclosed token error. The problem with the cryptic and incomplete error message was due to an outdated version of the XML-RPC library being used. Once I'd upgraded the version of WordPress, it provided me with the complete error output, including the memory error.
102,171
<p>I'm looking for a method that computes the line number of a given text position in a JTextPane with wrapping enabled.</p> <p>Example:</p> <blockquote> <p>This a very very very very very very very very very very very very very very very very very very very very very very long line.<br> This is another very very very very very very very very very very very very very very very very very very very very very very long line.<strong>|</strong></p> </blockquote> <p>The cursor is on line number four, not two.</p> <p>Can someone provide me with the implementation of the method:</p> <pre><code>int getLineNumber(JTextPane pane, int pos) { return ??? } </code></pre>
[ { "answer_id": 102737, "author": "Richard", "author_id": 16475, "author_profile": "https://Stackoverflow.com/users/16475", "pm_score": 4, "selected": true, "text": "<p>Try this</p>\n\n<pre><code> /**\n * Return an int containing the wrapped line index at the given position\n * @param...
2008/09/19
[ "https://Stackoverflow.com/questions/102171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8330/" ]
I'm looking for a method that computes the line number of a given text position in a JTextPane with wrapping enabled. Example: > > This a very very very very very very very very very very very very very very very very very very very very very very long line. > > This is another very very very very very very very very very very very very very very very very very very very very very very long line.**|** > > > The cursor is on line number four, not two. Can someone provide me with the implementation of the method: ``` int getLineNumber(JTextPane pane, int pos) { return ??? } ```
Try this ``` /** * Return an int containing the wrapped line index at the given position * @param component JTextPane * @param int pos * @return int */ public int getLineNumber(JTextPane component, int pos) { int posLine; int y = 0; try { Rectangle caretCoords = component.modelToView(pos); y = (int) caretCoords.getY(); } catch (BadLocationException ex) { } int lineHeight = component.getFontMetrics(component.getFont()).getHeight(); posLine = (y / lineHeight) + 1; return posLine; } ```
102,185
<p>MXML lets you do some really quite powerful data binding such as:</p> <pre><code>&lt;mx:Button id="myBtn" label="Buy an {itemName}" visible="{itemName!=null}"/&gt; </code></pre> <p>I've found that the BindingUtils class can bind values to simple properties, but neither of the bindings above do this. Is it possible to do the same in AS3 code, or is Flex silently generating many lines of code from my MXML? Can anyone duplicate the above in pure AS3, starting from:</p> <pre><code>var myBtn:Button = new Button(); myBtn.id="myBtn"; ??? </code></pre>
[ { "answer_id": 102851, "author": "Marc Hughes", "author_id": 6791, "author_profile": "https://Stackoverflow.com/users/6791", "pm_score": 0, "selected": false, "text": "<p>I believe flex generates a small anonymous function to deal with this.</p>\n\n<p>You could do similar using a ChangeW...
2008/09/19
[ "https://Stackoverflow.com/questions/102185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13220/" ]
MXML lets you do some really quite powerful data binding such as: ``` <mx:Button id="myBtn" label="Buy an {itemName}" visible="{itemName!=null}"/> ``` I've found that the BindingUtils class can bind values to simple properties, but neither of the bindings above do this. Is it possible to do the same in AS3 code, or is Flex silently generating many lines of code from my MXML? Can anyone duplicate the above in pure AS3, starting from: ``` var myBtn:Button = new Button(); myBtn.id="myBtn"; ??? ```
The way to do it is to use `bindSetter`. That is also how it is done behind the scenes when the MXML in your example is transformed to ActionScript before being compiled. ``` // assuming the itemName property is defined on this: BindingUtils.bindSetter(itemNameChanged, this, ["itemName"]); // ... private function itemNameChanged( newValue : String ) : void { myBtn.label = newValue; myBtn.visible = newValue != null; } ``` ...except that the code generated by the MXML to ActionScript conversion is longer as it has to be more general. In this example it would likely have generated two functions, one for each binding expression.
102,198
<p>Is there a way to "align" columns in a data repeater control? </p> <p>I.E currently it looks like this:</p> <pre><code>user1 - colA colB colC colD colE user2 - colD colE </code></pre> <p>I want it to look like:</p> <pre><code> user1 -colA -colB -colC -colD -colE user1 -colD -colE </code></pre> <p>I need to columns for each record to align properly when additional records might not have data for a given column.</p> <p>The requirements call for a repeater and not a grid control.</p> <p>Any ideas?</p>
[ { "answer_id": 102233, "author": "Nick Craver", "author_id": 13249, "author_profile": "https://Stackoverflow.com/users/13249", "pm_score": 2, "selected": false, "text": "<p>If you have access to how many columns are mising in the repeat, then just the following as the table tag. I you d...
2008/09/19
[ "https://Stackoverflow.com/questions/102198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is there a way to "align" columns in a data repeater control? I.E currently it looks like this: ``` user1 - colA colB colC colD colE user2 - colD colE ``` I want it to look like: ``` user1 -colA -colB -colC -colD -colE user1 -colD -colE ``` I need to columns for each record to align properly when additional records might not have data for a given column. The requirements call for a repeater and not a grid control. Any ideas?
If you have access to how many columns are mising in the repeat, then just the following as the table tag. I you don't have access to this, can you post the source for your data repeater and what DataSource you're going against? ``` <td colspan='<%# MissingCount(Contatiner.DataItem) %>'> ```
102,213
<p>I am getting ready to start a new asp.net web project, and I am going to LINQ-to-SQL. I have done a little bit of work getting my data layer setup using some info I found by <a href="http://mikehadlow.blogspot.com/" rel="nofollow noreferrer" title="Mike Hadlow">Mike Hadlow</a> that uses an Interface and generics to create a Repository for each table in the database. I thought this was an interesting approach at first. However, now I think it might make more sense to create a base Repository class and inherit from it to create a TableNameRepository class for the tables I need to access. </p> <p>Which approach will be allow me to add functionality specific to a Table in a clean testable way? Here is my Repository implementation for reference.</p> <pre><code>public class Repository&lt;T&gt; : IRepository&lt;T&gt; where T : class, new() { protected IDataConnection _dcnf; public Repository() { _dcnf = new DataConnectionFactory() as IDataConnection; } // Constructor injection for dependency on DataContext // to actually connect to a database public Repository(IDataConnection dc) { _dcnf = dc; } /// &lt;summary&gt; /// Return all instances of type T. /// &lt;/summary&gt; /// &lt;returns&gt;IEnumerable&lt;T&gt;&lt;/returns&gt; public virtual IEnumerable&lt;T&gt; GetAll() { return GetTable; } public virtual T GetById(int id) { var itemParam = Expression.Parameter(typeof(T), "item"); var whereExp = Expression.Lambda&lt;Func&lt;T, bool&gt;&gt; ( Expression.Equal( Expression.Property(itemParam, PrimaryKeyName), Expression.Constant(id) ), new ParameterExpression[] { itemParam } ); return _dcnf.Context.GetTable&lt;T&gt;().Where(whereExp).Single(); } /// &lt;summary&gt; /// Return all instances of type T that match the expression exp. /// &lt;/summary&gt; /// &lt;param name="exp"&gt;&lt;/param&gt; /// &lt;returns&gt;IEnumerable&lt;T&gt;&lt;/returns&gt; public virtual IEnumerable&lt;T&gt; FindByExp(Func&lt;T, bool&gt; exp) { return GetTable.Where&lt;T&gt;(exp); } /// &lt;summary&gt;See IRepository.&lt;/summary&gt; /// &lt;param name="exp"&gt;&lt;/param&gt;&lt;returns&gt;&lt;/returns&gt; public virtual T Single(Func&lt;T, bool&gt; exp) { return GetTable.Single(exp); } /// &lt;summary&gt;See IRepository.&lt;/summary&gt; /// &lt;param name="entity"&gt;&lt;/param&gt; public virtual void MarkForDeletion(T entity) { _dcnf.Context.GetTable&lt;T&gt;().DeleteOnSubmit(entity); } /// &lt;summary&gt; /// Create a new instance of type T. /// &lt;/summary&gt; /// &lt;returns&gt;T&lt;/returns&gt; public virtual T Create() { //T entity = Activator.CreateInstance&lt;T&gt;(); T entity = new T(); GetTable.InsertOnSubmit(entity); return entity; } /// &lt;summary&gt;See IRepository.&lt;/summary&gt; public virtual void SaveAll() { _dcnf.SaveAll(); } #region Properties private string PrimaryKeyName { get { return TableMetadata.RowType.IdentityMembers[0].Name; } } private System.Data.Linq.Table&lt;T&gt; GetTable { get { return _dcnf.Context.GetTable&lt;T&gt;(); } } private System.Data.Linq.Mapping.MetaTable TableMetadata { get { return _dcnf.Context.Mapping.GetTable(typeof(T)); } } private System.Data.Linq.Mapping.MetaType ClassMetadata { get { return _dcnf.Context.Mapping.GetMetaType(typeof(T)); } } #endregion } </code></pre>
[ { "answer_id": 103668, "author": "Squirrel", "author_id": 11835, "author_profile": "https://Stackoverflow.com/users/11835", "pm_score": 2, "selected": true, "text": "<p>I'd be tempted to suggest that whether you use concrete types or not shouldn't matter, as if your using dependency inje...
2008/09/19
[ "https://Stackoverflow.com/questions/102213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1203/" ]
I am getting ready to start a new asp.net web project, and I am going to LINQ-to-SQL. I have done a little bit of work getting my data layer setup using some info I found by [Mike Hadlow](http://mikehadlow.blogspot.com/ "Mike Hadlow") that uses an Interface and generics to create a Repository for each table in the database. I thought this was an interesting approach at first. However, now I think it might make more sense to create a base Repository class and inherit from it to create a TableNameRepository class for the tables I need to access. Which approach will be allow me to add functionality specific to a Table in a clean testable way? Here is my Repository implementation for reference. ``` public class Repository<T> : IRepository<T> where T : class, new() { protected IDataConnection _dcnf; public Repository() { _dcnf = new DataConnectionFactory() as IDataConnection; } // Constructor injection for dependency on DataContext // to actually connect to a database public Repository(IDataConnection dc) { _dcnf = dc; } /// <summary> /// Return all instances of type T. /// </summary> /// <returns>IEnumerable<T></returns> public virtual IEnumerable<T> GetAll() { return GetTable; } public virtual T GetById(int id) { var itemParam = Expression.Parameter(typeof(T), "item"); var whereExp = Expression.Lambda<Func<T, bool>> ( Expression.Equal( Expression.Property(itemParam, PrimaryKeyName), Expression.Constant(id) ), new ParameterExpression[] { itemParam } ); return _dcnf.Context.GetTable<T>().Where(whereExp).Single(); } /// <summary> /// Return all instances of type T that match the expression exp. /// </summary> /// <param name="exp"></param> /// <returns>IEnumerable<T></returns> public virtual IEnumerable<T> FindByExp(Func<T, bool> exp) { return GetTable.Where<T>(exp); } /// <summary>See IRepository.</summary> /// <param name="exp"></param><returns></returns> public virtual T Single(Func<T, bool> exp) { return GetTable.Single(exp); } /// <summary>See IRepository.</summary> /// <param name="entity"></param> public virtual void MarkForDeletion(T entity) { _dcnf.Context.GetTable<T>().DeleteOnSubmit(entity); } /// <summary> /// Create a new instance of type T. /// </summary> /// <returns>T</returns> public virtual T Create() { //T entity = Activator.CreateInstance<T>(); T entity = new T(); GetTable.InsertOnSubmit(entity); return entity; } /// <summary>See IRepository.</summary> public virtual void SaveAll() { _dcnf.SaveAll(); } #region Properties private string PrimaryKeyName { get { return TableMetadata.RowType.IdentityMembers[0].Name; } } private System.Data.Linq.Table<T> GetTable { get { return _dcnf.Context.GetTable<T>(); } } private System.Data.Linq.Mapping.MetaTable TableMetadata { get { return _dcnf.Context.Mapping.GetTable(typeof(T)); } } private System.Data.Linq.Mapping.MetaType ClassMetadata { get { return _dcnf.Context.Mapping.GetMetaType(typeof(T)); } } #endregion } ```
I'd be tempted to suggest that whether you use concrete types or not shouldn't matter, as if your using dependency injection (castle?) to create the repositories (so you can wrap them with different caches etc) then your codebase will be none the wiser whichever way you've done it. Then just ask your DI for a repository. E.g. for castle: ``` public class Home { public static IRepository<T> For<T> { get { return Container.Resolve<IRepository<T>>(); } } } ``` Personally, I'd not bottom out the types until you find a need to. I guess the other half of your question is whether you can easily provide an in memory implementation of IRepository for testing and caching purposes. For this I would watch out as linq-to-objects can be slow and you might find something like <http://www.codeplex.com/i4o> useful.
102,215
<p>What is the best way to add "Expires" in http header for static content? eg. images, css, js</p> <p>The web server is IIS 6.0; the language is classical ASP</p>
[ { "answer_id": 102302, "author": "Aaron", "author_id": 7659, "author_profile": "https://Stackoverflow.com/users/7659", "pm_score": -1, "selected": false, "text": "<p>I don't know if this is what you are looking for, but it does keep my pages from being cached.</p>\n\n<pre><code>&lt;META ...
2008/09/19
[ "https://Stackoverflow.com/questions/102215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1100/" ]
What is the best way to add "Expires" in http header for static content? eg. images, css, js The web server is IIS 6.0; the language is classical ASP
You could try something like this: ``` @ECHO OFF REM --------------------------------------------------------------------------- REM Caching - sets the caching on static files in a web site REM syntax REM Caching.CMD 1 d:\sites\MySite\WWWRoot\*.CSS REM REM %1 is the WebSite ID REM %2 is the path & Wildcard - for example, d:\sites\MySite\WWWRoot\*.CSS REM _adsutil is the path to ADSUtil.VBS REM --------------------------------------------------------------------------- SETLOCAL SET _adsutil=D:\Apps\Scripts\adsutil.vbs FOR %%i IN (%2) DO ( ECHO Setting Caching on %%~ni%%~xi CSCRIPT %_adsutil% CREATE W3SVC/%1/root/%%~ni%%~xi "IIsWebFile" CSCRIPT %_adsutil% SET W3SVC/%1/root/%%~ni%%~xi/HttpExpires "D, 0x69780" ECHO. ) ``` Which sets the caching value for each CSS file in a web root to 5 days, then run it like this: ``` Caching.CMD 1 \site\wwwroot\*.css Caching.CMD 1 \site\wwwroot\*.js Caching.CMD 1 \site\wwwroot\*.html Caching.CMD 1 \site\wwwroot\*.htm Caching.CMD 1 \site\wwwroot\*.gif Caching.CMD 1 \site\wwwroot\*.jpg ``` Kind of painful, but workable. BTW - to get the value for HttpExpires, set the value in the GUI, then run ``` AdsUtil.vbs ENUM W3SVC/1/root/File.txt ``` to get the actual value you need
102,261
<p>First off, I'm working on an app that's written such that some of your typical debugging tools can't be used (or at least I can't figure out how :). </p> <p>JavaScript, html, etc are all "cooked" and encoded (I think; I'm a little fuzzy on how the process works) before being deployed, so I can't attach VS 2005 to ie, and firebug lite doesn't work well. Also, the interface is in frames (yuck), so some other tools don't work as well.</p> <p>Firebug works great in Firefox, which isn't having this problem (nor is Safari), so I'm hoping someone might spot something "obviously" wrong with the way my code will play with IE. There's more information that can be given about its quirkiness, but let's start with this.</p> <p>Basically, I have a function that "collapses" tables into their headers by making normal table rows not visible. I have <code>"onclick='toggleDisplay("theTableElement", "theCollapseImageElement")'"</code> in the <code>&lt;tr&gt;</code> tags, and tables start off with "class='closed'". </p> <p>Single clicks collapse and expand tables in FF &amp; Safari, but IE tables require multiple clicks (a seemingly arbitrary number between 1 and 5) to expand. Sometimes after initially getting "opened", the tables will expand and collapse with a single click for a little while, only to eventually revert to requiring multiple clicks. I can tell from what little I can see in Visual Studio that the function is actually being reached each time. Thanks in advance for any advice!</p> <p>Here's the JS code:</p> <pre><code>bURL_RM_RID="some image prefix"; CLOSED_TBL="closed"; OPEN_TBL="open"; CLOSED_IMG= bURL_RM_RID+'166'; OPENED_IMG= bURL_RM_RID+'167'; //collapses/expands tbl (a table) and swaps out the image tblimg function toggleDisplay(tbl, tblimg) { var rowVisible; var tblclass = tbl.getAttribute("class"); var tblRows = tbl.rows; var img = tblimg; //Are we expanding or collapsing the table? if (tblclass == CLOSED_TBL) rowVisible = false; else rowVisible = true; for (i = 0; i &lt; tblRows.length; i++) { if (tblRows[i].className != "headerRow") { tblRows[i].style.display = (rowVisible) ? "none" : ""; } } //set the collapse images to the correct state and swap the class name rowVisible = !rowVisible; if (rowVisible) { img.setAttribute("src", CLOSED_IMG); tbl.setAttribute("class",OPEN_TBL); } else { img.setAttribute("src", OPENED_IMG); tbl.setAttribute("class",CLOSED_TBL); } } </code></pre> <p>­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 102295, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 2, "selected": false, "text": "<p>Have you tried changing this line</p>\n\n<pre><code>tblRows[i].style.display = (rowVisible) ? \"none\" : \"\";\n<...
2008/09/19
[ "https://Stackoverflow.com/questions/102261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18860/" ]
First off, I'm working on an app that's written such that some of your typical debugging tools can't be used (or at least I can't figure out how :). JavaScript, html, etc are all "cooked" and encoded (I think; I'm a little fuzzy on how the process works) before being deployed, so I can't attach VS 2005 to ie, and firebug lite doesn't work well. Also, the interface is in frames (yuck), so some other tools don't work as well. Firebug works great in Firefox, which isn't having this problem (nor is Safari), so I'm hoping someone might spot something "obviously" wrong with the way my code will play with IE. There's more information that can be given about its quirkiness, but let's start with this. Basically, I have a function that "collapses" tables into their headers by making normal table rows not visible. I have `"onclick='toggleDisplay("theTableElement", "theCollapseImageElement")'"` in the `<tr>` tags, and tables start off with "class='closed'". Single clicks collapse and expand tables in FF & Safari, but IE tables require multiple clicks (a seemingly arbitrary number between 1 and 5) to expand. Sometimes after initially getting "opened", the tables will expand and collapse with a single click for a little while, only to eventually revert to requiring multiple clicks. I can tell from what little I can see in Visual Studio that the function is actually being reached each time. Thanks in advance for any advice! Here's the JS code: ``` bURL_RM_RID="some image prefix"; CLOSED_TBL="closed"; OPEN_TBL="open"; CLOSED_IMG= bURL_RM_RID+'166'; OPENED_IMG= bURL_RM_RID+'167'; //collapses/expands tbl (a table) and swaps out the image tblimg function toggleDisplay(tbl, tblimg) { var rowVisible; var tblclass = tbl.getAttribute("class"); var tblRows = tbl.rows; var img = tblimg; //Are we expanding or collapsing the table? if (tblclass == CLOSED_TBL) rowVisible = false; else rowVisible = true; for (i = 0; i < tblRows.length; i++) { if (tblRows[i].className != "headerRow") { tblRows[i].style.display = (rowVisible) ? "none" : ""; } } //set the collapse images to the correct state and swap the class name rowVisible = !rowVisible; if (rowVisible) { img.setAttribute("src", CLOSED_IMG); tbl.setAttribute("class",OPEN_TBL); } else { img.setAttribute("src", OPENED_IMG); tbl.setAttribute("class",CLOSED_TBL); } } ``` ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
setAttribute is unreliable in IE. It treats attribute access and object property access as the same thing, so because the DOM property for the 'class' attribute is called 'className', you would have to use that instead on IE. This bug is fixed in the new IE8 beta, but it is easier simply to use the DOM Level 1 HTML property directly: ``` img.src= CLOSED_IMAGE; tbl.className= OPEN_TBL; ``` You can also do the table folding in the stylesheet, which will be faster and will save you the bother of having to loop over the table rows in script: ``` table.closed tr { display: none; } ```
102,271
<p>More information from <a href="http://en.wikipedia.org/wiki/Perl_6#Junctions" rel="noreferrer">the Perl 6 Wikipedia entry</a></p> <p><strong>Junctions</strong></p> <p>Perl 6 introduces the concept of junctions: values that are composites of other values.[24] In the earliest days of Perl 6's design, these were called "superpositions", by analogy to the concept in quantum physics of quantum superpositions — waveforms that can simultaneously occupy several states until observation "collapses" them. A Perl 5 module released in 2000 by Damian Conway called Quantum::Superpositions[25] provided an initial proof of concept. While at first, such superpositional values seemed like merely a programmatic curiosity, over time their utility and intuitiveness became widely recognized, and junctions now occupy a central place in Perl 6's design.</p> <p>In their simplest form, junctions are created by combining a set of values with junctive operators:</p> <pre><code>my $any_even_digit = 0|2|4|6|8; # any(0, 2, 4, 6, 8) my $all_odd_digits = 1&amp;3&amp;5&amp;7&amp;9; # all(1, 3, 5, 7, 9) </code></pre> <p>| indicates a value which is equal to either its left or right-hand arguments. &amp; indicates a value which is equal to both its left and right-hand arguments. These values can be used in any code that would use a normal value. Operations performed on a junction act on all members of the junction equally, and combine according to the junctive operator. So, ("apple"|"banana") ~ "s" would yield "apples"|"bananas". In comparisons, junctions return a single true or false result for the comparison. "any" junctions return true if the comparison is true for any one of the elements of the junction. "all" junctions return true if the comparison is true for all of the elements of the junction.</p> <p>Junctions can also be used to more richly augment the type system by introducing a style of generic programming that is constrained to junctions of types:</p> <pre><code>sub get_tint ( RGB_Color|CMYK_Color $color, num $opacity) { ... } sub store_record (Record&amp;Storable $rec) { ... } </code></pre>
[ { "answer_id": 117746, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 5, "selected": true, "text": "<p>How many days are in a given month?</p>\n\n<pre><code>given( $month ){\n when any(qw'1 3 5 7 8 10 12') {\n $day =...
2008/09/19
[ "https://Stackoverflow.com/questions/102271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18446/" ]
More information from [the Perl 6 Wikipedia entry](http://en.wikipedia.org/wiki/Perl_6#Junctions) **Junctions** Perl 6 introduces the concept of junctions: values that are composites of other values.[24] In the earliest days of Perl 6's design, these were called "superpositions", by analogy to the concept in quantum physics of quantum superpositions — waveforms that can simultaneously occupy several states until observation "collapses" them. A Perl 5 module released in 2000 by Damian Conway called Quantum::Superpositions[25] provided an initial proof of concept. While at first, such superpositional values seemed like merely a programmatic curiosity, over time their utility and intuitiveness became widely recognized, and junctions now occupy a central place in Perl 6's design. In their simplest form, junctions are created by combining a set of values with junctive operators: ``` my $any_even_digit = 0|2|4|6|8; # any(0, 2, 4, 6, 8) my $all_odd_digits = 1&3&5&7&9; # all(1, 3, 5, 7, 9) ``` | indicates a value which is equal to either its left or right-hand arguments. & indicates a value which is equal to both its left and right-hand arguments. These values can be used in any code that would use a normal value. Operations performed on a junction act on all members of the junction equally, and combine according to the junctive operator. So, ("apple"|"banana") ~ "s" would yield "apples"|"bananas". In comparisons, junctions return a single true or false result for the comparison. "any" junctions return true if the comparison is true for any one of the elements of the junction. "all" junctions return true if the comparison is true for all of the elements of the junction. Junctions can also be used to more richly augment the type system by introducing a style of generic programming that is constrained to junctions of types: ``` sub get_tint ( RGB_Color|CMYK_Color $color, num $opacity) { ... } sub store_record (Record&Storable $rec) { ... } ```
How many days are in a given month? ``` given( $month ){ when any(qw'1 3 5 7 8 10 12') { $day = 31 } when any(qw'4 6 9 11') { $day = 30 } when 2 { $day = 29 } } ```
102,278
<p>OK, so practically every database based application has to deal with "non-active" records. Either, soft-deletions or marking something as "to be ignored". I'm curious as to whether there are any radical alternatives thoughts on an `active' column (or a status column).</p> <p>For example, if I had a list of people</p> <pre><code>CREATE TABLE people ( id INTEGER PRIMARY KEY, name VARCHAR(100), active BOOLEAN, ... ); </code></pre> <p>That means to get a list of active people, you need to use</p> <pre><code>SELECT * FROM people WHERE active=True; </code></pre> <p>Does anyone suggest that non active records would be moved off to a separate table and where appropiate a UNION is done to join the two?</p> <p>Curiosity striking...</p> <p><strong>EDIT:</strong> I should make clear, I'm coming at this from a purist perspective. I can see how data archiving might be necessary for large amounts of data, but that is not where I'm coming from. If you do a SELECT * FROM people it would make sense to me that those entries are in a sense "active"</p> <p>Thanks</p>
[ { "answer_id": 102297, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 0, "selected": false, "text": "<p>We use active flags quite often. If your database is going to be very large, I could see the value in migrating ina...
2008/09/19
[ "https://Stackoverflow.com/questions/102278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1087/" ]
OK, so practically every database based application has to deal with "non-active" records. Either, soft-deletions or marking something as "to be ignored". I'm curious as to whether there are any radical alternatives thoughts on an `active' column (or a status column). For example, if I had a list of people ``` CREATE TABLE people ( id INTEGER PRIMARY KEY, name VARCHAR(100), active BOOLEAN, ... ); ``` That means to get a list of active people, you need to use ``` SELECT * FROM people WHERE active=True; ``` Does anyone suggest that non active records would be moved off to a separate table and where appropiate a UNION is done to join the two? Curiosity striking... **EDIT:** I should make clear, I'm coming at this from a purist perspective. I can see how data archiving might be necessary for large amounts of data, but that is not where I'm coming from. If you do a SELECT \* FROM people it would make sense to me that those entries are in a sense "active" Thanks
You partition the table on the active flag, so that active records are in one partition, and inactive records are in the other partition. Then you create an active view for each table which automatically has the active filter on it. The database query engine automatically restricts the query to the partition that has the active records in it, which is much faster than even using an index on that flag. Here is an example of how to create a partitioned table in Oracle. Oracle doesn't have boolean column types, so I've modified your table structure for Oracle purposes. ``` CREATE TABLE people ( id NUMBER(10), name VARCHAR2(100), active NUMBER(1) ) PARTITION BY LIST(active) ( PARTITION active_records VALUES (0) PARTITION inactive_records VALUES (1) ); ``` If you wanted to you could put each partition in different tablespaces. You can also partition your indexes as well. Incidentally, this seems a repeat of [this](https://stackoverflow.com/questions/68323/what-is-the-best-way-to-implement-soft-deletion) question, as a newbie I need to ask, what's the procedure on dealing with unintended duplicates? **Edit:** As requested in comments, provided an example for creating a partitioned table in Oracle
102,317
<p>I have two tables Organisation and Employee having one to many relation i.e one organisation can have multiple employees. Now I want to select all information of a particular organisation plus first name of all employees for this organisation. What’s the best way to do it? Can I get all of this in single record set or I will have to get multiple rows based on no. of employees? Here is a bit graphical demonstration of what I want:</p> <pre><code>Org_ID Org_Address Org_OtherDetails Employess 1 132A B Road List of details Emp1, Emp2, Emp3..... </code></pre>
[ { "answer_id": 102361, "author": "Mike McAllister", "author_id": 16247, "author_profile": "https://Stackoverflow.com/users/16247", "pm_score": 0, "selected": false, "text": "<p>If you use Oracle you can create a PL/SQL function you can use in your query that accepts an organization_id as...
2008/09/19
[ "https://Stackoverflow.com/questions/102317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have two tables Organisation and Employee having one to many relation i.e one organisation can have multiple employees. Now I want to select all information of a particular organisation plus first name of all employees for this organisation. What’s the best way to do it? Can I get all of this in single record set or I will have to get multiple rows based on no. of employees? Here is a bit graphical demonstration of what I want: ``` Org_ID Org_Address Org_OtherDetails Employess 1 132A B Road List of details Emp1, Emp2, Emp3..... ```
The original question was database specific, but perhaps this is a good place to include a more generic answer. It's a common question. The concept that you are describing is often referred to as 'Group Concatenation'. There's no standard solution in SQL-92 or SQL-99. So you'll need a vendor-specific solution. * **MySQL** - Use the built-in GROUP\_CONCAT function. In your example you would want something like this: ``` select o.ID, o.Address, o.OtherDetails, GROUP_CONCAT( concat(e.firstname, ' ', e.lastname) ) as Employees from employees e inner join organization o on o.org_id=e.org_id group by o.org_id ``` * **PostgreSQL** - PostgreSQL 9.0 is equally simple now that string\_agg(expression, delimiter) is built-in. Here it is with 'comma-space' between elements: ``` select o.ID, o.Address, o.OtherDetails, STRING_AGG( (e.firstname || ' ' || e.lastname), ', ' ) as Employees from employees e inner join organization o on o.org_id=e.org_id group by o.org_id ``` PostgreSQL before 9.0 allows you to define your own aggregate functions with CREATE AGGREGATE. Slightly more work than MySQL, but much more flexible. See this [other post](https://stackoverflow.com/questions/43870/how-to-concatenate-strings-of-a-string-field-in-a-postgresql-group-by-query) for more details. (Of course PostgreSQL 9.0 and later have this option as well.) * **Oracle** - same idea using **LISTAGG**. * **MS SQL Server** - same idea using **STRING\_AGG** * **Fallback solution** - in other database technologies or in very very old versions of the technologies listed above you don't have these group concatenation functions. In that case create a stored procedure that takes the org\_id as its input and outputs the concatenated employee names. Then use this stored procedure in your query. Some of the other responses here include some details about how to write stored procedures like these. ``` select o.ID, o.Address, o.OtherDetails, MY_CUSTOM_GROUP_CONCAT_PROCEDURE( o.ID ) as Employees from organization o ```
102,343
<p>I have a need to open a popup detail window from a gridview (VS 2005 / 2008). What I am trying to do is in the markup for my TemplateColumn have an asp:Button control, sort of like this:</p> <pre><code>&lt;asp:Button ID="btnShowDetails" runat="server" CausesValidation="false" CommandName="Details" Text="Order Details" onClientClick="window.open('PubsOrderDetails.aspx?OrderId=&lt;%# Eval("order_id") %&gt;', '','scrollbars=yes,resizable=yes, width=350, height=550');" </code></pre> <p>Of course, what isn't working is the appending of the &lt;%# Eval...%> section to set the query string variable.</p> <p>Any suggestions? Or is there a far better way of achieving the same result?</p>
[ { "answer_id": 102373, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 5, "selected": true, "text": "<p>I believe the way to do it is</p>\n\n<blockquote>\n<pre><code>onClientClick=&lt;%# string.Format(\"window.open('PubsOrd...
2008/09/19
[ "https://Stackoverflow.com/questions/102343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12253/" ]
I have a need to open a popup detail window from a gridview (VS 2005 / 2008). What I am trying to do is in the markup for my TemplateColumn have an asp:Button control, sort of like this: ``` <asp:Button ID="btnShowDetails" runat="server" CausesValidation="false" CommandName="Details" Text="Order Details" onClientClick="window.open('PubsOrderDetails.aspx?OrderId=<%# Eval("order_id") %>', '','scrollbars=yes,resizable=yes, width=350, height=550');" ``` Of course, what isn't working is the appending of the <%# Eval...%> section to set the query string variable. Any suggestions? Or is there a far better way of achieving the same result?
I believe the way to do it is > > > ``` > onClientClick=<%# string.Format("window.open('PubsOrderDetails.aspx?OrderId={0}',scrollbars=yes,resizable=yes, width=350, height=550);", Eval("order_id")) %> > > ``` > >
102,382
<p>I use ssh-agent with password-protected keys on Linux. Every time I log into a certain machine, I do this:</p> <pre><code>eval `ssh-agent` &amp;&amp; ssh-add </code></pre> <p>This works well enough, but every time I log in and do this, I create another ssh-agent. Once in a while, I will do a <code>killall ssh-agent</code> to reap them. Is there a simple way to reuse the same ssh-agent process across different sessions?</p>
[ { "answer_id": 102420, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 2, "selected": false, "text": "<p>How much control do you have over this machine? One answer would be to run ssh-agent as a daemon process. Other opti...
2008/09/19
[ "https://Stackoverflow.com/questions/102382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ]
I use ssh-agent with password-protected keys on Linux. Every time I log into a certain machine, I do this: ``` eval `ssh-agent` && ssh-add ``` This works well enough, but every time I log in and do this, I create another ssh-agent. Once in a while, I will do a `killall ssh-agent` to reap them. Is there a simple way to reuse the same ssh-agent process across different sessions?
have a look at Keychain. It was written b people in a similar situation to yourself. [Keychain](http://www.gentoo.org/proj/en/keychain/)
102,394
<p>I am trying to sort a dict based on its key and return an iterator to the values from within an overridden iter method in a class. Is there a nicer and more efficient way of doing this than creating a new list, inserting into the list as I sort through the keys?</p>
[ { "answer_id": 102438, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 2, "selected": false, "text": "<p>By far the easiest approach, and almost certainly the fastest, is something along the lines of:</p>\n\n<pre><cod...
2008/09/19
[ "https://Stackoverflow.com/questions/102394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18909/" ]
I am trying to sort a dict based on its key and return an iterator to the values from within an overridden iter method in a class. Is there a nicer and more efficient way of doing this than creating a new list, inserting into the list as I sort through the keys?
How about something like this: ``` def itersorted(d): for key in sorted(d): yield d[key] ```
102,457
<p>Given an existing valid SVG document, what's the best way to create "informational popups", so that when you hover or click on certain elements (let's say ) you popup a box with an arbitrary amount (i.e. not just a single line tooltip) of extra information?</p> <p>This should display correctly at least in Firefox and be invisible if the image was rasterized to a bitmap format.</p>
[ { "answer_id": 105636, "author": "Sparr", "author_id": 13675, "author_profile": "https://Stackoverflow.com/users/13675", "pm_score": 6, "selected": true, "text": "<pre><code>&lt;svg&gt;\n &lt;text id=\"thingyouhoverover\" x=\"50\" y=\"35\" font-size=\"14\"&gt;Mouse over me!&lt;/text&gt;...
2008/09/19
[ "https://Stackoverflow.com/questions/102457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2846/" ]
Given an existing valid SVG document, what's the best way to create "informational popups", so that when you hover or click on certain elements (let's say ) you popup a box with an arbitrary amount (i.e. not just a single line tooltip) of extra information? This should display correctly at least in Firefox and be invisible if the image was rasterized to a bitmap format.
``` <svg> <text id="thingyouhoverover" x="50" y="35" font-size="14">Mouse over me!</text> <text id="thepopup" x="250" y="100" font-size="30" fill="black" visibility="hidden">Change me <set attributeName="visibility" from="hidden" to="visible" begin="thingyouhoverover.mouseover" end="thingyouhoverover.mouseout"/> </text> </svg> ``` Further explanation can be found [here](http://web.archive.org/web/20121023190528/http://www.ibm.com/developerworks/library/x-svgint/).
102,468
<p>I'm trying to write a piece of code that will do the following:</p> <p>Take the numbers 0 to 9 and assign one or more letters to this number. For example:</p> <pre><code>0 = N, 1 = L, 2 = T, 3 = D, 4 = R, 5 = V or F, 6 = B or P, 7 = Z, 8 = H or CH or J, 9 = G </code></pre> <p>When I have a code like 0123, it's an easy job to encode it. It will obviously make up the code NLTD. When a number like 5,6 or 8 is introduced, things get different. A number like 051 would result in more than one possibility:</p> <p>NVL and NFL</p> <p>It should be obvious that this gets even &quot;worse&quot; with longer numbers that include several digits like 5,6 or 8.</p> <p>Being pretty bad at mathematics, I have not yet been able to come up with a decent solution that will allow me to feed the program a bunch of numbers and have it spit out all the possible letter combinations. So I'd love some help with it, 'cause I can't seem to figure it out. Dug up some information about permutations and combinations, but no luck.</p> <p>Thanks for any suggestions/clues. The language I need to write the code in is PHP, but any general hints would be highly appreciated.</p> <h3>Update:</h3> <p>Some more background: (and thanks a lot for the quick responses!)</p> <p>The idea behind my question is to build a script that will help people to easily convert numbers they want to remember to words that are far more easily remembered. This is sometimes referred to as &quot;pseudo-numerology&quot;.</p> <p>I want the script to give me all the possible combinations that are then held against a database of stripped words. These stripped words just come from a dictionary and have all the letters I mentioned in my question stripped out of them. That way, the number to be encoded can usually easily be related to a one or more database records. And when that happens, you end up with a list of words that you can use to remember the number you wanted to remember.</p>
[ { "answer_id": 102510, "author": "David Pierre", "author_id": 18296, "author_profile": "https://Stackoverflow.com/users/18296", "pm_score": 3, "selected": false, "text": "<p>It can be done easily recursively.</p>\n\n<p>The idea is that to handle the whole code of size n, you must handle ...
2008/09/19
[ "https://Stackoverflow.com/questions/102468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18922/" ]
I'm trying to write a piece of code that will do the following: Take the numbers 0 to 9 and assign one or more letters to this number. For example: ``` 0 = N, 1 = L, 2 = T, 3 = D, 4 = R, 5 = V or F, 6 = B or P, 7 = Z, 8 = H or CH or J, 9 = G ``` When I have a code like 0123, it's an easy job to encode it. It will obviously make up the code NLTD. When a number like 5,6 or 8 is introduced, things get different. A number like 051 would result in more than one possibility: NVL and NFL It should be obvious that this gets even "worse" with longer numbers that include several digits like 5,6 or 8. Being pretty bad at mathematics, I have not yet been able to come up with a decent solution that will allow me to feed the program a bunch of numbers and have it spit out all the possible letter combinations. So I'd love some help with it, 'cause I can't seem to figure it out. Dug up some information about permutations and combinations, but no luck. Thanks for any suggestions/clues. The language I need to write the code in is PHP, but any general hints would be highly appreciated. ### Update: Some more background: (and thanks a lot for the quick responses!) The idea behind my question is to build a script that will help people to easily convert numbers they want to remember to words that are far more easily remembered. This is sometimes referred to as "pseudo-numerology". I want the script to give me all the possible combinations that are then held against a database of stripped words. These stripped words just come from a dictionary and have all the letters I mentioned in my question stripped out of them. That way, the number to be encoded can usually easily be related to a one or more database records. And when that happens, you end up with a list of words that you can use to remember the number you wanted to remember.
The general structure you want to hold your number -> letter assignments is an array or arrays, similar to: ``` // 0 = N, 1 = L, 2 = T, 3 = D, 4 = R, 5 = V or F, 6 = B or P, 7 = Z, // 8 = H or CH or J, 9 = G $numberMap = new Array ( 0 => new Array("N"), 1 => new Array("L"), 2 => new Array("T"), 3 => new Array("D"), 4 => new Array("R"), 5 => new Array("V", "F"), 6 => new Array("B", "P"), 7 => new Array("Z"), 8 => new Array("H", "CH", "J"), 9 => new Array("G"), ); ``` Then, a bit of recursive logic gives us a function similar to: ``` function GetEncoding($number) { $ret = new Array(); for ($i = 0; $i < strlen($number); $i++) { // We're just translating here, nothing special. // $var + 0 is a cheap way of forcing a variable to be numeric $ret[] = $numberMap[$number[$i]+0]; } } function PrintEncoding($enc, $string = "") { // If we're at the end of the line, then print! if (count($enc) === 0) { print $string."\n"; return; } // Otherwise, soldier on through the possible values. // Grab the next 'letter' and cycle through the possibilities for it. foreach ($enc[0] as $letter) { // And call this function again with it! PrintEncoding(array_slice($enc, 1), $string.$letter); } } ``` Three cheers for recursion! This would be used via: ``` PrintEncoding(GetEncoding("052384")); ``` And if you really want it as an array, play with output buffering and explode using "\n" as your split string.
102,477
<p>Before, I have found the "Cost" in the execution plan to be a good indicator of relative execution time. Why is this case different? Am I a fool for thinking the execution plan has relevance? What specifically can I try to improve v_test performance?</p> <p>Thank you.</p> <p>Using Oracle 10g I have a simple query view defined below</p> <pre><code> create or replace view v_test as select distinct u.bo_id as bo_id, upper(trim(d.dept_id)) as dept_id from cust_bo_users u join cust_bo_roles r on u.role_name=r.role_name join cust_dept_roll_up_tbl d on (r.region is null or trim(r.region)=trim(d.chrgback_reg)) and (r.prod_id is null or trim(r.prod_id)=trim(d.prod_id)) and (r.div_id is null or trim(r.div_id)=trim(d.div_id )) and (r.clus_id is null or trim(r.clus_id )=trim( d.clus_id)) and (r.prod_ln_id is null or trim(r.prod_ln_id)=trim(d.prod_ln_id)) and (r.dept_id is null or trim(r.dept_id)=trim(d.dept_id)) </code></pre> <p>defined to replace the following view</p> <pre><code> create or replace view v_bo_secured_detail select distinct Q.BO_ID, Q.DEPT_ID from (select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D where U.ROLE_NAME = R.ROLE_NAME and R.ROLE_LEVEL = 'REGION' and trim(R.REGION) = UPPER(trim(D.CHRGBACK_REG)) union all select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D where U.ROLE_NAME = R.ROLE_NAME and R.ROLE_LEVEL = 'RG_PROD' and trim(R.REGION) = UPPER(trim(D.CHRGBACK_REG)) and trim(R.PROD_ID) = UPPER(trim(D.PROD_ID)) union all select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D where U.ROLE_NAME = R.ROLE_NAME and R.ROLE_LEVEL = 'PROD' and trim(R.PROD_ID) = UPPER(trim(D.PROD_ID)) union all select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D where U.ROLE_NAME = R.ROLE_NAME and R.ROLE_LEVEL = 'DIV' and trim(R.DIV_ID) = UPPER(trim(D.DIV_ID)) union all select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D where U.ROLE_NAME = R.ROLE_NAME and R.ROLE_LEVEL = 'RG_DIV' and trim(R.REGION) = UPPER(trim(D.CHRGBACK_REG)) and trim(R.DIV_ID) = UPPER(trim(D.DIV_ID)) union all select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D where U.ROLE_NAME = R.ROLE_NAME and R.ROLE_LEVEL = 'CLUS' and trim(R.CLUS_ID) = UPPER(trim(D.CLUS_ID)) union all select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D where U.ROLE_NAME = R.ROLE_NAME and R.ROLE_LEVEL = 'RG_CLUS' and trim(R.REGION) = UPPER(trim(D.CHRGBACK_REG)) and trim(R.CLUS_ID) = UPPER(trim(D.CLUS_ID)) union all select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D where U.ROLE_NAME = R.ROLE_NAME and R.ROLE_LEVEL = 'PROD_LN' and trim(R.PROD_LN_ID) = UPPER(trim(D.PROD_LN_ID)) union all select U.BO_ID BO_ID, UPPER(trim(R.DEPT_ID)) DEPT_ID from CUST_BO_USERS U, CUST_BO_ROLES R where U.ROLE_NAME = R.ROLE_NAME and R.ROLE_LEVEL = 'DEPT') Q </code></pre> <p>with the goal of removing the dependency on the ROLE_LEVEL column.</p> <p>The execution plan for v_test is significantly lower than v_bo_secured_detail for simple</p> <pre><code>select * from &lt;view&gt; where bo_id='value' </code></pre> <p>queries. And is significantly lower when used in a real world query</p> <pre><code> select CT_REPORT.RPT_KEY, CT_REPORT_ENTRY.RPE_KEY, CT_REPORT_ENTRY.CUSTOM16, Exp_Sub_Type.value, min(CT_REPORT_PAYMENT_CONF.PAY_DATE), CT_REPORT.PAID_DATE from CT_REPORT, &lt;VIEW&gt; SD, CT_REPORT_ENTRY, CT_LIST_ITEM_LANG Exp_Sub_Type, CT_REPORT_PAYMENT_CONF, CT_STATUS_LANG Payment_Status where (CT_REPORT_ENTRY.RPT_KEY = CT_REPORT.RPT_KEY) and (Payment_Status.STAT_KEY = CT_REPORT.PAY_KEY) and (Exp_Sub_Type.LI_KEY = CT_REPORT_ENTRY.CUSTOM9 and Exp_Sub_Type.LANG_CODE = 'en') and (CT_REPORT.RPT_KEY = CT_REPORT_PAYMENT_CONF.RPT_KEY) and (SD.BO_ID = 'JZHU9') and (SD.DEPT_ID = UPPER(CT_REPORT_ENTRY.CUSTOM5)) and (Payment_Status.name = 'Payment Confirmed' and (Payment_Status.LANG_CODE = 'en') and CT_REPORT.PAID_DATE &gt; to_date('01/01/2008', 'mm/dd/yyyy') and Exp_Sub_Type.value != 'Korea') group by CT_REPORT.RPT_KEY, CT_REPORT_ENTRY.RPE_KEY, CT_REPORT_ENTRY.CUSTOM16, Exp_Sub_Type.value, CT_REPORT.PAID_DATE </code></pre> <p>The execution times are WILDLY different. The v_test view taking 15 hours, and the v_bo_secured_detail taking a few seconds.</p> <hr> <p><strong>Thank you all who responded</strong></p> <p>This is one to remember for me. The places where the theory and mathematics of the expressions meets the reality of hardware based execution. Ouch.</p>
[ { "answer_id": 102749, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": 1, "selected": false, "text": "<p>One aspect of low-cost -- high execution time is that when you are looking at large data-sets, it is often more efficien...
2008/09/19
[ "https://Stackoverflow.com/questions/102477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1736623/" ]
Before, I have found the "Cost" in the execution plan to be a good indicator of relative execution time. Why is this case different? Am I a fool for thinking the execution plan has relevance? What specifically can I try to improve v\_test performance? Thank you. Using Oracle 10g I have a simple query view defined below ``` create or replace view v_test as select distinct u.bo_id as bo_id, upper(trim(d.dept_id)) as dept_id from cust_bo_users u join cust_bo_roles r on u.role_name=r.role_name join cust_dept_roll_up_tbl d on (r.region is null or trim(r.region)=trim(d.chrgback_reg)) and (r.prod_id is null or trim(r.prod_id)=trim(d.prod_id)) and (r.div_id is null or trim(r.div_id)=trim(d.div_id )) and (r.clus_id is null or trim(r.clus_id )=trim( d.clus_id)) and (r.prod_ln_id is null or trim(r.prod_ln_id)=trim(d.prod_ln_id)) and (r.dept_id is null or trim(r.dept_id)=trim(d.dept_id)) ``` defined to replace the following view ``` create or replace view v_bo_secured_detail select distinct Q.BO_ID, Q.DEPT_ID from (select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D where U.ROLE_NAME = R.ROLE_NAME and R.ROLE_LEVEL = 'REGION' and trim(R.REGION) = UPPER(trim(D.CHRGBACK_REG)) union all select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D where U.ROLE_NAME = R.ROLE_NAME and R.ROLE_LEVEL = 'RG_PROD' and trim(R.REGION) = UPPER(trim(D.CHRGBACK_REG)) and trim(R.PROD_ID) = UPPER(trim(D.PROD_ID)) union all select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D where U.ROLE_NAME = R.ROLE_NAME and R.ROLE_LEVEL = 'PROD' and trim(R.PROD_ID) = UPPER(trim(D.PROD_ID)) union all select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D where U.ROLE_NAME = R.ROLE_NAME and R.ROLE_LEVEL = 'DIV' and trim(R.DIV_ID) = UPPER(trim(D.DIV_ID)) union all select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D where U.ROLE_NAME = R.ROLE_NAME and R.ROLE_LEVEL = 'RG_DIV' and trim(R.REGION) = UPPER(trim(D.CHRGBACK_REG)) and trim(R.DIV_ID) = UPPER(trim(D.DIV_ID)) union all select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D where U.ROLE_NAME = R.ROLE_NAME and R.ROLE_LEVEL = 'CLUS' and trim(R.CLUS_ID) = UPPER(trim(D.CLUS_ID)) union all select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D where U.ROLE_NAME = R.ROLE_NAME and R.ROLE_LEVEL = 'RG_CLUS' and trim(R.REGION) = UPPER(trim(D.CHRGBACK_REG)) and trim(R.CLUS_ID) = UPPER(trim(D.CLUS_ID)) union all select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D where U.ROLE_NAME = R.ROLE_NAME and R.ROLE_LEVEL = 'PROD_LN' and trim(R.PROD_LN_ID) = UPPER(trim(D.PROD_LN_ID)) union all select U.BO_ID BO_ID, UPPER(trim(R.DEPT_ID)) DEPT_ID from CUST_BO_USERS U, CUST_BO_ROLES R where U.ROLE_NAME = R.ROLE_NAME and R.ROLE_LEVEL = 'DEPT') Q ``` with the goal of removing the dependency on the ROLE\_LEVEL column. The execution plan for v\_test is significantly lower than v\_bo\_secured\_detail for simple ``` select * from <view> where bo_id='value' ``` queries. And is significantly lower when used in a real world query ``` select CT_REPORT.RPT_KEY, CT_REPORT_ENTRY.RPE_KEY, CT_REPORT_ENTRY.CUSTOM16, Exp_Sub_Type.value, min(CT_REPORT_PAYMENT_CONF.PAY_DATE), CT_REPORT.PAID_DATE from CT_REPORT, <VIEW> SD, CT_REPORT_ENTRY, CT_LIST_ITEM_LANG Exp_Sub_Type, CT_REPORT_PAYMENT_CONF, CT_STATUS_LANG Payment_Status where (CT_REPORT_ENTRY.RPT_KEY = CT_REPORT.RPT_KEY) and (Payment_Status.STAT_KEY = CT_REPORT.PAY_KEY) and (Exp_Sub_Type.LI_KEY = CT_REPORT_ENTRY.CUSTOM9 and Exp_Sub_Type.LANG_CODE = 'en') and (CT_REPORT.RPT_KEY = CT_REPORT_PAYMENT_CONF.RPT_KEY) and (SD.BO_ID = 'JZHU9') and (SD.DEPT_ID = UPPER(CT_REPORT_ENTRY.CUSTOM5)) and (Payment_Status.name = 'Payment Confirmed' and (Payment_Status.LANG_CODE = 'en') and CT_REPORT.PAID_DATE > to_date('01/01/2008', 'mm/dd/yyyy') and Exp_Sub_Type.value != 'Korea') group by CT_REPORT.RPT_KEY, CT_REPORT_ENTRY.RPE_KEY, CT_REPORT_ENTRY.CUSTOM16, Exp_Sub_Type.value, CT_REPORT.PAID_DATE ``` The execution times are WILDLY different. The v\_test view taking 15 hours, and the v\_bo\_secured\_detail taking a few seconds. --- **Thank you all who responded** This is one to remember for me. The places where the theory and mathematics of the expressions meets the reality of hardware based execution. Ouch.
As [the Oracle documentation says](http://download.oracle.com/docs/cd/A87860_01/doc/server.817/a76965/c20a_opt.htm#16287), the cost is the estimated cost relative to a particular execution plan. When you tweak the query, the particular execution plan that costs are calculated relative to can change. Sometimes dramatically. The problem with v\_test's performance is that Oracle can think of no way to execute it other than performing a nested loop, for each cust\_bo\_roles, scan all of cust\_dept\_roll\_up\_tbl to find a match. If the table are of size n and m, this takes n\*m time, which is slow for large tables. By contrast v\_bo\_secured\_detail is set up so that it is a series of queries, each of which can be done through some other mechanism. (Oracle has a number it may use, including using an index, building a hash on the fly, or sorting the datasets and merging them. These operations are all O(n\*log(n)) or better.) A small series of fast queries is fast. As painful as it is, if you want this query to be fast then you need to break it out like the previous query did.
102,514
<p>I'm trying to create the IDL for the IConverterSession interface and I'm confused by the definition of the <a href="http://msdn.microsoft.com/en-us/library/bb905204.aspx" rel="nofollow noreferrer">MIMETOMAPI</a> method. It specifies the <code>LPMESSAGE pmsg</code> parameter as [out] yet the comments state its the pointer to the MAPI message to be loaded.</p> <p>Its unclear to me whether the functions allocates the MAPI message object and sets the pointer in which case shouldn't it be a pointer to a pointer of MESSAGE? OR is the calling code expected to have instanced the message object already in which case why is marked [out] and not [in]?</p> <p>Utlitmately this interface is to be consumed from VB6 code so it will either have to be [in] or [in, out] but I do need to know whether in the the IDL I used:-</p> <pre><code>[in] IMessage pmsg* </code></pre> <p>OR</p> <pre><code>[in, out] IMessage pmsg** </code></pre>
[ { "answer_id": 103283, "author": "Alejandro Bologna", "author_id": 9263, "author_profile": "https://Stackoverflow.com/users/9263", "pm_score": 3, "selected": true, "text": "<p>I think in this case the documentation is misleading when it marks the parameter as [out]. You have to pass a va...
2008/09/19
[ "https://Stackoverflow.com/questions/102514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17516/" ]
I'm trying to create the IDL for the IConverterSession interface and I'm confused by the definition of the [MIMETOMAPI](http://msdn.microsoft.com/en-us/library/bb905204.aspx) method. It specifies the `LPMESSAGE pmsg` parameter as [out] yet the comments state its the pointer to the MAPI message to be loaded. Its unclear to me whether the functions allocates the MAPI message object and sets the pointer in which case shouldn't it be a pointer to a pointer of MESSAGE? OR is the calling code expected to have instanced the message object already in which case why is marked [out] and not [in]? Utlitmately this interface is to be consumed from VB6 code so it will either have to be [in] or [in, out] but I do need to know whether in the the IDL I used:- ``` [in] IMessage pmsg* ``` OR ``` [in, out] IMessage pmsg** ```
I think in this case the documentation is misleading when it marks the parameter as [out]. You have to pass a valid LPMESSAGE to the method, and that's why is not a double pointer. So i would go with [in] on your idl definition.
102,521
<p>I know that <a href="http://wiki.lessthandot.com/index.php/How_to_find_the_first_and_last_days_in_years,_months_etc" rel="nofollow noreferrer">Sql Server has some handy built-in quarterly</a> stuff, but what about the .Net native <a href="http://msdn.microsoft.com/en-us/library/system.datetime_members(VS.80).aspx" rel="nofollow noreferrer">DateTime</a> object? What is the best way to add, subtract, and traverse quarters?</p> <p>Is it a <em>bad thing</em>™ to use the VB-specific <a href="http://msdn.microsoft.com/en-us/library/hcxe65wz(VS.80).aspx" rel="nofollow noreferrer">DateAdd()</a> function? e.g.:</p> <pre><code>Dim nextQuarter As DateTime = DateAdd(DateInterval.Quarter, 1, DateTime.Now) </code></pre> <p>Edit: Expanding @bslorence's function:</p> <pre><code>Public Shared Function AddQuarters(ByVal originalDate As DateTime, ByVal quarters As Integer) As Datetime Return originalDate.AddMonths(quarters * 3) End Function </code></pre> <p>Expanding @Matt's function:</p> <pre><code>Public Shared Function GetQuarter(ByVal fromDate As DateTime) As Integer Return ((fromDate.Month - 1) \ 3) + 1 End Function </code></pre> <p>Edit: here's a couple more functions that were handy:</p> <pre><code>Public Shared Function GetFirstDayOfQuarter(ByVal originalDate As DateTime) As DateTime Return AddQuarters(New DateTime(originalDate.Year, 1, 1), GetQuarter(originalDate) - 1) End Function Public Shared Function GetLastDayOfQuarter(ByVal originalDate As DateTime) As DateTime Return AddQuarters(New DateTime(originalDate.Year, 1, 1), GetQuarter(originalDate)).AddDays(-1) End Function </code></pre>
[ { "answer_id": 102712, "author": "Ben Dunlap", "author_id": 8722, "author_profile": "https://Stackoverflow.com/users/8722", "pm_score": 2, "selected": false, "text": "<p>How about this:</p>\n\n<pre><code>Dim nextQuarter As DateTime = DateTime.Now.AddMonths(3);\n</code></pre>\n" }, { ...
2008/09/19
[ "https://Stackoverflow.com/questions/102521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1414/" ]
I know that [Sql Server has some handy built-in quarterly](http://wiki.lessthandot.com/index.php/How_to_find_the_first_and_last_days_in_years,_months_etc) stuff, but what about the .Net native [DateTime](http://msdn.microsoft.com/en-us/library/system.datetime_members(VS.80).aspx) object? What is the best way to add, subtract, and traverse quarters? Is it a *bad thing*™ to use the VB-specific [DateAdd()](http://msdn.microsoft.com/en-us/library/hcxe65wz(VS.80).aspx) function? e.g.: ``` Dim nextQuarter As DateTime = DateAdd(DateInterval.Quarter, 1, DateTime.Now) ``` Edit: Expanding @bslorence's function: ``` Public Shared Function AddQuarters(ByVal originalDate As DateTime, ByVal quarters As Integer) As Datetime Return originalDate.AddMonths(quarters * 3) End Function ``` Expanding @Matt's function: ``` Public Shared Function GetQuarter(ByVal fromDate As DateTime) As Integer Return ((fromDate.Month - 1) \ 3) + 1 End Function ``` Edit: here's a couple more functions that were handy: ``` Public Shared Function GetFirstDayOfQuarter(ByVal originalDate As DateTime) As DateTime Return AddQuarters(New DateTime(originalDate.Year, 1, 1), GetQuarter(originalDate) - 1) End Function Public Shared Function GetLastDayOfQuarter(ByVal originalDate As DateTime) As DateTime Return AddQuarters(New DateTime(originalDate.Year, 1, 1), GetQuarter(originalDate)).AddDays(-1) End Function ```
I know you can calculate the quarter of a date by: ``` Dim quarter As Integer = (someDate.Month - 1) \ 3 + 1 ``` If you're using Visual Studio 2008, you could try bolting additional functionality on to the DateTime class by taking a look at [Extension Methods](http://msdn.microsoft.com/en-us/library/bb384936.aspx).
102,531
<p>Within an XSLT document, is it possible to loop over a set of files in the current directory?</p> <p>I have a situation where I have a directory full of xml files that need some analysis done to generate a report. I have my stylesheet operating on a single document fine, but I'd like to extend that without going to another tool to merge the xml documents. </p> <p>I was thinking along these lines:</p> <pre><code>&lt;xsl:for-each select="{IO Selector Here}"&gt; &lt;xsl:variable select="document(@url)" name="contents" /&gt; &lt;!--More stuff here--&gt; &lt;/xsl:for-each&gt; </code></pre>
[ { "answer_id": 102944, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 0, "selected": false, "text": "<p>I don't think XSL is set up to work that way: it's designed to be used by something else on one or more documents,...
2008/09/19
[ "https://Stackoverflow.com/questions/102531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1672/" ]
Within an XSLT document, is it possible to loop over a set of files in the current directory? I have a situation where I have a directory full of xml files that need some analysis done to generate a report. I have my stylesheet operating on a single document fine, but I'd like to extend that without going to another tool to merge the xml documents. I was thinking along these lines: ``` <xsl:for-each select="{IO Selector Here}"> <xsl:variable select="document(@url)" name="contents" /> <!--More stuff here--> </xsl:for-each> ```
In XSLT 2.0, and with Saxon, you can do this with the `collection()` function: ``` <xsl:for-each select="file:///path/to/directory"> <!-- process the documents --> </xsl:for-each> ``` See [http://www.saxonica.com/documentation/sourcedocs/collections.html](http://www.saxonica.com/documentation/sourcedocs/collections.html "Saxonica: XSLT and XQuery Processing: Collections") for more details. In XSLT 1.0, you have to create an index that lists the documents you want to process with a separate tool. Your environment may provide such a tool; for example, Cocoon has a [Directory Generator](http://cocoon.apache.org/2.1/userdocs/directory-generator.html) that creates such an index. But without knowing what your environment is, it's hard to know what to recommend.
102,534
<p>Here is the situation: I have 2 pages.</p> <p>What I want is to have a number of text links(<code>&lt;a href=""&gt;</code>) on page 1 all directing to page 2, but I want each link to send a different value.</p> <p>On page 2 I want to show that value like this: </p> <blockquote> <p>Hello you clicked {value}</p> </blockquote> <p>Another point to take into account is that I can't use any php in this situation, just html.</p>
[ { "answer_id": 102564, "author": "Haabda", "author_id": 16292, "author_profile": "https://Stackoverflow.com/users/16292", "pm_score": 0, "selected": false, "text": "<p>You might be able to accomplish this using HTML Anchors.</p>\n\n<p><a href=\"http://www.w3schools.com/HTML/html_links.as...
2008/09/19
[ "https://Stackoverflow.com/questions/102534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Here is the situation: I have 2 pages. What I want is to have a number of text links(`<a href="">`) on page 1 all directing to page 2, but I want each link to send a different value. On page 2 I want to show that value like this: > > Hello you clicked {value} > > > Another point to take into account is that I can't use any php in this situation, just html.
Can you use any scripting? Something like Javascript. If you can, then pass the values along in the query string (just add a "?ValueName=Value") to the end of your links. Then on the target page retrieve the query string value. The following site shows how to parse it out: [Parsing the Query String](http://adamv.com/dev/javascript/querystring). Here's the Javascript code you would need: ``` var qs = new Querystring(); var v1 = qs.get("ValueName") ``` From there you should be able to work with the passed value.
102,535
<p>I'm starting to learn Python and I've come across generator functions, those that have a yield statement in them. I want to know what types of problems that these functions are really good at solving.</p>
[ { "answer_id": 102612, "author": "Nickolay", "author_id": 1026, "author_profile": "https://Stackoverflow.com/users/1026", "pm_score": 5, "selected": false, "text": "<p>See the \"Motivation\" section in <a href=\"http://www.python.org/dev/peps/pep-0255/\" rel=\"noreferrer\">PEP 255</a>.</...
2008/09/19
[ "https://Stackoverflow.com/questions/102535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4834/" ]
I'm starting to learn Python and I've come across generator functions, those that have a yield statement in them. I want to know what types of problems that these functions are really good at solving.
Generators give you lazy evaluation. You use them by iterating over them, either explicitly with 'for' or implicitly by passing it to any function or construct that iterates. You can think of generators as returning multiple items, as if they return a list, but instead of returning them all at once they return them one-by-one, and the generator function is paused until the next item is requested. Generators are good for calculating large sets of results (in particular calculations involving loops themselves) where you don't know if you are going to need all results, or where you don't want to allocate the memory for all results at the same time. Or for situations where the generator uses *another* generator, or consumes some other resource, and it's more convenient if that happened as late as possible. Another use for generators (that is really the same) is to replace callbacks with iteration. In some situations you want a function to do a lot of work and occasionally report back to the caller. Traditionally you'd use a callback function for this. You pass this callback to the work-function and it would periodically call this callback. The generator approach is that the work-function (now a generator) knows nothing about the callback, and merely yields whenever it wants to report something. The caller, instead of writing a separate callback and passing that to the work-function, does all the reporting work in a little 'for' loop around the generator. For example, say you wrote a 'filesystem search' program. You could perform the search in its entirety, collect the results and then display them one at a time. All of the results would have to be collected before you showed the first, and all of the results would be in memory at the same time. Or you could display the results while you find them, which would be more memory efficient and much friendlier towards the user. The latter could be done by passing the result-printing function to the filesystem-search function, or it could be done by just making the search function a generator and iterating over the result. If you want to see an example of the latter two approaches, see os.path.walk() (the old filesystem-walking function with callback) and os.walk() (the new filesystem-walking generator.) Of course, if you really wanted to collect all results in a list, the generator approach is trivial to convert to the big-list approach: ``` big_list = list(the_generator) ```
102,547
<p>I am trying to add a new hello world service to amfphp, I am developing locally</p> <pre><code>&lt;?php /** * First tutorial class */ class HelloWorld { /** * first simple method * @returns a string saying 'Hello World!' */ function sayHello() { return "Hello World!"; } } ?&gt; </code></pre> <p>when exploring in the amfphp browser i get a "TypeError: Error #1009: Cannot access a property or method of a null object reference." need help...</p>
[ { "answer_id": 104013, "author": "Antti", "author_id": 6037, "author_profile": "https://Stackoverflow.com/users/6037", "pm_score": 0, "selected": false, "text": "<p>You're trying to access a variable/method that's null. The code here is fine so the problem is somewhere else..</p>\n" },...
2008/09/19
[ "https://Stackoverflow.com/questions/102547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to add a new hello world service to amfphp, I am developing locally ``` <?php /** * First tutorial class */ class HelloWorld { /** * first simple method * @returns a string saying 'Hello World!' */ function sayHello() { return "Hello World!"; } } ?> ``` when exploring in the amfphp browser i get a "TypeError: Error #1009: Cannot access a property or method of a null object reference." need help...
I recommend [Charles](http://www.charlesproxy.com/) for solving this type of problem, this let's you see what's going across the wire. In your case it's likely something simple as a syntax error in the php file. PHP will output the error information into what the Service Browser expects to be amf-encoded data, wreaking havoc to any parsing it tries. Using Charles you can easily see this and fix it!
102,567
<p>What's the best way to shut down the computer from a C# program?</p> <p>I've found a few methods that work - I'll post them below - but none of them are very elegant. I'm looking for something that's simpler and natively .net.</p>
[ { "answer_id": 102580, "author": "RichS", "author_id": 6247, "author_profile": "https://Stackoverflow.com/users/6247", "pm_score": 3, "selected": false, "text": "<p>You can launch the shutdown process:</p>\n\n<ul>\n<li><code>shutdown -s -t 0</code> - Shutdown</li>\n<li><code>shutdown -...
2008/09/19
[ "https://Stackoverflow.com/questions/102567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3464/" ]
What's the best way to shut down the computer from a C# program? I've found a few methods that work - I'll post them below - but none of them are very elegant. I'm looking for something that's simpler and natively .net.
Taken from: [a Geekpedia post](http://www.geekpedia.com/code36_Shut-down-system-using-Csharp.html) This method uses [WMI](http://en.wikipedia.org/wiki/Windows_Management_Instrumentation) to shutdown windows. You'll need to add a reference to System.Management to your project to use this. ``` using System.Management; void Shutdown() { ManagementBaseObject mboShutdown = null; ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem"); mcWin32.Get(); // You can't shutdown without security privileges mcWin32.Scope.Options.EnablePrivileges = true; ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown"); // Flag 1 means we want to shut down the system. Use "2" to reboot. mboShutdownParams["Flags"] = "1"; mboShutdownParams["Reserved"] = "0"; foreach (ManagementObject manObj in mcWin32.GetInstances()) { mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null); } } ```
102,568
<p>I'm trying to understand someone else's Perl code without knowing much Perl myself. I would appreciate your help.</p> <p>I've encountered a Perl function along these lines:</p> <pre><code>MyFunction($arg1,$arg2__size,$arg3) </code></pre> <p>Is there a meaning to the double-underscore syntax in <code>$arg2</code>, or is it just part of the name of the second argument?</p>
[ { "answer_id": 102582, "author": "Haabda", "author_id": 16292, "author_profile": "https://Stackoverflow.com/users/16292", "pm_score": 1, "selected": false, "text": "<p>I'm fairly certain arg2__size is just the name of a variable.</p>\n" }, { "answer_id": 102636, "author": "Ma...
2008/09/19
[ "https://Stackoverflow.com/questions/102568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10261/" ]
I'm trying to understand someone else's Perl code without knowing much Perl myself. I would appreciate your help. I've encountered a Perl function along these lines: ``` MyFunction($arg1,$arg2__size,$arg3) ``` Is there a meaning to the double-underscore syntax in `$arg2`, or is it just part of the name of the second argument?
There is no specific meaning to the use of a \_\_ inside of a perl variable name. It's likely programmer preference, especially in the case that you've cited in your question. You can see more information about perl variable naming [here](http://perldoc.perl.org/perlvar.html#Technical-Note-on-the-Syntax-of-Variable-Names).
102,591
<p>In my database (SQL 2005) I have a field which holds a comment but in the comment I have an id and I would like to strip out just the id, and IF possible convert it to an int:</p> <p><code>activation successful of id 1010101</code></p> <p>The line above is the exact structure of the data in the db field.</p> <p>And no I don't want to do this in the code of the application, I actually don't want to touch it, just in case you were wondering ;-)</p>
[ { "answer_id": 102687, "author": "Cervo", "author_id": 16219, "author_profile": "https://Stackoverflow.com/users/16219", "pm_score": 0, "selected": false, "text": "<pre><code>-- Test table, you will probably use some query \nDECLARE @testTable TABLE(comment VARCHAR(255)) \nINSERT INTO ...
2008/09/19
[ "https://Stackoverflow.com/questions/102591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1841427/" ]
In my database (SQL 2005) I have a field which holds a comment but in the comment I have an id and I would like to strip out just the id, and IF possible convert it to an int: `activation successful of id 1010101` The line above is the exact structure of the data in the db field. And no I don't want to do this in the code of the application, I actually don't want to touch it, just in case you were wondering ;-)
This should do the trick: ``` SELECT SUBSTRING(column, PATINDEX('%[0-9]%', column), 999) FROM table ``` Based on your sample data, this that there is only one occurence of an integer in the string and that it is at the end.
102,606
<p>Below is part of the XML which I am processing with <a href="http://php.net/XSLTProcessor" rel="nofollow noreferrer">PHP's XSLTProcessor</a>:</p> <pre><code>&lt;result&gt; &lt;uf x="20" y="0"/&gt; &lt;uf x="22" y="22"/&gt; &lt;uf x="4" y="3"/&gt; &lt;uf x="15" y="15"/&gt; &lt;/result&gt; </code></pre> <p>I need to know how many "uf" nodes exist where x == y.</p> <p>In the above example, that would be 2.</p> <p>I've tried looping and incrementing a counter variable, but I can't redefine variables.</p> <p>I've tried lots of combinations of xsl:number, with count/from, but couldn't get the XPath expression right.</p> <p>Thanks!</p>
[ { "answer_id": 102707, "author": "Oliver Mellet", "author_id": 12001, "author_profile": "https://Stackoverflow.com/users/12001", "pm_score": 1, "selected": false, "text": "<pre><code>count('/result/uf[@x = @y]')\n</code></pre>\n" }, { "answer_id": 102708, "author": "Mike Tunn...
2008/09/19
[ "https://Stackoverflow.com/questions/102606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14645/" ]
Below is part of the XML which I am processing with [PHP's XSLTProcessor](http://php.net/XSLTProcessor): ``` <result> <uf x="20" y="0"/> <uf x="22" y="22"/> <uf x="4" y="3"/> <uf x="15" y="15"/> </result> ``` I need to know how many "uf" nodes exist where x == y. In the above example, that would be 2. I've tried looping and incrementing a counter variable, but I can't redefine variables. I've tried lots of combinations of xsl:number, with count/from, but couldn't get the XPath expression right. Thanks!
``` <xsl:value-of select="count(/result/uf[@y=@x])" /> ```
102,614
<p>I am looking for a way to have some control over the shape of a simple MessageBox in Winforms. I would like to control where the passed in text wraps so that the dialog rect is narrower. Windows seems to want to make the dialog as wide as possible before wrapping the text. Is there an easy way to control the maximum width of the dialog without resorting to creating my own custom form?</p>
[ { "answer_id": 102622, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 3, "selected": true, "text": "<p>You can embed newlines in the text to force it to wrap at a certain point. e.g.</p>\n\n<pre><code>\"message text...\\nmo...
2008/09/19
[ "https://Stackoverflow.com/questions/102614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12281/" ]
I am looking for a way to have some control over the shape of a simple MessageBox in Winforms. I would like to control where the passed in text wraps so that the dialog rect is narrower. Windows seems to want to make the dialog as wide as possible before wrapping the text. Is there an easy way to control the maximum width of the dialog without resorting to creating my own custom form?
You can embed newlines in the text to force it to wrap at a certain point. e.g. ``` "message text...\nmore text..." ``` update: I posted that thinking it was a win32 API question, but I think the principle should still apply. I assume WinForms eventually calls MessageBox().
102,626
<p>I get this error when I do a <strong>bulk insert</strong> with <code>select * from [table_name]</code>, and another table name:</p> <pre><code>the locale id '0' of the source column 'PAT_NUM_ADT' and the locale id '1033' of the destination column 'PAT_ID_OLD' do not match </code></pre> <p>I tried resetting my db collation but this did not help. </p> <p>Has anyone seen this error?</p>
[ { "answer_id": 102675, "author": "hova", "author_id": 2170, "author_profile": "https://Stackoverflow.com/users/2170", "pm_score": 0, "selected": false, "text": "<p>I would check what your default locale settings are. Also, you'll need to check the locale of both tables using sp_help to...
2008/09/19
[ "https://Stackoverflow.com/questions/102626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I get this error when I do a **bulk insert** with `select * from [table_name]`, and another table name: ``` the locale id '0' of the source column 'PAT_NUM_ADT' and the locale id '1033' of the destination column 'PAT_ID_OLD' do not match ``` I tried resetting my db collation but this did not help. Has anyone seen this error?
If you are copying less than a full set of fields from one table to another, whether that table is on another domain across the world, or is collocated in the same database, you just have to select them in order. SqlBulkCopyColumnMappings do not work. Yes, I tried. I used all four possible constructors, and I used them both as SqlBulkCopyMapping objects and just by providing the same information to the Add method of SqlBulkCopy.ColumnMappings.Add. My columns are named the same. If you're using a different name as well as a different order, you may well find that you have to actually rename the columns. Good luck.