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
85,459
<p>I have a series of PDFs named sequentially like so:</p> <ul> <li>01_foo.pdf</li> <li>02_bar.pdf</li> <li>03_baz.pdf</li> <li>etc.</li> </ul> <p>Using Ruby, is it possible to combine these into one big PDF while keeping them in sequence? I don't mind installing any necessary gems to do the job.</p> <p>If this isn't possible in Ruby, how about another language? No commercial components, if possible.</p> <hr> <p><strong>Update:</strong> <a href="https://stackoverflow.com/questions/85459/is-it-possible-to-combine-a-series-of-pdfs-into-one-using-ruby#85618">Jason Navarrete's suggestion</a> lead to the perfect solution:</p> <p>Place the PDF files needing to be combined in a directory along with <a href="http://www.accesspdf.com/pdftk/" rel="nofollow noreferrer">pdftk</a> (or make sure pdftk is in your PATH), then run the following script:</p> <pre><code>pdfs = Dir["[0-9][0-9]_*"].sort.join(" ") `pdftk #{pdfs} output combined.pdf` </code></pre> <p>Or I could even do it as a one-liner from the command-line:</p> <pre><code>ruby -e '`pdftk #{Dir["[0-9][0-9]_*"].sort.join(" ")} output combined.pdf`' </code></pre> <p>Great suggestion Jason, perfect solution, thanks. <strong>Give him an up-vote people</strong>.</p>
[ { "answer_id": 85493, "author": "akauppi", "author_id": 14455, "author_profile": "https://Stackoverflow.com/users/14455", "pm_score": 0, "selected": false, "text": "<p>I don't think Ruby has tools for that. You might check ImageMagick and Cairo. ImageMagick can be used for binding mult...
2008/09/17
[ "https://Stackoverflow.com/questions/85459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1944/" ]
I have a series of PDFs named sequentially like so: * 01\_foo.pdf * 02\_bar.pdf * 03\_baz.pdf * etc. Using Ruby, is it possible to combine these into one big PDF while keeping them in sequence? I don't mind installing any necessary gems to do the job. If this isn't possible in Ruby, how about another language? No commercial components, if possible. --- **Update:** [Jason Navarrete's suggestion](https://stackoverflow.com/questions/85459/is-it-possible-to-combine-a-series-of-pdfs-into-one-using-ruby#85618) lead to the perfect solution: Place the PDF files needing to be combined in a directory along with [pdftk](http://www.accesspdf.com/pdftk/) (or make sure pdftk is in your PATH), then run the following script: ``` pdfs = Dir["[0-9][0-9]_*"].sort.join(" ") `pdftk #{pdfs} output combined.pdf` ``` Or I could even do it as a one-liner from the command-line: ``` ruby -e '`pdftk #{Dir["[0-9][0-9]_*"].sort.join(" ")} output combined.pdf`' ``` Great suggestion Jason, perfect solution, thanks. **Give him an up-vote people**.
A [Ruby-Talk](http://www.ruby-forum.com/topic/120008#new) post suggests using the **[pdftk](http://www.accesspdf.com/pdftk/)** toolkit to merge the PDFs. It should be relatively straightforward to call *pdftk* as an external process and have it handle the merging. *PDF::Writer* may be overkill because all you're looking to accomplish is a simple append.
85,479
<p>Can someone give an example of a good time to actually use "unsafe" and "fixed" in C# code? I've played with it before, but never actually found a good use for it. </p> <p>Consider this code...</p> <pre><code>fixed (byte* pSrc = src, pDst = dst) { //Code that copies the bytes in a loop } </code></pre> <p>compared to simply using...</p> <pre><code>Array.Copy(source, target, source.Length); </code></pre> <p>The second is the code found in the .NET Framework, the first a part of the code copied from the Microsoft website, <a href="http://msdn.microsoft.com/en-us/library/28k1s2k6(VS.80).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/28k1s2k6(VS.80).aspx</a>.</p> <p>The built in Array.Copy() is dramatically faster than using Unsafe code. This might just because the second is just better written and the first is just an example, but what kinds of situations would you really even need to use Unsafe/Fixed code for anything? Or is this poor web developer messing with something above his head?</p>
[ { "answer_id": 85527, "author": "Matt Wilkinson", "author_id": 12832, "author_profile": "https://Stackoverflow.com/users/12832", "pm_score": 1, "selected": false, "text": "<p>I believe unsafe code is used if you want to access something outside of the .NET runtime, ie. it is not managed ...
2008/09/17
[ "https://Stackoverflow.com/questions/85479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Can someone give an example of a good time to actually use "unsafe" and "fixed" in C# code? I've played with it before, but never actually found a good use for it. Consider this code... ``` fixed (byte* pSrc = src, pDst = dst) { //Code that copies the bytes in a loop } ``` compared to simply using... ``` Array.Copy(source, target, source.Length); ``` The second is the code found in the .NET Framework, the first a part of the code copied from the Microsoft website, <http://msdn.microsoft.com/en-us/library/28k1s2k6(VS.80).aspx>. The built in Array.Copy() is dramatically faster than using Unsafe code. This might just because the second is just better written and the first is just an example, but what kinds of situations would you really even need to use Unsafe/Fixed code for anything? Or is this poor web developer messing with something above his head?
It's useful for interop with unmanaged code. Any pointers passed to unmanaged functions need to be fixed (aka. pinned) to prevent the garbage collector from relocating the underlying memory. If you are using P/Invoke, then the default marshaller will pin objects for you. Sometimes it's necessary to perform custom marshalling, and sometimes it's necessary to pin an object for longer than the duration of a single P/Invoke call.
85,481
<p>Say I've got this table (SQL Server 2005):</p> <pre><code>Id =&gt; integer MyField =&gt; XML </code></pre> <p><b>Id MyField</b> </p> <pre><code>1 &lt; Object&gt;&lt; Type&gt;AAA&lt; /Type&gt;&lt; Value&gt;10&lt; /Value&gt;&lt; /Object&gt;&lt; Object&gt;&lt; Type&gt;BBB&lt; /Type&gt;&lt;Value&gt;20&lt; /Value&gt;&lt; /Object&gt; 2 &lt; Object&gt;&lt; Type&gt;AAA&lt; /Type&gt;&lt; Value&gt;15&lt; /Value&gt;&lt; /Object&gt; 3 &lt; Object&gt;&lt; Type&gt;AAA&lt; /Type&gt;&lt; Value&gt;20&lt; /Value&gt;&lt; /Object&gt;&lt; Object&gt;&lt; Type&gt;BBB&lt; /Type&gt;&lt; Value&gt;30&lt; /Value&gt;&lt; /Object&gt; </code></pre> <p>I need a TSQL query which would return something like this:</p> <pre><code>Id AAA BBB 1 10 20 2 15 NULL 3 20 30 </code></pre> <p>Note that I won't know if advance how many <code>'Type'</code> (eg AAA, BBB, CCC,DDD, etc.) there will be in the xml string.</p>
[ { "answer_id": 85535, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 1, "selected": false, "text": "<p>You will need to use the <a href=\"http://msdn.microsoft.com/en-us/library/ms345122.aspx#sql2k5_xqueryintro_topic8\" rel=\...
2008/09/17
[ "https://Stackoverflow.com/questions/85481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15928/" ]
Say I've got this table (SQL Server 2005): ``` Id => integer MyField => XML ``` **Id MyField** ``` 1 < Object>< Type>AAA< /Type>< Value>10< /Value>< /Object>< Object>< Type>BBB< /Type><Value>20< /Value>< /Object> 2 < Object>< Type>AAA< /Type>< Value>15< /Value>< /Object> 3 < Object>< Type>AAA< /Type>< Value>20< /Value>< /Object>< Object>< Type>BBB< /Type>< Value>30< /Value>< /Object> ``` I need a TSQL query which would return something like this: ``` Id AAA BBB 1 10 20 2 15 NULL 3 20 30 ``` Note that I won't know if advance how many `'Type'` (eg AAA, BBB, CCC,DDD, etc.) there will be in the xml string.
You will need to use the [XML querying in sql server](http://msdn.microsoft.com/en-us/library/ms345122.aspx#sql2k5_xqueryintro_topic8) to do that. somethings like ``` select id, MyField.query('/Object/Type[.="AAA"]/Value') as AAA, MyField.query('/Object/Type[.="BBB"]/Value) AS BBB ``` not sure if that's 100% correct xquery syntax, but it's going to be something like that.
85,500
<p>First time working with UpdatePanels in .NET. </p> <p>I have an updatepanel with a trigger pointed to an event on a FormView control. The UpdatePanel holds a ListView with related data from a separate database.</p> <p>When the UpdatePanel refreshes, it needs values from the FormView control so that on the server it can use them to query the database.</p> <p>For the life if me, I can't figure out how to get those values. The event I'm triggering from has them, but I want the updatepanel to refresh asynchronously. How do I pass values to the load event on the panel?</p> <p>Googled this ad nauseum and can't seem to get to an answer here. A link or an explanation would be immensely helpful..</p> <p>Jeff</p>
[ { "answer_id": 85554, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 1, "selected": false, "text": "<p>Try </p>\n\n<ul>\n<li>...looking in the Request and\nResponse. </li>\n<li>...setting a breakpoint\non the Load() meth...
2008/09/17
[ "https://Stackoverflow.com/questions/85500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16426/" ]
First time working with UpdatePanels in .NET. I have an updatepanel with a trigger pointed to an event on a FormView control. The UpdatePanel holds a ListView with related data from a separate database. When the UpdatePanel refreshes, it needs values from the FormView control so that on the server it can use them to query the database. For the life if me, I can't figure out how to get those values. The event I'm triggering from has them, but I want the updatepanel to refresh asynchronously. How do I pass values to the load event on the panel? Googled this ad nauseum and can't seem to get to an answer here. A link or an explanation would be immensely helpful.. Jeff
make a javascript function that will collect the pieces of form data, and then sends that data to an ASHX handler. the ASHX handler will do some work, and can reply with a response. This is an example I made that calls a database to populate a grid using AJAX calls. There are better libraries for doing AJAX (prototype, ExtJS, etc), but this is the raw deal. (I ***know*** this can be refactored to be even cleaner, but you can get the idea well enough) Works like this... * User enters text in the search box, * User clicks search button, * JavaScript gets form data, * javascript makes ajax call to ASHX, * ASHX receives request, * ASHX queries database, * ASHX parses the response into JSON/Javascript array, * ASHX sends response, * Javascript receives response, * javascript Eval()'s response to object, * javascript iterates object properties and fills grid The html will look like this... ``` <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <script type="text/javascript" src="AjaxHelper.js"></script> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="txtSearchValue" runat="server"></asp:TextBox> <input id="btnSearch" type="button" value="Search by partial full name" onclick="doSearch()"/> <igtbl:ultrawebgrid id="uwgUsers" runat="server" //infragistics grid crap </igtbl:ultrawebgrid>--%> </div> </form> </body> </html> ``` The script that fires on click will look like this... ``` //this is tied to the button click. It takes care of input cleanup and calling the AJAX method function doSearch(){ var eleVal; var eleBtn; eleVal = document.getElementById('txtSearchValue').value; eleBtn = document.getElementById('btnSearch'); eleVal = trim(eleVal); if (eleVal.length > 0) { eleBtn.value = 'Searching...'; eleBtn.disabled = true; refreshGridData(eleVal); } else { alert("Please enter a value to search with. Unabated searches are not permitted."); } } //This is the function that will go out and get the data and call load the Grid on AJAX call //return. function refreshGridData(searchString){ if (searchString =='undefined'){ searchString = ""; } var xhr; var gridData; var url; url = "DefaultHandler.ashx?partialUserFullName=" + escape(searchString); xhr = GetXMLHttpRequestObject(); xhr.onreadystatechange = function() { if (xhr.readystate==4) { gridData = eval(xhr.responseText); if (gridData.length > 0) { //clear and fill the grid clearAndPopulateGrid(gridData); } else { //display appropriate message } } //if (xhr.readystate==4) { } //xhr.onreadystatechange = function() { xhr.open("GET", url, true); xhr.send(null); } //this does the grid clearing and population, and enables the search button when complete. function clearAndPopulateGrid(jsonObject) { var grid = igtbl_getGridById('uwgUsers'); var eleBtn; eleBtn = document.getElementById('btnSearch'); //clear the rows for (x = grid.Rows.length; x >= 0; x--) { grid.Rows.remove(x, false); } //add the new ones for (x = 0; x < jsonObject.length; x++) { var newRow = igtbl_addNew(grid.Id, 0, false, false); //the cells should not be referenced by index value, so a name lookup should be implemented newRow.getCell(0).setValue(jsonObject[x][1]); newRow.getCell(1).setValue(jsonObject[x][2]); newRow.getCell(2).setValue(jsonObject[x][3]); } grid = null; eleBtn.disabled = false; eleBtn.value = "Search by partial full name"; } // this function will return the XMLHttpRequest Object for the current browser function GetXMLHttpRequestObject() { var XHR; //the object to return var ua = navigator.userAgent.toLowerCase(); //gets the useragent text try { //determine the browser type if (!window.ActiveXObject) { //Non IE Browsers XHR = new XMLHttpRequest(); } else { if (ua.indexOf('msie 5') == -1) { //IE 5.x XHR = new ActiveXObject("Msxml2.XMLHTTP"); } else { //IE 6.x and up XHR = new ActiveXObject("Microsoft.XMLHTTP"); } } //end if (!window.ActiveXObject) if (XHR == null) { throw "Unable to instantiate the XMLHTTPRequest object."; } } catch (e) { alert("This browser does not appear to support AJAX functionality. error: " + e.name + " description: " + e.message); } return XHR; } //end function GetXMLHttpRequestObject() function trim(stringToTrim){ return stringToTrim.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); } ``` And the ashx handler looks like this.... ``` Imports System.Web Imports System.Web.Services Imports System.Data Imports System.Data.SqlClient Public Class DefaultHandler Implements System.Web.IHttpHandler Private Const CONN_STRING As String = "Data Source=;Initial Catalog=;User ID=;Password=;" Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest context.Response.ContentType = "text/plain" context.Response.Expires = -1 Dim strPartialUserName As String Dim strReturnValue As String = String.Empty If context.Request.QueryString("partialUserFullName") Is Nothing = False Then strPartialUserName = context.Request.QueryString("partialUserFullName").ToString() If String.IsNullOrEmpty(strPartialUserName) = False Then strReturnValue = SearchAndReturnJSResult(strPartialUserName) End If End If context.Response.Write(strReturnValue) End Sub Private Function SearchAndReturnJSResult(ByVal partialUserName As String) As String Dim strReturnValue As New StringBuilder() Dim conn As SqlConnection Dim strSQL As New StringBuilder() Dim objParam As SqlParameter Dim da As SqlDataAdapter Dim ds As New DataSet() Dim dr As DataRow 'define sql strSQL.Append(" SELECT ") strSQL.Append(" [id] ") strSQL.Append(" ,([first_name] + ' ' + [last_name]) ") strSQL.Append(" ,[email] ") strSQL.Append(" FROM [person] (NOLOCK) ") strSQL.Append(" WHERE [last_name] LIKE @lastName") 'clean up the partial user name for use in a like search If partialUserName.EndsWith("%", StringComparison.InvariantCultureIgnoreCase) = False Then partialUserName = partialUserName & "%" End If If partialUserName.StartsWith("%", StringComparison.InvariantCultureIgnoreCase) = False Then partialUserName = partialUserName.Insert(0, "%") End If 'create the oledb parameter... parameterized queries perform far better on repeatable 'operations objParam = New SqlParameter("@lastName", SqlDbType.VarChar, 100) objParam.Value = partialUserName conn = New SqlConnection(CONN_STRING) da = New SqlDataAdapter(strSQL.ToString(), conn) da.SelectCommand.Parameters.Add(objParam) Try 'to get a dataset. da.Fill(ds) Catch sqlex As SqlException 'Throw an appropriate exception if you can add details that will help understand the problem. Throw New DataException("Unable to retrieve the results from the user search.", sqlex) Finally If conn.State = ConnectionState.Open Then conn.Close() End If conn.Dispose() da.Dispose() End Try 'make sure we have a return value If ds Is Nothing OrElse ds.Tables(0) Is Nothing OrElse ds.Tables(0).Rows.Count <= 0 Then Return String.Empty End If 'This converts the table into JS array. strReturnValue.Append("[") For Each dr In ds.Tables(0).Rows strReturnValue.Append("['" & CStr(dr("username")) & "','" & CStr(dr("userfullname")) & "','" & CStr(dr("useremail")) & "'],") Next strReturnValue.Remove(strReturnValue.Length - 1, 1) strReturnValue.Append("]") 'de-allocate what can be deallocated. Setting to Nothing for smaller types may 'incur performance hit because of a forced allocation to nothing before they are deallocated 'by garbage collection. ds.Dispose() strSQL.Length = 0 Return strReturnValue.ToString() End Function ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable Get Return False End Get End Property End Class ```
85,532
<p>Ok, I've run across my first StackOverflowError since joining this site, I figured this is a must post :-). My environment is Seam 2.0.1.GA, JBoss 4.2.2.GA and I'm using JSF. I am in the process of converting from a facelets view to JSP to take advantage of some existing JSP tags used on our existing site. I changed the faces-config.xml and the web.xml configuration files and started to receive the following error when trying to render a jsp page. Anyone have any thoughts?</p> <blockquote> <p>2008-09-17 09:45:17,537 DEBUG [org.jboss.seam.contexts.FacesLifecycle] Begin JSF request for /form_home.jsp 2008-09-17 09:45:17,587 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[localhost].[/].[Faces Servlet]] Servlet.service() for servlet Faces Servlet threw exception java.lang.StackOverflowError at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:210) at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:222) at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:222) at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:222) ...</p> </blockquote> <p>My faces-config.xml file is now empty with no FaceletsViewHandler:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"&gt; &lt;/faces-config&gt; </code></pre> <p>And my Web.xml file:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"&gt; &lt;!-- Ajax4jsf --&gt; &lt;context-param&gt; &lt;param-name&gt;org.richfaces.SKIN&lt;/param-name&gt; &lt;param-value&gt;blueSky&lt;/param-value&gt; &lt;/context-param&gt; &lt;!-- Seam --&gt; &lt;listener&gt; &lt;listener-class&gt;org.jboss.seam.servlet.SeamListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;filter&gt; &lt;filter-name&gt;Seam Filter&lt;/filter-name&gt; &lt;filter-class&gt;org.jboss.seam.servlet.SeamFilter&lt;/filter-class&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;Seam Filter&lt;/filter-name&gt; &lt;url-pattern&gt;*.jsp&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;servlet&gt; &lt;servlet-name&gt;Seam Resource Servlet&lt;/servlet-name&gt; &lt;servlet-class&gt;org.jboss.seam.servlet.SeamResourceServlet &lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;Seam Resource Servlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/seam/resource/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;!-- Seam end --&gt; &lt;!-- JSF --&gt; &lt;context-param&gt; &lt;param-name&gt;javax.faces.DEFAULT_SUFFIX&lt;/param-name&gt; &lt;param-value&gt;.jsp&lt;/param-value&gt; &lt;/context-param&gt; &lt;servlet&gt; &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt; &lt;servlet-class&gt;javax.faces.webapp.FacesServlet&lt;/servlet-class&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt; &lt;url-pattern&gt;*.jsp&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; </code></pre>
[ { "answer_id": 90220, "author": "Peter", "author_id": 17123, "author_profile": "https://Stackoverflow.com/users/17123", "pm_score": 2, "selected": false, "text": "<p>Stack overflows in java are almost always caused by infinite recursion / method calls. In your case given the stack trace...
2008/09/17
[ "https://Stackoverflow.com/questions/85532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5917/" ]
Ok, I've run across my first StackOverflowError since joining this site, I figured this is a must post :-). My environment is Seam 2.0.1.GA, JBoss 4.2.2.GA and I'm using JSF. I am in the process of converting from a facelets view to JSP to take advantage of some existing JSP tags used on our existing site. I changed the faces-config.xml and the web.xml configuration files and started to receive the following error when trying to render a jsp page. Anyone have any thoughts? > > 2008-09-17 09:45:17,537 DEBUG > [org.jboss.seam.contexts.FacesLifecycle] > Begin JSF request for /form\_home.jsp > 2008-09-17 09:45:17,587 ERROR > [org.apache.catalina.core.ContainerBase.[jboss.web].[localhost].[/].[Faces > Servlet]] Servlet.service() for > servlet Faces Servlet threw exception > java.lang.StackOverflowError > at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:210) > at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:222) > at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:222) > at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:222) > ... > > > My faces-config.xml file is now empty with no FaceletsViewHandler: ``` <?xml version="1.0" encoding="UTF-8"?> <faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"> </faces-config> ``` And my Web.xml file: ``` <?xml version="1.0"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- Ajax4jsf --> <context-param> <param-name>org.richfaces.SKIN</param-name> <param-value>blueSky</param-value> </context-param> <!-- Seam --> <listener> <listener-class>org.jboss.seam.servlet.SeamListener</listener-class> </listener> <filter> <filter-name>Seam Filter</filter-name> <filter-class>org.jboss.seam.servlet.SeamFilter</filter-class> </filter> <filter-mapping> <filter-name>Seam Filter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> <servlet> <servlet-name>Seam Resource Servlet</servlet-name> <servlet-class>org.jboss.seam.servlet.SeamResourceServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>Seam Resource Servlet</servlet-name> <url-pattern>/seam/resource/*</url-pattern> </servlet-mapping> <!-- Seam end --> <!-- JSF --> <context-param> <param-name>javax.faces.DEFAULT_SUFFIX</param-name> <param-value>.jsp</param-value> </context-param> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsp</url-pattern> </servlet-mapping> ```
I was able to figure out this problem. Apparently you can not configure web.xml to have the same param-value of .jsp for Javax.faces.DEFAULT\_SUFFIX as the Faces Servlet url-pattern (\*.jsp). If you change your url-pattern to *.jspx or to /whateverdirnameyouwant/* the application starts up with no stack overflow errors. (note: the key is that DEFAULT\_SUFFIX and Faces Servlet url-pattern cannot be the same regardless of what they are.) Hope this helps anyone else that experiences this specific problem.
85,559
<p>I have a problem in my project with the .designer which as everyone know is autogenerated and I ahvent changed at all. One day I was working fine, I did a back up and next day boom! the project suddenly stops working and sends a message that the designer cant procees a code line... and due to this I get more errores (2 in my case), I even had a back up from the day it was working and is useless too, I get the same error, I tryed in my laptop and the same problem comes. How can I delete the &quot;FitTrack&quot;? The incredible part is that while I was trying on the laptop the errors on the desktop were gone in front of my eyes, one and one second later the other one (but still have the warning from the designer and cant see the form), I closed and open it again and again I have the errors...</p> <p>The error is:</p> <pre><code>Warning 1 The designer cannot process the code at line 27: Me.CrystalReportViewer1.ReportSource = Me.CrystalReport11 The code within the method 'InitializeComponent' is generated by the designer and should not be manually modified. Please remove any changes and try opening the designer again. C:\Documents and Settings\Alan Cardero\Desktop\Reportes Liquidacion\Reportes Liquidacion\Reportes Liquidacion\Form1.Designer.vb 28 0 </code></pre>
[ { "answer_id": 85602, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 1, "selected": false, "text": "<p>I would take out the static assignment in the designer to the resource CrystalReport11 and then add a load hand...
2008/09/17
[ "https://Stackoverflow.com/questions/85559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a problem in my project with the .designer which as everyone know is autogenerated and I ahvent changed at all. One day I was working fine, I did a back up and next day boom! the project suddenly stops working and sends a message that the designer cant procees a code line... and due to this I get more errores (2 in my case), I even had a back up from the day it was working and is useless too, I get the same error, I tryed in my laptop and the same problem comes. How can I delete the "FitTrack"? The incredible part is that while I was trying on the laptop the errors on the desktop were gone in front of my eyes, one and one second later the other one (but still have the warning from the designer and cant see the form), I closed and open it again and again I have the errors... The error is: ``` Warning 1 The designer cannot process the code at line 27: Me.CrystalReportViewer1.ReportSource = Me.CrystalReport11 The code within the method 'InitializeComponent' is generated by the designer and should not be manually modified. Please remove any changes and try opening the designer again. C:\Documents and Settings\Alan Cardero\Desktop\Reportes Liquidacion\Reportes Liquidacion\Reportes Liquidacion\Form1.Designer.vb 28 0 ```
I would back up the designer.cs file associated with it (like copy it to the desktop), then edit the designer.cs file and remove the offending lines (keeping track of what they do) and then I'd try to redo those lines via the design mode of that form.
85,588
<p>I have a line of C# in my ASP.NET code behind that looks like this:</p> <pre><code>DropDownList ddlStates = (DropDownList)fvAccountSummary.FindControl("ddlStates"); </code></pre> <p>The DropDownList control is explicitly declared in the markup on the page, not dynamically created. It is inside of a FormView control. When my code hits this line, I am getting an ArithmeticException with the message "Value was either too large or too small for an Int32." This code has worked previously, and is in production right now. I fired up VS2008 to make some changes to the site, but before I changed anything, I got this exception from the page. Anyone seen this one before?</p>
[ { "answer_id": 85727, "author": "Adam Weber", "author_id": 9324, "author_profile": "https://Stackoverflow.com/users/9324", "pm_score": 0, "selected": false, "text": "<p>Are you 100% sure that's the line of code that's throwing the exception? I'm pretty certain that the FindControl method...
2008/09/17
[ "https://Stackoverflow.com/questions/85588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1284/" ]
I have a line of C# in my ASP.NET code behind that looks like this: ``` DropDownList ddlStates = (DropDownList)fvAccountSummary.FindControl("ddlStates"); ``` The DropDownList control is explicitly declared in the markup on the page, not dynamically created. It is inside of a FormView control. When my code hits this line, I am getting an ArithmeticException with the message "Value was either too large or too small for an Int32." This code has worked previously, and is in production right now. I fired up VS2008 to make some changes to the site, but before I changed anything, I got this exception from the page. Anyone seen this one before?
If that's the stacktrace, its comingn from databinding, not from the line you posted. Is it possible that you have some really large data set? I've seen a 6000-page GridView overflow an Int16, although it seems pretty unlikely you'd actually overflow an Int32... Check to make sure you're passing in sane data into, say, the startpageIndex or pageSize of your datasource, for example.
85,622
<p>Most precompiled Windows binaries are made with the MSYS+gcc toolchain. It uses MSVCRT runtime, which is incompatible with Visual C++ 2005/2008.</p> <p>So, how to go about and compile Cairo 1.6.4 (or later) for Visual C++ only. Including dependencies (png,zlib,pixman).</p>
[ { "answer_id": 91312, "author": "Roel", "author_id": 11449, "author_profile": "https://Stackoverflow.com/users/11449", "pm_score": 1, "selected": false, "text": "<p>Did you check here: <a href=\"http://cairographics.org/visualstudio/\" rel=\"nofollow noreferrer\">http://cairographics.org...
2008/09/17
[ "https://Stackoverflow.com/questions/85622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14455/" ]
Most precompiled Windows binaries are made with the MSYS+gcc toolchain. It uses MSVCRT runtime, which is incompatible with Visual C++ 2005/2008. So, how to go about and compile Cairo 1.6.4 (or later) for Visual C++ only. Including dependencies (png,zlib,pixman).
Here are instructions for building Cairo/Cairomm with Visual C++. Required: * Visual C++ 2008 Express SP1 (now includes SDK) * MSYS 1.0 To use VC++ command line tools, a batch file 'vcvars32.bat' needs to be run. ``` C:\Program Files\Microsoft Visual Studio 9.0\Common7\Tools\vcvars32.bat ``` ZLib ---- Download (and extract) zlib123.zip from <http://www.zlib.net/> ``` cd zlib123 nmake /f win32/Makefile.msc dir # zlib.lib is the static library # # zdll.lib is the import library for zlib1.dll # zlib1.dll is the shared library ``` libpng ------ Download (and extract) lpng1231.zip from <http://www.libpng.org/pub/png/libpng.html> The VC++ 9.0 compiler gives loads of "this might be unsafe" warnings. Ignore them; this is MS security panic (the code is good). ``` cd lpng1231\lpng1231 # for some reason this is two stories deep nmake /f ../../lpng1231.nmake ZLIB_PATH=../zlib123 dir # libpng.lib is the static library # # dll is not being created ``` Pixman ------ Pixman is part of Cairo, but a separate download. Download (and extract) pixman-0.12.0.tar.gz from <http://www.cairographics.org/releases/> Use MSYS to untar via 'tar -xvzf pixman\*.tar.gz' Both Pixman and Cairo have Makefiles for Visual C++ command line compiler (cl), but they use Gnu makefile and Unix-like tools (sed etc.). This means we have to run the make from within MSYS. Open a command prompt with VC++ command line tools enabled (try 'cl /?'). Turn that command prompt into an MSYS prompt by 'C:\MSYS\1.0\MSYS.BAT'. DO NOT use the MSYS icon, because then your prompt will now know of VC++. You cannot run .bat files from MSYS. Try that VC++ tools work from here: 'cl -?' Try that Gnu make also works: 'make -v'. Cool. ``` cd (use /d/... instead of D:) cd pixman-0.12.0/pixman make -f Makefile.win32 ``` This defaults to MMX and SSE2 optimizations, which require a newish x86 processor (Pentium 4 or Pentium M or above: <http://fi.wikipedia.org/wiki/SSE2> ) There's quite some warnings but it seems to succeed. ``` ls release # pixman-1.lib (static lib required by Cairo) ``` Stay in the VC++ spiced MSYS prompt for also Cairo to compile. cairo ----- Download (and extract) cairo-1.6.4.tar.gz from <http://www.cairographics.org/releases/> ``` cd cd cairo-1.6.4 ``` The Makefile.win32 here is almost good, but has the Pixman path hardwired. Use the modified 'Makefile-cairo.win32': ``` make -f ../Makefile-cairo.win32 CFG=release \ PIXMAN_PATH=../../pixman-0.12.0 \ LIBPNG_PATH=../../lpng1231 \ ZLIB_PATH=../../zlib123 ``` (Write everything on one line, ignoring the backslashes) It says "no rule to make 'src/cairo-features.h'. Use the manually prepared one (in Cairo > 1.6.4 there may be a 'src/cairo-features-win32.h' that you can simply rename): ``` cp ../cairo-features.h src/ ``` Retry the make command (arrow up remembers it). ``` ls src/release # # cairo-static.lib ``` cairomm (C++ API) ----------------- Download (and extract) cairomm-1.6.4.tar.gz from <http://www.cairographics.org/releases/> There is a Visual C++ 2005 Project that we can use (via open & upgrade) for 2008. ``` cairomm-1.6.4\MSCV_Net2005\cairomm\cairomm.vcproj ``` Changes that need to be done: * Change active configuration to "Release" * Cairomm-1.0 properties (with right click menu) ``` C++/General/Additional Include Directories: ..\..\..\cairo-1.6.4\src (append to existing) Linker/General/Additional library directories: ..\..\..\cairo-1.6.4\src\release ..\..\..\lpng1231\lpng1231 ..\..\..\zlib123 Linker/Input/Additional dependencies: cairo-static.lib libpng.lib zlib.lib msimg32.lib ``` * Optimization: fast FPU code ``` C++/Code generation/Floating point model Fast ``` Right click on 'cairomm-1.0' and 'build'. There are some warnings. ``` dir cairomm-1.6.4\MSVC_Net2005\cairomm\Release # # cairomm-1.0.lib # cairomm-1.0.dll # cairomm.def ```
85,675
<p>I have two tables I would like to complare. One of the columns is type CLOB. I would like to do something like this:</p> <pre><code>select key, clob_value source_table minus select key, clob_value target_table </code></pre> <p>Unfortunately, Oracle can't perform minus operations on clobs. How can I do this?</p>
[ { "answer_id": 85716, "author": "hamishmcn", "author_id": 3590, "author_profile": "https://Stackoverflow.com/users/3590", "pm_score": 2, "selected": false, "text": "<p>Can you access the data via a built in package? If so then perhaps you could write a function that returned a string rep...
2008/09/17
[ "https://Stackoverflow.com/questions/85675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16484/" ]
I have two tables I would like to complare. One of the columns is type CLOB. I would like to do something like this: ``` select key, clob_value source_table minus select key, clob_value target_table ``` Unfortunately, Oracle can't perform minus operations on clobs. How can I do this?
The format is this: ``` dbms_lob.compare( lob_1 IN BLOB, lob_2 IN BLOB, amount IN INTEGER := 18446744073709551615, offset_1 IN INTEGER := 1, offset_2 IN INTEGER := 1) RETURN INTEGER; ``` --- If dbms\_lob.compare(lob1, lob2) = 0, they are identical. Here's an example query based on your example: ``` Select key, glob_value From source_table Left Join target_table On source_table.key = target_table.key Where target_table.glob_value is Null Or dbms_lob.compare(source_table.glob_value, target_table.glob_value) <> 0 ```
85,701
<p>I have a database field that contains a raw date field (stored as character data), such as </p> <blockquote> <p>Friday, September 26, 2008 8:30 PM Eastern Daylight Time</p> </blockquote> <p>I can parse this as a Date easily, with SimpleDateFormat</p> <pre><code>DateFormat dbFormatter = new SimpleDateFormat("EEEE, MMMM dd, yyyy hh:mm aa zzzz"); Date scheduledDate = dbFormatter.parse(rawDate); </code></pre> <p>What I'd like to do is extract a TimeZone object from this string. The default TimeZone in the JVM that this application runs in is GMT, so I can't use <code>.getTimezoneOffset()</code> from the <code>Date</code> parsed above (because it will return the default TimeZone).</p> <p>Besides tokenizing the raw string and finding the start position of the Timezone string (since I know the format will always be <code>EEEE, MMMM dd, yyyy hh:mm aa zzzz</code>) is there a way using the DateFormat/SimpleDateFormat/Date/Calendar API to extract a TimeZone object - which will have the same TimeZone as the String I've parsed apart with <code>DateFormat.parse()</code>?</p> <p>One thing that bugs me about <code>Date</code> vs <code>Calendar</code> in the Java API is that <code>Calendar</code> is supposed to replace <code>Date</code> in all places... but then they decided, oh hey let's still use <code>Date</code>'s in the <code>DateFormat</code> classes.</p>
[ { "answer_id": 85862, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>Well as a partial solution you could use a RegEx match to get the timezone since you will always have the same t...
2008/09/17
[ "https://Stackoverflow.com/questions/85701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ]
I have a database field that contains a raw date field (stored as character data), such as > > Friday, September 26, 2008 8:30 PM Eastern Daylight Time > > > I can parse this as a Date easily, with SimpleDateFormat ``` DateFormat dbFormatter = new SimpleDateFormat("EEEE, MMMM dd, yyyy hh:mm aa zzzz"); Date scheduledDate = dbFormatter.parse(rawDate); ``` What I'd like to do is extract a TimeZone object from this string. The default TimeZone in the JVM that this application runs in is GMT, so I can't use `.getTimezoneOffset()` from the `Date` parsed above (because it will return the default TimeZone). Besides tokenizing the raw string and finding the start position of the Timezone string (since I know the format will always be `EEEE, MMMM dd, yyyy hh:mm aa zzzz`) is there a way using the DateFormat/SimpleDateFormat/Date/Calendar API to extract a TimeZone object - which will have the same TimeZone as the String I've parsed apart with `DateFormat.parse()`? One thing that bugs me about `Date` vs `Calendar` in the Java API is that `Calendar` is supposed to replace `Date` in all places... but then they decided, oh hey let's still use `Date`'s in the `DateFormat` classes.
I found that the following: ``` DateFormat dbFormatter = new SimpleDateFormat("EEEE, MMMM dd, yyyy hh:mm aa zzzz"); dbFormatter.setTimeZone(TimeZone.getTimeZone("America/Chicago")); Date scheduledDate = dbFormatter.parse("Friday, September 26, 2008 8:30 PM Eastern Daylight Time"); System.out.println(scheduledDate); System.out.println(dbFormatter.format(scheduledDate)); TimeZone tz = dbFormatter.getTimeZone(); System.out.println(tz.getDisplayName()); dbFormatter.setTimeZone(TimeZone.getTimeZone("America/Chicago")); System.out.println(dbFormatter.format(scheduledDate)); ``` Produces the following: ``` Fri Sep 26 20:30:00 CDT 2008 Friday, September 26, 2008 08:30 PM Eastern Standard Time Eastern Standard Time Friday, September 26, 2008 08:30 PM Central Daylight Time ``` I actually found this to be somewhat surprising. But, I guess that shows that the answer to your question is to simply call getTimeZone on the formatter after you've parsed. Edit: The above was run with Sun's JDK 1.6.
85,702
<p>I want to have a "select-only" <code>ComboBox</code> that provides a list of items for the user to select from. Typing should be disabled in the text portion of the <code>ComboBox</code> control.</p> <p>My initial googling of this turned up an overly complex, misguided suggestion to capture the <code>KeyPress</code> event.</p>
[ { "answer_id": 85706, "author": "Cory Engebretson", "author_id": 3406, "author_profile": "https://Stackoverflow.com/users/3406", "pm_score": 10, "selected": true, "text": "<p>To make the text portion of a ComboBox non-editable, set the DropDownStyle property to \"DropDownList\". The Com...
2008/09/17
[ "https://Stackoverflow.com/questions/85702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3406/" ]
I want to have a "select-only" `ComboBox` that provides a list of items for the user to select from. Typing should be disabled in the text portion of the `ComboBox` control. My initial googling of this turned up an overly complex, misguided suggestion to capture the `KeyPress` event.
To make the text portion of a ComboBox non-editable, set the DropDownStyle property to "DropDownList". The ComboBox is now essentially select-only for the user. You can do this in the Visual Studio designer, or in C# like this: ``` stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList; ``` Link to the documentation for the [ComboBox DropDownStyle property](http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.dropdownstyle.aspx) on MSDN.
85,761
<p>I have an external variable coming in as a string and I would like to do a switch/case on it. How do I do that in xquery?</p>
[ { "answer_id": 85780, "author": "Sixty4Bit", "author_id": 1681, "author_profile": "https://Stackoverflow.com/users/1681", "pm_score": 2, "selected": false, "text": "<p>XQuery doesn't have a function for switching on anything other than elements.</p>\n\n<p>The first thing you do is conver...
2008/09/17
[ "https://Stackoverflow.com/questions/85761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1681/" ]
I have an external variable coming in as a string and I would like to do a switch/case on it. How do I do that in xquery?
Starting with XQuery 1.1, use switch: <http://www.w3.org/TR/xquery-11/#id-switch> ```xquery switch ($animal) case "Cow" return "Moo" case "Cat" return "Meow" case "Duck" return "Quack" default return "What's that odd noise?" ```
85,770
<p>here is the input i am getting from my flash file </p> <p>process.php?Q2=898&amp;Aa=Grade1&amp;Tim=0%3A0%3A12&amp;Q1=908&amp;Bb=lkj&amp;Q4=jhj&amp;Q3=08&amp;Cc=North%20America&amp;Q0=1</p> <p>and in php i use this code foreach ($_GET as $field => $label) { $datarray[]=$_GET[$field];</p> <pre><code>echo "$field :"; echo $_GET[$field];; echo "&lt;br&gt;"; </code></pre> <p>i get this out put</p> <p>Q2 :898 Aa :Grade1 Tim :0:0:12 Q1 :908 Bb :lkj Q4 :jhj Q3 :08 Cc :North America Q0 :1</p> <p>now my question is how do i sort it alphabaticaly so it should look like this Aa :Grade1 Bb :lkj Cc :North America Q0 :1 Q1 :908</p> <p>and so on....before i can insert it into the DB</p>
[ { "answer_id": 85792, "author": "terminus", "author_id": 9232, "author_profile": "https://Stackoverflow.com/users/9232", "pm_score": 4, "selected": true, "text": "<pre><code>ksort($_GET);\n</code></pre>\n<p>This should <a href=\"http://php.net/manual/en/function.ksort.php\" rel=\"nofollo...
2008/09/17
[ "https://Stackoverflow.com/questions/85770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16458/" ]
here is the input i am getting from my flash file process.php?Q2=898&Aa=Grade1&Tim=0%3A0%3A12&Q1=908&Bb=lkj&Q4=jhj&Q3=08&Cc=North%20America&Q0=1 and in php i use this code foreach ($\_GET as $field => $label) { $datarray[]=$\_GET[$field]; ``` echo "$field :"; echo $_GET[$field];; echo "<br>"; ``` i get this out put Q2 :898 Aa :Grade1 Tim :0:0:12 Q1 :908 Bb :lkj Q4 :jhj Q3 :08 Cc :North America Q0 :1 now my question is how do i sort it alphabaticaly so it should look like this Aa :Grade1 Bb :lkj Cc :North America Q0 :1 Q1 :908 and so on....before i can insert it into the DB
``` ksort($_GET); ``` This should [ksort](http://php.net/manual/en/function.ksort.php) the `$_GET` array by it's keys. [krsort](http://php.net/manual/en/function.krsort.php) for reverse order.
85,773
<p>My source code needs to support both .NET version 1.1 and 2.0 ... how do I test for the different versions &amp; what is the best way to deal with this situation.</p> <p>I'm wondering if I should have the two sections of code inline, in separate classes, methods etc. What do you think?</p>
[ { "answer_id": 85827, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>I would be asking the question of WHY you have to maintain two code bases, I would pick one and go with it if th...
2008/09/17
[ "https://Stackoverflow.com/questions/85773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491/" ]
My source code needs to support both .NET version 1.1 and 2.0 ... how do I test for the different versions & what is the best way to deal with this situation. I'm wondering if I should have the two sections of code inline, in separate classes, methods etc. What do you think?
If you want to do something like this you will need to use preprocessor commands and conditional compilation symbols. I would use symbols that clearly indicate the version of .NET you are targeting (say NET11 and NET20) and then wrap the relevant code like this: ``` #if NET11 // .NET 1.1 code #elif NET20 // .NET 2.0 code #endif ``` The reason for doing it this way rather than a simple if/else is an extra layer of protection in case someone forgets to define the symbol. That being said, you should really drill down to the heart of the reason why you want/need to do this.
85,815
<p>How do you tell if a function in JavaScript is defined?</p> <p>I want to do something like this</p> <pre><code>function something_cool(text, callback) { alert(text); if( callback != null ) callback(); } </code></pre> <p>But it gets me a</p> <blockquote> <p>callback is not a function</p> </blockquote> <p>error when callback is not defined.</p>
[ { "answer_id": 85822, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 10, "selected": true, "text": "<pre><code>typeof callback === \"function\"\n</code></pre>\n" }, { "answer_id": 85825, "author": "bdukes", ...
2008/09/17
[ "https://Stackoverflow.com/questions/85815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8351/" ]
How do you tell if a function in JavaScript is defined? I want to do something like this ``` function something_cool(text, callback) { alert(text); if( callback != null ) callback(); } ``` But it gets me a > > callback is not a function > > > error when callback is not defined.
``` typeof callback === "function" ```
85,816
<p>I've got just one page that I want to force to be accessed as an HTTPS page (PHP on Apache). How do I do this without making the whole directory require HTTPS? Or, if you submit a form to an HTTPS page from an HTTP page, does it send it by HTTPS instead of HTTP?</p> <p>Here is my example:</p> <pre><code>http://www.example.com/some-page.php </code></pre> <p>I want it to only be accessed through:</p> <pre><code>https://www.example.com/some-page.php </code></pre> <p>Sure, I can put all of the links to this page pointed at the HTTPS version, but that doesn't stop some fool from accessing it through HTTP on purpose...</p> <p>One thing I thought was putting a redirect in the header of the PHP file to check to be sure that they are accessing the HTTPS version:</p> <pre><code>if($_SERVER[&quot;SCRIPT_URI&quot;] == &quot;http://www.example.com/some-page.php&quot;){ header('Location: https://www.example.com/some-page.php'); } </code></pre> <p>But that can't be the right way, can it?</p>
[ { "answer_id": 85835, "author": "thebigjc", "author_id": 16507, "author_profile": "https://Stackoverflow.com/users/16507", "pm_score": 6, "selected": false, "text": "<p>You could do it with a directive and mod_rewrite on Apache:</p>\n\n<pre><code>&lt;Location /buyCrap.php&gt;\nRewriteEn...
2008/09/17
[ "https://Stackoverflow.com/questions/85816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've got just one page that I want to force to be accessed as an HTTPS page (PHP on Apache). How do I do this without making the whole directory require HTTPS? Or, if you submit a form to an HTTPS page from an HTTP page, does it send it by HTTPS instead of HTTP? Here is my example: ``` http://www.example.com/some-page.php ``` I want it to only be accessed through: ``` https://www.example.com/some-page.php ``` Sure, I can put all of the links to this page pointed at the HTTPS version, but that doesn't stop some fool from accessing it through HTTP on purpose... One thing I thought was putting a redirect in the header of the PHP file to check to be sure that they are accessing the HTTPS version: ``` if($_SERVER["SCRIPT_URI"] == "http://www.example.com/some-page.php"){ header('Location: https://www.example.com/some-page.php'); } ``` But that can't be the right way, can it?
The way I've done it before is basically like what you wrote, but doesn't have any hardcoded values: ``` if($_SERVER["HTTPS"] != "on") { header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]); exit(); } ```
85,880
<p>Currently I'm doing some unit tests which are executed from bash. Unit tests are initialized, executed and cleaned up in a bash script. This script usualy contains an init(), execute() and cleanup() functions. But they are not mandatory. I'd like to test if they are or are not defined.</p> <p>I did this previously by greping and seding the source, but it seemed wrong. Is there a more elegant way to do this?</p> <p>Edit: The following sniplet works like a charm:</p> <pre><code>fn_exists() { LC_ALL=C type $1 | grep -q 'shell function' } </code></pre>
[ { "answer_id": 85903, "author": "JBB", "author_id": 12332, "author_profile": "https://Stackoverflow.com/users/12332", "pm_score": 9, "selected": true, "text": "<p>Like this: <code>[[ $(type -t foo) == function ]] &amp;&amp; echo &quot;Foo exists&quot;</code></p>\n<p>The built-in <code>ty...
2008/09/17
[ "https://Stackoverflow.com/questions/85880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9232/" ]
Currently I'm doing some unit tests which are executed from bash. Unit tests are initialized, executed and cleaned up in a bash script. This script usualy contains an init(), execute() and cleanup() functions. But they are not mandatory. I'd like to test if they are or are not defined. I did this previously by greping and seding the source, but it seemed wrong. Is there a more elegant way to do this? Edit: The following sniplet works like a charm: ``` fn_exists() { LC_ALL=C type $1 | grep -q 'shell function' } ```
Like this: `[[ $(type -t foo) == function ]] && echo "Foo exists"` The built-in `type` command will tell you whether something is a function, built-in function, external command, or just not defined. Additional examples: ```none $ LC_ALL=C type foo bash: type: foo: not found $ LC_ALL=C type ls ls is aliased to `ls --color=auto' $ which type $ LC_ALL=C type type type is a shell builtin $ LC_ALL=C type -t rvm function $ if [ -n "$(LC_ALL=C type -t rvm)" ] && [ "$(LC_ALL=C type -t rvm)" = function ]; then echo rvm is a function; else echo rvm is NOT a function; fi rvm is a function ```
85,892
<p>I'm trying to determine if there's a way in Visual Basic 2008 (Express edition if that matters) to do inline collection initialization, a la JavaScript or Python:</p> <pre><code>Dim oMapping As Dictionary(Of Integer, String) = {{1,"First"}, {2, "Second"}} </code></pre> <p>I know Visual Basic 2008 supports array initialization like this, but I can't seem to get it to work for collections... Do I have the syntax wrong, or is it just not implemented?</p>
[ { "answer_id": 85914, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": true, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Visual_Basic_.NET#Visual_Basic_2008_.28VB_9.0.29\" rel=\"nofollow noreferrer\...
2008/09/17
[ "https://Stackoverflow.com/questions/85892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7542/" ]
I'm trying to determine if there's a way in Visual Basic 2008 (Express edition if that matters) to do inline collection initialization, a la JavaScript or Python: ``` Dim oMapping As Dictionary(Of Integer, String) = {{1,"First"}, {2, "Second"}} ``` I know Visual Basic 2008 supports array initialization like this, but I can't seem to get it to work for collections... Do I have the syntax wrong, or is it just not implemented?
[Visual Basic 9.0](http://en.wikipedia.org/wiki/Visual_Basic_.NET#Visual_Basic_2008_.28VB_9.0.29) doesn't support this yet. However, [Visual Basic 10.0](http://en.wikipedia.org/wiki/Visual_Basic_.NET#Visual_Basic_2010_.28VB_10.0.29) [will](http://msdn.microsoft.com/en-us/library/dd293617.aspx).
85,941
<p>I get the following error when running my Visual Studio 2008 ASP.NET project (start without Debugging) on my XP Professional box:</p> <pre><code>System.Web.HttpException: The current identity (machinename\ASPNET) does not have write access to 'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files'. </code></pre> <p>How can I resolve this?</p>
[ { "answer_id": 85956, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 5, "selected": true, "text": "<p>Have you tried, the aspnet_regiis exe in the framework folder?</p>\n" }, { "answer_id": 85966, "a...
2008/09/17
[ "https://Stackoverflow.com/questions/85941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/417/" ]
I get the following error when running my Visual Studio 2008 ASP.NET project (start without Debugging) on my XP Professional box: ``` System.Web.HttpException: The current identity (machinename\ASPNET) does not have write access to 'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files'. ``` How can I resolve this?
Have you tried, the aspnet\_regiis exe in the framework folder?
85,978
<p>For a given table 'foo', I need a query to generate a set of tables that have foreign keys that point to foo. I'm using Oracle 10G.</p>
[ { "answer_id": 86104, "author": "Mike Monette", "author_id": 6166, "author_profile": "https://Stackoverflow.com/users/6166", "pm_score": 7, "selected": true, "text": "<p>This should work (or something close):</p>\n\n<pre><code>select table_name\nfrom all_constraints\nwhere constraint_typ...
2008/09/17
[ "https://Stackoverflow.com/questions/85978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
For a given table 'foo', I need a query to generate a set of tables that have foreign keys that point to foo. I'm using Oracle 10G.
This should work (or something close): ``` select table_name from all_constraints where constraint_type='R' and r_constraint_name in (select constraint_name from all_constraints where constraint_type in ('P','U') and table_name='<your table here>'); ```
85,992
<p>How do I enumerate the properties of a JavaScript object?</p> <p>I actually want to list all the defined variables and their values, but I've learned that defining a variable actually creates a property of the window object.</p>
[ { "answer_id": 86014, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 11, "selected": true, "text": "<p>Simple enough:</p>\n\n<pre><code>for(var propertyName in myObject) {\n // propertyName is what you want\n // you...
2008/09/17
[ "https://Stackoverflow.com/questions/85992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4777/" ]
How do I enumerate the properties of a JavaScript object? I actually want to list all the defined variables and their values, but I've learned that defining a variable actually creates a property of the window object.
Simple enough: ``` for(var propertyName in myObject) { // propertyName is what you want // you can get the value like this: myObject[propertyName] } ``` Now, you will not get private variables this way because they are not available. --- EDIT: [@bitwiseplatypus](https://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object#86306) is correct that unless you use the `hasOwnProperty()` method, you will get properties that are inherited - however, I don't know why anyone familiar with object-oriented programming would expect anything less! Typically, someone that brings this up has been subjected to Douglas Crockford's warnings about this, which still confuse me a bit. Again, inheritance is a normal part of OO languages and is therefore part of JavaScript, notwithstanding it being prototypical. Now, that said, `hasOwnProperty()` *is* useful for filtering, but we don't need to sound a warning as if there is something dangerous in getting inherited properties. EDIT 2: [@bitwiseplatypus](https://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object#86306) brings up the situation that would occur should someone add properties/methods to your objects at a point in time later than when you originally wrote your objects (via its prototype) - while it is true that this might cause unexpected behavior, I personally don't see that as my problem entirely. Just a matter of opinion. Besides, what if I design things in such a way that I use prototypes during the construction of my objects and yet have code that iterates over the properties of the object and I want all inherited properties? I wouldn't use `hasOwnProperty()`. Then, let's say, someone adds new properties later. Is that my fault if things behave badly at that point? I don't think so. I think this is why jQuery, as an example, has specified ways of extending how it works (via `jQuery.extend` and `jQuery.fn.extend`).
85,996
<p>I wrote myself a little downloading application so that I could easily grab a set of files from my server and put them all onto a new pc with a clean install of Windows, without actually going on the net. Unfortunately I'm having problems creating the folder I want to put them in and am unsure how to go about it.</p> <p>I want my program to download the apps to <code>program files\any name here\</code></p> <p>So basically I need a function that checks if a folder exists, and if it doesn't it creates it.</p>
[ { "answer_id": 86009, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 3, "selected": false, "text": "<p>Try this: <code>Directory.Exists(TheFolderName)</code> and <code>Directory.CreateDirectory(TheFolderName)</code></p>\n\n<p...
2008/09/17
[ "https://Stackoverflow.com/questions/85996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I wrote myself a little downloading application so that I could easily grab a set of files from my server and put them all onto a new pc with a clean install of Windows, without actually going on the net. Unfortunately I'm having problems creating the folder I want to put them in and am unsure how to go about it. I want my program to download the apps to `program files\any name here\` So basically I need a function that checks if a folder exists, and if it doesn't it creates it.
``` If Not System.IO.Directory.Exists(YourPath) Then System.IO.Directory.CreateDirectory(YourPath) End If ```
86,002
<p>I need to write a Delphi application that pulls entries up from various tables in a database, and different entries will be in different currencies. Thus, I need to show a different number of decimal places and a different currency character for every Currency data type ($, Pounds, Euros, etc) depending on the currency of the item I've loaded.</p> <p>Is there a way to change the currency almost-globally, that is, for all Currency data shown in a form?</p>
[ { "answer_id": 86289, "author": "user16120", "author_id": 16120, "author_profile": "https://Stackoverflow.com/users/16120", "pm_score": 3, "selected": false, "text": "<p>I'd use SysUtils.CurrToStr(Value: Currency; var FormatSettings: TFormatSettings): string;</p>\n\n<p>I'd setup an array...
2008/09/17
[ "https://Stackoverflow.com/questions/86002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42219/" ]
I need to write a Delphi application that pulls entries up from various tables in a database, and different entries will be in different currencies. Thus, I need to show a different number of decimal places and a different currency character for every Currency data type ($, Pounds, Euros, etc) depending on the currency of the item I've loaded. Is there a way to change the currency almost-globally, that is, for all Currency data shown in a form?
Even with the same currency, you may have to display values with a different format (separators for instance), so I would recommend that you associate a LOCALE instead of the currency only with your values. You can use a simple Integer to hold the LCID (locale ID). See the list here: <http://msdn.microsoft.com/en-us/library/0h88fahh.aspx> Then to display the values, use something like: ``` function CurrFormatFromLCID(const AValue: Currency; const LCID: Integer = LOCALE_SYSTEM_DEFAULT): string; var AFormatSettings: TFormatSettings; begin GetLocaleFormatSettings(LCID, AFormatSettings); Result := CurrToStrF(AValue, ffCurrency, AFormatSettings.CurrencyDecimals, AFormatSettings); end; function USCurrFormat(const AValue: Currency): string; begin Result := CurrFormatFromLCID(AValue, 1033); //1033 = US_LCID end; function FrenchCurrFormat(const AValue: Currency): string; begin Result := CurrFormatFromLCID(AValue, 1036); //1036 = French_LCID end; procedure TestIt; var val: Currency; begin val:=1234.56; ShowMessage('US: ' + USCurrFormat(val)); ShowMessage('FR: ' + FrenchCurrFormat(val)); ShowMessage('GB: ' + CurrFormatFromLCID(val, 2057)); // 2057 = GB_LCID ShowMessage('def: ' + CurrFormatFromLCID(val)); end; ```
86,018
<p>If you are using HAML and SASS in your Rails application, then any templates you define in public/stylesheet/*.sass will be compiled into *.css stylesheets. From your code, you use stylesheet_link_tag to pull in the asset by name without having to worry about the extension. </p> <p>Many people dislike storing generated code or compiled code in version control, and it also stands to reason that the public/ directory shouldn't contain elements that you don't send to the browser. </p> <p>What is the best pattern to follow when laying out SASS resources in your Rails project?</p>
[ { "answer_id": 86106, "author": "Pete", "author_id": 13472, "author_profile": "https://Stackoverflow.com/users/13472", "pm_score": 0, "selected": false, "text": "<p>If I can manage it, I like to store all of my styles in SASS templates when I choose HAML/SASS for a project, and I'll remo...
2008/09/17
[ "https://Stackoverflow.com/questions/86018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13472/" ]
If you are using HAML and SASS in your Rails application, then any templates you define in public/stylesheet/\*.sass will be compiled into \*.css stylesheets. From your code, you use stylesheet\_link\_tag to pull in the asset by name without having to worry about the extension. Many people dislike storing generated code or compiled code in version control, and it also stands to reason that the public/ directory shouldn't contain elements that you don't send to the browser. What is the best pattern to follow when laying out SASS resources in your Rails project?
I always version all stylesheets in "public/stylesheets/sass/\*.sass" and set up an exclude filter for compiled ones: ``` /public/stylesheets/*.css ```
86,049
<p>How do I ignore files in Subversion?</p> <p>Also, how do I find files which are not under version control?</p>
[ { "answer_id": 86052, "author": "andyuk", "author_id": 2108, "author_profile": "https://Stackoverflow.com/users/2108", "pm_score": 11, "selected": true, "text": "<p>(This answer has been updated to match SVN 1.8 and 1.9's behaviour)</p>\n\n<p>You have 2 questions:</p>\n\n<h1>Marking file...
2008/09/17
[ "https://Stackoverflow.com/questions/86049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2108/" ]
How do I ignore files in Subversion? Also, how do I find files which are not under version control?
(This answer has been updated to match SVN 1.8 and 1.9's behaviour) You have 2 questions: Marking files as ignored: ========================= By "ignored file" I mean the file won't appear in lists even as "unversioned": your SVN client will pretend the file doesn't exist at all in the filesystem. Ignored files are specified by a "file pattern". The syntax and format of file patterns is explained in SVN's online documentation: <http://svnbook.red-bean.com/nightly/en/svn.advanced.props.special.ignore.html> "File Patterns in Subversion". Subversion, as of version 1.8 (June 2013) and later, supports 3 different ways of specifying file patterns. Here's a summary with examples: 1 - Runtime Configuration Area - `global-ignores` option: --------------------------------------------------------- * This is a **client-side only** setting, so your `global-ignores` list won't be shared by other users, and it applies to all repos you checkout onto your computer. * This setting is defined in your Runtime Configuration Area file: + Windows (file-based) - `C:\Users\{you}\AppData\Roaming\Subversion\config` + Windows (registry-based) - `Software\Tigris.org\Subversion\Config\Miscellany\global-ignores` in both `HKLM` and `HKCU`. + Linux/Unix - `~/.subversion/config` 2 - The `svn:ignore` property, which is set on directories (not files): ----------------------------------------------------------------------- * This is stored within the repo, so other users will have the same ignore files. Similar to how `.gitignore` works. * `svn:ignore` is applied to directories and is non-recursive or inherited. Any file or *immediate* subdirectory of the parent directory that matches the File Pattern will be excluded. * While SVN 1.8 adds the concept of "inherited properties", the `svn:ignore` property itself is ignored in non-immediate descendant directories: ``` cd ~/myRepoRoot # Open an existing repo. echo "foo" > "ignoreThis.txt" # Create a file called "ignoreThis.txt". svn status # Check to see if the file is ignored or not. > ? ./ignoreThis.txt > 1 unversioned file # ...it is NOT currently ignored. svn propset svn:ignore "ignoreThis.txt" . # Apply the svn:ignore property to the "myRepoRoot" directory. svn status > 0 unversioned files # ...but now the file is ignored! cd subdirectory # now open a subdirectory. echo "foo" > "ignoreThis.txt" # create another file named "ignoreThis.txt". svn status > ? ./subdirectory/ignoreThis.txt # ...and is is NOT ignored! > 1 unversioned file ``` (So the file `./subdirectory/ignoreThis` is not ignored, even though "`ignoreThis.txt`" is applied on the `.` repo root). * Therefore, to apply an ignore list recursively you must use `svn propset svn:ignore <filePattern> . --recursive`. + This will create a copy of the property on every subdirectory. + If the `<filePattern>` value is different in a child directory then the child's value completely overrides the parents, so there is no "additive" effect. + So if you change the `<filePattern>` on the root `.`, then you must change it with `--recursive` to overwrite it on the child and descendant directories. * I note that the command-line syntax is counter-intuitive. + I started-off assuming that you would ignore a file in SVN by typing something like `svn ignore pathToFileToIgnore.txt` however this is not how SVN's ignore feature works. 3- The `svn:global-ignores` property. Requires SVN 1.8 (June 2013): ------------------------------------------------------------------- * This is similar to `svn:ignore`, except it makes use of SVN 1.8's "inherited properties" feature. * Compare to `svn:ignore`, the file pattern is automatically applied in every descendant directory (not just immediate children). + This means that is unnecessary to set `svn:global-ignores` with the `--recursive` flag, as inherited ignore file patterns are automatically applied as they're inherited. * Running the same set of commands as in the previous example, but using `svn:global-ignores` instead: ``` cd ~/myRepoRoot # Open an existing repo echo "foo" > "ignoreThis.txt" # Create a file called "ignoreThis.txt" svn status # Check to see if the file is ignored or not > ? ./ignoreThis.txt > 1 unversioned file # ...it is NOT currently ignored svn propset svn:global-ignores "ignoreThis.txt" . svn status > 0 unversioned files # ...but now the file is ignored! cd subdirectory # now open a subdirectory echo "foo" > "ignoreThis.txt" # create another file named "ignoreThis.txt" svn status > 0 unversioned files # the file is ignored here too! ``` For TortoiseSVN users: ---------------------- This whole arrangement was confusing for me, because TortoiseSVN's terminology (as used in their Windows Explorer menu system) was initially misleading to me - I was unsure what the significance of the Ignore menu's "Add recursively", "Add \*" and "Add " options. I hope this post explains how the Ignore feature ties-in to the SVN Properties feature. That said, I suggest using the command-line to set ignored files so you get a feel for how it works instead of using the GUI, and only using the GUI to manipulate properties after you're comfortable with the command-line. Listing files that are ignored: =============================== The command `svn status` will hide ignored files (that is, files that match an RGA `global-ignores` pattern, or match an immediate parent directory's `svn:ignore` pattern or match any ancesor directory's `svn:global-ignores` pattern. Use the `--no-ignore` option to see those files listed. Ignored files have a status of `I`, then pipe the output to `grep` to only show lines starting with "I". The command is: ``` svn status --no-ignore | grep "^I" ``` For example: ``` svn status > ? foo # An unversioned file > M modifiedFile.txt # A versioned file that has been modified svn status --no-ignore > ? foo # An unversioned file > I ignoreThis.txt # A file matching an svn:ignore pattern > M modifiedFile.txt # A versioned file that has been modified svn status --no-ignore | grep "^I" > I ignoreThis.txt # A file matching an svn:ignore pattern ``` ta-da!
86,119
<p>I am trying to have Apache follow a symlink to a raid array server that will contain some large data files. I have tried modifying <code>httpd.conf</code> to have an entry like this</p> <pre><code>&lt;Directory "/Users/imagine/Sites"&gt; Options FollowSymLinks AllowOverride all Order allow,deny Allow from all &lt;/Directory&gt; </code></pre> <p>to have Apache follow any sym link in the Sites folder.</p> <p>I keep getting an error return that seems to indicate I don't have any permissions to access the files. The error is:</p> <blockquote> <p>Forbidden</p> <p>You don't have permission to access /~imagine/imageLibraryTest/videoClips/imageLibraryVideos/imageLibraryVideos/Data13/0002RT-1.mov on this server.</p> </blockquote> <p>The sys link file is the last "imageLibraryVideos" in the line with the Data13 being the sub dir on the server containing the file. </p> <p>The 0002RT-1.mov file hase these permissions:</p> <pre><code>-rwxrwxrwx 1 imagine staff 1138757 Sep 15 17:01 0002RT-1.mov </code></pre> <p>and is in this path:</p> <pre><code>cd /Volumes/ImagineProducts-1/Users/imagine/Sites/imageLibraryVideos/Data13 </code></pre> <p>the link points to:</p> <pre><code>lrwxr-xr-x 1 imagine staff 65 Sep 15 16:40 imageLibraryVideos -&gt; /Volumes/ImagineProducts-1/Users/imagine/Sites/imageLibraryVideos </code></pre>
[ { "answer_id": 86137, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": 1, "selected": false, "text": "<p>Look in the enclosing directories. They need to be at least mode 711. (<code>drwx--x--x</code>)</p>\n\n<p>Also, look in <co...
2008/09/17
[ "https://Stackoverflow.com/questions/86119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to have Apache follow a symlink to a raid array server that will contain some large data files. I have tried modifying `httpd.conf` to have an entry like this ``` <Directory "/Users/imagine/Sites"> Options FollowSymLinks AllowOverride all Order allow,deny Allow from all </Directory> ``` to have Apache follow any sym link in the Sites folder. I keep getting an error return that seems to indicate I don't have any permissions to access the files. The error is: > > Forbidden > > > You don't have permission to access > /~imagine/imageLibraryTest/videoClips/imageLibraryVideos/imageLibraryVideos/Data13/0002RT-1.mov > on this server. > > > The sys link file is the last "imageLibraryVideos" in the line with the Data13 being the sub dir on the server containing the file. The 0002RT-1.mov file hase these permissions: ``` -rwxrwxrwx 1 imagine staff 1138757 Sep 15 17:01 0002RT-1.mov ``` and is in this path: ``` cd /Volumes/ImagineProducts-1/Users/imagine/Sites/imageLibraryVideos/Data13 ``` the link points to: ``` lrwxr-xr-x 1 imagine staff 65 Sep 15 16:40 imageLibraryVideos -> /Volumes/ImagineProducts-1/Users/imagine/Sites/imageLibraryVideos ```
I had the same problem last week and the solution was pretty simple for me. Run: ``` sudo -i -u www-data ``` And then try navigating the path, directory by directory. You will notice at some point that you don't have access to open the dir. If you get into the last directory, check that you can read the file (with head for example).
86,129
<p>I can make a DAO recordset in VB6/Access do anything - add data, clean data, move data, get data dressed in the morning and take it to school. But I don't even know where to start in .NET. </p> <p>I'm not having any problems retrieving data from the database, but what do real people do when they need to edit data and put it back?</p> <p>What's the easiest and most direct way to edit, update and append data into related tables in .NET and SQL Server?</p>
[ { "answer_id": 86137, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": 1, "selected": false, "text": "<p>Look in the enclosing directories. They need to be at least mode 711. (<code>drwx--x--x</code>)</p>\n\n<p>Also, look in <co...
2008/09/17
[ "https://Stackoverflow.com/questions/86129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16415/" ]
I can make a DAO recordset in VB6/Access do anything - add data, clean data, move data, get data dressed in the morning and take it to school. But I don't even know where to start in .NET. I'm not having any problems retrieving data from the database, but what do real people do when they need to edit data and put it back? What's the easiest and most direct way to edit, update and append data into related tables in .NET and SQL Server?
I had the same problem last week and the solution was pretty simple for me. Run: ``` sudo -i -u www-data ``` And then try navigating the path, directory by directory. You will notice at some point that you don't have access to open the dir. If you get into the last directory, check that you can read the file (with head for example).
86,138
<p>I need to get the default printer name. I'll be using C# but I suspect this is more of a framework question and isn't language specific.</p>
[ { "answer_id": 86185, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 8, "selected": true, "text": "<p>The easiest way I found is to create a new <code>PrinterSettings</code> object. It starts with all default values, so you ca...
2008/09/17
[ "https://Stackoverflow.com/questions/86138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7176/" ]
I need to get the default printer name. I'll be using C# but I suspect this is more of a framework question and isn't language specific.
The easiest way I found is to create a new `PrinterSettings` object. It starts with all default values, so you can check its *Name* property to get the name of the default printer. `PrinterSettings` is in System.Drawing.dll in the namespace `System.Drawing.Printing`. ``` PrinterSettings settings = new PrinterSettings(); Console.WriteLine(settings.PrinterName); ``` Alternatively, you could maybe use the static `PrinterSettings.InstalledPrinters` method to get a list of all printer names, then set the *PrinterName* property and check the *IsDefaultPrinter*. I haven't tried this, but the documentation seems to suggest it won't work. Apparently *IsDefaultPrinter* is only true when *PrinterName* is not explicitly set.
86,143
<p>There are a couple of tricks for getting glass support for .Net forms.</p> <p>I think the original source for this method is here: <a href="http://blogs.msdn.com/tims/archive/2006/04/18/578637.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/tims/archive/2006/04/18/578637.aspx</a></p> <p>Basically:</p> <pre><code>//reference Desktop Windows Manager (DWM API) [DllImport( "dwmapi.dll" )] static extern void DwmIsCompositionEnabled( ref bool pfEnabled ); [DllImport( "dwmapi.dll" )] static extern int DwmExtendFrameIntoClientArea( IntPtr hWnd, ref MARGINS pMarInset ); //then on form load //check for Vista if ( Environment.OSVersion.Version.Major &gt;= 6 ) { //check for support bool isGlassSupported = false; DwmIsCompositionEnabled( ref isGlassSupported ); if ( isGlassSupported ) DwmExtendFrameIntoClientArea( this.Handle, ref margins ); ... //finally on print draw a black box over the alpha-ed area //Before SP1 you could also use a black form background </code></pre> <p>That final step is the issue - any sub controls drawn over that area seem to also treat black as the alpha transparency mask.</p> <p>For instance a tab strip over the class area will have transparent text.</p> <p>Is there a way around this?</p> <p>Is there an easier way to do this?</p> <p>The applications I'm working on have to work on both XP and Vista - I need them to degrade gracefully. Are there any best practices here?</p>
[ { "answer_id": 86168, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 3, "selected": true, "text": "<p>There really isn't an easier way to do this. These APIs are not exposed by the .NET Framework (yet), so the only way...
2008/09/17
[ "https://Stackoverflow.com/questions/86143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
There are a couple of tricks for getting glass support for .Net forms. I think the original source for this method is here: <http://blogs.msdn.com/tims/archive/2006/04/18/578637.aspx> Basically: ``` //reference Desktop Windows Manager (DWM API) [DllImport( "dwmapi.dll" )] static extern void DwmIsCompositionEnabled( ref bool pfEnabled ); [DllImport( "dwmapi.dll" )] static extern int DwmExtendFrameIntoClientArea( IntPtr hWnd, ref MARGINS pMarInset ); //then on form load //check for Vista if ( Environment.OSVersion.Version.Major >= 6 ) { //check for support bool isGlassSupported = false; DwmIsCompositionEnabled( ref isGlassSupported ); if ( isGlassSupported ) DwmExtendFrameIntoClientArea( this.Handle, ref margins ); ... //finally on print draw a black box over the alpha-ed area //Before SP1 you could also use a black form background ``` That final step is the issue - any sub controls drawn over that area seem to also treat black as the alpha transparency mask. For instance a tab strip over the class area will have transparent text. Is there a way around this? Is there an easier way to do this? The applications I'm working on have to work on both XP and Vista - I need them to degrade gracefully. Are there any best practices here?
There really isn't an easier way to do this. These APIs are not exposed by the .NET Framework (yet), so the only way to do it is through some kind of interop (or WPF). As for working with both Windows versions, the code you have should be fine, since the runtime does not go looking for the entry point to the DLL until you actually call the function.
86,175
<p>On all my Windows servers, except for one machine, when I execute the following code to allocate a temporary files folder:</p> <pre><code>use CGI; my $tmpfile = new CGITempFile(1); print "tmpfile='", $tmpfile-&gt;as_string(), "'\n"; </code></pre> <p>The variable <code>$tmpfile</code> is assigned the value <code>'.\CGItemp1'</code> and this is what I want. But on one of my servers it's incorrectly set to <code>C:\temp\CGItemp1</code>.</p> <p>All the servers are running Windows 2003 Standard Edition, IIS6 and ActivePerl 5.8.8.822 (upgrading to later version of Perl not an option). The result is always the same when running a script from the command line or in IIS as a CGI script (where scriptmap <code>.pl</code> = <code>c:\perl\bin\perl.exe "%s" %s</code>).</p> <p>How I can fix this Perl installation and force it to return '<code>.\CGItemp1</code>' by default?</p> <p>I've even copied the whole Perl folder from one of the working servers to this machine but no joy.</p> <p><a href="https://stackoverflow.com/questions/86175/where-is-cgi-pm-supposed-to-create-temporary-files/86200#86200">@Hometoast:</a></p> <p>I checked the '<code>TMP</code>' and '<code>TEMP</code>' environment variables and also <code>$ENV{TMP}</code> and <code>$ENV{TEMP}</code> and they're identical. </p> <p>From command line they point to the user profile directory, for example: </p> <blockquote> <p><code>C:\DOCUME~1\[USERNAME]\LOCALS~1\Temp\1</code></p> </blockquote> <p>When run under IIS as a CGI script they both point to:</p> <blockquote> <p><code>c:\windows\temp</code></p> </blockquote> <p>In registry key <code>HKEY_USERS/.DEFAULT/Environment</code>, both servers have:</p> <blockquote> <p><code>%USERPROFILE%\Local Settings\Temp</code></p> </blockquote> <p>The ActiveState implementation of <code>CGITempFile()</code> is clearly using an alternative mechanism to determine how it should generate the temporary folder.</p> <p><a href="https://stackoverflow.com/questions/86175/where-is-cgi-pm-supposed-to-create-temporary-files/86993#86993">@Ranguard:</a></p> <p>The real problem is with the <code>CGI.pm</code> module and attachment handling. Whenever a file is uploaded to the site <code>CGI.pm</code> needs to store it somewhere temporary. To do this <code>CGITempFile()</code> is called within <code>CGI.pm</code> to allocate a temporary folder. So unfortunately I can't use <code>File::Temp</code>. Thanks anyway.</p> <p><a href="https://stackoverflow.com/questions/86175/where-is-cgi-pm-supposed-to-create-temporary-files/86874#86874">@Chris:</a></p> <p>That helped a bunch. I did have a quick scan through the <code>CGI.pm</code> source earlier but your suggestion made me go back and look at it more studiously to understand the underlying algorithm. I got things working, but the oddest thing is that there was originally no <code>c:\temp</code> folder on the server. </p> <p>To obtain a temporary fix I created a <code>c:\temp</code> folder and set the relevant permissions for the website's anonymous user account. But because this is a shared box I couldn't leave things that way, even though the temp files were being deleted. To cut a long story short, I renamed the <code>c:\temp</code> folder to something different and magically the correct '<code>.\</code>' folder path was being returned. I also noticed that the customer had enabled FrontPage extensions on the site, which removes write access for the anonymous user account on the website folders, so this permission needed re-applying. I'm still at a loss as to why at the start of this issue <code>CGITempFile()</code> was returning <code>c:\temp</code>, even though that folder didn't exist, and why it magically started working again.</p>
[ { "answer_id": 86200, "author": "hometoast", "author_id": 2009, "author_profile": "https://Stackoverflow.com/users/2009", "pm_score": 1, "selected": false, "text": "<p>If you're running this script as you, check the %TEMP% environment variable to see if if it differs.</p>\n\n<p>If IIS is...
2008/09/17
[ "https://Stackoverflow.com/questions/86175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/419/" ]
On all my Windows servers, except for one machine, when I execute the following code to allocate a temporary files folder: ``` use CGI; my $tmpfile = new CGITempFile(1); print "tmpfile='", $tmpfile->as_string(), "'\n"; ``` The variable `$tmpfile` is assigned the value `'.\CGItemp1'` and this is what I want. But on one of my servers it's incorrectly set to `C:\temp\CGItemp1`. All the servers are running Windows 2003 Standard Edition, IIS6 and ActivePerl 5.8.8.822 (upgrading to later version of Perl not an option). The result is always the same when running a script from the command line or in IIS as a CGI script (where scriptmap `.pl` = `c:\perl\bin\perl.exe "%s" %s`). How I can fix this Perl installation and force it to return '`.\CGItemp1`' by default? I've even copied the whole Perl folder from one of the working servers to this machine but no joy. [@Hometoast:](https://stackoverflow.com/questions/86175/where-is-cgi-pm-supposed-to-create-temporary-files/86200#86200) I checked the '`TMP`' and '`TEMP`' environment variables and also `$ENV{TMP}` and `$ENV{TEMP}` and they're identical. From command line they point to the user profile directory, for example: > > `C:\DOCUME~1\[USERNAME]\LOCALS~1\Temp\1` > > > When run under IIS as a CGI script they both point to: > > `c:\windows\temp` > > > In registry key `HKEY_USERS/.DEFAULT/Environment`, both servers have: > > `%USERPROFILE%\Local Settings\Temp` > > > The ActiveState implementation of `CGITempFile()` is clearly using an alternative mechanism to determine how it should generate the temporary folder. [@Ranguard:](https://stackoverflow.com/questions/86175/where-is-cgi-pm-supposed-to-create-temporary-files/86993#86993) The real problem is with the `CGI.pm` module and attachment handling. Whenever a file is uploaded to the site `CGI.pm` needs to store it somewhere temporary. To do this `CGITempFile()` is called within `CGI.pm` to allocate a temporary folder. So unfortunately I can't use `File::Temp`. Thanks anyway. [@Chris:](https://stackoverflow.com/questions/86175/where-is-cgi-pm-supposed-to-create-temporary-files/86874#86874) That helped a bunch. I did have a quick scan through the `CGI.pm` source earlier but your suggestion made me go back and look at it more studiously to understand the underlying algorithm. I got things working, but the oddest thing is that there was originally no `c:\temp` folder on the server. To obtain a temporary fix I created a `c:\temp` folder and set the relevant permissions for the website's anonymous user account. But because this is a shared box I couldn't leave things that way, even though the temp files were being deleted. To cut a long story short, I renamed the `c:\temp` folder to something different and magically the correct '`.\`' folder path was being returned. I also noticed that the customer had enabled FrontPage extensions on the site, which removes write access for the anonymous user account on the website folders, so this permission needed re-applying. I'm still at a loss as to why at the start of this issue `CGITempFile()` was returning `c:\temp`, even though that folder didn't exist, and why it magically started working again.
The name of the temporary directory is held in `$CGITempFile::TMPDIRECTORY` and initialised in the `find_tempdir` function in CGI.pm. The algorithm for choosing the temporary directory is described in the CGI.pm documentation (search for **-private\_tempfiles**). IIUC, if a C:\Temp folder exists on the server, CGI.pm will use it. If none of the directories checked in `find_tempdir` exist, then the current directory "." is used. I hope this helps.
86,202
<p>Does <a href="https://facelets.dev.java.net/" rel="nofollow noreferrer">Facelets</a> have any features for neater or more readable internationalised user interface text labels that what you can otherwise do using JSF?</p> <p>For example, with plain JSF, using h:outputFormat is a very verbose way to interpolate variables in messages.</p> <p><em>Clarification:</em> I know that I can add a message file entry that looks like:</p> <pre><code>label.widget.count = You have a total of {0} widgets. </code></pre> <p>and display this (if I'm using Seam) with:</p> <pre><code>&lt;h:outputFormat value="#{messages['label.widget.count']}"&gt; &lt;f:param value="#{widgetCount}"/&gt; &lt;/h:outputFormat&gt; </code></pre> <p>but that's a lot of clutter to output one sentence - just the sort of thing that gives JSF a bad name.</p>
[ { "answer_id": 92356, "author": "Javaxpert", "author_id": 15241, "author_profile": "https://Stackoverflow.com/users/15241", "pm_score": -1, "selected": false, "text": "<p>Use ResourceBundle and property files.</p>\n" }, { "answer_id": 93224, "author": "Community", "author...
2008/09/17
[ "https://Stackoverflow.com/questions/86202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2670/" ]
Does [Facelets](https://facelets.dev.java.net/) have any features for neater or more readable internationalised user interface text labels that what you can otherwise do using JSF? For example, with plain JSF, using h:outputFormat is a very verbose way to interpolate variables in messages. *Clarification:* I know that I can add a message file entry that looks like: ``` label.widget.count = You have a total of {0} widgets. ``` and display this (if I'm using Seam) with: ``` <h:outputFormat value="#{messages['label.widget.count']}"> <f:param value="#{widgetCount}"/> </h:outputFormat> ``` but that's a lot of clutter to output one sentence - just the sort of thing that gives JSF a bad name.
You could create your own faces tag library to make it less verbose, something like: ``` <ph:i18n key="label.widget.count" p0="#{widgetCount}"/> ``` Then create the taglib in your view dir: /components/ph.taglib.xml ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE facelet-taglib PUBLIC "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN" "https://facelets.dev.java.net/source/browse/*checkout*/facelets/src/etc/facelet-taglib_1_0.dtd"> <facelet-taglib xmlns="http://java.sun.com/JSF/Facelet"> <namespace>http://peterhilton.com/core</namespace> <tag> <tag-name>i18n</tag-name> <source>i18n.xhtml</source> </tag> </facelet-taglib> ``` create /components/i18n.xhtml ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <h:outputFormat value="#{messages[key]}"> <!-- crude but it works --> <f:param value="#{p0}" /> <f:param value="#{p1}" /> <f:param value="#{p2}" /> <f:param value="#{p3}" /> </h:outputFormat> </ui:composition> ``` You can probably find an elegant way of passing the arguments with a little research. Now register your new taglib in web.xml ``` <context-param> <param-name>facelets.LIBRARIES</param-name> <param-value> /components/ph.taglib.xml </param-value> </context-param> ``` Just add `xmlns:ph="http://peterhilton.com/core"` to your views and you're all set!
86,269
<p>So, I am seeing a curious problem. If I have a function</p> <pre><code>// counter wraps around to beginning eventually, omitted for clarity. var counter; cycleCharts(chartId) { // chartId should be undefined when called from setInterval console.log('chartId: ' + chartId); if(typeof chartId == 'undefined' || chartId &lt; 0) { next = counter++; } else { next = chartId; } // ... do stuff to display the next chart } </code></pre> <p>This function can be called explicitly by user action, in which case <code>chartId</code> is passed in as an argument, and the selected chart is shown; or it can be in autoplay mode, in which case it's called by a <code>setInterval</code> which is initialized by the following:</p> <pre><code>var cycleId = setInterval(cycleCharts, 10000); </code></pre> <p>The odd thing is, I'm actually seeing the <code>cycleCharts()</code> get a <code>chartId</code> argument even when it's called from <code>setInterval</code>! The <code>setInterval</code> doesn't even have any parameters to pass along to the <code>cycleCharts</code> function, so I'm very baffled as to why <code>chartId</code> is not undefined when <code>cycleCharts</code> is called from the <code>setInterval</code>.</p>
[ { "answer_id": 86309, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 3, "selected": true, "text": "<p>setInterval is feeding cycleCharts actual timing data ( so one can work out the actual time it ran and use to produc...
2008/09/17
[ "https://Stackoverflow.com/questions/86269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13289/" ]
So, I am seeing a curious problem. If I have a function ``` // counter wraps around to beginning eventually, omitted for clarity. var counter; cycleCharts(chartId) { // chartId should be undefined when called from setInterval console.log('chartId: ' + chartId); if(typeof chartId == 'undefined' || chartId < 0) { next = counter++; } else { next = chartId; } // ... do stuff to display the next chart } ``` This function can be called explicitly by user action, in which case `chartId` is passed in as an argument, and the selected chart is shown; or it can be in autoplay mode, in which case it's called by a `setInterval` which is initialized by the following: ``` var cycleId = setInterval(cycleCharts, 10000); ``` The odd thing is, I'm actually seeing the `cycleCharts()` get a `chartId` argument even when it's called from `setInterval`! The `setInterval` doesn't even have any parameters to pass along to the `cycleCharts` function, so I'm very baffled as to why `chartId` is not undefined when `cycleCharts` is called from the `setInterval`.
setInterval is feeding cycleCharts actual timing data ( so one can work out the actual time it ran and use to produce a less stilted response, mostly practical in animation ) you want ``` var cycleId = setInterval(function(){ cycleCharts(); }, 10000); ``` ( this behavior may not be standardized, so don't rely on it too heavily )
86,271
<p>I am attempting to find xml files with large swaths of commented out xml. I would like to programmatically search for xml comments that stretch beyond a given number of lines. Is there an easy way of doing this?</p>
[ { "answer_id": 86332, "author": "Sam", "author_id": 9406, "author_profile": "https://Stackoverflow.com/users/9406", "pm_score": 1, "selected": false, "text": "<p>Considering that XML doesn't use a line based format, you should probably check the number of characters. With a regular expre...
2008/09/17
[ "https://Stackoverflow.com/questions/86271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am attempting to find xml files with large swaths of commented out xml. I would like to programmatically search for xml comments that stretch beyond a given number of lines. Is there an easy way of doing this?
Considering that XML doesn't use a line based format, you should probably check the number of characters. With a regular expression, you can create a pattern to match the comment prefix and match a minimum number of characters before it matches the first comment suffix. <http://www.regular-expressions.info/> Here is the pattern that worked in some preliminary tests: ``` <!-- (.[^-->]|[\r\n][^-->]){5}(.[^-->]|[\r\n][^-->])*? --> ``` It will match the starting comment prefix and everything including newline character (on a windows OS) and it's lazy so it will stop at the first comment suffix. Sorry for the edits, you are correct here is an updated pattern. It's obviously not optimized, but in some tests it seems to resolve the error you pointed out.
86,292
<p>I would much prefer to do this without catching an exception in <code>LoadXml()</code> and using this results as part of my logic. Any ideas for a solution that doesn't involve manually parsing the xml myself? I think VB has a return value of false for this function instead of throwing an XmlException. Xml input is provided from the user. Thanks much!</p> <pre><code>if (!loaded) { this.m_xTableStructure = new XmlDocument(); try { this.m_xTableStructure.LoadXml(input); loaded = true; } catch { loaded = false; } } </code></pre>
[ { "answer_id": 86330, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 4, "selected": false, "text": "<p>Using a XmlValidatingReader will prevent the exceptions, if you provide your own ValidationEventHandler.</p>\n" },...
2008/09/17
[ "https://Stackoverflow.com/questions/86292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1551/" ]
I would much prefer to do this without catching an exception in `LoadXml()` and using this results as part of my logic. Any ideas for a solution that doesn't involve manually parsing the xml myself? I think VB has a return value of false for this function instead of throwing an XmlException. Xml input is provided from the user. Thanks much! ``` if (!loaded) { this.m_xTableStructure = new XmlDocument(); try { this.m_xTableStructure.LoadXml(input); loaded = true; } catch { loaded = false; } } ```
Just catch the exception. The small overhead from catching an exception drowns compared to parsing the XML. If you want the function (for stylistic reasons, not for performance), implement it yourself: ``` public class MyXmlDocument: XmlDocument { bool TryParseXml(string xml){ try{ ParseXml(xml); return true; }catch(XmlException e){ return false; } } ```
86,365
<p>Suppose I have a class module <code>clsMyClass</code> with an object as a member variable. Listed below are two complete implementations of this very simple class.</p> <p>Implementation 1:</p> <pre><code>Dim oObj As New clsObject </code></pre> <p>Implementation 2:</p> <pre><code>Dim oObj As clsObject Private Sub Class_Initialize() Set oObj = New clsObject End Sub Private Sub Class_Terminate() Set oObj = Nothing End Sub </code></pre> <p>Is there any functional difference between these two? In particular, is the lifetime of <code>oObj</code> the same?</p>
[ { "answer_id": 86390, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>If in implementation 1 the declaration is inside the class and not a sub, yes the scope is the same for both exa...
2008/09/17
[ "https://Stackoverflow.com/questions/86365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/863/" ]
Suppose I have a class module `clsMyClass` with an object as a member variable. Listed below are two complete implementations of this very simple class. Implementation 1: ``` Dim oObj As New clsObject ``` Implementation 2: ``` Dim oObj As clsObject Private Sub Class_Initialize() Set oObj = New clsObject End Sub Private Sub Class_Terminate() Set oObj = Nothing End Sub ``` Is there any functional difference between these two? In particular, is the lifetime of `oObj` the same?
In implementation 1 the clsObject will not get instantiated until it is used. If it is never used, then the clsObject.Class\_Initialize event will never fire. In implementation 2, the clsObject instance will be created at the same time that the clsMyClass is instantiated. The clsObject.Class\_Initialize will always be executed if clsMyClass is created.
86,402
<p>Is my best be going to be a shell script which replaces symlinks with copies, or is there another way of telling Git to follow symlinks?</p> <p>PS: I know it's not very secure, but I only want to do it in a few specific cases.</p>
[ { "answer_id": 86459, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 7, "selected": true, "text": "<p><strong>NOTE:</strong> This advice is now out-dated as per comment since Git 1.6.1. Git used to behave this way, and...
2008/09/17
[ "https://Stackoverflow.com/questions/86402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15368/" ]
Is my best be going to be a shell script which replaces symlinks with copies, or is there another way of telling Git to follow symlinks? PS: I know it's not very secure, but I only want to do it in a few specific cases.
**NOTE:** This advice is now out-dated as per comment since Git 1.6.1. Git used to behave this way, and no longer does. --- Git by default attempts to store symlinks instead of following them (for compactness, and it's generally what people want). However, I accidentally managed to get it to add files beyond the symlink when the symlink is a directory. I.e.: ``` /foo/ /foo/baz /bar/foo --> /foo /bar/foo/baz ``` by doing ``` git add /bar/foo/baz ``` it appeared to work when I tried it. That behavior was however unwanted by me at the time, so I can't give you information beyond that.
86,408
<p>Let's say I have an aspx page with this calendar control:</p> <pre><code>&lt;asp:Calendar ID="Calendar1" runat="server" SelectedDate="" &gt;&lt;/asp:Calendar&gt; </code></pre> <p>Is there anything I can put in for SelectedDate to make it use the current date by default, without having to use the code-behind?</p>
[ { "answer_id": 86543, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 5, "selected": true, "text": "<p>If you are already doing databinding:</p>\n\n<pre><code>&lt;asp:Calendar ID=\"Calendar1\" runat=\"server\" Selected...
2008/09/17
[ "https://Stackoverflow.com/questions/86408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
Let's say I have an aspx page with this calendar control: ``` <asp:Calendar ID="Calendar1" runat="server" SelectedDate="" ></asp:Calendar> ``` Is there anything I can put in for SelectedDate to make it use the current date by default, without having to use the code-behind?
If you are already doing databinding: ``` <asp:Calendar ID="Calendar1" runat="server" SelectedDate="<%# DateTime.Today %>" /> ``` Will do it. This does require that somewhere you are doing a Page.DataBind() call (or a databind call on a parent control). If you are not doing that and you absolutely do not want any codebehind on the page, then you'll have to create a usercontrol that contains a calendar control and sets its selecteddate.
86,413
<p>What is the best way to create a fixed width file in C#. I have a bunch of fields with lengths to write out. Say 20,80.10,2 etc all left aligned. Is there an easy way to do this? </p>
[ { "answer_id": 86445, "author": "artur02", "author_id": 13937, "author_profile": "https://Stackoverflow.com/users/13937", "pm_score": 0, "selected": false, "text": "<p>Can't you use standard text file? You can read back data line by line.</p>\n" }, { "answer_id": 86452, "auth...
2008/09/17
[ "https://Stackoverflow.com/questions/86413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
What is the best way to create a fixed width file in C#. I have a bunch of fields with lengths to write out. Say 20,80.10,2 etc all left aligned. Is there an easy way to do this?
You can use string.Format to easily pad a value with spaces e.g. ``` string a = String.Format("|{0,5}|{1,5}|{2,5}", 1, 20, 300); string b = String.Format("|{0,-5}|{1,-5}|{2,-5}", 1, 20, 300); // 'a' will be equal to "| 1| 20| 300|" // 'b' will be equal to "|1 |20 |300 |" ```
86,417
<p>I have a custom (code-based) workflow, deployed in WSS via features in a .wsp file. The workflow is configured with a custom task content type (ie, the Workflow element contains a TaskListContentTypeId attribute). This content type's declaration contains a FormUrls element pointing to a custom task edit page.</p> <p>When the workflow attempts to create a task, the workflow throws this exception:</p> <p><code>Invalid field name. {17ca3a22-fdfe-46eb-99b5-9646baed3f16</code></p> <p>This is the ID of the FormURN site column. I thought FormURN is only used for InfoPath forms, not regular aspx forms...</p> <p>Does anyone have any idea how to solve this, so I can create tasks in my workflow?</p>
[ { "answer_id": 86445, "author": "artur02", "author_id": 13937, "author_profile": "https://Stackoverflow.com/users/13937", "pm_score": 0, "selected": false, "text": "<p>Can't you use standard text file? You can read back data line by line.</p>\n" }, { "answer_id": 86452, "auth...
2008/09/17
[ "https://Stackoverflow.com/questions/86417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5782/" ]
I have a custom (code-based) workflow, deployed in WSS via features in a .wsp file. The workflow is configured with a custom task content type (ie, the Workflow element contains a TaskListContentTypeId attribute). This content type's declaration contains a FormUrls element pointing to a custom task edit page. When the workflow attempts to create a task, the workflow throws this exception: `Invalid field name. {17ca3a22-fdfe-46eb-99b5-9646baed3f16` This is the ID of the FormURN site column. I thought FormURN is only used for InfoPath forms, not regular aspx forms... Does anyone have any idea how to solve this, so I can create tasks in my workflow?
You can use string.Format to easily pad a value with spaces e.g. ``` string a = String.Format("|{0,5}|{1,5}|{2,5}", 1, 20, 300); string b = String.Format("|{0,-5}|{1,-5}|{2,-5}", 1, 20, 300); // 'a' will be equal to "| 1| 20| 300|" // 'b' will be equal to "|1 |20 |300 |" ```
86,428
<p>I would like to reload an <code>&lt;iframe&gt;</code> using JavaScript. The best way I found until now was set the iframe’s <code>src</code> attribute to itself, but this isn’t very clean. Any ideas?</p>
[ { "answer_id": 86441, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 4, "selected": false, "text": "<pre><code>window.frames['frameNameOrIndex'].location.reload();\n</code></pre>\n" }, { "answer_id": 86771, "aut...
2008/09/17
[ "https://Stackoverflow.com/questions/86428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8276/" ]
I would like to reload an `<iframe>` using JavaScript. The best way I found until now was set the iframe’s `src` attribute to itself, but this isn’t very clean. Any ideas?
``` document.getElementById('some_frame_id').contentWindow.location.reload(); ``` be careful, in Firefox, `window.frames[]` cannot be indexed by id, but by name or index
86,435
<p>I'm receiving feedback from a developer that "The only way visual basic (6) can deal with a UNC path is to map it to a drive." Is this accurate? And, if so, what's the underlying issue and are there any alternatives other than a mapped drive?</p>
[ { "answer_id": 86463, "author": "Mike L", "author_id": 12085, "author_profile": "https://Stackoverflow.com/users/12085", "pm_score": 3, "selected": false, "text": "<p>We have a legacy VB6 app that uses UNC to build a connection string, so I know VB6 can do it. Often, you'll find permiss...
2008/09/17
[ "https://Stackoverflow.com/questions/86435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5199/" ]
I'm receiving feedback from a developer that "The only way visual basic (6) can deal with a UNC path is to map it to a drive." Is this accurate? And, if so, what's the underlying issue and are there any alternatives other than a mapped drive?
Here is one way that works. ``` Sub Main() Dim fs As New FileSystemObject ' Add Reference to Microsoft Scripting Runtime MsgBox fs.FileExists("\\server\folder\file.ext") End Sub ```
86,477
<p>In JavaScript:</p> <pre><code>encodeURIComponent("©√") == "%C2%A9%E2%88%9A" </code></pre> <p>Is there an equivalent for C# applications? For escaping HTML characters I used:</p> <pre><code>txtOut.Text = Regex.Replace(txtIn.Text, @"[\u0080-\uFFFF]", m =&gt; @"&amp;#" + ((int)m.Value[0]).ToString() + ";"); </code></pre> <p>But I'm not sure how to convert the match to the correct hexadecimal format that JS uses. For example this code:</p> <pre><code>txtOut.Text = Regex.Replace(txtIn.Text, @"[\u0080-\uFFFF]", m =&gt; @"%" + String.Format("{0:x}", ((int)m.Value[0]))); </code></pre> <p>Returns "<code>%a9%221a"</code> for <code>"©√"</code> instead of <code>"%C2%A9%E2%88%9A"</code>. It looks like I need to split the string up into bytes or something.</p> <p>Edit: This is for a windows app, the only items available in <code>System.Web</code> are: <code>AspNetHostingPermission</code>, <code>AspNetHostingPermissionAttribute</code>, and <code>AspNetHostingPermissionLevel</code>.</p>
[ { "answer_id": 86484, "author": "David Thibault", "author_id": 5903, "author_profile": "https://Stackoverflow.com/users/5903", "pm_score": 4, "selected": false, "text": "<p><code>HttpUtility.HtmlEncode</code> / Decode<br>\n<code>HttpUtility.UrlEncode</code> / Decode</p>\n\n<p>You can add...
2008/09/17
[ "https://Stackoverflow.com/questions/86477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1414/" ]
In JavaScript: ``` encodeURIComponent("©√") == "%C2%A9%E2%88%9A" ``` Is there an equivalent for C# applications? For escaping HTML characters I used: ``` txtOut.Text = Regex.Replace(txtIn.Text, @"[\u0080-\uFFFF]", m => @"&#" + ((int)m.Value[0]).ToString() + ";"); ``` But I'm not sure how to convert the match to the correct hexadecimal format that JS uses. For example this code: ``` txtOut.Text = Regex.Replace(txtIn.Text, @"[\u0080-\uFFFF]", m => @"%" + String.Format("{0:x}", ((int)m.Value[0]))); ``` Returns "`%a9%221a"` for `"©√"` instead of `"%C2%A9%E2%88%9A"`. It looks like I need to split the string up into bytes or something. Edit: This is for a windows app, the only items available in `System.Web` are: `AspNetHostingPermission`, `AspNetHostingPermissionAttribute`, and `AspNetHostingPermissionLevel`.
`Uri.EscapeDataString` or `HttpUtility.UrlEncode` is the correct way to escape a string meant to be part of a URL. Take for example the string `"Stack Overflow"`: * `HttpUtility.UrlEncode("Stack Overflow")` --> `"Stack+Overflow"` * `Uri.EscapeUriString("Stack Overflow")` --> `"Stack%20Overflow"` * `Uri.EscapeDataString("Stack + Overflow")` --> Also encodes `"+" to "%2b"` ---->`Stack%20%2B%20%20Overflow` Only the last is correct when used as an actual part of the URL (as opposed to the value of one of the query string parameters)
86,491
<p>ASP.NET 2.0 provides the <code>ClientScript.RegisterClientScriptBlock()</code> method for registering JavaScript in an ASP.NET Page.</p> <p>The issue I'm having is passing the script when it's located in another directory. Specifically, the following syntax does not work:</p> <pre><code>ClientScript.RegisterClientScriptBlock(this.GetType(), "scriptName", "../dir/subdir/scriptName.js", true); </code></pre> <p>Instead of dropping the code into the page like <a href="http://msdn.microsoft.com/en-us/library/aa479390.aspx#javawasp2_topic7" rel="nofollow noreferrer">this page</a> says it should, it instead displays <code>../dir/subdir/script.js</code> , my question is this:</p> <p>Has anyone dealt with this before, and found a way to drop in the javascript in a separate file? Am I going about this the wrong way?</p>
[ { "answer_id": 86496, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": -1, "selected": false, "text": "<p>Your script value has to be a full script, so put in the following for your script value.</p>\n\n<pre><code>&lt...
2008/09/17
[ "https://Stackoverflow.com/questions/86491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16587/" ]
ASP.NET 2.0 provides the `ClientScript.RegisterClientScriptBlock()` method for registering JavaScript in an ASP.NET Page. The issue I'm having is passing the script when it's located in another directory. Specifically, the following syntax does not work: ``` ClientScript.RegisterClientScriptBlock(this.GetType(), "scriptName", "../dir/subdir/scriptName.js", true); ``` Instead of dropping the code into the page like [this page](http://msdn.microsoft.com/en-us/library/aa479390.aspx#javawasp2_topic7) says it should, it instead displays `../dir/subdir/script.js` , my question is this: Has anyone dealt with this before, and found a way to drop in the javascript in a separate file? Am I going about this the wrong way?
What you're after is: ``` ClientScript.RegisterClientScriptInclude(this.GetType(), "scriptName", "../dir/subdir/scriptName.js") ```
86,515
<p>I'm using CVS on Windows (with the WinCVS front end), and would like to add details of the last check in to the email from our automated build process, whenever a build fails, in order to make it easier to fix.</p> <p>I need to know the files that have changed, the user that changed them, and the comment.</p> <p>I've been trying to work out the command line options, but never seem to get accurate results (either get too many result rather than just from one checkin, or details of some random check in from two weeks ago)</p>
[ { "answer_id": 86547, "author": "Zathrus", "author_id": 16220, "author_profile": "https://Stackoverflow.com/users/16220", "pm_score": 1, "selected": false, "text": "<p>CVS does not provide this capability. You can, however, get it by buying a license for <a href=\"http://www.atlassian.co...
2008/09/17
[ "https://Stackoverflow.com/questions/86515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1078/" ]
I'm using CVS on Windows (with the WinCVS front end), and would like to add details of the last check in to the email from our automated build process, whenever a build fails, in order to make it easier to fix. I need to know the files that have changed, the user that changed them, and the comment. I've been trying to work out the command line options, but never seem to get accurate results (either get too many result rather than just from one checkin, or details of some random check in from two weeks ago)
Wow. I'd forgotten how hard this is to do. What I'd done before was a two stage process. Firstly, running ``` cvs history -c -a -D "7 days ago" | gawk '{ print "$1 == \"" $6 "\" && $2 == \"" $8 "/" $7 "\" { print \"" $2 " " $3 " " $6 " " $5 " " $8 "/" $7 "\"; next }" }' > /tmp/$$.awk ``` to gather information about all checkins in the previous 7 days and to generate a script that would be used to create a part of the email that was sent. I then trawled the CVS/Entries file in the directory that contained the broken file(s) to get more info. Mungeing the two together allowed me to finger the culprit and send an email to them notifying them that they'de broken the build. Sorry that this answer isn't as complete as I'd hoped.
86,526
<p>I have an Ant script that performs a copy operation using the <a href="http://ant.apache.org/manual/Tasks/copy.html" rel="noreferrer">'copy' task</a>. It was written for Windows, and has a hardcoded C:\ path as the 'todir' argument. I see the 'exec' task has an OS argument, is there a similar way to branch a copy based on OS?</p>
[ { "answer_id": 86593, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 1, "selected": false, "text": "<p>You can't use a variable and assign it depending on the type? You could put it in a <code>build.properties</code> file. Or...
2008/09/17
[ "https://Stackoverflow.com/questions/86526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/99021/" ]
I have an Ant script that performs a copy operation using the ['copy' task](http://ant.apache.org/manual/Tasks/copy.html). It was written for Windows, and has a hardcoded C:\ path as the 'todir' argument. I see the 'exec' task has an OS argument, is there a similar way to branch a copy based on OS?
I would recommend putting the path in a property, then setting the property conditionally based on the current OS. ``` <condition property="foo.path" value="C:\Foo\Dir"> <os family="windows"/> </condition> <condition property="foo.path" value="/home/foo/dir"> <os family="unix"/> </condition> <fail unless="foo.path">No foo.path set for this OS!</fail> ``` As a side benefit, once it is in a property you can override it without editing the Ant script.
86,534
<p>I have a .csv file that is frequently updated (about 20 to 30 times per minute). I want to insert the newly added lines to a database as soon as they are written to the file.</p> <p>The <a href="http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx" rel="nofollow noreferrer">FileSystemWatcher</a> class listens to the file system change notifications and can raise an event whenever there is a change in a specified file. The problem is that the FileSystemWatcher cannot determine exactly which lines were added or removed (as far as I know).</p> <p>One way to read those lines is to save and compare the line count between changes and read the difference between the last and second last change. However, I am looking for a cleaner (perhaps more elegant) solution.</p>
[ { "answer_id": 86622, "author": "expedient", "author_id": 4248, "author_profile": "https://Stackoverflow.com/users/4248", "pm_score": 0, "selected": false, "text": "<p>off the top of my head, you could store the last known file size. Check against the file size, and when it changes, open...
2008/09/17
[ "https://Stackoverflow.com/questions/86534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4714/" ]
I have a .csv file that is frequently updated (about 20 to 30 times per minute). I want to insert the newly added lines to a database as soon as they are written to the file. The [FileSystemWatcher](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx) class listens to the file system change notifications and can raise an event whenever there is a change in a specified file. The problem is that the FileSystemWatcher cannot determine exactly which lines were added or removed (as far as I know). One way to read those lines is to save and compare the line count between changes and read the difference between the last and second last change. However, I am looking for a cleaner (perhaps more elegant) solution.
I've written something very similar. I used the FileSystemWatcher to get notifications about changes. I then used a FileStream to read the data (keeping track of my last position within the file and seeking to that before reading the new data). Then I add the read data to a buffer which automatically extracts complete lines and then outputs then to the UI. Note: "this.MoreData(..) is an event, the listener of which adds to the aforementioned buffer, and handles the complete line extraction. Note: As has already been mentioned, this will only work if the modifications are always additions to the file. Any deletions will cause problems. Hope this helps. ``` public void File_Changed( object source, FileSystemEventArgs e ) { lock ( this ) { if ( !this.bPaused ) { bool bMoreData = false; // Read from current seek position to end of file byte[] bytesRead = new byte[this.iMaxBytes]; FileStream fs = new FileStream( this.strFilename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite ); if ( 0 == this.iPreviousSeekPos ) { if ( this.bReadFromStart ) { if ( null != this.BeginReadStart ) { this.BeginReadStart( null, null ); } this.bReadingFromStart = true; } else { if ( fs.Length > this.iMaxBytes ) { this.iPreviousSeekPos = fs.Length - this.iMaxBytes; } } } this.iPreviousSeekPos = (int)fs.Seek( this.iPreviousSeekPos, SeekOrigin.Begin ); int iNumBytes = fs.Read( bytesRead, 0, this.iMaxBytes ); this.iPreviousSeekPos += iNumBytes; // If we haven't read all the data, then raise another event if ( this.iPreviousSeekPos < fs.Length ) { bMoreData = true; } fs.Close(); string strData = this.encoding.GetString( bytesRead ); this.MoreData( this, strData ); if ( bMoreData ) { File_Changed( null, null ); } else { if ( this.bReadingFromStart ) { this.bReadingFromStart = false; if ( null != this.EndReadStart ) { this.EndReadStart( null, null ); } } } } } ```
86,561
<p>Is there any difference to the following code:</p> <pre><code>class Foo { inline int SomeFunc() { return 42; } int AnotherFunc() { return 42; } }; </code></pre> <p>Will both functions gets inlined? Does inline actually make any difference? Are there any rules on when you should or shouldn't inline code? I often use the <code>AnotherFunc</code> syntax (accessors for example) but I rarely specify <code>inline</code> directly.</p>
[ { "answer_id": 86576, "author": "Branan", "author_id": 13894, "author_profile": "https://Stackoverflow.com/users/13894", "pm_score": 5, "selected": true, "text": "<p>Both forms should be inlined in the exact same way. Inline is implicit for function bodies defined in a class definition.<...
2008/09/17
[ "https://Stackoverflow.com/questions/86561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
Is there any difference to the following code: ``` class Foo { inline int SomeFunc() { return 42; } int AnotherFunc() { return 42; } }; ``` Will both functions gets inlined? Does inline actually make any difference? Are there any rules on when you should or shouldn't inline code? I often use the `AnotherFunc` syntax (accessors for example) but I rarely specify `inline` directly.
Both forms should be inlined in the exact same way. Inline is implicit for function bodies defined in a class definition.
86,563
<p>I'm creating a custom drop down list with AJAX dropdownextender. Inside my drop panel I have linkbuttons for my options.</p> <pre><code>&lt;asp:Label ID="ddl_Remit" runat="server" Text="Select remit address." Style="display: block; width: 300px; padding:2px; padding-right: 50px; font-family: Tahoma; font-size: 11px;" /&gt; &lt;asp:Panel ID="DropPanel" runat="server" CssClass="ContextMenuPanel" Style="display :none; visibility: hidden;"&gt; &lt;asp:LinkButton runat="server" ID="Option1z" Text="451 Stinky Place Drive &lt;br/&gt;North Nowhere, Nebraska 20503-2343 " OnClick="OnSelect" CssClass="ContextMenuItem" /&gt; &lt;asp:LinkButton runat="server" ID="Option2z" Text="451 Stinky Place Drive &lt;br/&gt;North Nowhere, Nebraska 20503-2343 " OnClick="OnSelect" CssClass="ContextMenuItem" /&gt; &lt;asp:LinkButton runat="server" ID="Option3z" Text="451 Stinky Place Drive &lt;br/&gt;North Nowhere, Nebraska 20503-2343 " OnClick="OnSelect" CssClass="ContextMenuItem" /&gt;--&gt; &lt;/asp:Panel&gt; &lt;ajaxToolkit:DropDownExtender runat="server" ID="DDE" TargetControlID="ddl_Remit" DropDownControlID="DropPanel" /&gt; </code></pre> <p>And this works well. Now what I have to do is dynamically fill this dropdownlist. Here is my best attempt:</p> <pre><code>private void fillRemitDDL() { //LinkButton Text="451 Stinky Place Drive &lt;br/&gt;North Nowhere, Nebraska 20503-2343 " OnClick="OnSelect" CssClass="ContextMenuItem" DAL_ScanlineTableAdapters.SL_GetRemitByScanlineIDTableAdapter ta = new DAL_ScanlineTableAdapters.SL_GetRemitByScanlineIDTableAdapter(); DataTable dt = (DataTable)ta.GetData(int.Parse(this.SLID)); if (dt.Rows.Count &gt; 0) { Panel ddl = this.FindControl("DropPanel") as Panel; ddl.Controls.Clear(); for (int x = 0; x &lt; dt.Rows.Count; x++) { LinkButton lb = new LinkButton(); lb.Text = dt.Rows[x]["Remit3"].ToString().Trim() + "&lt;br /&gt;" + dt.Rows[x]["Remit4"].ToString().Trim() + "&lt;br /&gt;" + dt.Rows[x]["RemitZip"].ToString().Trim(); lb.CssClass = "ContextMenuItem"; lb.Attributes.Add("onclick", "setDDL(" + lb.Text + ")"); ddl.Controls.Add(lb); } } } </code></pre> <p>My problem is that I cannot get the event to run script! I've tried the above code as well as replacing </p> <pre><code>lb.Attributes.Add("onclick", "setDDL(" + lb.Text + ")"); </code></pre> <p>with</p> <pre><code>lb.Click += new EventHandler(OnSelect); </code></pre> <p>and also </p> <pre><code>lb.OnClientClick = "setDDL(" + lb.Text + ")"); </code></pre> <p>I'm testing the the branches with Alerts on client-side and getting nothing.</p> <p>Edit: I would like to try adding the generic anchor but I think I can add the element to an asp.net control. Nor can I access a client-side div from server code to add it that way. I'm going to have to use some sort of control with an event. My setDLL function goes as follows:</p> <pre><code>function setDDL(var) { alert(var); document.getElementById('ctl00_ContentPlaceHolder1_Scanline1_ddl_Remit').innerText = var; } </code></pre> <p>Also I just took out the string variable in the function call (i.e. from </p> <pre><code>lb.Attributes.Add("onclick", "setDDL(" + lb.Text + ")"); </code></pre> <p>to </p> <pre><code>lb.Attributes.Add("onclick", "setDDL()"); </code></pre>
[ { "answer_id": 86675, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 2, "selected": true, "text": "<p>I'm not sure what your setDDL method does in your script but it should fire if one of the link buttons is clicke...
2008/09/17
[ "https://Stackoverflow.com/questions/86563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1491425/" ]
I'm creating a custom drop down list with AJAX dropdownextender. Inside my drop panel I have linkbuttons for my options. ``` <asp:Label ID="ddl_Remit" runat="server" Text="Select remit address." Style="display: block; width: 300px; padding:2px; padding-right: 50px; font-family: Tahoma; font-size: 11px;" /> <asp:Panel ID="DropPanel" runat="server" CssClass="ContextMenuPanel" Style="display :none; visibility: hidden;"> <asp:LinkButton runat="server" ID="Option1z" Text="451 Stinky Place Drive <br/>North Nowhere, Nebraska 20503-2343 " OnClick="OnSelect" CssClass="ContextMenuItem" /> <asp:LinkButton runat="server" ID="Option2z" Text="451 Stinky Place Drive <br/>North Nowhere, Nebraska 20503-2343 " OnClick="OnSelect" CssClass="ContextMenuItem" /> <asp:LinkButton runat="server" ID="Option3z" Text="451 Stinky Place Drive <br/>North Nowhere, Nebraska 20503-2343 " OnClick="OnSelect" CssClass="ContextMenuItem" />--> </asp:Panel> <ajaxToolkit:DropDownExtender runat="server" ID="DDE" TargetControlID="ddl_Remit" DropDownControlID="DropPanel" /> ``` And this works well. Now what I have to do is dynamically fill this dropdownlist. Here is my best attempt: ``` private void fillRemitDDL() { //LinkButton Text="451 Stinky Place Drive <br/>North Nowhere, Nebraska 20503-2343 " OnClick="OnSelect" CssClass="ContextMenuItem" DAL_ScanlineTableAdapters.SL_GetRemitByScanlineIDTableAdapter ta = new DAL_ScanlineTableAdapters.SL_GetRemitByScanlineIDTableAdapter(); DataTable dt = (DataTable)ta.GetData(int.Parse(this.SLID)); if (dt.Rows.Count > 0) { Panel ddl = this.FindControl("DropPanel") as Panel; ddl.Controls.Clear(); for (int x = 0; x < dt.Rows.Count; x++) { LinkButton lb = new LinkButton(); lb.Text = dt.Rows[x]["Remit3"].ToString().Trim() + "<br />" + dt.Rows[x]["Remit4"].ToString().Trim() + "<br />" + dt.Rows[x]["RemitZip"].ToString().Trim(); lb.CssClass = "ContextMenuItem"; lb.Attributes.Add("onclick", "setDDL(" + lb.Text + ")"); ddl.Controls.Add(lb); } } } ``` My problem is that I cannot get the event to run script! I've tried the above code as well as replacing ``` lb.Attributes.Add("onclick", "setDDL(" + lb.Text + ")"); ``` with ``` lb.Click += new EventHandler(OnSelect); ``` and also ``` lb.OnClientClick = "setDDL(" + lb.Text + ")"); ``` I'm testing the the branches with Alerts on client-side and getting nothing. Edit: I would like to try adding the generic anchor but I think I can add the element to an asp.net control. Nor can I access a client-side div from server code to add it that way. I'm going to have to use some sort of control with an event. My setDLL function goes as follows: ``` function setDDL(var) { alert(var); document.getElementById('ctl00_ContentPlaceHolder1_Scanline1_ddl_Remit').innerText = var; } ``` Also I just took out the string variable in the function call (i.e. from ``` lb.Attributes.Add("onclick", "setDDL(" + lb.Text + ")"); ``` to ``` lb.Attributes.Add("onclick", "setDDL()"); ```
I'm not sure what your setDDL method does in your script but it should fire if one of the link buttons is clicked. I think you might be better off just inserting a generic html anchor though instead of a .net linkbutton as you will have no reference to the control on the server side. Then you can handle the data excahnge with your setDDL method. Furthermore you might want to quote the string you are placing inside the call to setDDL because will cause script issues (like not calling the method + page errors) given you are placing literal string data without quotes.
86,582
<p>Edit: From another question I provided an answer that has links to a lot of questions/answers about singletons: <a href="https://stackoverflow.com/questions/1008019/c-singleton-design-pattern/1008289#1008289">More info about singletons here:</a></p> <p>So I have read the thread <a href="https://stackoverflow.com/questions/11831/singletons-good-design-or-a-crutch">Singletons: good design or a crutch?</a><br> And the argument still rages.</p> <p>I see Singletons as a Design Pattern (good and bad).<br><br> The problem with Singleton is not the Pattern but rather the users (sorry everybody). Everybody and their father thinks they can implement one correctly (and from the many interviews I have done, most people can't). Also because everybody thinks they can implement a correct Singleton they abuse the Pattern and use it in situations that are not appropriate (replacing global variables with Singletons!).</p> <p>So the main questions that need to be answered are:</p> <ul> <li>When should you use a Singleton</li> <li>How do you implement a Singleton correctly</li> </ul> <p>My hope for this article is that we can collect together in a single place (rather than having to google and search multiple sites) an authoritative source of when (and then how) to use a Singleton correctly. Also appropriate would be a list of Anti-Usages and common bad implementations explaining why they fail to work and for good implementations their weaknesses.<br><br><hr></p> <p>So get the ball rolling:<br> I will hold my hand up and say this is what I use but probably has problems.<br> I like "Scott Myers" handling of the subject in his books "Effective C++"</p> <blockquote> <p>Good Situations to use Singletons (not many):</p> <ul> <li>Logging frameworks</li> <li>Thread recycling pools</li> </ul> </blockquote> <pre><code>/* * C++ Singleton * Limitation: Single Threaded Design * See: http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf * For problems associated with locking in multi threaded applications * * Limitation: * If you use this Singleton (A) within a destructor of another Singleton (B) * This Singleton (A) must be fully constructed before the constructor of (B) * is called. */ class MySingleton { private: // Private Constructor MySingleton(); // Stop the compiler generating methods of copy the object MySingleton(MySingleton const&amp; copy); // Not Implemented MySingleton&amp; operator=(MySingleton const&amp; copy); // Not Implemented public: static MySingleton&amp; getInstance() { // The only instance // Guaranteed to be lazy initialized // Guaranteed that it will be destroyed correctly static MySingleton instance; return instance; } }; </code></pre> <p>OK. Lets get some criticism and other implementations together.<br> :-)</p>
[ { "answer_id": 86609, "author": "Rob", "author_id": 9236, "author_profile": "https://Stackoverflow.com/users/9236", "pm_score": 3, "selected": false, "text": "<p>The first example isn't thread safe - if two threads call getInstance at the same time, that static is going to be a PITA. So...
2008/09/17
[ "https://Stackoverflow.com/questions/86582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14065/" ]
Edit: From another question I provided an answer that has links to a lot of questions/answers about singletons: [More info about singletons here:](https://stackoverflow.com/questions/1008019/c-singleton-design-pattern/1008289#1008289) So I have read the thread [Singletons: good design or a crutch?](https://stackoverflow.com/questions/11831/singletons-good-design-or-a-crutch) And the argument still rages. I see Singletons as a Design Pattern (good and bad). The problem with Singleton is not the Pattern but rather the users (sorry everybody). Everybody and their father thinks they can implement one correctly (and from the many interviews I have done, most people can't). Also because everybody thinks they can implement a correct Singleton they abuse the Pattern and use it in situations that are not appropriate (replacing global variables with Singletons!). So the main questions that need to be answered are: * When should you use a Singleton * How do you implement a Singleton correctly My hope for this article is that we can collect together in a single place (rather than having to google and search multiple sites) an authoritative source of when (and then how) to use a Singleton correctly. Also appropriate would be a list of Anti-Usages and common bad implementations explaining why they fail to work and for good implementations their weaknesses. --- So get the ball rolling: I will hold my hand up and say this is what I use but probably has problems. I like "Scott Myers" handling of the subject in his books "Effective C++" > > Good Situations to use Singletons (not many): > > > * Logging frameworks > * Thread recycling pools > > > ``` /* * C++ Singleton * Limitation: Single Threaded Design * See: http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf * For problems associated with locking in multi threaded applications * * Limitation: * If you use this Singleton (A) within a destructor of another Singleton (B) * This Singleton (A) must be fully constructed before the constructor of (B) * is called. */ class MySingleton { private: // Private Constructor MySingleton(); // Stop the compiler generating methods of copy the object MySingleton(MySingleton const& copy); // Not Implemented MySingleton& operator=(MySingleton const& copy); // Not Implemented public: static MySingleton& getInstance() { // The only instance // Guaranteed to be lazy initialized // Guaranteed that it will be destroyed correctly static MySingleton instance; return instance; } }; ``` OK. Lets get some criticism and other implementations together. :-)
Answer: Use a Singleton if: * You need to have one and only one object of a type in system Do not use a Singleton if: * You want to save memory * You want to try something new * You want to show off how much you know * Because everyone else is doing it (See [cargo cult programmer](http://en.wikipedia.org/wiki/Cargo_cult_programming) in wikipedia) * In user interface widgets * It is supposed to be a cache * In strings * In Sessions * I can go all day long How to create the best singleton: * The smaller, the better. I am a minimalist * Make sure it is thread safe * Make sure it is never null * Make sure it is created only once * Lazy or system initialization? Up to your requirements * Sometimes the OS or the JVM creates singletons for you (e.g. in Java every class definition is a singleton) * Provide a destructor or somehow figure out how to dispose resources * Use little memory
86,607
<p>I have two classes, and want to include a static instance of one class inside the other and access the static fields from the second class via the first. </p> <p>This is so I can have non-identical instances with the same name. </p> <pre><code>Class A { public static package1.Foo foo; } Class B { public static package2.Foo foo; } //package1 Foo { public final static int bar = 1; } // package2 Foo { public final static int bar = 2; } // usage assertEquals(A.foo.bar, 1); assertEquals(B.foo.bar, 2); </code></pre> <p>This works, but I get a warning "The static field Foo.bar shoudl be accessed in a static way". Can someone explain why this is and offer a "correct" implementation.</p> <p>I realize I could access the static instances directly, but if you have a long package hierarchy, that gets ugly:</p> <pre><code>assertEquals(net.FooCorp.divisions.A.package.Foo.bar, 1); assertEquals(net.FooCorp.divisions.B.package.Foo.bar, 2); </code></pre>
[ { "answer_id": 86625, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 3, "selected": false, "text": "<p>You should use:</p>\n\n<pre><code>Foo.bar\n</code></pre>\n\n<p>And not:</p>\n\n<pre><code>A.foo.bar\n</code></pre>\n\n...
2008/09/17
[ "https://Stackoverflow.com/questions/86607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12982/" ]
I have two classes, and want to include a static instance of one class inside the other and access the static fields from the second class via the first. This is so I can have non-identical instances with the same name. ``` Class A { public static package1.Foo foo; } Class B { public static package2.Foo foo; } //package1 Foo { public final static int bar = 1; } // package2 Foo { public final static int bar = 2; } // usage assertEquals(A.foo.bar, 1); assertEquals(B.foo.bar, 2); ``` This works, but I get a warning "The static field Foo.bar shoudl be accessed in a static way". Can someone explain why this is and offer a "correct" implementation. I realize I could access the static instances directly, but if you have a long package hierarchy, that gets ugly: ``` assertEquals(net.FooCorp.divisions.A.package.Foo.bar, 1); assertEquals(net.FooCorp.divisions.B.package.Foo.bar, 2); ```
I agree with others that you're probably thinking about this the wrong way. With that out of the way, this may work for you if you are only accessing static members: ``` public class A { public static class Foo extends package1.Foo {} } public class B { public static class Foo extends package2.Foo {} } ```
86,653
<p>I would like my JSON output in Ruby on Rails to be "pretty" or nicely formatted. </p> <p>Right now, I call <code>to_json</code> and my JSON is all on one line. At times this can be difficult to see if there is a problem in the JSON output stream.</p> <p>Is there way to configure to make my JSON "pretty" or nicely formatted in Rails?</p>
[ { "answer_id": 1823885, "author": "lambshaanxy", "author_id": 218340, "author_profile": "https://Stackoverflow.com/users/218340", "pm_score": 11, "selected": true, "text": "<p>Use the <code>pretty_generate()</code> function, built into later versions of JSON. For example:</p>\n\n<pre><co...
2008/09/17
[ "https://Stackoverflow.com/questions/86653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10333/" ]
I would like my JSON output in Ruby on Rails to be "pretty" or nicely formatted. Right now, I call `to_json` and my JSON is all on one line. At times this can be difficult to see if there is a problem in the JSON output stream. Is there way to configure to make my JSON "pretty" or nicely formatted in Rails?
Use the `pretty_generate()` function, built into later versions of JSON. For example: ``` require 'json' my_object = { :array => [1, 2, 3, { :sample => "hash"} ], :foo => "bar" } puts JSON.pretty_generate(my_object) ``` Which gets you: ``` { "array": [ 1, 2, 3, { "sample": "hash" } ], "foo": "bar" } ```
86,685
<p>I am having a really hard time attempting to debug LINQ to SQL and submitting changes.</p> <p>I have been using <a href="http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx" rel="noreferrer">http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx</a>, which works great for debugging simple queries.</p> <p>I'm working in the DataContext Class for my project with the following snippet from my application:</p> <pre><code>JobMaster newJobToCreate = new JobMaster(); newJobToCreate.JobID = 9999 newJobToCreate.ProjectID = "New Project"; this.UpdateJobMaster(newJobToCreate); this.SubmitChanges(); </code></pre> <p>I will catch some very odd exceptions when I run this.SubmitChanges;</p> <pre><code>Index was outside the bounds of the array. </code></pre> <p>The stack trace goes places I cannot step into:</p> <pre><code>at System.Data.Linq.IdentityManager.StandardIdentityManager.MultiKeyManager`3.TryCreateKeyFromValues(Object[] values, MultiKey`2&amp; k) at System.Data.Linq.IdentityManager.StandardIdentityManager.IdentityCache`2.Find(Object[] keyValues) at System.Data.Linq.IdentityManager.StandardIdentityManager.Find(MetaType type, Object[] keyValues) at System.Data.Linq.CommonDataServices.GetCachedObject(MetaType type, Object[] keyValues) at System.Data.Linq.ChangeProcessor.GetOtherItem(MetaAssociation assoc, Object instance) at System.Data.Linq.ChangeProcessor.BuildEdgeMaps() at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) at System.Data.Linq.DataContext.SubmitChanges() at JobTrakDataContext.CreateNewJob(NewJob job, String userName) in D:\JobTrakDataContext.cs:line 1119 </code></pre> <p>Does anyone have any tools or techniques they use? Am I missing something simple?</p> <p><strong>EDIT</strong>: I've setup .net debugging using Slace's suggestion, however the .net 3.5 code is not yet available: <a href="http://referencesource.microsoft.com/netframework.aspx" rel="noreferrer">http://referencesource.microsoft.com/netframework.aspx</a></p> <p><strong>EDIT2</strong>: I've changed to InsertOnSubmit as per sirrocco's suggestion, still getting the same error.</p> <p><strong>EDIT3:</strong> I've implemented Sam's suggestions trying to log the SQL generated and to catch the ChangeExceptoinException. These suggestions do not shed any more light, I'm never actually getting to generate SQL when my exception is being thrown.</p> <p><strong>EDIT4:</strong> I found an answer that works for me below. Its just a theory but it has fixed my current issue.</p>
[ { "answer_id": 86704, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 1, "selected": false, "text": "<p>A simple solution could be to run a trace on your database and inspect the queries run against it - filt...
2008/09/17
[ "https://Stackoverflow.com/questions/86685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7561/" ]
I am having a really hard time attempting to debug LINQ to SQL and submitting changes. I have been using <http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx>, which works great for debugging simple queries. I'm working in the DataContext Class for my project with the following snippet from my application: ``` JobMaster newJobToCreate = new JobMaster(); newJobToCreate.JobID = 9999 newJobToCreate.ProjectID = "New Project"; this.UpdateJobMaster(newJobToCreate); this.SubmitChanges(); ``` I will catch some very odd exceptions when I run this.SubmitChanges; ``` Index was outside the bounds of the array. ``` The stack trace goes places I cannot step into: ``` at System.Data.Linq.IdentityManager.StandardIdentityManager.MultiKeyManager`3.TryCreateKeyFromValues(Object[] values, MultiKey`2& k) at System.Data.Linq.IdentityManager.StandardIdentityManager.IdentityCache`2.Find(Object[] keyValues) at System.Data.Linq.IdentityManager.StandardIdentityManager.Find(MetaType type, Object[] keyValues) at System.Data.Linq.CommonDataServices.GetCachedObject(MetaType type, Object[] keyValues) at System.Data.Linq.ChangeProcessor.GetOtherItem(MetaAssociation assoc, Object instance) at System.Data.Linq.ChangeProcessor.BuildEdgeMaps() at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) at System.Data.Linq.DataContext.SubmitChanges() at JobTrakDataContext.CreateNewJob(NewJob job, String userName) in D:\JobTrakDataContext.cs:line 1119 ``` Does anyone have any tools or techniques they use? Am I missing something simple? **EDIT**: I've setup .net debugging using Slace's suggestion, however the .net 3.5 code is not yet available: <http://referencesource.microsoft.com/netframework.aspx> **EDIT2**: I've changed to InsertOnSubmit as per sirrocco's suggestion, still getting the same error. **EDIT3:** I've implemented Sam's suggestions trying to log the SQL generated and to catch the ChangeExceptoinException. These suggestions do not shed any more light, I'm never actually getting to generate SQL when my exception is being thrown. **EDIT4:** I found an answer that works for me below. Its just a theory but it has fixed my current issue.
First, thanks everyone for the help, I finally found it. The solution was to drop the .dbml file from the project, add a blank .dbml file and repopulate it with the tables needed for my project from the 'Server Explorer'. I noticed a couple of things while I was doing this: * There are a few tables in the system named with two words and a space in between the words, i.e. 'Job Master'. When I was pulling that table back into the .dbml file it would create a table called 'Job\_Master', it would replace the space with an underscore. * In the orginal .dbml file one of my developers had gone through the .dbml file and removed all of the underscores, thus 'Job\_Master' would become 'JobMaster' in the .dbml file. In code we could then refer to the table in a more, for us, standard naming convention. * My theory is that somewhere, the translation from 'JobMaster' to 'Job Master' while was lost while doing the projection, and I kept coming up with the array out of bounds error. It is only a theory. If someone can better explain it I would love to have a concrete answer here.
86,726
<p>I have the following type :</p> <pre><code>// incomplete class definition public class Person { private string name; public string Name { get { return this.name; } } } </code></pre> <p>I want this type to be <strong>created</strong> and <strong>updated</strong> with some sort of dedicated controller/builder, but I want it to remain <strong>read-only for other types</strong>.</p> <p>This object also needs to fire an event every time it is updated by its controller/builder.</p> <p>To summary, according to the previous type definition skeleton :</p> <ul> <li>The <code>Person</code> could only be instantiated by a specific controller</li> <li>This controller could <strong>update</strong> the state of the <code>Person</code> (<code>name</code> field) at any time</li> <li>The <code>Person</code> need to send a <strong>notification</strong> to the rest of the world when it occurs</li> <li>All other types should only be able to <strong>read</strong> <code>Person</code> attributes</li> </ul> <p>How should I implement this ? I'm talking about a controller/builder here, but all others solutions are welcome.</p> <p>Note : <em>I would be able to rely on the <code>internal</code> modifier, but ideally all my stuff should be in the same assembly.</em></p>
[ { "answer_id": 86753, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 1, "selected": false, "text": "<p>I like to have a read-only interface. Then the builder/controller/whatever can reference the object directly, but when...
2008/09/17
[ "https://Stackoverflow.com/questions/86726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4687/" ]
I have the following type : ``` // incomplete class definition public class Person { private string name; public string Name { get { return this.name; } } } ``` I want this type to be **created** and **updated** with some sort of dedicated controller/builder, but I want it to remain **read-only for other types**. This object also needs to fire an event every time it is updated by its controller/builder. To summary, according to the previous type definition skeleton : * The `Person` could only be instantiated by a specific controller * This controller could **update** the state of the `Person` (`name` field) at any time * The `Person` need to send a **notification** to the rest of the world when it occurs * All other types should only be able to **read** `Person` attributes How should I implement this ? I'm talking about a controller/builder here, but all others solutions are welcome. Note : *I would be able to rely on the `internal` modifier, but ideally all my stuff should be in the same assembly.*
Create an interface IReadOnlyPerson which exposes only get accessors. Have Person implement IReadOnlyPerson. Store the reference to Person in your controller. Give other clients only the read only version. This will protect against mistakes, but not fraud, as with most OO features. Clients can runtime cast to Person if they happen to know (or suspect) IReadOnlyPerson is implemented by Person. **Update, per the comment:** The Read Only interface may also expose an event delegate, just like any other object. The idiom generally used in C# doesn't prevent clients from messing with the list of listeners, but convention is only to add listeners, so that should be adequate. Inside any set accessor or function with state-changing side effects, just call the event delegate with a guard for the null (no listeners) case.
86,763
<p>I'm trying to create a build script for my current project, which includes an Excel Add-in. The Add-in contains a VBProject with a file modGlobal with a variable version_Number. This number needs to be changed for every build. The exact steps:</p> <ol> <li>Open XLA document with Excel.</li> <li>Switch to VBEditor mode. (Alt+F11)</li> <li>Open VBProject, entering a password.</li> <li>Open modGlobal file.</li> <li>Change variable's default value to the current date.</li> <li>Close &amp; save the project.</li> </ol> <p>I'm at a loss for how to automate the process. The best I can come up with is an excel macro or Auto-IT script. I could also write a custom MSBuild task, but that might get... tricky. Does anyone else have any other suggestions?</p>
[ { "answer_id": 89121, "author": "Mark Nold", "author_id": 4134, "author_profile": "https://Stackoverflow.com/users/4134", "pm_score": 1, "selected": false, "text": "<p>I'm not 100% sure how to do exactly what you have requested. But guessing the goal you have in mind there are a few poss...
2008/09/17
[ "https://Stackoverflow.com/questions/86763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1390/" ]
I'm trying to create a build script for my current project, which includes an Excel Add-in. The Add-in contains a VBProject with a file modGlobal with a variable version\_Number. This number needs to be changed for every build. The exact steps: 1. Open XLA document with Excel. 2. Switch to VBEditor mode. (Alt+F11) 3. Open VBProject, entering a password. 4. Open modGlobal file. 5. Change variable's default value to the current date. 6. Close & save the project. I'm at a loss for how to automate the process. The best I can come up with is an excel macro or Auto-IT script. I could also write a custom MSBuild task, but that might get... tricky. Does anyone else have any other suggestions?
An alternative way of handling versioning of an XLA file is to use a custom property in Document Properties. You can access and manipulate using COM as described here: <http://support.microsoft.com/?kbid=224351>. Advantages of this are: * You can examine the version number without opening the XLA file * You don't need Excel on your build machine - only the DsoFile.dll component Another alternative would be to store the version number (possibly other configuration data too) on a worksheet in the XLA file. The worksheet would not be visible to users of the XLA. One technique I have used in the past is to store the add-in as an XLS file in source control, then as part of the build process (e.g. in a Post-Build event) run the script below to convert it to an XLA in the output directory. This script could be easily extended to update a version number in a worksheet before saving. In my case I did this because my Excel Add-in used VSTO, and Visual Studio doesn't support XLA files directly. ``` ' ' ConvertToXla.vbs ' ' VBScript to convert an Excel spreadsheet (.xls) into an Excel Add-In (.xla) ' ' The script takes two arguments: ' ' - the name of the input XLS file. ' ' - the name of the output XLA file. ' Option Explicit Dim nResult On Error Resume Next nResult = DoAction If Err.Number <> 0 Then Wscript.Echo Err.Description Wscript.Quit 1 End If Wscript.Quit nResult Private Function DoAction() Dim sInputFile, sOutputFile Dim argNum, argCount: argCount = Wscript.Arguments.Count If argCount < 2 Then Err.Raise 1, "ConvertToXla.vbs", "Missing argument" End If sInputFile = WScript.Arguments(0) sOutputFile = WScript.Arguments(1) Dim xlApplication Set xlApplication = WScript.CreateObject("Excel.Application") On Error Resume Next ConvertFileToXla xlApplication, sInputFile, sOutputFile If Err.Number <> 0 Then Dim nErrNumber Dim sErrSource Dim sErrDescription nErrNumber = Err.Number sErrSource = Err.Source sErrDescription = Err.Description xlApplication.Quit Err.Raise nErrNumber, sErrSource, sErrDescription Else xlApplication.Quit End If End Function Public Sub ConvertFileToXla(xlApplication, sInputFile, sOutputFile) Dim xlAddIn xlAddIn = 18 ' XlFileFormat.xlAddIn Dim w Set w = xlApplication.Workbooks.Open(sInputFile,,,,,,,,,True) w.IsAddIn = True w.SaveAs sOutputFile, xlAddIn w.Close False End Sub ```
86,766
<p>Often I find myself interacting with files in some way but after writing the code I'm always uncertain how robust it actually is. The problem is that I'm not entirely sure how file related operations can fail and, therefore, the best way to handle exceptions.</p> <p>The simple solution would seem to be just to catch any <code>IOExceptions</code> thrown by the code and give the user an &quot;Inaccessible file&quot; error message, but is it possible to get a bit more fine-grained error messages? Is there a way to determine the difference between such errors as a file being locked by another program and the data being unreadable due to a hardware error?</p> <p>Given the following C# code, how would you handle errors in a user friendly (as informative as possible) way?</p> <pre><code>public class IO { public List&lt;string&gt; ReadFile(string path) { FileInfo file = new FileInfo(path); if (!file.Exists) { throw new FileNotFoundException(); } StreamReader reader = file.OpenText(); List&lt;string&gt; text = new List&lt;string&gt;(); while (!reader.EndOfStream) { text.Add(reader.ReadLine()); } reader.Close(); reader.Dispose(); return text; } public void WriteFile(List&lt;string&gt; text, string path) { FileInfo file = new FileInfo(path); if (!file.Exists) { throw new FileNotFoundException(); } StreamWriter writer = file.CreateText(); foreach(string line in text) { writer.WriteLine(line); } writer.Flush(); writer.Close(); writer.Dispose(); } } </code></pre>
[ { "answer_id": 86855, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 3, "selected": false, "text": "<p>The first thing you should change are your calls to StreamWriter and StreamReader to wrap them in a using statement, ...
2008/09/17
[ "https://Stackoverflow.com/questions/86766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4055/" ]
Often I find myself interacting with files in some way but after writing the code I'm always uncertain how robust it actually is. The problem is that I'm not entirely sure how file related operations can fail and, therefore, the best way to handle exceptions. The simple solution would seem to be just to catch any `IOExceptions` thrown by the code and give the user an "Inaccessible file" error message, but is it possible to get a bit more fine-grained error messages? Is there a way to determine the difference between such errors as a file being locked by another program and the data being unreadable due to a hardware error? Given the following C# code, how would you handle errors in a user friendly (as informative as possible) way? ``` public class IO { public List<string> ReadFile(string path) { FileInfo file = new FileInfo(path); if (!file.Exists) { throw new FileNotFoundException(); } StreamReader reader = file.OpenText(); List<string> text = new List<string>(); while (!reader.EndOfStream) { text.Add(reader.ReadLine()); } reader.Close(); reader.Dispose(); return text; } public void WriteFile(List<string> text, string path) { FileInfo file = new FileInfo(path); if (!file.Exists) { throw new FileNotFoundException(); } StreamWriter writer = file.CreateText(); foreach(string line in text) { writer.WriteLine(line); } writer.Flush(); writer.Close(); writer.Dispose(); } } ```
> > ...but is it possible to get a bit more fine-grained error messages. > > > Yes. Go ahead and catch `IOException`, and use the `Exception.ToString()` method to get a relatively relevant error message to display. Note that the exceptions generated by the .NET Framework will supply these useful strings, but if you are going to throw your own exception, you must remember to plug in that string into the `Exception`'s constructor, like: `throw new FileNotFoundException("File not found");` Also, absolutely, as per [Scott Dorman](https://stackoverflow.com/users/1559/scott-dorman), use that `using` statement. The thing to notice, though, is that the `using` statement doesn't actually `catch` anything, which is the way it ought to be. Your test to see if the file exists, for instance, will introduce a race condition that may be rather [vexing](http://blogs.msdn.com/ericlippert/archive/2008/09/10/vexing-exceptions.aspx). It doesn't really do you any good to have it in there. So, now, for the reader we have: ``` try { using (StreamReader reader = file.OpenText()) { // Your processing code here } } catch (IOException e) { UI.AlertUserSomehow(e.ToString()); } ``` In short, for basic file operations: 1. Use `using` 2, Wrap the using statement or function in a `try`/`catch` that `catch`es `IOException` 3. Use `Exception.ToString()` in your `catch` to get a useful error message 4. Don't try to detect exceptional file issues yourself. Let .NET do the throwing for you.
86,780
<p>Say I have two strings,</p> <pre><code>String s1 = "AbBaCca"; String s2 = "bac"; </code></pre> <p>I want to perform a check returning that <code>s2</code> is contained within <code>s1</code>. I can do this with:</p> <pre><code>return s1.contains(s2); </code></pre> <p>I am pretty sure that <code>contains()</code> is case sensitive, however I can't determine this for sure from reading the documentation. If it is then I suppose my best method would be something like:</p> <pre><code>return s1.toLowerCase().contains(s2.toLowerCase()); </code></pre> <p>All this aside, is there another (possibly better) way to accomplish this without caring about case-sensitivity?</p>
[ { "answer_id": 86832, "author": "Dave L.", "author_id": 3093, "author_profile": "https://Stackoverflow.com/users/3093", "pm_score": 9, "selected": true, "text": "<p>Yes, contains is case sensitive. You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive m...
2008/09/17
[ "https://Stackoverflow.com/questions/86780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2628/" ]
Say I have two strings, ``` String s1 = "AbBaCca"; String s2 = "bac"; ``` I want to perform a check returning that `s2` is contained within `s1`. I can do this with: ``` return s1.contains(s2); ``` I am pretty sure that `contains()` is case sensitive, however I can't determine this for sure from reading the documentation. If it is then I suppose my best method would be something like: ``` return s1.toLowerCase().contains(s2.toLowerCase()); ``` All this aside, is there another (possibly better) way to accomplish this without caring about case-sensitivity?
Yes, contains is case sensitive. You can use java.util.regex.Pattern with the CASE\_INSENSITIVE flag for case insensitive matching: ``` Pattern.compile(Pattern.quote(wantedStr), Pattern.CASE_INSENSITIVE).matcher(source).find(); ``` **EDIT:** If s2 contains regex special characters (of which there are many) it's important to quote it first. I've corrected my answer since it is the first one people will see, but vote up Matt Quail's since he pointed this out.
86,793
<p>If a user select all items in a .NET 2.0 ListView, the ListView will fire a <strong>SelectedIndexChanged</strong> event for every item, rather than firing an event to indicate that the <em>selection</em> has changed.</p> <p>If the user then clicks to select just one item in the list, the ListView will fire a <strong>SelectedIndexChanged</strong> event for <em>every</em> item that is getting unselected, and then an <strong>SelectedIndexChanged</strong> event for the single newly selected item, rather than firing an event to indicate that the selection has changed.</p> <p>If you have code in the <strong>SelectedIndexChanged</strong> event handler, the program will become pretty unresponsive when you begin to have a few hundred/thousand items in the list.</p> <p>I've thought about <em>dwell timers</em>, etc.</p> <p>But does anyone have a good solution to avoid thousands of needless ListView.<strong>SelectedIndexChange</strong> events, when really <strong>one event</strong> will do?</p>
[ { "answer_id": 86893, "author": "Rob", "author_id": 12413, "author_profile": "https://Stackoverflow.com/users/12413", "pm_score": 0, "selected": false, "text": "<p>I would either try tying the postback to a button to allow the user to submit their changes and unhook the event handler.</p...
2008/09/17
[ "https://Stackoverflow.com/questions/86793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
If a user select all items in a .NET 2.0 ListView, the ListView will fire a **SelectedIndexChanged** event for every item, rather than firing an event to indicate that the *selection* has changed. If the user then clicks to select just one item in the list, the ListView will fire a **SelectedIndexChanged** event for *every* item that is getting unselected, and then an **SelectedIndexChanged** event for the single newly selected item, rather than firing an event to indicate that the selection has changed. If you have code in the **SelectedIndexChanged** event handler, the program will become pretty unresponsive when you begin to have a few hundred/thousand items in the list. I've thought about *dwell timers*, etc. But does anyone have a good solution to avoid thousands of needless ListView.**SelectedIndexChange** events, when really **one event** will do?
Good solution from Ian. I took that and made it into a reusable class, making sure to dispose of the timer properly. I also reduced the interval to get a more responsive app. This control also doublebuffers to reduce flicker. ``` public class DoublebufferedListView : System.Windows.Forms.ListView { private Timer m_changeDelayTimer = null; public DoublebufferedListView() : base() { // Set common properties for our listviews if (!SystemInformation.TerminalServerSession) { DoubleBuffered = true; SetStyle(ControlStyles.ResizeRedraw, true); } } /// <summary> /// Make sure to properly dispose of the timer /// </summary> /// <param name="disposing"></param> protected override void Dispose(bool disposing) { if (disposing && m_changeDelayTimer != null) { m_changeDelayTimer.Tick -= ChangeDelayTimerTick; m_changeDelayTimer.Dispose(); } base.Dispose(disposing); } /// <summary> /// Hack to avoid lots of unnecessary change events by marshaling with a timer: /// http://stackoverflow.com/questions/86793/how-to-avoid-thousands-of-needless-listview-selectedindexchanged-events /// </summary> /// <param name="e"></param> protected override void OnSelectedIndexChanged(EventArgs e) { if (m_changeDelayTimer == null) { m_changeDelayTimer = new Timer(); m_changeDelayTimer.Tick += ChangeDelayTimerTick; m_changeDelayTimer.Interval = 40; } // When a new SelectedIndexChanged event arrives, disable, then enable the // timer, effectively resetting it, so that after the last one in a batch // arrives, there is at least 40 ms before we react, plenty of time // to wait any other selection events in the same batch. m_changeDelayTimer.Enabled = false; m_changeDelayTimer.Enabled = true; } private void ChangeDelayTimerTick(object sender, EventArgs e) { m_changeDelayTimer.Enabled = false; base.OnSelectedIndexChanged(new EventArgs()); } } ``` Do let me know if this can be improved.
86,800
<p>I've recently embarked upon the <em>grand voyage</em> of Wordpress theming and I've been reading through the Wordpress documentation for how to write a theme. One thing I came across <a href="http://codex.wordpress.org/Theme_Development" rel="nofollow noreferrer">here</a> was that the <code>style.css</code> file must contain a specific header in order to be used by the Wordpress engine. They give a brief example but I haven't been able to turn up any formal description of what must be in the <code>style.css</code> header portion. Does this exist on the Wordpress site? If it doesn't could we perhaps describe it here?</p>
[ { "answer_id": 86841, "author": "Martin", "author_id": 15840, "author_profile": "https://Stackoverflow.com/users/15840", "pm_score": 1, "selected": false, "text": "<p>You are probably thinking about this:</p>\n\n<pre><code>/*\nTHEME NAME: Parallax\nTHEME URI: http://parallaxdenigrate.net...
2008/09/17
[ "https://Stackoverflow.com/questions/86800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16562/" ]
I've recently embarked upon the *grand voyage* of Wordpress theming and I've been reading through the Wordpress documentation for how to write a theme. One thing I came across [here](http://codex.wordpress.org/Theme_Development) was that the `style.css` file must contain a specific header in order to be used by the Wordpress engine. They give a brief example but I haven't been able to turn up any formal description of what must be in the `style.css` header portion. Does this exist on the Wordpress site? If it doesn't could we perhaps describe it here?
Based on <http://codex.wordpress.org/Theme_Development>: The following is an example of the first few lines of the stylesheet, called the style sheet header, for the Theme "Rose": ``` /* Theme Name: Rose Theme URI: the-theme's-homepage Description: a-brief-description Author: your-name Author URI: your-URI Template: use-this-to-define-a-parent-theme--optional Version: a-number--optional Tags: a-comma-delimited-list--optional . General comments/License Statement if any. . */ ``` The simplest Theme includes only a style.css file, plus images if any. To create such a Theme, you must specify a set of templates to inherit for use with the Theme by editing the Template: line in the style.css header comments. For example, if you wanted the Theme "Rose" to inherit the templates from another Theme called "test", you would include Template: test in the comments at the beginning of Rose's style.css. Now "test" is the parent Theme for "Rose", which still consists only of a style.css file and the concomitant images, all located in the directory wp-content/themes/Rose. (Note that specifying a parent Theme will inherit all of the template files from that Theme — meaning that any template files in the child Theme's directory will be ignored.) The comment header lines in style.css are required for WordPress to be able to identify a Theme and display it in the Administration Panel under Design > Themes as an available Theme option along with any other installed Themes. The Theme Name, Version, Author, and Author URI fields are parsed by WordPress and used to display that data in the Current Theme area on the top line of the current theme information, where the Author's Name is hyperlinked to the Author URI. The Description and Tag fields are parsed and displayed in the body of the theme's information, and if the theme has a parent theme, that information is placed in the information body as well. In the Available Themes section, only the Theme Name, Description, and Tags fields are used. None of these fields have any restrictions - all are parsed as strings. In addition, none of them are required in the code, though in practice the fields not marked as optional in the list above are all used to provide contextual information to the WordPress administrator and should be included for all themes.
86,824
<p>I'm getting a <code>ConnectException: Connection timed out</code> with some frequency from my code. The URL I am trying to hit is up. The same code works for some users, but not others. It seems like once one user starts to get this exception they continue to get the exception.</p> <p>Here is the stack trace:</p> <pre><code>java.net.ConnectException: Connection timed out Caused by: java.net.ConnectException: Connection timed out at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182) at java.net.Socket.connect(Socket.java:516) at java.net.Socket.connect(Socket.java:466) at sun.net.NetworkClient.doConnect(NetworkClient.java:157) at sun.net.www.http.HttpClient.openServer(HttpClient.java:365) at sun.net.www.http.HttpClient.openServer(HttpClient.java:477) at sun.net.www.http.HttpClient.&lt;init&gt;(HttpClient.java:214) at sun.net.www.http.HttpClient.New(HttpClient.java:287) at sun.net.www.http.HttpClient.New(HttpClient.java:299) at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:796) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:748) at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:673) at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:840) </code></pre> <p>Here is a snippet from my code:</p> <pre><code>URLConnection urlConnection = null; OutputStream outputStream = null; OutputStreamWriter outputStreamWriter = null; InputStream inputStream = null; try { URL url = new URL(urlBase); urlConnection = url.openConnection(); urlConnection.setDoOutput(true); outputStream = urlConnection.getOutputStream(); // exception occurs on this line outputStreamWriter = new OutputStreamWriter(outputStream); outputStreamWriter.write(urlString); outputStreamWriter.flush(); inputStream = urlConnection.getInputStream(); String response = IOUtils.toString(inputStream); return processResponse(urlString, urlBase, response); } catch (IOException e) { throw new Exception("Error querying url: " + urlString, e); } finally { IoUtil.close(inputStream); IoUtil.close(outputStreamWriter); IoUtil.close(outputStream); } </code></pre>
[ { "answer_id": 86876, "author": "larsivi", "author_id": 14047, "author_profile": "https://Stackoverflow.com/users/14047", "pm_score": 0, "selected": false, "text": "<p>There is a possibility that your IP/host are blocked by the remote host, especially if it thinks you are hitting it too ...
2008/09/17
[ "https://Stackoverflow.com/questions/86824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16677/" ]
I'm getting a `ConnectException: Connection timed out` with some frequency from my code. The URL I am trying to hit is up. The same code works for some users, but not others. It seems like once one user starts to get this exception they continue to get the exception. Here is the stack trace: ``` java.net.ConnectException: Connection timed out Caused by: java.net.ConnectException: Connection timed out at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182) at java.net.Socket.connect(Socket.java:516) at java.net.Socket.connect(Socket.java:466) at sun.net.NetworkClient.doConnect(NetworkClient.java:157) at sun.net.www.http.HttpClient.openServer(HttpClient.java:365) at sun.net.www.http.HttpClient.openServer(HttpClient.java:477) at sun.net.www.http.HttpClient.<init>(HttpClient.java:214) at sun.net.www.http.HttpClient.New(HttpClient.java:287) at sun.net.www.http.HttpClient.New(HttpClient.java:299) at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:796) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:748) at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:673) at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:840) ``` Here is a snippet from my code: ``` URLConnection urlConnection = null; OutputStream outputStream = null; OutputStreamWriter outputStreamWriter = null; InputStream inputStream = null; try { URL url = new URL(urlBase); urlConnection = url.openConnection(); urlConnection.setDoOutput(true); outputStream = urlConnection.getOutputStream(); // exception occurs on this line outputStreamWriter = new OutputStreamWriter(outputStream); outputStreamWriter.write(urlString); outputStreamWriter.flush(); inputStream = urlConnection.getInputStream(); String response = IOUtils.toString(inputStream); return processResponse(urlString, urlBase, response); } catch (IOException e) { throw new Exception("Error querying url: " + urlString, e); } finally { IoUtil.close(inputStream); IoUtil.close(outputStreamWriter); IoUtil.close(outputStream); } ```
Connection timeouts (assuming a local network and several client machines) typically result from a) some kind of firewall on the way that simply eats the packets without telling the sender things like "No Route to host" b) packet loss due to wrong network configuration or line overload c) too many requests overloading the server d) a small number of simultaneously available threads/processes on the server which leads to all of them being taken. This happens especially with requests that take a long time to run and may combine with c). Hope this helps.
86,849
<p>If I have the following:</p> <pre><code>{"hdrs": ["Make","Model","Year"], "data" : [ {"Make":"Honda","Model":"Accord","Year":"2008"} {"Make":"Toyota","Model":"Corolla","Year":"2008"} {"Make":"Honda","Model":"Pilot","Year":"2008"}] } </code></pre> <p>And I have a "hdrs" name (i.e. "Make"), how can I reference the <code>data</code> array instances? seems like <code>data["Make"][0]</code> should work...but unable to get the right reference</p> <p><strong>EDIT</strong> </p> <p>Sorry for the ambiguity.. I can loop through <code>hdrs</code> to get each hdr name, but I need to use each instance value of <code>hdrs</code> to find all the data elements in <code>data</code> (not sure that is any better of an explanation). and I will have it in a variable <code>t</code> since it is JSON (appreciate the re-tagging) I would like to be able to reference with something like this: <code>t.data[hdrs[i]][j]</code></p>
[ { "answer_id": 86892, "author": "Adam Weber", "author_id": 9324, "author_profile": "https://Stackoverflow.com/users/9324", "pm_score": 0, "selected": false, "text": "<p>perhaps try data[0].Make</p>\n" }, { "answer_id": 86903, "author": "Stephen Wrighton", "author_id": 751...
2008/09/17
[ "https://Stackoverflow.com/questions/86849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ]
If I have the following: ``` {"hdrs": ["Make","Model","Year"], "data" : [ {"Make":"Honda","Model":"Accord","Year":"2008"} {"Make":"Toyota","Model":"Corolla","Year":"2008"} {"Make":"Honda","Model":"Pilot","Year":"2008"}] } ``` And I have a "hdrs" name (i.e. "Make"), how can I reference the `data` array instances? seems like `data["Make"][0]` should work...but unable to get the right reference **EDIT** Sorry for the ambiguity.. I can loop through `hdrs` to get each hdr name, but I need to use each instance value of `hdrs` to find all the data elements in `data` (not sure that is any better of an explanation). and I will have it in a variable `t` since it is JSON (appreciate the re-tagging) I would like to be able to reference with something like this: `t.data[hdrs[i]][j]`
I had to alter your code a little: ``` var x = {"hdrs": ["Make","Model","Year"], "data" : [ {"Make":"Honda","Model":"Accord","Year":"2008"}, {"Make":"Toyota","Model":"Corolla","Year":"2008"}, {"Make":"Honda","Model":"Pilot","Year":"2008"}] }; alert( x.data[0].Make ); ``` EDIT: in response to your edit ``` var x = {"hdrs": ["Make","Model","Year"], "data" : [ {"Make":"Honda","Model":"Accord","Year":"2008"}, {"Make":"Toyota","Model":"Corolla","Year":"2008"}, {"Make":"Honda","Model":"Pilot","Year":"2008"}] }; var Header = 0; // Make for( var i = 0; i <= x.data.length - 1; i++ ) { alert( x.data[i][x.hdrs[Header]] ); } ```
86,878
<p>I am having problem that even though I specify the level to ERROR in the root tag, the specified appender logs all levels (debug, info, warn) to the file regardless the settings. I am not a Log4j expert so any help is appreciated.</p> <p>I have checked the classpath for log4j.properties (there is none) except the log4j.xml.</p> <p>Here is the log4j.xml file:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt; &lt;!DOCTYPE log4j:configuration SYSTEM &quot;log4j.dtd&quot;&gt; &lt;log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'&gt; &lt;!-- ============================== --&gt; &lt;!-- Append messages to the console --&gt; &lt;!-- ============================== --&gt; &lt;appender name=&quot;console&quot; class=&quot;org.apache.log4j.ConsoleAppender&quot;&gt; &lt;param name=&quot;Target&quot; value=&quot;System.out&quot; /&gt; &lt;layout class=&quot;org.apache.log4j.PatternLayout&quot;&gt; &lt;!-- The default pattern: Date Priority [Category] Message\n --&gt; &lt;param name=&quot;ConversionPattern&quot; value=&quot;[AC - %5p] [%d{ISO8601}] [%t] [%c{1} - %L] %m%n&quot; /&gt; &lt;/layout&gt; &lt;/appender&gt; &lt;appender name=&quot;logfile&quot; class=&quot;org.apache.log4j.RollingFileAppender&quot;&gt; &lt;param name=&quot;File&quot; value=&quot;./logs/server.log&quot; /&gt; &lt;param name=&quot;MaxFileSize&quot; value=&quot;1000KB&quot; /&gt; &lt;param name=&quot;MaxBackupIndex&quot; value=&quot;2&quot; /&gt; &lt;layout class=&quot;org.apache.log4j.PatternLayout&quot;&gt; &lt;param name=&quot;ConversionPattern&quot; value=&quot;[AC - %-5p] {%d{dd.MM.yyyy - HH.mm.ss}} %m%n&quot; /&gt; &lt;/layout&gt; &lt;/appender&gt; &lt;appender name=&quot;payloadAppender&quot; class=&quot;org.apache.log4j.RollingFileAppender&quot;&gt; &lt;param name=&quot;File&quot; value=&quot;./logs/payload.log&quot; /&gt; &lt;param name=&quot;MaxFileSize&quot; value=&quot;1000KB&quot; /&gt; &lt;param name=&quot;MaxBackupIndex&quot; value=&quot;10&quot; /&gt; &lt;layout class=&quot;org.apache.log4j.PatternLayout&quot;&gt; &lt;param name=&quot;ConversionPattern&quot; value=&quot;[AC - %-5p] {%d{dd.MM.yyyy - HH.mm.ss}} %m%n&quot; /&gt; &lt;/layout&gt; &lt;/appender&gt; &lt;appender name=&quot;errorLog&quot; class=&quot;org.apache.log4j.RollingFileAppender&quot;&gt; &lt;param name=&quot;File&quot; value=&quot;./logs/error.log&quot; /&gt; &lt;param name=&quot;MaxFileSize&quot; value=&quot;1000KB&quot; /&gt; &lt;param name=&quot;MaxBackupIndex&quot; value=&quot;10&quot; /&gt; &lt;layout class=&quot;org.apache.log4j.PatternLayout&quot;&gt; &lt;param name=&quot;ConversionPattern&quot; value=&quot;[AC - %-5p] {%d{dd.MM.yyyy - HH.mm.ss}} %m%n&quot; /&gt; &lt;/layout&gt; &lt;/appender&gt; &lt;appender name=&quot;traceLog&quot; class=&quot;org.apache.log4j.RollingFileAppender&quot;&gt; &lt;param name=&quot;File&quot; value=&quot;./logs/trace.log&quot; /&gt; &lt;param name=&quot;MaxFileSize&quot; value=&quot;1000KB&quot; /&gt; &lt;param name=&quot;MaxBackupIndex&quot; value=&quot;20&quot; /&gt; &lt;layout class=&quot;org.apache.log4j.PatternLayout&quot;&gt; &lt;param name=&quot;ConversionPattern&quot; value=&quot;[AccessControl - %-5p] {%t: %d{dd.MM.yyyy - HH.mm.ss,SSS}} %m%n&quot; /&gt; &lt;/layout&gt; &lt;/appender&gt; &lt;appender name=&quot;traceSocketAppender&quot; class=&quot;org.apache.log4j.net.SocketAppender&quot;&gt; &lt;param name=&quot;remoteHost&quot; value=&quot;localhost&quot; /&gt; &lt;param name=&quot;port&quot; value=&quot;4445&quot; /&gt; &lt;param name=&quot;locationInfo&quot; value=&quot;true&quot; /&gt; &lt;/appender&gt; &lt;logger name=&quot;TraceLogger&quot;&gt; &lt;level value=&quot;trace&quot; /&gt; &lt;!-- Set level to trace to activate tracing --&gt; &lt;appender-ref ref=&quot;traceLog&quot; /&gt; &lt;/logger&gt; &lt;logger name=&quot;org.springframework.ws.server.endpoint.interceptor&quot;&gt; &lt;level value=&quot;DEBUG&quot; /&gt; &lt;appender-ref ref=&quot;payloadAppender&quot; /&gt; &lt;/logger&gt; &lt;root&gt; &lt;level value=&quot;error&quot; /&gt; &lt;appender-ref ref=&quot;errorLog&quot; /&gt; &lt;/root&gt; &lt;/log4j:configuration&gt; </code></pre> <p>If I replace the root with another logger, then nothing gets logged at all to the specified appender.</p> <pre class="lang-xml prettyprint-override"><code>&lt;logger name=&quot;com.mydomain.logic&quot;&gt; &lt;level value=&quot;error&quot; /&gt; &lt;appender-ref ref=&quot;errorLog&quot; /&gt; &lt;/logger&gt; </code></pre>
[ { "answer_id": 86928, "author": "Asgeir S. Nilsen", "author_id": 16023, "author_profile": "https://Stackoverflow.com/users/16023", "pm_score": 3, "selected": false, "text": "<p>Two things: Check additivity and decide whether you want log events captured by more detailed levels of loggin...
2008/09/17
[ "https://Stackoverflow.com/questions/86878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15045/" ]
I am having problem that even though I specify the level to ERROR in the root tag, the specified appender logs all levels (debug, info, warn) to the file regardless the settings. I am not a Log4j expert so any help is appreciated. I have checked the classpath for log4j.properties (there is none) except the log4j.xml. Here is the log4j.xml file: ```xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'> <!-- ============================== --> <!-- Append messages to the console --> <!-- ============================== --> <appender name="console" class="org.apache.log4j.ConsoleAppender"> <param name="Target" value="System.out" /> <layout class="org.apache.log4j.PatternLayout"> <!-- The default pattern: Date Priority [Category] Message\n --> <param name="ConversionPattern" value="[AC - %5p] [%d{ISO8601}] [%t] [%c{1} - %L] %m%n" /> </layout> </appender> <appender name="logfile" class="org.apache.log4j.RollingFileAppender"> <param name="File" value="./logs/server.log" /> <param name="MaxFileSize" value="1000KB" /> <param name="MaxBackupIndex" value="2" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[AC - %-5p] {%d{dd.MM.yyyy - HH.mm.ss}} %m%n" /> </layout> </appender> <appender name="payloadAppender" class="org.apache.log4j.RollingFileAppender"> <param name="File" value="./logs/payload.log" /> <param name="MaxFileSize" value="1000KB" /> <param name="MaxBackupIndex" value="10" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[AC - %-5p] {%d{dd.MM.yyyy - HH.mm.ss}} %m%n" /> </layout> </appender> <appender name="errorLog" class="org.apache.log4j.RollingFileAppender"> <param name="File" value="./logs/error.log" /> <param name="MaxFileSize" value="1000KB" /> <param name="MaxBackupIndex" value="10" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[AC - %-5p] {%d{dd.MM.yyyy - HH.mm.ss}} %m%n" /> </layout> </appender> <appender name="traceLog" class="org.apache.log4j.RollingFileAppender"> <param name="File" value="./logs/trace.log" /> <param name="MaxFileSize" value="1000KB" /> <param name="MaxBackupIndex" value="20" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[AccessControl - %-5p] {%t: %d{dd.MM.yyyy - HH.mm.ss,SSS}} %m%n" /> </layout> </appender> <appender name="traceSocketAppender" class="org.apache.log4j.net.SocketAppender"> <param name="remoteHost" value="localhost" /> <param name="port" value="4445" /> <param name="locationInfo" value="true" /> </appender> <logger name="TraceLogger"> <level value="trace" /> <!-- Set level to trace to activate tracing --> <appender-ref ref="traceLog" /> </logger> <logger name="org.springframework.ws.server.endpoint.interceptor"> <level value="DEBUG" /> <appender-ref ref="payloadAppender" /> </logger> <root> <level value="error" /> <appender-ref ref="errorLog" /> </root> </log4j:configuration> ``` If I replace the root with another logger, then nothing gets logged at all to the specified appender. ```xml <logger name="com.mydomain.logic"> <level value="error" /> <appender-ref ref="errorLog" /> </logger> ```
The root logger resides at the top of the logger hierarchy. It is exceptional in three ways: * it always exists, * its level cannot be set to null * it cannot be retrieved by name. **The rootLogger is the father of all appenders. Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy (including rootLogger)** For example, if the `console` appender is added to the `root logger`, then all enabled logging requests will **at least** print on the console. If in addition a file appender is added to a logger, say `L`, then enabled logging requests for `L` and `L's` children will print on a file **and** on the `console`. It is possible to override this default behavior so that appender accumulation is no longer additive **by setting the additivity flag to false**. *From the log4j manual* To sum up: If you want not to propagate a logging event to the parents loggers (say rootLogger) then add the additivity flag to false in those loggers. In your case: ```xml <logger name="org.springframework.ws.server.endpoint.interceptor" additivity="false"> <level value="DEBUG" /> <appender-ref ref="payloadAppender" /> </logger> ``` In standard log4j config style (which I prefer to XML): ``` log4j.logger.org.springframework.ws.server.endpoint.interceptor = INFO, payloadAppender log4j.additivity.org.springframework.ws.server.endpoint.interceptor = false ``` Hope this helps.
86,901
<p>I would like a panel in GWT to fill the page without actually having to set the size. Is there a way to do this? Currently I have the following:</p> <pre><code>public class Main implements EntryPoint { public void onModuleLoad() { HorizontalSplitPanel split = new HorizontalSplitPanel(); //split.setSize("250px", "500px"); split.setSplitPosition("30%"); DecoratorPanel dp = new DecoratorPanel(); dp.setWidget(split); RootPanel.get().add(dp); } } </code></pre> <p>With the previous code snippet, nothing shows up. Is there a method call I am missing?</p> <p>Thanks.</p> <hr> <p><strong>UPDATE Sep 17 '08 at 20:15</strong> </p> <p>I put some buttons (explicitly set their size) on each side and that still doesn't work. I'm really surprised there isn't like a FillLayout class or a setFillLayout method or setDockStyle(DockStyle.Fill) or something like that. Maybe it's not possible? But for as popular as GWT is, I would think it would be possible.</p> <p><strong>UPDATE Sep 18 '08 at 14:38</strong> </p> <p>I have tried setting the RootPanel width and height to 100% and that still didn't work. Thanks for the suggestion though, that seemed like it maybe was going to work. Any other suggestions??</p>
[ { "answer_id": 86996, "author": "Mike Monette", "author_id": 6166, "author_profile": "https://Stackoverflow.com/users/6166", "pm_score": 0, "selected": false, "text": "<p>I think you'll need to put something on the left and/or right of the split (split.setLeftWidget(widget), split.setRig...
2008/09/17
[ "https://Stackoverflow.com/questions/86901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10333/" ]
I would like a panel in GWT to fill the page without actually having to set the size. Is there a way to do this? Currently I have the following: ``` public class Main implements EntryPoint { public void onModuleLoad() { HorizontalSplitPanel split = new HorizontalSplitPanel(); //split.setSize("250px", "500px"); split.setSplitPosition("30%"); DecoratorPanel dp = new DecoratorPanel(); dp.setWidget(split); RootPanel.get().add(dp); } } ``` With the previous code snippet, nothing shows up. Is there a method call I am missing? Thanks. --- **UPDATE Sep 17 '08 at 20:15** I put some buttons (explicitly set their size) on each side and that still doesn't work. I'm really surprised there isn't like a FillLayout class or a setFillLayout method or setDockStyle(DockStyle.Fill) or something like that. Maybe it's not possible? But for as popular as GWT is, I would think it would be possible. **UPDATE Sep 18 '08 at 14:38** I have tried setting the RootPanel width and height to 100% and that still didn't work. Thanks for the suggestion though, that seemed like it maybe was going to work. Any other suggestions??
Google has answered the main part of your question in one of their FAQs: <http://code.google.com/webtoolkit/doc/1.6/FAQ_UI.html#How_do_I_create_an_app_that_fills_the_page_vertically_when_the_b> The primary point is that you can't set height to 100%, you must do something like this: ``` final VerticalPanel vp = new VerticalPanel(); vp.add(mainPanel); vp.setWidth("100%"); vp.setHeight(Window.getClientHeight() + "px"); Window.addResizeHandler(new ResizeHandler() { public void onResize(ResizeEvent event) { int height = event.getHeight(); vp.setHeight(height + "px"); } }); RootPanel.get().add(vp); ```
86,905
<p>In <a href="https://stackoverflow.com/questions/48669/are-there-any-tools-out-there-to-compare-the-structure-of-2-web-pages">this post</a> I asked if there were any tools that compare the structure (not actual content) of 2 HTML pages. I ask because I receive HTML templates from our designers, and frequently miss minor formatting changes in my implementation. I then waste a few hours of designer time sifting through my pages to find my mistakes. </p> <p>The thread offered some good suggestions, but there was nothing that fit the bill. "Fine, then", thought I, "I'll just crank one out myself. I'm a halfway-decent developer, right?".</p> <p>Well, once I started to think about it, I couldn't quite figure out how to go about it. I can crank out a data-driven website easily enough, or do a CMS implementation, or throw documents in and out of BizTalk all day. Can't begin to figure out how to compare HTML docs.</p> <p>Well, sure, I have to read the DOM, and iterate through the nodes. I have to map the structure to some data structure (how??), and then compare them (how??). It's a development task like none I've ever attempted.</p> <p>So now that I've identified a weakness in my knowledge, I'm even more challenged to figure this out. Any suggestions on how to get started?</p> <p>clarification: the actual <i>content</i> isn't what I want to compare -- the creative guys fill their pages with <i>lorem ipsum</i>, and I use real content. Instead, I want to compare structure:</p> <pre> &lt;div class="foo"&gt;lorem ipsum&lt;div&gt;</pre> <p>is different that</p> <pre> <br/>&lt;div class="foo"&gt;<br/>&lt;p&gt;lorem ipsum&lt;p&gt;<br/>&lt;div&gt;</pre>
[ { "answer_id": 86924, "author": "Mike", "author_id": 1115144, "author_profile": "https://Stackoverflow.com/users/1115144", "pm_score": -1, "selected": false, "text": "<p>Open each page in the browser and save them as .htm files. Compare the two using windiff.</p>\n" }, { "answer...
2008/09/17
[ "https://Stackoverflow.com/questions/86905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2757/" ]
In [this post](https://stackoverflow.com/questions/48669/are-there-any-tools-out-there-to-compare-the-structure-of-2-web-pages) I asked if there were any tools that compare the structure (not actual content) of 2 HTML pages. I ask because I receive HTML templates from our designers, and frequently miss minor formatting changes in my implementation. I then waste a few hours of designer time sifting through my pages to find my mistakes. The thread offered some good suggestions, but there was nothing that fit the bill. "Fine, then", thought I, "I'll just crank one out myself. I'm a halfway-decent developer, right?". Well, once I started to think about it, I couldn't quite figure out how to go about it. I can crank out a data-driven website easily enough, or do a CMS implementation, or throw documents in and out of BizTalk all day. Can't begin to figure out how to compare HTML docs. Well, sure, I have to read the DOM, and iterate through the nodes. I have to map the structure to some data structure (how??), and then compare them (how??). It's a development task like none I've ever attempted. So now that I've identified a weakness in my knowledge, I'm even more challenged to figure this out. Any suggestions on how to get started? clarification: the actual *content* isn't what I want to compare -- the creative guys fill their pages with *lorem ipsum*, and I use real content. Instead, I want to compare structure: ``` <div class="foo">lorem ipsum<div> ``` is different that ``` <div class="foo"> <p>lorem ipsum<p> <div> ```
The DOM is a data structure - it's a tree.
86,907
<p>I'm using exim on both the sending and relay hosts, the sending host seems to offer:</p> <pre><code>HELO foo_bar.example.com </code></pre> <p>Response: </p> <pre><code>501 Syntactically invalid HELO argument(s) </code></pre>
[ { "answer_id": 86953, "author": "benefactual", "author_id": 6445, "author_profile": "https://Stackoverflow.com/users/6445", "pm_score": 4, "selected": true, "text": "<p>Possibly a problem with underscores in the hostname?\n<a href=\"http://www.exim.org/lurker/message/20041124.113314.c44c...
2008/09/17
[ "https://Stackoverflow.com/questions/86907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12850/" ]
I'm using exim on both the sending and relay hosts, the sending host seems to offer: ``` HELO foo_bar.example.com ``` Response: ``` 501 Syntactically invalid HELO argument(s) ```
Possibly a problem with underscores in the hostname? <http://www.exim.org/lurker/message/20041124.113314.c44c83b2.en.html>
86,913
<p>I have a variety of time-series data stored on a more-or-less georeferenced grid, e.g. one value per 0.2 degrees of latitude and longitude. Currently the data are stored in text files, so at day-of-year 251 you might see:</p> <pre><code>251 12.76 12.55 12.55 12.34 [etc., 200 more values...] 13.02 12.95 12.70 12.40 [etc., 200 more values...] [etc., 250 more lines] 252 [etc., etc.] </code></pre> <p>I'd like to raise the level of abstraction, improve performance, and reduce fragility (for example, the current code can't insert a day between two existing ones!). We'd messed around with BLOB-y RDBMS hacks and even replicating each line of the text file format as a row in a table (one row per timestamp/latitude pair, one column per longitude increment -- yecch!).</p> <p>We could go to a "real" geodatabase, but the overhead of tagging each individual value with a lat and long seems prohibitive. The size and resolution of the data haven't changed in ten years and are unlikely to do so.</p> <p>I've been noodling around with putting everything in NetCDF files, but think we need to get past the file mindset entirely -- I hate that all my software has to figure out filenames from dates, deal with multiple files for multiple years, etc.. The alternative, putting all ten years' (and counting) data into a single file, doesn't seem workable either.</p> <p>Any bright ideas or products?</p>
[ { "answer_id": 86961, "author": "jjrv", "author_id": 16509, "author_profile": "https://Stackoverflow.com/users/16509", "pm_score": 0, "selected": false, "text": "<p>I'd definitely change from text to binary but keep each day in a separate file still. You could name them in such a way tha...
2008/09/17
[ "https://Stackoverflow.com/questions/86913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a variety of time-series data stored on a more-or-less georeferenced grid, e.g. one value per 0.2 degrees of latitude and longitude. Currently the data are stored in text files, so at day-of-year 251 you might see: ``` 251 12.76 12.55 12.55 12.34 [etc., 200 more values...] 13.02 12.95 12.70 12.40 [etc., 200 more values...] [etc., 250 more lines] 252 [etc., etc.] ``` I'd like to raise the level of abstraction, improve performance, and reduce fragility (for example, the current code can't insert a day between two existing ones!). We'd messed around with BLOB-y RDBMS hacks and even replicating each line of the text file format as a row in a table (one row per timestamp/latitude pair, one column per longitude increment -- yecch!). We could go to a "real" geodatabase, but the overhead of tagging each individual value with a lat and long seems prohibitive. The size and resolution of the data haven't changed in ten years and are unlikely to do so. I've been noodling around with putting everything in NetCDF files, but think we need to get past the file mindset entirely -- I hate that all my software has to figure out filenames from dates, deal with multiple files for multiple years, etc.. The alternative, putting all ten years' (and counting) data into a single file, doesn't seem workable either. Any bright ideas or products?
I've assembled your comments here: 1. I'd like to do all this "w/o writing my own file I/O code" 2. I need access from "Java Ruby MATLAB" and "FORTRAN routines" When you add these up, you definitely don't want a new file format. **Stick with the one you've got.** If we can get you to relax your first requirement - ie, if you'd be willing to write your own file I/O code, then there are some interesting options for you. I'd write C++ classes, and I'd use something like SWIG to make your new classes available to the multiple languages you need. (But I'm not sure you'd be able to use SWIG to give you access from Java, Ruby, MATLAB and FORTRAN. You might need something else. Not really sure how to do it, myself.) You also said, "Actually, if I have to have files, I prefer text because then I can just go in and hand-edit when necessary." My belief is that this is a misguided statement. If you'd be willing to make your own file I/O routines then there are very clever things you could do... And as an ultimate fallback, you could give yourself a tool that converts from the new file format to the same old text format you're used to... And another tool that converts back. I'll come back to this at the end of my post... You said something that I want to address: "leverage 40 yrs of DB optimization" Databases are meant for relational data, not raster data. You will not leverage anyone's DB **optimizations** with this kind of data. You might be able to cram your data into a DB, but that's hardly the same thing. **Here's the most useful thing I can tell you, based on everything you've told us.** You said this: "I am more interested in optimizing *my* time than the CPU's, though exec speed is good!" This is frankly going to require TOOLS. Stop thinking of it as a text file. Start thinking of the common tasks you do, and write small tools - in WHATEVER LANGAUGE(S) - to make those things TRIVIAL to do. And if your tools turn out to have lousy performance? Guess what - it's because your flat text file is a cruddy format. But that's just my opinion. :)
86,919
<p>I have a simple xml document that looks like the following snippet. I need to write a XSLT transform that basically 'unpivots' this document based on some of the attributes.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;root xmlns:z="foo"&gt; &lt;z:row A="1" X="2" Y="n1" Z="500"/&gt; &lt;z:row A="2" X="5" Y="n2" Z="1500"/&gt; &lt;/root&gt; </code></pre> <p>This is what I expect the output to be -</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;root xmlns:z="foo"&gt; &lt;z:row A="1" X="2" /&gt; &lt;z:row A="1" Y="n1" /&gt; &lt;z:row A="1" Z="500"/&gt; &lt;z:row A="2" X="5" /&gt; &lt;z:row A="2" Y="n2"/&gt; &lt;z:row A="2" Z="1500"/&gt; &lt;/root&gt; </code></pre> <p>Appreciate your help.</p>
[ { "answer_id": 87086, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 0, "selected": false, "text": "<p>Here is a bit of a brute force way:</p>\n\n<p>\n </p>\n\n<pre><code>&lt;xsl:template match=\"z:row\"&gt;\n &lt...
2008/09/17
[ "https://Stackoverflow.com/questions/86919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4088/" ]
I have a simple xml document that looks like the following snippet. I need to write a XSLT transform that basically 'unpivots' this document based on some of the attributes. ``` <?xml version="1.0" encoding="utf-8" ?> <root xmlns:z="foo"> <z:row A="1" X="2" Y="n1" Z="500"/> <z:row A="2" X="5" Y="n2" Z="1500"/> </root> ``` This is what I expect the output to be - ``` <?xml version="1.0" encoding="utf-8" ?> <root xmlns:z="foo"> <z:row A="1" X="2" /> <z:row A="1" Y="n1" /> <z:row A="1" Z="500"/> <z:row A="2" X="5" /> <z:row A="2" Y="n2"/> <z:row A="2" Z="1500"/> </root> ``` Appreciate your help.
``` <xsl:template match="row"> <row A="{$A}" X="{$X}" /> <row A="{$A}" Y="{$Y}" /> <row A="{$A}" Z="{$Z}" /> </xsl:template> ``` Plus obvious boilerplate.
86,947
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/73713/how-do-i-check-for-nulls-in-an-operator-overload-without-infinite-recursion">How do I check for nulls in an &#39;==&#39; operator overload without infinite recursion?</a> </p> </blockquote> <p>When I overload the == operator for objects I typically write something like this:</p> <pre><code> public static bool operator ==(MyObject uq1, MyObject uq2) { if (((object)uq1 == null) || ((object)uq2 == null)) return false; return uq1.Field1 == uq2.Field1 &amp;&amp; uq1.Field2 == uq2.Field2; } </code></pre> <p>If you don't down-cast to object the function recurses into itself but I have to wonder if there isn't a better way?</p>
[ { "answer_id": 86968, "author": "Juanma", "author_id": 3730, "author_profile": "https://Stackoverflow.com/users/3730", "pm_score": 2, "selected": false, "text": "<p>ReferenceEquals(object obj1, object obj2)</p>\n" }, { "answer_id": 86986, "author": "Timothy Carter", "auth...
2008/09/17
[ "https://Stackoverflow.com/questions/86947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
> > **Possible Duplicate:** > > [How do I check for nulls in an '==' operator overload without infinite recursion?](https://stackoverflow.com/questions/73713/how-do-i-check-for-nulls-in-an-operator-overload-without-infinite-recursion) > > > When I overload the == operator for objects I typically write something like this: ``` public static bool operator ==(MyObject uq1, MyObject uq2) { if (((object)uq1 == null) || ((object)uq2 == null)) return false; return uq1.Field1 == uq2.Field1 && uq1.Field2 == uq2.Field2; } ``` If you don't down-cast to object the function recurses into itself but I have to wonder if there isn't a better way?
As Microsoft says, > > A common error in overloads of > operator == is to use (a == b), (a == > null), or (b == null) to check for > reference equality. This instead > results in a call to the overloaded > operator ==, causing an infinite loop. > Use ReferenceEquals or cast the type > to Object, to avoid the loop. > > > So use ReferenceEquals(a, null) || ReferenceEquals(b, null) is one possibility, but casting to object is just as good (is actually equivalent, I believe). So yes, it seems there should be a better way, but the method you use is the one recommended. However, as has been pointed out, you really SHOULD override Equals as well when overriding ==. With LINQ providers being written in different languages and doing expression resolution at runtime, who knows when you'll be bit by not doing it even if you own all the code yourself.
86,963
<p>More than once I've lost work by accidentally killing a temporary buffer in Emacs. Can I set up Emacs to give me a warning when I kill a buffer not associated with a file?</p>
[ { "answer_id": 87080, "author": "EfForEffort", "author_id": 14113, "author_profile": "https://Stackoverflow.com/users/14113", "pm_score": 5, "selected": true, "text": "<p>Make a function that will ask you whether you're sure when the buffer has been edited and is not associated with a fi...
2008/09/17
[ "https://Stackoverflow.com/questions/86963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207/" ]
More than once I've lost work by accidentally killing a temporary buffer in Emacs. Can I set up Emacs to give me a warning when I kill a buffer not associated with a file?
Make a function that will ask you whether you're sure when the buffer has been edited and is not associated with a file. Then add that function to the list `kill-buffer-query-functions`. Looking at the documentation for [Buffer File Name](http://www.gnu.org/software/emacs/manual/html_node/elisp/Buffer-File-Name.html) you understand: * a buffer is not visiting a file if and only if the variable `buffer-file-name` is nil Use that insight to write the function: ```lisp (defun maybe-kill-buffer () (if (and (not buffer-file-name) (buffer-modified-p)) ;; buffer is not visiting a file (y-or-n-p "This buffer is not visiting a file but has been edited. Kill it anyway? ") t)) ``` And then add the function to the hook like so: ``` (add-to-list 'kill-buffer-query-functions 'maybe-kill-buffer) ```
86,987
<p>I'm trying this with Oracle SQL Developer and am on an Intel MacBook Pro. But I believe this same error happens with other clients. I can ping the server hosting the database fine so it appears not to be an actual network problem.</p> <p>Also, I believe I'm filling in the connection info correctly. It's something like this:</p> <pre> host = foo1.com port = 1530 server = DEDICATED service_name = FOO type = session method = basic </pre>
[ { "answer_id": 87429, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 1, "selected": false, "text": "<p>That's the message you get when you don't have the right connection parameters. The SID, in particular, tends to trip up ...
2008/09/17
[ "https://Stackoverflow.com/questions/86987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4234/" ]
I'm trying this with Oracle SQL Developer and am on an Intel MacBook Pro. But I believe this same error happens with other clients. I can ping the server hosting the database fine so it appears not to be an actual network problem. Also, I believe I'm filling in the connection info correctly. It's something like this: ``` host = foo1.com port = 1530 server = DEDICATED service_name = FOO type = session method = basic ```
My problem turned out to be some kind of ACL problem. I needed to SSH tunnel in through a "blessed host". I put the following in my .ssh/config ``` Host=blessedhost HostName=blessedhost.whatever.com User=alice Compression=yes Protocol=2 LocalForward=2202 oraclemachine.whatever.com:1521 Host=foo HostName=localhost Port=2202 User=alice Compression=yes Protocol=2 ``` (I don't think the second block is really necessary.) Then I change the host and port in the oracle connection info to localhost:2202.
86,992
<p>I have an application with multiple &quot;pick list&quot; entities, such as used to populate choices of dropdown selection boxes. These entities need to be stored in the database. How do one persist these entities in the database?</p> <p>Should I create a new table for each pick list? Is there a better solution?</p>
[ { "answer_id": 87014, "author": "neouser99", "author_id": 10669, "author_profile": "https://Stackoverflow.com/users/10669", "pm_score": 0, "selected": false, "text": "<p>Depending on your needs, you can just have an options table that has a list identifier and a list value as the primary...
2008/09/17
[ "https://Stackoverflow.com/questions/86992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8852/" ]
I have an application with multiple "pick list" entities, such as used to populate choices of dropdown selection boxes. These entities need to be stored in the database. How do one persist these entities in the database? Should I create a new table for each pick list? Is there a better solution?
Well, you could do something like this: ``` PickListContent IdList IdPick Text 1 1 Apples 1 2 Oranges 1 3 Pears 2 1 Dogs 2 2 Cats ``` and optionally.. ``` PickList Id Description 1 Fruit 2 Pets ```
87,021
<p>Given a moderately complex XML structure (dozens of elements, hundreds of attributes) with no XSD and a desire to create an object model, what's an elegant way to avoid writing boilerplate from_xml() and to_xml() methods? </p> <p>For instance, given:</p> <pre><code>&lt;Foo bar="1"&gt;&lt;Bat baz="blah"/&gt;&lt;/Foo&gt; </code></pre> <p>How do I avoid writing endless sequences of:</p> <pre><code>class Foo attr_reader :bar, :bat def from_xml(el) @bar = el.attributes['bar'] @bat = Bat.new() @bat.from_xml(XPath.first(el, "./bat") end etc... </code></pre> <p>I don't mind creating the object structure explicitly; it's the serialization that I'm just sure can be taken care of with some higher-level programming...</p> <hr> <p>I am not trying to save a line or two per class (by moving from_xml behavior into initializer or class method, etc.). I am looking for the "meta" solution that duplicates my mental process:</p> <p>"I know that every element is going to become a class name. I know that every XML attribute is going to be a field name. I know that the code to assign is just @#{attribute_name} = el.[#{attribute_name}] and then recurse into sub-elements. And reverse on to_xml."</p> <hr> <p>I agree with suggestion that a "builder" class plus XmlSimple seems the right path. XML -> Hash -> ? -> Object model (and Profit!)</p> <hr> <p>Update 2008-09-18 AM: Excellent suggestions from @Roman, @fatgeekuk, and @ScottKoon seem to have broken the problem open. I downloaded HPricot source to see how it solved the problem; key methods are clearly instance_variable_set and class_eval . irb work is very encouraging, am now moving towards implementation .... Very excited</p>
[ { "answer_id": 87079, "author": "Jim Deville", "author_id": 1591, "author_profile": "https://Stackoverflow.com/users/1591", "pm_score": 0, "selected": false, "text": "<p>Could you define a method missing that allows you to do:</p>\n\n<p>@bar = el.bar? That would get rid of some boilerpla...
2008/09/17
[ "https://Stackoverflow.com/questions/87021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10116/" ]
Given a moderately complex XML structure (dozens of elements, hundreds of attributes) with no XSD and a desire to create an object model, what's an elegant way to avoid writing boilerplate from\_xml() and to\_xml() methods? For instance, given: ``` <Foo bar="1"><Bat baz="blah"/></Foo> ``` How do I avoid writing endless sequences of: ``` class Foo attr_reader :bar, :bat def from_xml(el) @bar = el.attributes['bar'] @bat = Bat.new() @bat.from_xml(XPath.first(el, "./bat") end etc... ``` I don't mind creating the object structure explicitly; it's the serialization that I'm just sure can be taken care of with some higher-level programming... --- I am not trying to save a line or two per class (by moving from\_xml behavior into initializer or class method, etc.). I am looking for the "meta" solution that duplicates my mental process: "I know that every element is going to become a class name. I know that every XML attribute is going to be a field name. I know that the code to assign is just @#{attribute\_name} = el.[#{attribute\_name}] and then recurse into sub-elements. And reverse on to\_xml." --- I agree with suggestion that a "builder" class plus XmlSimple seems the right path. XML -> Hash -> ? -> Object model (and Profit!) --- Update 2008-09-18 AM: Excellent suggestions from @Roman, @fatgeekuk, and @ScottKoon seem to have broken the problem open. I downloaded HPricot source to see how it solved the problem; key methods are clearly instance\_variable\_set and class\_eval . irb work is very encouraging, am now moving towards implementation .... Very excited
You could use Builder instead of creating your to\_xml method, and you could use XMLSimple to pull your xml file into a Hash instead of using the from \_xml method. Unfortunately, I'm not sure you'll really gain all that much from using these techniques.
87,023
<p>Is there a straightforward way to query a web service to see which messages it supports? The C# .NET application I'm working on needs to be able to handle an older version of the web service, which does not implement the message I'm trying to send. The web service does not expose a version number, so Plan B is to see if the message is defined.</p> <p>I'm assuming I can just make an HTTP request for the WSDL and parse it, but before I go down that path, I want to make sure there's not a simpler approach.</p> <p>Update: I've decided to get the WSDL and get messages directly. Here's the rough draft for getting all the messages:</p> <pre><code>HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create( "http://your/web/service/here.asmx?WSDL" ); webRequest.PreAuthenticate = // details elided webRequest.Credentials = // details elided webRequest.Timeout = // details elided HttpWebResponse webResponse = (HttpWebResponse) webRequest.GetResponse(); XPathDocument xpathDocument = new XPathDocument( webResponse.GetResponseStream() ); XPathNavigator xpathNavigator = xpathDocument.CreateNavigator(); XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager( new NameTable() ); xmlNamespaceManager.AddNamespace( "wsdl", "http://schemas.xmlsoap.org/wsdl/" ); foreach( XPathNavigator node in xpathNavigator.Select( "//wsdl:message/@name", xmlNamespaceManager ) ) { string messageName = node.Value; } </code></pre>
[ { "answer_id": 87131, "author": "David Thibault", "author_id": 5903, "author_profile": "https://Stackoverflow.com/users/5903", "pm_score": 1, "selected": true, "text": "<p>I'm pretty sure WSDL is the way to do this.</p>\n" }, { "answer_id": 87495, "author": "Tegan Mulholland"...
2008/09/17
[ "https://Stackoverflow.com/questions/87023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8492/" ]
Is there a straightforward way to query a web service to see which messages it supports? The C# .NET application I'm working on needs to be able to handle an older version of the web service, which does not implement the message I'm trying to send. The web service does not expose a version number, so Plan B is to see if the message is defined. I'm assuming I can just make an HTTP request for the WSDL and parse it, but before I go down that path, I want to make sure there's not a simpler approach. Update: I've decided to get the WSDL and get messages directly. Here's the rough draft for getting all the messages: ``` HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create( "http://your/web/service/here.asmx?WSDL" ); webRequest.PreAuthenticate = // details elided webRequest.Credentials = // details elided webRequest.Timeout = // details elided HttpWebResponse webResponse = (HttpWebResponse) webRequest.GetResponse(); XPathDocument xpathDocument = new XPathDocument( webResponse.GetResponseStream() ); XPathNavigator xpathNavigator = xpathDocument.CreateNavigator(); XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager( new NameTable() ); xmlNamespaceManager.AddNamespace( "wsdl", "http://schemas.xmlsoap.org/wsdl/" ); foreach( XPathNavigator node in xpathNavigator.Select( "//wsdl:message/@name", xmlNamespaceManager ) ) { string messageName = node.Value; } ```
I'm pretty sure WSDL is the way to do this.
87,030
<p>Where can I download the JSSE and JCE source code for the latest release of Java? The source build available at <a href="https://jdk6.dev.java.net/" rel="noreferrer">https://jdk6.dev.java.net/</a> does not include the javax.crypto (JCE) packages nor the com.sun.net.ssl.internal (JSSE) packages.</p> <p>Not being able to debug these classes makes solving SSL issues incredibly difficult.</p>
[ { "answer_id": 87106, "author": "PW.", "author_id": 927, "author_profile": "https://Stackoverflow.com/users/927", "pm_score": 4, "selected": false, "text": "<p>there: <a href=\"http://openjdk.java.net/groups/security/\" rel=\"noreferrer\">openjdk javax.net</a> in the security group </p>\...
2008/09/17
[ "https://Stackoverflow.com/questions/87030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Where can I download the JSSE and JCE source code for the latest release of Java? The source build available at <https://jdk6.dev.java.net/> does not include the javax.crypto (JCE) packages nor the com.sun.net.ssl.internal (JSSE) packages. Not being able to debug these classes makes solving SSL issues incredibly difficult.
there: [openjdk javax.net](http://openjdk.java.net/groups/security/) in the security group ``` src/share/classes/javax/net src/share/classes/com/sun/net/ssl src/share/classes/sun/security/ssl src/share/classes/sun/net/www/protocol/https ``` also on this page: ``` src/share/classes/javax/crypto src/share/classes/com/sun/crypto/provider src/share/classes/sun/security/pkcs11 src/share/classes/sun/security/mscapi ``` > > These directories contain the core > cryptography framework and three > providers (SunJCE, SunPKCS11, > SunMSCAPI). **SunJCE** contains Java > implementations of many popular > algorithms, and the latter two > libraries allow calls made through the > standard Java cryptography APIs to be > routed into their respective native > libraries. > > >
87,096
<p>I really hate using STL containers because they make the debug version of my code run really slowly. What do other people use instead of STL that has reasonable performance for debug builds?</p> <p>I'm a game programmer and this has been a problem on many of the projects I've worked on. It's pretty hard to get 60 fps when you use STL container for everything.</p> <p>I use MSVC for most of my work.</p>
[ { "answer_id": 87108, "author": "Fred Larson", "author_id": 10077, "author_profile": "https://Stackoverflow.com/users/10077", "pm_score": 2, "selected": false, "text": "<p>I'll bet your STL uses a checked implementation for debug. This is probably a good thing, as it will catch iterator...
2008/09/17
[ "https://Stackoverflow.com/questions/87096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16679/" ]
I really hate using STL containers because they make the debug version of my code run really slowly. What do other people use instead of STL that has reasonable performance for debug builds? I'm a game programmer and this has been a problem on many of the projects I've worked on. It's pretty hard to get 60 fps when you use STL container for everything. I use MSVC for most of my work.
EASTL is a possibility, but still not perfect. Paul Pedriana of Electronic Arts did an investigation of various STL implementations with respect to performance in game applications the summary of which is found here: <http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html> Some of these adjustments to are being reviewed for inclusion in the C++ standard. And note, even EASTL doesn't optimize for the non-optimized case. I had an excel file w/ some timing a while back but I think I've lost it, but for access it was something like: ``` debug release STL 100 10 EASTL 10 3 array[i] 3 1 ``` The most success I've had was rolling my own containers. You can get those down to near array[x] performance.
87,101
<p>What is a good way to select all or select no items in a listview without using:</p> <pre><code>foreach (ListViewItem item in listView1.Items) { item.Selected = true; } </code></pre> <p>or</p> <pre><code>foreach (ListViewItem item in listView1.Items) { item.Selected = false; } </code></pre> <p>I know the underlying Win32 listview common control supports <a href="http://msdn.microsoft.com/en-us/library/bb761196(VS.85).aspx" rel="nofollow noreferrer">LVM_SETITEMSTATE message</a> which you can use to set the selected state, and by passing -1 as the index it will apply to all items. I'd rather not be PInvoking messages to the control that happens to be behind the .NET Listview control (I don't want to be a bad developer and rely on undocumented behavior - for when they change it to a fully managed ListView class)</p> <h2>Bump</h2> <p><a href="https://stackoverflow.com/questions/87101/how-to-selectall-selectnone-in-net-2-0-listview/87209#87209">Pseudo Masochist</a> has the <strong>SelectNone</strong> case:</p> <pre><code>ListView1.SelectedItems.Clear(); </code></pre> <p>Now just need the <strong>SelectAll</strong> code</p>
[ { "answer_id": 87108, "author": "Fred Larson", "author_id": 10077, "author_profile": "https://Stackoverflow.com/users/10077", "pm_score": 2, "selected": false, "text": "<p>I'll bet your STL uses a checked implementation for debug. This is probably a good thing, as it will catch iterator...
2008/09/17
[ "https://Stackoverflow.com/questions/87101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
What is a good way to select all or select no items in a listview without using: ``` foreach (ListViewItem item in listView1.Items) { item.Selected = true; } ``` or ``` foreach (ListViewItem item in listView1.Items) { item.Selected = false; } ``` I know the underlying Win32 listview common control supports [LVM\_SETITEMSTATE message](http://msdn.microsoft.com/en-us/library/bb761196(VS.85).aspx) which you can use to set the selected state, and by passing -1 as the index it will apply to all items. I'd rather not be PInvoking messages to the control that happens to be behind the .NET Listview control (I don't want to be a bad developer and rely on undocumented behavior - for when they change it to a fully managed ListView class) Bump ---- [Pseudo Masochist](https://stackoverflow.com/questions/87101/how-to-selectall-selectnone-in-net-2-0-listview/87209#87209) has the **SelectNone** case: ``` ListView1.SelectedItems.Clear(); ``` Now just need the **SelectAll** code
EASTL is a possibility, but still not perfect. Paul Pedriana of Electronic Arts did an investigation of various STL implementations with respect to performance in game applications the summary of which is found here: <http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html> Some of these adjustments to are being reviewed for inclusion in the C++ standard. And note, even EASTL doesn't optimize for the non-optimized case. I had an excel file w/ some timing a while back but I think I've lost it, but for access it was something like: ``` debug release STL 100 10 EASTL 10 3 array[i] 3 1 ``` The most success I've had was rolling my own containers. You can get those down to near array[x] performance.
87,107
<p>I've setup a new .net 2.0 website on IIS 7 under Win Server 2k8 and when browsing to a page it gives me a 404.17 error, claiming that the file (default.aspx in this case) appears to be a script but is being handled by the static file handler. It SOUNDS like the module mappings for ASP.Net got messed up, but they look fine in the configurations. Does anyone have a suggestion for correcting this error?</p>
[ { "answer_id": 87412, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 6, "selected": true, "text": "<p>I had this problem on IIS6 one time when somehow the ASP.NET ISAPI stuff was broke.</p>\n\n<p>Running </p>\n\n<pre>...
2008/09/17
[ "https://Stackoverflow.com/questions/87107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16729/" ]
I've setup a new .net 2.0 website on IIS 7 under Win Server 2k8 and when browsing to a page it gives me a 404.17 error, claiming that the file (default.aspx in this case) appears to be a script but is being handled by the static file handler. It SOUNDS like the module mappings for ASP.Net got messed up, but they look fine in the configurations. Does anyone have a suggestion for correcting this error?
I had this problem on IIS6 one time when somehow the ASP.NET ISAPI stuff was broke. Running ``` %windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -i ``` to recreate the settings took care of it.
87,177
<p>I had data in XML that had line feeds, spaces, and tabs that I wanted to preserve in the output HTML (so I couldn't use &lt;p&gt;) but I also wanted the lines to wrap when the side of the screen was reached (so I couldn't use &lt;pre&gt;).</p>
[ { "answer_id": 87194, "author": "James A. N. Stauffer", "author_id": 6770, "author_profile": "https://Stackoverflow.com/users/6770", "pm_score": 0, "selected": false, "text": "<p>I and a co-worker (Patricia Eromosele) came up with the following solution: (Is there a better solution?)</p...
2008/09/17
[ "https://Stackoverflow.com/questions/87177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6770/" ]
I had data in XML that had line feeds, spaces, and tabs that I wanted to preserve in the output HTML (so I couldn't use <p>) but I also wanted the lines to wrap when the side of the screen was reached (so I couldn't use <pre>).
Another way of putting this is that you want to turn all pairs of spaces into two non-breaking spaces, tabs into four non-breaking spaces and all line breaks into `<br>` elements. In XSLT 1.0, I'd do: ``` <xsl:template name="replace-spaces"> <xsl:param name="text" /> <xsl:choose> <xsl:when test="contains($text, ' ')"> <xsl:call-template name="replace-spaces"> <xsl:with-param name="text" select="substring-before($text, ' ')"/> </xsl:call-template> <xsl:text>&#xA0;&#xA0;</xsl:text> <xsl:call-template name="replace-spaces"> <xsl:with-param name="text" select="substring-before($text, ' ')" /> </xsl:call-template> </xsl:when> <xsl:when test="contains($text, '&#x9;')"> <xsl:call-template name="replace-spaces"> <xsl:with-param name="text" select="substring-before($text, '&#x9;')"/> </xsl:call-template> <xsl:text>&#xA0;&#xA0;&#xA0;&#xA0;</xsl:text> <xsl:call-template name="replace-spaces"> <xsl:with-param name="text" select="substring-before($text, '&#x9;')" /> </xsl:call-template> </xsl:when> <xsl:when test="contains($text, '&#xA;')"> <xsl:call-template name="replace-spaces"> <xsl:with-param name="text" select="substring-before($text, '&#xA;')" /> </xsl:call-template> <br /> <xsl:call-template name="replace-spaces"> <xsl:with-param name="text" select="substring-after($text, '&#xA;')" /> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select="$text" /> </xsl:otherwise> </xsl:choose> </xsl:template> ``` Not being able to use tail recursion is a bit of a pain, but it shouldn't be a real problem unless the text is *very* long. An XSLT 2.0 solution would use `<xsl:analyze-string>`.
87,221
<p><a href="https://stackoverflow.com/questions/2262/aspnet-url-rewriting">So this post</a> talked about how to actually implement url rewriting in an ASP.NET application to get "friendly urls". That works perfect and it is great for sending a user to a specific page, but does anyone know of a good solution for creating "Friendly" URLs inside your code when using one of the tools referenced?</p> <p>For example listing a link inside of an asp.net control as ~/mypage.aspx?product=12 when a rewrite rule exists would be an issue as then you are linking to content in two different ways.</p> <p>I'm familiar with using DotNetNuke and FriendlyUrl's where there is a "NavigateUrl" method that will get the friendly Url code from the re-writer but I'm not finding examples of how to do this with UrlRewriting.net or the other solutions out there. </p> <p>Ideally I'd like to be able to get something like this.</p> <pre><code>string friendlyUrl = GetFriendlyUrl("~/MyUnfriendlyPage.aspx?myid=13"); </code></pre> <p><strong>EDIT:</strong> I am looking for a generic solution, not something that I have to implement for every page in my site, but potentially something that can match against the rules in the opposite direction.</p>
[ { "answer_id": 87263, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 0, "selected": false, "text": "<p>Create a UrlBuilder class with methods for each page like so:</p>\n\n<pre><code>public class UrlBuilder\n{\n publi...
2008/09/17
[ "https://Stackoverflow.com/questions/87221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13279/" ]
[So this post](https://stackoverflow.com/questions/2262/aspnet-url-rewriting) talked about how to actually implement url rewriting in an ASP.NET application to get "friendly urls". That works perfect and it is great for sending a user to a specific page, but does anyone know of a good solution for creating "Friendly" URLs inside your code when using one of the tools referenced? For example listing a link inside of an asp.net control as ~/mypage.aspx?product=12 when a rewrite rule exists would be an issue as then you are linking to content in two different ways. I'm familiar with using DotNetNuke and FriendlyUrl's where there is a "NavigateUrl" method that will get the friendly Url code from the re-writer but I'm not finding examples of how to do this with UrlRewriting.net or the other solutions out there. Ideally I'd like to be able to get something like this. ``` string friendlyUrl = GetFriendlyUrl("~/MyUnfriendlyPage.aspx?myid=13"); ``` **EDIT:** I am looking for a generic solution, not something that I have to implement for every page in my site, but potentially something that can match against the rules in the opposite direction.
See [System.Web.Routing](http://www.codethinked.com/post/2008/08/20/Exploring-SystemWebRouting.aspx) Routing is a different from rewriting. Implementing this technique does require minor changes to your pages (namely, any code accessing querystring parameters will need to be modified), but it allows you to generate links based on the routes you define. It's used by ASP.NET MVC, but can be employed in any ASP.NET application. Routing is part of .Net 3.5 SP1
87,222
<p>How do i represent CRLF using Hex in C#?</p>
[ { "answer_id": 87227, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 2, "selected": false, "text": "<p>Not sure why, but it's 0x0d, 0x0a, aka \"\\r\\n\".</p>\n" }, { "answer_id": 87312, "author": "James Cu...
2008/09/17
[ "https://Stackoverflow.com/questions/87222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do i represent CRLF using Hex in C#?
Since no one has actually given the answer requested, here it is: ``` "\x0d\x0a" ```
87,224
<p>It is obviosly some Perl extensions. Perl version is 5.8.8.</p> <p>I found Error.pm, but now I'm looking for Core.pm. </p> <p>While we're at it: how do you guys search for those modules. I tried Google, but that didn't help much. Thanks.</p> <hr> <p>And finally, after I built everything, running: </p> <pre><code>./Build install </code></pre> <p>gives me:</p> <pre><code>Running make install-lib /bin/ginstall -c -d /usr/lib/perl5/site_perl/5.8.8/i486-linux-thread-multi/Alien/SVN --prefix=/usr /bin/ginstall: unrecognized option `--prefix=/usr' Try `/bin/ginstall --help' for more information. make: *** [install-fsmod-lib] Error 1 installing libs failed at inc/My/SVN/Builder.pm line 165. </code></pre> <p>Looks like Slackware's 'ginstall' really does not have that option. I think I'm going to Google a little bit now, to see how to get around this.</p>
[ { "answer_id": 87311, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 2, "selected": true, "text": "<p>It should be compatible. The <a href=\"http://bbbike.radzeit.de/~slaven/cpantestersmatrix.cgi?dist=Error+0.17015\" r...
2008/09/17
[ "https://Stackoverflow.com/questions/87224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14690/" ]
It is obviosly some Perl extensions. Perl version is 5.8.8. I found Error.pm, but now I'm looking for Core.pm. While we're at it: how do you guys search for those modules. I tried Google, but that didn't help much. Thanks. --- And finally, after I built everything, running: ``` ./Build install ``` gives me: ``` Running make install-lib /bin/ginstall -c -d /usr/lib/perl5/site_perl/5.8.8/i486-linux-thread-multi/Alien/SVN --prefix=/usr /bin/ginstall: unrecognized option `--prefix=/usr' Try `/bin/ginstall --help' for more information. make: *** [install-fsmod-lib] Error 1 installing libs failed at inc/My/SVN/Builder.pm line 165. ``` Looks like Slackware's 'ginstall' really does not have that option. I think I'm going to Google a little bit now, to see how to get around this.
It should be compatible. The [CPAN Tester's matrix](http://bbbike.radzeit.de/~slaven/cpantestersmatrix.cgi?dist=Error+0.17015) shows no failures for Perl 5.8.8 on any platform. Per the [README](https://metacpan.org/source/SHLOMIF/Error-0.17022/README), you can install it by doing: ``` perl Makefile.pl make make test make install ```
87,262
<p>I need to find the frequency of a sample, stored (in vb) as an array of byte. Sample is a sine wave, known frequency, so I can check), but the numbers are a bit odd, and my maths-foo is weak. Full range of values 0-255. 99% of numbers are in range 235 to 245, but there are some outliers down to 0 and 1, and up to 255 in the remaining 1%. How do I normalise this to remove outliers, (calculating the 235-245 interval as it may change with different samples), and how do I then calculate zero-crossings to get the frequency? Apologies if this description is rubbish!</p>
[ { "answer_id": 87292, "author": "Purfideas", "author_id": 4615, "author_profile": "https://Stackoverflow.com/users/4615", "pm_score": 2, "selected": false, "text": "<p>Use the Fourier transform, it's much more noise insensitive than counting zero crossings</p>\n<p>Edit: @WaveyDavey</p>\n...
2008/09/17
[ "https://Stackoverflow.com/questions/87262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2135219/" ]
I need to find the frequency of a sample, stored (in vb) as an array of byte. Sample is a sine wave, known frequency, so I can check), but the numbers are a bit odd, and my maths-foo is weak. Full range of values 0-255. 99% of numbers are in range 235 to 245, but there are some outliers down to 0 and 1, and up to 255 in the remaining 1%. How do I normalise this to remove outliers, (calculating the 235-245 interval as it may change with different samples), and how do I then calculate zero-crossings to get the frequency? Apologies if this description is rubbish!
The FFT is probably the best answer, but if you really want to do it by your method, try this: To normalize, first make a histogram to count how many occurrances of each value from 0 to 255. Then throw out X percent of the values from each end with something like: ``` for (i=lower=0;i< N*(X/100); lower++) i+=count[lower]; //repeat in other direction for upper ``` Now normalize with ``` A[i] = 255*(A[i]-lower)/(upper-lower)-128 ``` Throw away results outside the -128..127 range. Now you can count zero crossings. To make sure you are not fooled by noise, you might want to keep track of the slope over the last several points, and only count crossings when the average slope is going the right way.
87,290
<p>Although I don't have an iPhone to test this out, my colleague told me that embedded media files such as the one in the snippet below, only works when the iphone is connected over the WLAN connection or 3G, and does not work when connecting via GPRS.</p> <pre><code>&lt;html&gt;&lt;body&gt; &lt;object data="http://joliclic.free.fr/html/object-tag/en/data/test.mp3" type="audio/mpeg"&gt; &lt;p&gt;alternate text&lt;/p&gt; &lt;/object&gt; &lt;/body&gt;&lt;/html&gt; </code></pre> <p>Is there an example URL with a media file, that will play in an iPhone browser when the iphone connects using GPRS (not 3G)?</p>
[ { "answer_id": 88508, "author": "Grank", "author_id": 12975, "author_profile": "https://Stackoverflow.com/users/12975", "pm_score": 0, "selected": false, "text": "<p>I wasn't aware of that limitation. Although it does make sense to disable potentially data-hefty OBJECT or EMBED tags whe...
2008/09/17
[ "https://Stackoverflow.com/questions/87290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6225/" ]
Although I don't have an iPhone to test this out, my colleague told me that embedded media files such as the one in the snippet below, only works when the iphone is connected over the WLAN connection or 3G, and does not work when connecting via GPRS. ``` <html><body> <object data="http://joliclic.free.fr/html/object-tag/en/data/test.mp3" type="audio/mpeg"> <p>alternate text</p> </object> </body></html> ``` Is there an example URL with a media file, that will play in an iPhone browser when the iphone connects using GPRS (not 3G)?
The iPhone YouTube application automatically downloads lower quality video when connected via EDGE than when connected via Wi-Fi, because the network is much slower. That fact leads me to believe Apple would make the design decision to not bother downloading an MP3 over EDGE. The browser has no way to know in advance if the bit rate is low enough, and chances are, it won't be. So rather than frustrate the users with a sound file that takes too long to play (and prevents thems from receiving a call while downloading), it's better to spare them the grief and encourage them to find a Wi-Fi hotspot.
87,303
<p>I know I can edit each individual DTS package and save it as a Visual Basic script, but with hundreds of packages on the server, that will take forever. How can I script them all at once? I'd like to be able to create one file per package so that I can check them into source control, search them to see which one references a specific table, or compare the packages on our development server to the packages on our production server.</p>
[ { "answer_id": 89343, "author": "Tom Resing", "author_id": 17063, "author_profile": "https://Stackoverflow.com/users/17063", "pm_score": 0, "selected": false, "text": "<p>You might try working with the system table sysdtspackages as demonstrated on sqldts.com in <a href=\"http://www.sqld...
2008/09/17
[ "https://Stackoverflow.com/questions/87303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I know I can edit each individual DTS package and save it as a Visual Basic script, but with hundreds of packages on the server, that will take forever. How can I script them all at once? I'd like to be able to create one file per package so that I can check them into source control, search them to see which one references a specific table, or compare the packages on our development server to the packages on our production server.
I ended up digging through the SQL 2000 documentation (Building SQL Server Applications / DTS Programming / Programming DTS Applications / DTS Object Model) and creating a VBS script to read the packages and write XML files. It's not complete, and it could be improved in several ways, but it's a big start: GetPackages.vbs ``` Option Explicit Sub GetProperties (strPackageName, dtsProperties, xmlDocument, xmlProperties) Dim dtsProperty If Not dtsProperties Is Nothing Then For Each dtsProperty in dtsProperties If dtsProperty.Set Then Dim xmlProperty Set xmlProperty = xmlProperties.insertBefore ( _ xmlDocument.createElement ("Property"), _ xmlProperties.selectSingleNode ("Property[@Name > '" & dtsProperty.Name & "']")) 'properties 'xmlProperty.setAttribute "Get", dtsProperty.Get 'xmlProperty.setAttribute "Set", dtsProperty.Set xmlProperty.setAttribute "Type", dtsProperty.Type xmlProperty.setAttribute "Name", dtsProperty.Name If not isnull(dtsProperty.Value) Then xmlProperty.setAttribute "Value", dtsProperty.Value End If 'collections 'getting properties of properties causes a stack overflow 'GetProperties strPackageName, dtsProperty.Properties, xmlDocument, xmlProperty.appendChild (xmlDocument.createElement ("Properties")) End If Next End If End Sub Sub GetOLEDBProperties (strPackageName, dtsOLEDBProperties, xmlDocument, xmlOLEDBProperties) Dim dtsOLEDBProperty For Each dtsOLEDBProperty in dtsOLEDBProperties If dtsOLEDBProperty.IsDefaultValue = 0 Then Dim xmlOLEDBProperty Set xmlOLEDBProperty = xmlOLEDBProperties.insertBefore ( _ xmlDocument.createElement ("OLEDBProperty"), _ xmlOLEDBProperties.selectSingleNode ("OLEDBProperty[@Name > '" & dtsOLEDBProperty.Name & "']")) 'properties xmlOLEDBProperty.setAttribute "Name", dtsOLEDBProperty.Name 'xmlOLEDBProperty.setAttribute "PropertyID", dtsOLEDBProperty.PropertyID 'xmlOLEDBProperty.setAttribute "PropertySet", dtsOLEDBProperty.PropertySet xmlOLEDBProperty.setAttribute "Value", dtsOLEDBProperty.Value 'xmlOLEDBProperty.setAttribute "IsDefaultValue", dtsOLEDBProperty.IsDefaultValue 'collections 'these properties are the same as the ones directly above 'GetProperties strPackageName, dtsOLEDBProperty.Properties, xmlDocument, xmlOLEDBProperty.appendChild (xmlDocument.createElement ("Properties")) End If Next End Sub Sub GetConnections (strPackageName, dtsConnections, xmlDocument, xmlConnections) Dim dtsConnection2 For Each dtsConnection2 in dtsConnections Dim xmlConnection2 Set xmlConnection2 = xmlConnections.insertBefore ( _ xmlDocument.createElement ("Connection2"), _ xmlConnections.selectSingleNode ("Connection2[@Name > '" & dtsConnection2.Name & "']")) 'properties xmlConnection2.setAttribute "ID", dtsConnection2.ID xmlConnection2.setAttribute "Name", dtsConnection2.Name xmlConnection2.setAttribute "ProviderID", dtsConnection2.ProviderID 'collections GetProperties strPackageName, dtsConnection2.Properties, xmlDocument, xmlConnection2.appendChild (xmlDocument.createElement ("Properties")) Dim dtsOLEDBProperties On Error Resume Next Set dtsOLEDBProperties = dtsConnection2.ConnectionProperties If Err.Number = 0 Then On Error Goto 0 GetOLEDBProperties strPackageName, dtsOLEDBProperties, xmlDocument, xmlConnection2.appendChild (xmlDocument.createElement ("ConnectionProperties")) Else MsgBox Err.Description & vbCrLf & "ProviderID: " & dtsConnection2.ProviderID & vbCrLf & "Connection Name: " & dtsConnection2.Name, , strPackageName On Error Goto 0 End If Next End Sub Sub GetGlobalVariables (strPackageName, dtsGlobalVariables, xmlDocument, xmlGlobalVariables) Dim dtsGlobalVariable2 For Each dtsGlobalVariable2 in dtsGlobalVariables Dim xmlGlobalVariable2 Set xmlGlobalVariable2 = xmlGlobalVariables.insertBefore ( _ xmlDocument.createElement ("GlobalVariable2"), _ xmlGlobalVariables.selectSingleNode ("GlobalVariable2[@Name > '" & dtsGlobalVariable2.Name & "']")) 'properties xmlGlobalVariable2.setAttribute "Name", dtsGlobalVariable2.Name If Not Isnull(dtsGlobalVariable2.Value) Then xmlGlobalVariable2.setAttribute "Value", dtsGlobalVariable2.Value End If 'no extended properties 'collections 'GetProperties strPackageName, dtsGlobalVariable2.Properties, xmlDocument, xmlGlobalVariable2.appendChild (xmlDocument.createElement ("Properties")) Next End Sub Sub GetSavedPackageInfos (strPackageName, dtsSavedPackageInfos, xmlDocument, xmlSavedPackageInfos) Dim dtsSavedPackageInfo For Each dtsSavedPackageInfo in dtsSavedPackageInfos Dim xmlSavedPackageInfo Set xmlSavedPackageInfo = xmlSavedPackageInfos.appendChild (xmlDocument.createElement ("SavedPackageInfo")) 'properties xmlSavedPackageInfo.setAttribute "Description", dtsSavedPackageInfo.Description xmlSavedPackageInfo.setAttribute "IsVersionEncrypted", dtsSavedPackageInfo.IsVersionEncrypted xmlSavedPackageInfo.setAttribute "PackageCreationDate", dtsSavedPackageInfo.PackageCreationDate xmlSavedPackageInfo.setAttribute "PackageID", dtsSavedPackageInfo.PackageID xmlSavedPackageInfo.setAttribute "PackageName", dtsSavedPackageInfo.PackageName xmlSavedPackageInfo.setAttribute "VersionID", dtsSavedPackageInfo.VersionID xmlSavedPackageInfo.setAttribute "VersionSaveDate", dtsSavedPackageInfo.VersionSaveDate Next End Sub Sub GetPrecedenceConstraints (strPackageName, dtsPrecedenceConstraints, xmlDocument, xmlPrecedenceConstraints) Dim dtsPrecedenceConstraint For Each dtsPrecedenceConstraint in dtsPrecedenceConstraints Dim xmlPrecedenceConstraint Set xmlPrecedenceConstraint = xmlPrecedenceConstraints.insertBefore ( _ xmlDocument.createElement ("PrecedenceConstraint"), _ xmlPrecedenceConstraints.selectSingleNode ("PrecedenceConstraint[@StepName > '" & dtsPrecedenceConstraint.StepName & "']")) 'properties xmlPrecedenceConstraint.setAttribute "StepName", dtsPrecedenceConstraint.StepName 'collections GetProperties strPackageName, dtsPrecedenceConstraint.Properties, xmlDocument, xmlPrecedenceConstraint.appendChild (xmlDocument.createElement ("Properties")) Next End Sub Sub GetSteps (strPackageName, dtsSteps, xmlDocument, xmlSteps) Dim dtsStep2 For Each dtsStep2 in dtsSteps Dim xmlStep2 Set xmlStep2 = xmlSteps.insertBefore ( _ xmlDocument.createElement ("Step2"), _ xmlSteps.selectSingleNode ("Step2[@Name > '" & dtsStep2.Name & "']")) 'properties xmlStep2.setAttribute "Name", dtsStep2.Name xmlStep2.setAttribute "Description", dtsStep2.Description 'collections GetProperties strPackageName, dtsStep2.Properties, xmlDocument, xmlStep2.appendChild (xmlDocument.createElement ("Properties")) GetPrecedenceConstraints strPackageName, dtsStep2.PrecedenceConstraints, xmlDocument, xmlStep2.appendChild (xmlDocument.createElement ("PrecedenceConstraints")) Next End Sub Sub GetColumns (strPackageName, dtsColumns, xmlDocument, xmlColumns) Dim dtsColumn For Each dtsColumn in dtsColumns Dim xmlColumn Set xmlColumn = xmlColumns.appendChild (xmlDocument.createElement ("Column")) GetProperties strPackageName, dtsColumn.Properties, xmlDocument, xmlColumn.appendChild (xmlDocument.createElement ("Properties")) Next End Sub Sub GetLookups (strPackageName, dtsLookups, xmlDocument, xmlLookups) Dim dtsLookup For Each dtsLookup in dtsLookups Dim xmlLookup Set xmlLookup = xmlLookups.appendChild (xmlDocument.createElement ("Lookup")) GetProperties strPackageName, dtsLookup.Properties, xmlDocument, xmlLookup.appendChild (xmlDocument.createElement ("Properties")) Next End Sub Sub GetTransformations (strPackageName, dtsTransformations, xmlDocument, xmlTransformations) Dim dtsTransformation For Each dtsTransformation in dtsTransformations Dim xmlTransformation Set xmlTransformation = xmlTransformations.appendChild (xmlDocument.createElement ("Transformation")) GetProperties strPackageName, dtsTransformation.Properties, xmlDocument, xmlTransformation.appendChild (xmlDocument.createElement ("Properties")) Next End Sub Sub GetTasks (strPackageName, dtsTasks, xmlDocument, xmlTasks) Dim dtsTask For each dtsTask in dtsTasks Dim xmlTask Set xmlTask = xmlTasks.insertBefore ( _ xmlDocument.createElement ("Task"), _ xmlTasks.selectSingleNode ("Task[@Name > '" & dtsTask.Name & "']")) ' The task can be of any task type, and each type of task has different properties. 'properties xmlTask.setAttribute "CustomTaskID", dtsTask.CustomTaskID xmlTask.setAttribute "Name", dtsTask.Name xmlTask.setAttribute "Description", dtsTask.Description 'collections GetProperties strPackageName, dtsTask.Properties, xmlDocument, xmlTask.appendChild (xmlDocument.createElement ("Properties")) If dtsTask.CustomTaskID = "DTSDataPumpTask" Then GetOLEDBProperties strPackageName, dtsTask.CustomTask.SourceCommandProperties, xmlDocument, xmlTask.appendChild (xmlDocument.createElement ("SourceCommandProperties")) GetOLEDBProperties strPackageName, dtsTask.CustomTask.DestinationCommandProperties, xmlDocument, xmlTask.appendChild (xmlDocument.createElement ("DestinationCommandProperties")) GetColumns strPackageName, dtsTask.CustomTask.DestinationColumnDefinitions, xmlDocument, xmlTask.appendChild (xmlDocument.createElement ("DestinationColumnDefinitions")) GetLookups strPackageName, dtsTask.CustomTask.Lookups, xmlDocument, xmlTask.appendChild (xmlDocument.createElement ("Lookups")) GetTransformations strPackageName, dtsTask.CustomTask.Transformations, xmlDocument, xmlTask.appendChild (xmlDocument.createElement ("Transformations")) End If Next End Sub Sub FormatXML (xmlDocument, xmlElement, intIndent) Dim xmlSubElement For Each xmlSubElement in xmlElement.selectNodes ("*") xmlElement.insertBefore xmlDocument.createTextNode (vbCrLf & String (intIndent + 1, vbTab)), xmlSubElement FormatXML xmlDocument, xmlSubElement, intIndent + 1 Next If xmlElement.selectNodes ("*").length > 0 Then xmlElement.appendChild xmlDocument.createTextNode (vbCrLf & String (intIndent, vbTab)) End If End Sub Sub GetPackage (strServerName, strPackageName) Dim dtsPackage2 Set dtsPackage2 = CreateObject ("DTS.Package2") Dim DTSSQLStgFlag_Default Dim DTSSQLStgFlag_UseTrustedConnection DTSSQLStgFlag_Default = 0 DTSSQLStgFlag_UseTrustedConnection = 256 On Error Resume Next dtsPackage2.LoadFromSQLServer strServerName, , , DTSSQLStgFlag_UseTrustedConnection, , , , strPackageName If Err.Number = 0 Then On Error Goto 0 'fsoTextStream.WriteLine dtsPackage2.Name Dim xmlDocument Set xmlDocument = CreateObject ("Msxml2.DOMDocument.3.0") Dim xmlPackage2 Set xmlPackage2 = xmlDocument.appendChild (xmlDocument.createElement ("Package2")) 'properties xmlPackage2.setAttribute "Name", dtsPackage2.Name 'collections GetProperties strPackageName, dtsPackage2.Properties, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement("Properties")) GetConnections strPackageName, dtsPackage2.Connections, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement ("Connections")) GetGlobalVariables strPackageName, dtsPackage2.GlobalVariables, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement ("GlobalVariables")) 'SavedPackageInfos only apply to DTS packages saved in structured storage files 'GetSavedPackageInfos strPackageName, dtsPackage2.SavedPackageInfos, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement ("SavedPackageInfos")) GetSteps strPackageName, dtsPackage2.Steps, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement ("Steps")) GetTasks strPackageName, dtsPackage2.Tasks, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement ("Tasks")) FormatXML xmlDocument, xmlPackage2, 0 xmlDocument.save strPackageName + ".xml" Else MsgBox Err.Description, , strPackageName On Error Goto 0 End If End Sub Sub Main Dim strServerName strServerName = Trim (InputBox ("Server:")) If strServerName "" Then Dim cnSQLServer Set cnSQLServer = CreateObject ("ADODB.Connection") cnSQLServer.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=msdb;Data Source=" & strServerName Dim rsDTSPackages Set rsDTSPackages = cnSQLServer.Execute ("SELECT DISTINCT name FROM sysdtspackages ORDER BY name") Dim strPackageNames Do While Not rsDTSPackages.EOF GetPackage strServerName, rsDTSPackages ("name") rsDTSPackages.MoveNext Loop rsDTSPackages.Close set rsDTSPackages = Nothing cnSQLServer.Close Set cnSQLServer = Nothing Dim strCustomTaskIDs Dim strCustomTaskID MsgBox "Finished", , "GetPackages.vbs" End If End Sub Main ```
87,304
<p>What's a good algorithm for calculating frames per second in a game? I want to show it as a number in the corner of the screen. If I just look at how long it took to render the last frame the number changes too fast.</p> <p>Bonus points if your answer updates each frame and doesn't converge differently when the frame rate is increasing vs decreasing.</p>
[ { "answer_id": 87333, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 7, "selected": false, "text": "<p>You need a smoothed average, the easiest way is to take the current answer (the time to draw the last frame) and ...
2008/09/17
[ "https://Stackoverflow.com/questions/87304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16679/" ]
What's a good algorithm for calculating frames per second in a game? I want to show it as a number in the corner of the screen. If I just look at how long it took to render the last frame the number changes too fast. Bonus points if your answer updates each frame and doesn't converge differently when the frame rate is increasing vs decreasing.
You need a smoothed average, the easiest way is to take the current answer (the time to draw the last frame) and combine it with the previous answer. ``` // eg. float smoothing = 0.9; // larger=more smoothing measurement = (measurement * smoothing) + (current * (1.0-smoothing)) ``` By adjusting the 0.9 / 0.1 ratio you can change the 'time constant' - that is how quickly the number responds to changes. A larger fraction in favour of the old answer gives a slower smoother change, a large fraction in favour of the new answer gives a quicker changing value. Obviously the two factors must add to one!
87,317
<p>I need to get a list of attribute values from child elements in Python.</p> <p>It's easiest to explain with an example.</p> <p>Given some XML like this:</p> <pre><code>&lt;elements&gt; &lt;parent name="CategoryA"&gt; &lt;child value="a1"/&gt; &lt;child value="a2"/&gt; &lt;child value="a3"/&gt; &lt;/parent&gt; &lt;parent name="CategoryB"&gt; &lt;child value="b1"/&gt; &lt;child value="b2"/&gt; &lt;child value="b3"/&gt; &lt;/parent&gt; &lt;/elements&gt; </code></pre> <p>I want to be able to do something like:</p> <pre class="lang-python prettyprint-override"><code>&gt;&gt;&gt; getValues("CategoryA") ['a1', 'a2', 'a3'] &gt;&gt;&gt; getValues("CategoryB") ['b1', 'b2', 'b3'] </code></pre> <p>It looks like a job for XPath but I'm open to all recommendations. I'd also like to hear about your favourite Python XML libraries.</p>
[ { "answer_id": 87503, "author": "pjz", "author_id": 8002, "author_profile": "https://Stackoverflow.com/users/8002", "pm_score": 2, "selected": false, "text": "<p>I must admit I'm a fan of <a href=\"http://www.aaronsw.com/2002/xmltramp/\" rel=\"nofollow noreferrer\">xmltramp</a> due to it...
2008/09/17
[ "https://Stackoverflow.com/questions/87317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3464/" ]
I need to get a list of attribute values from child elements in Python. It's easiest to explain with an example. Given some XML like this: ``` <elements> <parent name="CategoryA"> <child value="a1"/> <child value="a2"/> <child value="a3"/> </parent> <parent name="CategoryB"> <child value="b1"/> <child value="b2"/> <child value="b3"/> </parent> </elements> ``` I want to be able to do something like: ```python >>> getValues("CategoryA") ['a1', 'a2', 'a3'] >>> getValues("CategoryB") ['b1', 'b2', 'b3'] ``` It looks like a job for XPath but I'm open to all recommendations. I'd also like to hear about your favourite Python XML libraries.
I'm not really an old hand at Python, but here's an XPath solution using libxml2. ``` import libxml2 DOC = """<elements> <parent name="CategoryA"> <child value="a1"/> <child value="a2"/> <child value="a3"/> </parent> <parent name="CategoryB"> <child value="b1"/> <child value="b2"/> <child value="b3"/> </parent> </elements>""" doc = libxml2.parseDoc(DOC) def getValues(cat): return [attr.content for attr in doc.xpathEval("/elements/parent[@name='%s']/child/@value" % (cat))] print getValues("CategoryA") ``` With result... ``` ['a1', 'a2', 'a3'] ```
87,330
<p>Is there a canonical ordering of submatch expressions in a regular expression? </p> <p>For example: What is the order of the submatches in<br> "(([0-9]{3}).([0-9]{3}).([0-9]{3}).([0-9]{3}))\s+([A-Z]+)" ?</p> <pre><code>a. (([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3}))\s+([A-Z]+) (([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3})) ([A-Z]+) ([0-9]{3}) ([0-9]{3}) ([0-9]{3}) ([0-9]{3}) b. (([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3}))\s+([A-Z]+) (([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3})) ([0-9]{3}) ([0-9]{3}) ([0-9]{3}) ([0-9]{3}) ([A-Z]+) </code></pre> <p>or</p> <pre><code>c. somthin' else. </code></pre>
[ { "answer_id": 87354, "author": "jjrv", "author_id": 16509, "author_profile": "https://Stackoverflow.com/users/16509", "pm_score": 2, "selected": false, "text": "<p>They tend to be numbered in the order the capturing parens start, left to right. Therefore, option b.</p>\n" }, { "...
2008/09/17
[ "https://Stackoverflow.com/questions/87330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16753/" ]
Is there a canonical ordering of submatch expressions in a regular expression? For example: What is the order of the submatches in "(([0-9]{3}).([0-9]{3}).([0-9]{3}).([0-9]{3}))\s+([A-Z]+)" ? ``` a. (([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3}))\s+([A-Z]+) (([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3})) ([A-Z]+) ([0-9]{3}) ([0-9]{3}) ([0-9]{3}) ([0-9]{3}) b. (([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3}))\s+([A-Z]+) (([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3})) ([0-9]{3}) ([0-9]{3}) ([0-9]{3}) ([0-9]{3}) ([A-Z]+) ``` or ``` c. somthin' else. ```
They tend to be numbered in the order the capturing parens start, left to right. Therefore, option b.
87,372
<p>I'm asking for a template trick to detect if a class has a specific member function of a given signature.</p> <p>The problem is similar to the one cited here <a href="http://www.gotw.ca/gotw/071.htm" rel="noreferrer">http://www.gotw.ca/gotw/071.htm</a> but not the same: in the item of Sutter's book he answered to the question that a class C MUST PROVIDE a member function with a particular signature, else the program won't compile. In my problem I need to do something if a class has that function, else do "something else". </p> <p>A similar problem was faced by boost::serialization but I don't like the solution they adopted: a template function that invokes by default a free function (that you have to define) with a particular signature unless you define a particular member function (in their case "serialize" that takes 2 parameters of a given type) with a particular signature, else a compile error will happens. That is to implement both intrusive and non-intrusive serialization. </p> <p>I don't like that solution for two reasons:</p> <ol> <li>To be non intrusive you must override the global "serialize" function that is in boost::serialization namespace, so you have IN YOUR CLIENT CODE to open namespace boost and namespace serialization!</li> <li>The stack to resolve that mess was 10 to 12 function invocations.</li> </ol> <p>I need to define a custom behavior for classes that has not that member function, and my entities are inside different namespaces (and I don't want to override a global function defined in one namespace while I'm in another one)</p> <p>Can you give me a hint to solve this puzzle?</p>
[ { "answer_id": 87474, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "<p>To be non-intrusive, you can also put <code>serialize</code> in the namespace of the class being serialised, or of the arc...
2008/09/17
[ "https://Stackoverflow.com/questions/87372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10120/" ]
I'm asking for a template trick to detect if a class has a specific member function of a given signature. The problem is similar to the one cited here <http://www.gotw.ca/gotw/071.htm> but not the same: in the item of Sutter's book he answered to the question that a class C MUST PROVIDE a member function with a particular signature, else the program won't compile. In my problem I need to do something if a class has that function, else do "something else". A similar problem was faced by boost::serialization but I don't like the solution they adopted: a template function that invokes by default a free function (that you have to define) with a particular signature unless you define a particular member function (in their case "serialize" that takes 2 parameters of a given type) with a particular signature, else a compile error will happens. That is to implement both intrusive and non-intrusive serialization. I don't like that solution for two reasons: 1. To be non intrusive you must override the global "serialize" function that is in boost::serialization namespace, so you have IN YOUR CLIENT CODE to open namespace boost and namespace serialization! 2. The stack to resolve that mess was 10 to 12 function invocations. I need to define a custom behavior for classes that has not that member function, and my entities are inside different namespaces (and I don't want to override a global function defined in one namespace while I'm in another one) Can you give me a hint to solve this puzzle?
I'm not sure if I understand you correctly, but you may exploit SFINAE to detect function presence at compile-time. Example from my code (tests if class has member function size\_t used\_memory() const). ``` template<typename T> struct HasUsedMemoryMethod { template<typename U, size_t (U::*)() const> struct SFINAE {}; template<typename U> static char Test(SFINAE<U, &U::used_memory>*); template<typename U> static int Test(...); static const bool Has = sizeof(Test<T>(0)) == sizeof(char); }; template<typename TMap> void ReportMemUsage(const TMap& m, std::true_type) { // We may call used_memory() on m here. } template<typename TMap> void ReportMemUsage(const TMap&, std::false_type) { } template<typename TMap> void ReportMemUsage(const TMap& m) { ReportMemUsage(m, std::integral_constant<bool, HasUsedMemoryMethod<TMap>::Has>()); } ```
87,381
<p>With ViEmu you really need to unbind a lot of resharpers keybindings to make it work well.</p> <p>Does anyone have what they think is a good set of keybindings that work well for resharper when using ViEmu?</p> <p>What I'm doing at the moment using the Visual Studio bindings from Resharper. Toasting all the conflicting ones with ViEmu, and then just driving the rest through the menu modifiers ( Alt-R keyboard shortcut for the menu item ). I also do the same with Visual Assist shortcuts ( for C++ )</p> <p>if anyones got any tips and tricks for ViEmu / Resharper or Visual Assist working together well I'd most apprciate it!</p>
[ { "answer_id": 88223, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 0, "selected": false, "text": "<p>I use both plugins, but I really prefer the power of the Vi input model that ViEmu gives. I really don't miss...
2008/09/17
[ "https://Stackoverflow.com/questions/87381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10431/" ]
With ViEmu you really need to unbind a lot of resharpers keybindings to make it work well. Does anyone have what they think is a good set of keybindings that work well for resharper when using ViEmu? What I'm doing at the moment using the Visual Studio bindings from Resharper. Toasting all the conflicting ones with ViEmu, and then just driving the rest through the menu modifiers ( Alt-R keyboard shortcut for the menu item ). I also do the same with Visual Assist shortcuts ( for C++ ) if anyones got any tips and tricks for ViEmu / Resharper or Visual Assist working together well I'd most apprciate it!
You can also create mappings in ViEmu that will call the VS and R# actions. For example, I have these lines in my \_viemurc file for commenting and uncommenting a selection: ``` map <C-S-c> gS:vsc Edit.CommentSelection<CR> map <C-A-c> gS:vsc Edit.UncommentSelection<CR> ``` The :vsc is for "visual studio command," and then you enter the exact text of the command, as it appears in the commands list when you go to Tool>Options>Keyboard I don't use any of the R# ones in this way, but it does work, as with: ``` map <C-S-A-f> gS:vsc ReSharper.FindUsages<CR> ```
87,458
<p>I want to do this so that I can say something like, <code>svn mv *.php php-folder/</code>, but it does not seem to be working. Is it even possible? No mention of it is made on the relevant page in the <a href="http://svnbook.red-bean.com/en/1.0/re18.html" rel="noreferrer">svn book</a>.</p> <p>Example output of <code>svn mv *.php php-folder/</code> :<br> <code>svn: Client error in parsing arguments</code></p> <p>Being able to move a whole file system would be a plus, so if any answers given could try to include that ability, that'd be cool.</p> <p>Thanks in advance!</p>
[ { "answer_id": 87488, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 0, "selected": false, "text": "<p>If you're in the correct checked out directory, I don't see why it wouldn't work? Your shell should expand the *.php to a ...
2008/09/17
[ "https://Stackoverflow.com/questions/87458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16562/" ]
I want to do this so that I can say something like, `svn mv *.php php-folder/`, but it does not seem to be working. Is it even possible? No mention of it is made on the relevant page in the [svn book](http://svnbook.red-bean.com/en/1.0/re18.html). Example output of `svn mv *.php php-folder/` : `svn: Client error in parsing arguments` Being able to move a whole file system would be a plus, so if any answers given could try to include that ability, that'd be cool. Thanks in advance!
Not sure about svn itself, but either your shell should be able to expand that wildcard and svn can take multiple source arguments, or you can use something like ``` for file in *.php; do svn mv $file php-folder/; done ``` in a bash shell, for example.
87,459
<p>I have a class with a string property that's actually several strings joined with a separator.</p> <p>I'm wondering if it is good form to have a proxy property like this:</p> <pre><code>public string ActualProperty { get { return actualProperty; } set { actualProperty = value; } } public string[] IndividualStrings { get { return ActualProperty.Split(.....); } set { // join strings from array in propval .... ; ActualProperty = propval; } } </code></pre> <p>Is there any risks I have overlooked?</p>
[ { "answer_id": 87491, "author": "typemismatch", "author_id": 13714, "author_profile": "https://Stackoverflow.com/users/13714", "pm_score": 0, "selected": false, "text": "<p>Well I'd say your \"set\" is high risk, what if somebody didn't know they had to pass an already joined sequence of...
2008/09/17
[ "https://Stackoverflow.com/questions/87459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4192/" ]
I have a class with a string property that's actually several strings joined with a separator. I'm wondering if it is good form to have a proxy property like this: ``` public string ActualProperty { get { return actualProperty; } set { actualProperty = value; } } public string[] IndividualStrings { get { return ActualProperty.Split(.....); } set { // join strings from array in propval .... ; ActualProperty = propval; } } ``` Is there any risks I have overlooked?
Linking two settable properties together is bad juju in my opinion. Switch to using explicit get / set methods instead of a property if this is really what you want. Code which has non-obvious side-effects will almost always bite you later on. Keep things simple and straightforward as much as possible. Also, if you have a property which is a formatted string containing sub-strings, it looks like what you really want is a separate struct / class for that property rather than misusing a primitive type.
87,468
<p>Essentially I have a PHP page that calls out some other HTML to be rendered through an object's method. It looks like this:</p> <p>MY PHP PAGE:</p> <pre><code>// some content... &lt;?php $GLOBALS["topOfThePage"] = true; $this-&gt;renderSomeHTML(); ?&gt; // some content... &lt;?php $GLOBALS["topOfThePage"] = false; $this-&gt;renderSomeHTML(); ?&gt; </code></pre> <p>The first method call is cached, but I need renderSomeHTML() to display slightly different based upon its location in the page. I tried passing through to $GLOBALS, but the value doesn't change, so I'm assuming it is getting cached.</p> <p>Is this not possible without passing an argument through the method or by not caching it? Any help is appreciated. This is not my application -- it is Magento.</p> <p><strong>Edit:</strong></p> <p>This is Magento, and it looks to be using memcached. I tried to pass an argument through renderSomeHTML(), but when I use func_get_args() on the PHP include to be rendered, what comes out is not what I put into it.</p> <p><strong>Edit:</strong></p> <p>Further down the line I was able to "invalidate" the cache by calling a different method that pulled the same content and passing in an argument that turned off caching. Thanks everyone for your help.</p>
[ { "answer_id": 87507, "author": "DGM", "author_id": 14253, "author_profile": "https://Stackoverflow.com/users/14253", "pm_score": 1, "selected": false, "text": "<p>Chaching is handled differently by different frameworks, so you'd have to help us out with some more information. But I als...
2008/09/17
[ "https://Stackoverflow.com/questions/87468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Essentially I have a PHP page that calls out some other HTML to be rendered through an object's method. It looks like this: MY PHP PAGE: ``` // some content... <?php $GLOBALS["topOfThePage"] = true; $this->renderSomeHTML(); ?> // some content... <?php $GLOBALS["topOfThePage"] = false; $this->renderSomeHTML(); ?> ``` The first method call is cached, but I need renderSomeHTML() to display slightly different based upon its location in the page. I tried passing through to $GLOBALS, but the value doesn't change, so I'm assuming it is getting cached. Is this not possible without passing an argument through the method or by not caching it? Any help is appreciated. This is not my application -- it is Magento. **Edit:** This is Magento, and it looks to be using memcached. I tried to pass an argument through renderSomeHTML(), but when I use func\_get\_args() on the PHP include to be rendered, what comes out is not what I put into it. **Edit:** Further down the line I was able to "invalidate" the cache by calling a different method that pulled the same content and passing in an argument that turned off caching. Thanks everyone for your help.
Obviously, you cannot. The whole point of caching is that the 'thing' you cache is not going to change. So you either: * provide a parameter * aviod caching * invalidate the cache when you set a different parameter Or, you rewrite the cache mechanism yourself - to support some dynamic binding.
87,514
<p>I'm an experienced programmer in a legacy (yet object oriented) development tool and making the switch to C#/.Net. I'm writing a small single user app using SQL server CE 3.5. I've read the conceptual DataSet and related doc and my code works.</p> <p>Now I want to make sure that I'm doing it "right", get some feedback from experienced .Net/SQL Server coders, the kind you don't get from reading the doc.</p> <p>I've noticed that I have code like this in a few places:</p> <pre><code>var myTableDataTable = new MyDataSet.MyTableDataTable(); myTableTableAdapter.Fill(MyTableDataTable); ... // other code </code></pre> <p>In a single user app, would you typically just do this once when the app starts, instantiate a DataTable object for each table and then store a ref to it so you ever just use that single object which is already filled with data? This way you would ever only read the data from the db once instead of potentially multiple times. Or is the overhead of this so small that it just doesn't matter (plus could be counterproductive with large tables)?</p>
[ { "answer_id": 87538, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>For CE, it's probably a non issue. If you were pushing this app to thousands of users and they were all hitting a centralize...
2008/09/17
[ "https://Stackoverflow.com/questions/87514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16757/" ]
I'm an experienced programmer in a legacy (yet object oriented) development tool and making the switch to C#/.Net. I'm writing a small single user app using SQL server CE 3.5. I've read the conceptual DataSet and related doc and my code works. Now I want to make sure that I'm doing it "right", get some feedback from experienced .Net/SQL Server coders, the kind you don't get from reading the doc. I've noticed that I have code like this in a few places: ``` var myTableDataTable = new MyDataSet.MyTableDataTable(); myTableTableAdapter.Fill(MyTableDataTable); ... // other code ``` In a single user app, would you typically just do this once when the app starts, instantiate a DataTable object for each table and then store a ref to it so you ever just use that single object which is already filled with data? This way you would ever only read the data from the db once instead of potentially multiple times. Or is the overhead of this so small that it just doesn't matter (plus could be counterproductive with large tables)?
For CE, it's probably a non issue. If you were pushing this app to thousands of users and they were all hitting a centralized DB, you might want to spend some time on optimization. In a single-user instance DB like CE, unless you've got data that says you need to optimize, I wouldn't spend any time worrying about it. Premature optimization, etc.
87,541
<p>What column names cannot be used when creating an Excel spreadsheet with ADO.</p> <p>I have a statement that creates a page in a spreadsheet:</p> <pre><code>CREATE TABLE [TableName] (Column string, Column2 string); </code></pre> <p>I have found that using a column name of <code>Date</code> or <code>Container</code> will generate an error when the statement is executed.</p> <p>Does anyone have a complete (or partial) list of words that cannot be used as column names? This is for use in a user-driven environment and it would be better to "fix" the columns than to crash. </p> <p>My work-around for these is to replace any occurences of <code>Date</code> or <code>Container</code> with <code>Date_</code> and <code>Container_</code> respectively.</p>
[ { "answer_id": 89923, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 1, "selected": false, "text": "<p>It may be possible to define a custom template for the DIP and deploy that to the site, setting the content type to link to ...
2008/09/17
[ "https://Stackoverflow.com/questions/87541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5008/" ]
What column names cannot be used when creating an Excel spreadsheet with ADO. I have a statement that creates a page in a spreadsheet: ``` CREATE TABLE [TableName] (Column string, Column2 string); ``` I have found that using a column name of `Date` or `Container` will generate an error when the statement is executed. Does anyone have a complete (or partial) list of words that cannot be used as column names? This is for use in a user-driven environment and it would be better to "fix" the columns than to crash. My work-around for these is to replace any occurences of `Date` or `Container` with `Date_` and `Container_` respectively.
It may be possible to define a custom template for the DIP and deploy that to the site, setting the content type to link to that template.
87,557
<p>I have a class with many embedded assets. </p> <p>Within the class, I would like to get the class definition of an asset by name. I have tried using getDefinitionByName(), and also ApplicationDomain.currentDomain.getDefinition() but neither work.</p> <p>Example:</p> <pre><code>public class MyClass { [Embed(source="images/image1.png")] private static var Image1Class:Class; [Embed(source="images/image2.png")] private static var Image2Class:Class; [Embed(source="images/image3.png")] private static var Image3Class:Class; private var _image:Bitmap; public function MyClass(name:String) { var ClassDef:Class = getDefinitionByName(name) as Class; //&lt;&lt;-- Fails _image = new ClassDef() as Bitmap; } } var cls:MyClass = new MyClass("Image1Class"); </code></pre>
[ { "answer_id": 87596, "author": "Marc Hughes", "author_id": 6791, "author_profile": "https://Stackoverflow.com/users/6791", "pm_score": 4, "selected": true, "text": "<p>This doesn't answer your question, but it may solve your problem. I believe doing something like this should work:</p>...
2008/09/17
[ "https://Stackoverflow.com/questions/87557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8399/" ]
I have a class with many embedded assets. Within the class, I would like to get the class definition of an asset by name. I have tried using getDefinitionByName(), and also ApplicationDomain.currentDomain.getDefinition() but neither work. Example: ``` public class MyClass { [Embed(source="images/image1.png")] private static var Image1Class:Class; [Embed(source="images/image2.png")] private static var Image2Class:Class; [Embed(source="images/image3.png")] private static var Image3Class:Class; private var _image:Bitmap; public function MyClass(name:String) { var ClassDef:Class = getDefinitionByName(name) as Class; //<<-- Fails _image = new ClassDef() as Bitmap; } } var cls:MyClass = new MyClass("Image1Class"); ```
This doesn't answer your question, but it may solve your problem. I believe doing something like this should work: ``` public class MyClass { [Embed(source="images/image1.png")] private static var Image1Class:Class; [Embed(source="images/image2.png")] private static var Image2Class:Class; [Embed(source="images/image3.png")] private static var Image3Class:Class; private var _image:Bitmap; public function MyClass(name:String) { _image = new this[name]() as Bitmap; } } var cls:MyClass = new MyClass("Image1Class"); ``` I'm having a tough time remembering if bracket notation works on sealed classes. If it doesn't, a simple solution is to mark the class as dynamic.
87,561
<p>I'd like to add some pie, bar and scatter charts to my Ruby on Rails web application. I want want them to be atractive, easy to add and not introduce much overhead. </p> <p>What charting solution would you recommend?<br> What are its drawbacks (requires Javascript, Flash, expensive, etc)?</p>
[ { "answer_id": 87579, "author": "David Heggie", "author_id": 4309, "author_profile": "https://Stackoverflow.com/users/4309", "pm_score": 3, "selected": false, "text": "<p>Have you tried the <a href=\"http://code.google.com/apis/chart/\" rel=\"nofollow noreferrer\">Google Charts API</a>? ...
2008/09/17
[ "https://Stackoverflow.com/questions/87561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16779/" ]
I'd like to add some pie, bar and scatter charts to my Ruby on Rails web application. I want want them to be atractive, easy to add and not introduce much overhead. What charting solution would you recommend? What are its drawbacks (requires Javascript, Flash, expensive, etc)?
[Google Charts](http://code.google.com/apis/chart/) is an excellent choice if you don't want to use Flash. It's pretty easy to use on its own, but for Rails, it's even easier with the [gchartrb](http://badpopcorn.com/blog/2008/09/08/rails-google-charts-gchartrb/) gem. An example: ``` GoogleChart::PieChart.new('320x200', "Things I Like To Eat", false) do |pc| pc.data "Broccoli", 30 pc.data "Pizza", 20 pc.data "PB&J", 40 pc.data "Turnips", 10 puts pc.to_url end ```
87,587
<p>Continuing my problem from yesterday, the Silverlight datagrid I have from this <a href="https://stackoverflow.com/questions/74461/silverlight-datagrid-control-selection-changed-event-interfering-with-sorting">issue</a> is now causing Stack Overflow errors when sorting a column with a large amount of data (Like the text column that contains a where clause for a SQL statment). When you sort, it'll fire the SelectedIndexChanged event for the datagrid and then still try to stort. If you click the header again the stack overflow occours. </p> <p>Does anyone have an idea on how to stop the sorting on this control for a column? All the other columns sort fine (but still fire that darn SelectedIndexChanged event), but if I could shut off the column for whereClause it'd be perfect.</p> <p>Does anyone have a better idea at how to get this to work?</p>
[ { "answer_id": 88253, "author": "BKimmel", "author_id": 13776, "author_profile": "https://Stackoverflow.com/users/13776", "pm_score": 0, "selected": false, "text": "<p>Give this a shot:</p>\n\n<pre><code>dataGridView1.Columns[*Numberofthecolumnyoudontwantsorted*].SortMode\n= DataGridView...
2008/09/17
[ "https://Stackoverflow.com/questions/87587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12413/" ]
Continuing my problem from yesterday, the Silverlight datagrid I have from this [issue](https://stackoverflow.com/questions/74461/silverlight-datagrid-control-selection-changed-event-interfering-with-sorting) is now causing Stack Overflow errors when sorting a column with a large amount of data (Like the text column that contains a where clause for a SQL statment). When you sort, it'll fire the SelectedIndexChanged event for the datagrid and then still try to stort. If you click the header again the stack overflow occours. Does anyone have an idea on how to stop the sorting on this control for a column? All the other columns sort fine (but still fire that darn SelectedIndexChanged event), but if I could shut off the column for whereClause it'd be perfect. Does anyone have a better idea at how to get this to work?
I'm only familiar with the WPF version of this datagrid, but try this: ``` <data:DataGridTextColumn CanUserSort="False" Header="First Name" Binding="{Binding FirstName}" /> ``` Add the CanUserSort="False" attribute on each column you don't want sorted.
87,621
<p>I have an XML that I want to load to objects, manipulate those objects (set values, read values) and then save those XMLs back. It is important for me to have the XML in the structure (xsd) that I created.</p> <p>One way to do that is to write my own serializer, but is there a built in support for it or open source in C# that I can use? </p>
[ { "answer_id": 87633, "author": "dcstraw", "author_id": 10391, "author_profile": "https://Stackoverflow.com/users/10391", "pm_score": 0, "selected": false, "text": "<p>I'll bet NetDataContractSerializer can do what you want.</p>\n" }, { "answer_id": 87638, "author": "ljs", ...
2008/09/17
[ "https://Stackoverflow.com/questions/87621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9855/" ]
I have an XML that I want to load to objects, manipulate those objects (set values, read values) and then save those XMLs back. It is important for me to have the XML in the structure (xsd) that I created. One way to do that is to write my own serializer, but is there a built in support for it or open source in C# that I can use?
You can generate serializable C# classes from a schema (xsd) using xsd.exe: ``` xsd.exe dependency1.xsd dependency2.xsd schema.xsd /out:outputDir ``` If the schema has dependencies (included/imported schemas), they must all be included on the same command line.
87,647
<p>I have a DTS package with a data transformation task (data pump). I’d like to source the data with the results of a stored procedure that takes parameters, but DTS won’t preview the result set and can’t define the columns in the data transformation task.</p> <p>Has anyone gotten this to work?</p> <p>Caveat: The stored procedure uses two temp tables (and cleans them up, of course)</p>
[ { "answer_id": 87746, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>You would need to actually load them into a table, then you can use a SQL task to move it from that table into t...
2008/09/17
[ "https://Stackoverflow.com/questions/87647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16813/" ]
I have a DTS package with a data transformation task (data pump). I’d like to source the data with the results of a stored procedure that takes parameters, but DTS won’t preview the result set and can’t define the columns in the data transformation task. Has anyone gotten this to work? Caveat: The stored procedure uses two temp tables (and cleans them up, of course)
Enter some valid values for the stored procedure parameters so it runs and returns some data (or even no data, you just need the columns). Then you should be able to do the mapping/etc.. Then do a disconnected edit and change to the actual parameter values (I assume you are getting them from a global variable). ``` DECLARE @param1 DataType1 DECLARE @param2 DataType2 SET @param1 = global variable SET @param2 = global variable (I forget exact syntax) --EXEC procedure @param1, @param2 EXEC dbo.proc value1, value2 ``` Basically you run it like this so the procedure returns results. Do the mapping, then in disconnected edit comment out the second `EXEC` and uncomment the first `EXEC` and it should work. Basically you just need to make the procedure run and spit out results. Even if you get no rows back, it will still map the columns correctly. I don't have access to our production system (or even database) to create dts packages. So I create them in a dummy database and replace the stored procedure with something that returns the same columns that the production app would run, but no rows of data. Then after the mapping is done I move it to the production box with the real procedure and it works. This works great if you keep track of the database via scripts. You can just run the script to build an empty shell procedure and when done run the script to put back the true procedure.
87,689
<p>I have several applications that are part of a suite of tools that various developers at our studio use. these applications are mainly command line apps that open a DOS cmd shell. These apps in turn start up a GUI application that tracks output and status (via sockets) of these command line apps.</p> <p>The command line apps can be started with the user is logged in, when their workstation is locked (they fire off a batch file and then immediately lock their workstaion), and when they are logged out (via a scheduled task). The problems that I have are with the last two cases.</p> <p>If any of these apps fire off when the user is locked or logged out, these command will spawn the GUI windows which tracks the output/status. That's fine, but say the user has their workstation locked -- when they unlock their workstation, the GUI isn't visible. It's running the task list, but it's not visible. The next time these users run some of our command line apps, the GUI doesn't get launched (because it's already running), but because it's not visible on the desktop, users don't see any output.</p> <p>What I'm looking for is a way to tell from my command line apps if they are running behind a locked workstation or when a user is logged out (via scheduled task) -- basically are they running without a user's desktop visible. If I can tell that, then I can simply not start up our GUI and can prevent a lot of problem.</p> <p>These apps that I need to test are C/C++ Windows applications.</p> <p>I hope that this make sense.</p>
[ { "answer_id": 87816, "author": "Adam Neal", "author_id": 13791, "author_profile": "https://Stackoverflow.com/users/13791", "pm_score": 1, "selected": false, "text": "<p>You might be able to use SENS (System Event Notification Services). I've never used it myself, but I'm almost positiv...
2008/09/17
[ "https://Stackoverflow.com/questions/87689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4405/" ]
I have several applications that are part of a suite of tools that various developers at our studio use. these applications are mainly command line apps that open a DOS cmd shell. These apps in turn start up a GUI application that tracks output and status (via sockets) of these command line apps. The command line apps can be started with the user is logged in, when their workstation is locked (they fire off a batch file and then immediately lock their workstaion), and when they are logged out (via a scheduled task). The problems that I have are with the last two cases. If any of these apps fire off when the user is locked or logged out, these command will spawn the GUI windows which tracks the output/status. That's fine, but say the user has their workstation locked -- when they unlock their workstation, the GUI isn't visible. It's running the task list, but it's not visible. The next time these users run some of our command line apps, the GUI doesn't get launched (because it's already running), but because it's not visible on the desktop, users don't see any output. What I'm looking for is a way to tell from my command line apps if they are running behind a locked workstation or when a user is logged out (via scheduled task) -- basically are they running without a user's desktop visible. If I can tell that, then I can simply not start up our GUI and can prevent a lot of problem. These apps that I need to test are C/C++ Windows applications. I hope that this make sense.
I found the programmatic answer that I was looking for. It has to do with stations. Apparently anything running on the desktop will run on a station with a particular name. Anything that isn't on the desktop (i.e. a process started by the task manager when logged off or on a locked workstation) will get started with a different station name. Example code: ``` HWINSTA dHandle = GetProcessWindowStation(); if ( GetUserObjectInformation(dHandle, UOI_NAME, nameBuffer, bufferLen, &lenNeeded) ) { if ( stricmp(nameBuffer, "winsta0") ) { // when we get here, we are not running on the real desktop return false; } } ``` If you get inside the 'if' statement, then your process is not on the desktop, but running "somewhere else". I looked at the namebuffer value when not running from the desktop and the names don't mean much, but they are not WinSta0. Link to the docs [here](http://msdn.microsoft.com/en-us/library/ms681928.aspx).
87,692
<p>How can I, as the wiki admin, enter scripting (Javascript) into a Sharepoint wiki page?<br><br> I would like to enter a title and, when clicking on that, having displayed under it a small explanation. I usually have done that with javascript, any other idea?</p>
[ { "answer_id": 87701, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "<p>That sounds like a security risk. It seems it's possible for the wiki admin to install scripts, see <a href=\"http://en.wi...
2008/09/17
[ "https://Stackoverflow.com/questions/87692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15346/" ]
How can I, as the wiki admin, enter scripting (Javascript) into a Sharepoint wiki page? I would like to enter a title and, when clicking on that, having displayed under it a small explanation. I usually have done that with javascript, any other idea?
Assuming you're the administrator of the wiki and are willing display this on mouseover instead of on click, you don't need javascript at all -- you can use straight CSS. Here's an example of the styles and markup: ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Test</title> <style type="text/css"> h1 { padding-bottom: .5em; position: relative; } h1 span { font-weight: normal; font-size: small; position: absolute; bottom: 0; display: none; } h1:hover span { display: block; } </style> </head> <body> <h1>Here is the title! <span>Here is a little explanation</span> </h1> <p>Here is some page content</p> </body> </html> ``` With some more involved styles, your tooltip box can look as nice as you'd like.