input
stringlengths 51
42.3k
| output
stringlengths 18
55k
|
---|---|
Can you have more than one ASP.NET State Server Service in a cluster? <p>We have a 4 server cluster running ASP.NET web application using ASP.NET State Server Service for session. On one of the 4 servers ASP.NET State Server Service is running and other servers are configured to look at this. Very often we have to patch the servers, and applying patch on the State Server requires few minutes of downtime. </p>
<p>Is there a way to configure more than two ASP.NET State Server Services in a cluster, so if one goes down, the other takes over?</p>
| <p>I'd look into Session State Partitioning. Good info here:
<a href="http://blog.maartenballiauw.be/post/2008/01/ASPNET-Session-State-Partitioning-using-State-Server-Load-Balancing.aspx" rel="nofollow">http://blog.maartenballiauw.be/post/2008/01/ASPNET-Session-State-Partitioning-using-State-Server-Load-Balancing.aspx</a></p>
|
How to fix an MFC Painting Glitch? <p>I'm trying to implement some drag and drop functionality for a material system being developed at my work. Part of this system includes a 'Material Library' which acts as a repository, divided into groups, of saved materials on the user's hard drive.</p>
<p>As part of some UI polish, I was hoping to implement a 'highlight' type feature. When dragging and dropping, windows that you can legally drop a material onto will very subtly change color to improve feedback to the user that this is a valid action.</p>
<p>In the included screenshot, I am changing the bar with 'Basic Materials' (Just a CWnd with a CStatic) from having a medium gray background when unhighlighed to a blue background when hovered over. It all works well, the OnDragEnter and OnDragExit messages seem robust and set a flag indicating the highlight status. Then in OnCtrlColor I do this:</p>
<pre><code> if (!m_bHighlighted) {
pDC->FillSolidRect(0, 0, m_SizeX, kGroupHeaderHeight, kBackgroundColour);
}
else {
pDC->FillSolidRect(0, 0, m_SizeX, kGroupHeaderHeight, kHighlightedBackgroundColour);
}
</code></pre>
<p><img src="http://www.aliparr.net/badmfcpaint.jpg" alt="Material Library Badness" /></p>
<p>However, as you can see in the screenshot, the painting 'glitches' below the dragged object, leaving the original gray in place. It looks really ugly and basically spoils the whole effect.</p>
<p>Is there any way I can get around this? MFC isn't fun at the best of times, and this is causing me to tear my hair out.</p>
<p>All help gratefully appreciated.</p>
| <p>Remote debugging is a godsend for debugging visual issues. It's a pain to set up, but having a VM ready for remote debugging will pay off for sure.</p>
<p>What I like to do is set a ton of breakpoints in my paint handling, as well as in the framework paint code itself. This allows you to effectively "freeze frame" the painting without borking it up by flipping into devenv. This way you can get the true picture of who's painting in what order, and where you've got the chance to break in a fill that rect the way you need to.</p>
|
Random in python 2.5 not working? <p>I am trying to use the <code>import random</code> statement in python, but it doesn't appear to have any methods in it to use.</p>
<p>Am I missing something?</p>
| <p>You probably have a file named random.py or random.pyc in your working directory. That's shadowing the built-in random module. You need to rename random.py to something like my_random.py and/or remove the random.pyc file.</p>
<p>To tell for sure what's going on, do this:</p>
<pre><code>>>> import random
>>> print random.__file__
</code></pre>
<p>That will show you exactly which file is being imported.</p>
|
VisualSVN Server wants a username and password <p>I've renamed my server and am trying to get to the VisualSVN Server repository via TortoiseSVN. In <a href="http://stackoverflow.com/questions/69646/svn-and-renaming-the-server-its-running-on">this post</a> Gordon helped me find the right command - thanks Gordon.</p>
<p>Now VisualSVN Server is asking me for a username and password. I don't recall setting one and if I did I've forgotten it. Any idea how to reset this username / password?</p>
| <p>It depends on how your Visual SVN Server is set up. If you are using native windows authentication, just enter you domain username and password. Otherwise, you will have to log into the machine running Visual SVN Server and reset your password there. Visual SVN Server provides a convenient tool for managing users, passwords, permissions, etc. This tool should be available from the Start Menu on your server.</p>
|
CSS : Bad Gray Line to the side of the Navigation Bar on http://perl-begin.org/ <p>I'm maintaining <a href="http://perl-begin.org/" rel="nofollow">the Perl Beginners' Site</a> and used a modified template from Open Source Web Designs. Now, the problem is that I still have an undesired artifact: a gray line on the left side of the main frame, to the left of the navigation menu. Here's <a href="http://www.shlomifish.org/Files/files/images/Computer/Screenshots/perl-begin-bad-artif.png" rel="nofollow">an image</a> highlighting the undesired effect.</p>
<p>How can I fix the CSS to remedy this problem?</p>
| <p>It's the <code>background-image</code> on the body showing through. Quick fix (edit style.css or add elsewhere):</p>
<pre><code>#page-container
{
background-color: white;
}
</code></pre>
|
Date.getTime() not including time? <p>Can't understand why the following takes place:</p>
<pre><code>String date = "06-04-2007 07:05";
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm");
Date myDate = fmt.parse(date);
System.out.println(myDate); //Mon Jun 04 07:05:00 EDT 2007
long timestamp = myDate.getTime();
System.out.println(timestamp); //1180955100000 -- where are the milliseconds?
// on the other hand...
myDate = new Date();
System.out.println(myDate); //Tue Sep 16 13:02:44 EDT 2008
timestamp = myDate.getTime();
System.out.println(timestamp); //1221584564703 -- why, oh, why?
</code></pre>
| <p>What milliseconds? You are providing only minutes information in the first example, whereas your second example grabs current date from the system with milliseconds, what is it you're looking for?</p>
<pre><code>String date = "06-04-2007 07:05:00.999";
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss.S");
Date myDate = fmt.parse(date);
System.out.println(myDate);
long timestamp = myDate.getTime();
System.out.println(timestamp);
</code></pre>
|
How do I store the window size between sessions in Qt? <p>I have a QMainWindow in a Qt application. When I close it I want it to store its current restore size (the size of the window when it is not maximized). This works well when I close the window in restore mode (that is, not maximized). But if I close the window if it is maximized, then next time i start the application and restore the application (because it starts in maximized mode), then it does not remember the size it should restore to. Is there a way to do this?</p>
| <p>Use the <a href="http://doc.qt.io/qt-4.8/qwidget.html#saveGeometry" rel="nofollow">QWidget::saveGeometry</a> feature to write the current settings into the registry.(The registry is accessed using QSettings). Then use restoreGeometry() upon startup to return to the previous state.</p>
|
is there a way for my binary to react to some global hotkeys in linux? <p>Is it possible to listen for a certain hotkey ( e.g:<kbd>Ctrl</kbd><kbd>-</kbd><kbd>I</kbd> ) and then perform a specific action ? My application is written in C , will only run on Linux , and it doesn't have a GUI . Are there any libraries that help with this kind of task ?</p>
<p>EDIT:as an example,amarok has global shortcuts , so for example if you map a combination of keys to an action ( let's say <kbd>Ctrl</kbd><kbd>-</kbd><kbd>+</kbd> , <kbd>Ctrl</kbd> and <kbd>+</kbd> ) you could execute that action when you press the keys . If I would map <kbd>Ctrl</kbd><kbd>-</kbd><kbd>+</kbd> to the volume increase action , each time I press <kbd>ctrl</kbd><kbd>-</kbd><kbd>+</kbd> the volume would increase by a certain amount .</p>
<p>Thanks</p>
| <p>How global do your hotkeys need to be? Is it enough for them to be global for a X session? In that case you should be able to open an Xlib connection and listen for the events you need.</p>
<p>Ordinarily keyboard events in X are delivered to the window that currently has the focus, and propagated up the hierarchy until they are handled. Clearly this is not what we want. We need to process the event before any other window can get to it. We need to call <a href="http://tronche.com/gui/x/xlib/input/XGrabKey.html" rel="nofollow">XGrabKey</a> on the root window with the keycode and modifiers of our hotkey to accomplish this.</p>
<p>I found a good example <a href="http://ubuntuforums.org/showpost.php?p=5419687&postcount=1" rel="nofollow">here</a>.</p>
|
Delegating a task in and getting notified when it completes (in C#) <p>Conceptually, I would like to accomplish the following but have had trouble understand how to code it properly in C#:</p>
<pre><code>
SomeMethod { // Member of AClass{}
DoSomething;
Start WorkerMethod() from BClass in another thread;
DoSomethingElse;
}
</code></pre>
<p>Then, when WorkerMethod() is complete, run this:</p>
<p><pre><code>
void SomeOtherMethod() // Also member of AClass{}
{ ... }
</pre></code></p>
<p>Can anyone please give an example of that? </p>
| <p>The <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx">BackgroundWorker</a> class was added to .NET 2.0 for this exact purpose.</p>
<p>In a nutshell you do:</p>
<pre><code>BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate { myBClass.DoHardWork(); }
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(SomeOtherMethod);
worker.RunWorkerAsync();
</code></pre>
<p>You can also add fancy stuff like cancellation and progress reporting if you want :)</p>
|
How do I add a namespace reference to a SOAP response with Apache Axis2 and WSDL2Java <p>I'm looking at the SOAP output from a web service I'm developing, and I noticed something curious:</p>
<pre><code><soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
<soapenv:Body>
<ns1:CreateEntityTypesResponse xmlns:ns1="http://somedomain.com/wsinterface">
<newKeys>
<value>1234</value>
</newKeys>
<newKeys>
<value>2345</value>
</newKeys>
<newKeys>
<value>3456</value>
</newKeys>
<newKeys xsi:nil="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
<newKeys xsi:nil="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
<errors>Error1</errors>
<errors>Error2</errors>
</ns1:CreateEntityTypesResponse>
</soapenv:Body>
</soapenv:Envelope>
</code></pre>
<p>I have two newKeys elements that are nil, and both elements insert a namespace reference for xsi. I'd like to include that namespace in the soapenv:Envelope element so that the namespace reference is only sent once.</p>
<p>I am using WSDL2Java to generate the service skeleton, so I don't directly have access to the Axis2 API.</p>
| <h3>Using WSDL2Java</h3>
<p>If you have used the Axis2 WSDL2Java tool you're kind of stuck with what it generates for you. However you can try to change the skeleton in this section:</p>
<pre><code> // create SOAP envelope with that payload
org.apache.axiom.soap.SOAPEnvelope env = null;
env = toEnvelope(
getFactory(_operationClient.getOptions().getSoapVersionURI()),
methodName,
optimizeContent(new javax.xml.namespace.QName
("http://tempuri.org/","methodName")));
//adding SOAP soap_headers
_serviceClient.addHeadersToEnvelope(env);
</code></pre>
<p>To add the namespace to the envelope add these lines somewhere in there:</p>
<pre><code>OMNamespace xsi = getFactory(_operationClient.getOptions().getSoapVersionURI()).
createOMNamespace("http://www.w3.org/2001/XMLSchema-instance", "xsi");
env.declareNamespace(xsi);
</code></pre>
<h3>Hand-coded</h3>
<p>If you are "hand-coding" the service you might do something like this:</p>
<pre><code>SOAPFactory fac = OMAbstractFactory.getSOAP11Factory();
SOAPEnvelope envelope = fac.getDefaultEnvelope();
OMNamespace xsi = fac.createOMNamespace("http://www.w3.org/2001/XMLSchema-instance", "xsi");
envelope.declareNamespace(xsi);
OMNamespace methodNs = fac.createOMNamespace("http://somedomain.com/wsinterface", "ns1");
OMElement method = fac.createOMElement("CreateEntityTypesResponse", methodNs);
//add the newkeys and errors as OMElements here...
</code></pre>
<h3>Exposing service in aar</h3>
<p>If you are creating a service inside an aar you may be able to influence the SOAP message produced by using the target namespace or schema namespace properties (see <a href="http://wso2.org/library/2060">this article</a>).</p>
<p>Hope that helps.</p>
|
How to display a dynamically allocated array in the Visual Studio debugger? <p>If you have a statically allocated array, the Visual Studio debugger can easily display all of the array elements. However, if you have an array allocated dynamically and pointed to by a pointer, it will only display the first element of the array when you click the + to expand it. Is there an easy way to tell the debugger, show me this data as an array of type Foo and size X?</p>
| <p>Yes, simple.
say you have</p>
<pre><code>char *a = new char[10];
</code></pre>
<p>writing in the debugger:</p>
<pre><code>a,10
</code></pre>
<p>would show you the content as if it were an array.</p>
|
How do you quickly find the URL for a Win32 API on MSDN? <p>How do you quickly find the URL for a Win32 API on MSDN? It's easy for .NET methods -- just add the method name (for example, System.Byte.ToString) to <a href="http://msdn.microsoft.com/library/" rel="nofollow">http://msdn.microsoft.com/library/</a>.</p>
<p>However, for Win32 APIs (say GetLongPathName), this doesn't work: <a href="http://msdn.microsoft.com/en-us/library/GetLongPathName" rel="nofollow">http://msdn.microsoft.com/en-us/library/GetLongPathName</a>.</p>
<p>I want to be able to use the URL in code comments or documentation. So the URL one gets with an MSDN or Google search (for example, <a href="http://msdn.microsoft.com/library/aa364980.aspx" rel="nofollow">http://msdn.microsoft.com/library/aa364980.aspx</a>) isn't really what I'm looking for. I'd really like my code comments to look something like:</p>
<p>// blah blah blah. See <a href="http://msdn.microsoft.com/en-us/library/GetLongPathName" rel="nofollow">http://msdn.microsoft.com/en-us/library/GetLongPathName</a> for more information.</p>
<p>What's the magic pixie dust for Win32 APIs? Or does it only work for .NET methods?</p>
| <p>Google might be your best bet. I know the msdn site search has time and again pointed me in the wrong direction, but a quick switch to Google ("GetLongPathName site:msdn.microsoft.com") never steers me wrong.</p>
|
Open Source Database Plugin For Eclipse? <p>Does anyone know of a good open source plugin for database querying and exploring within Eclipse? </p>
<p>The active Database Exploring plugin within Eclipse is really geared around being associated with a Java project. While I am just trying to run ad-hoc queries and explore the schema. I am effectively looking for a just a common, quick querying tool without the overhead of having to create a code project. I have found a couple open source database plugins for Eclipse but these have not seen active development in over a year.</p>
<p>Any suggestions?</p>
| <p>I use SQL Explorer.</p>
<p>It comes as an Eclipse plugin or standalone.</p>
<p><a href="http://eclipsesql.sourceforge.net/" rel="nofollow">http://eclipsesql.sourceforge.net/</a></p>
|
XSLT processing in/from ruby <p>Can anyone recommend an efficient method to execute XSLT transforms of XML data within a Ruby application? The XSL gem (REXSL) is not available yet, and while I have seen a project or two that implement it, I'm wary of using them so early on. A friend had recommended a shell out call to Perl, but I'm worried about resources. </p>
<p>This is for a linux environment.</p>
| <p>Try the "libxslt-ruby" gem. It depends on the "libxmlr-ruby" bindings for libxml library, which you probably already have installed if you're developing on Linux.</p>
|
NHibernate to not cache a property <p>How can I configure NHibernate to not cache a file?<br>
I know I can create a method that does an HSQL, but can I through a configuration setting in the <class>.xml file or the hibernate xml file itself to not cache a property?</p>
| <p>You cannot set secondary caching settings at property level (as far as I know), but you can individually tune cache settings for each entity directly in their XML files.</p>
<p>For instance:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="ClassName" table="Table">
<cache usage="nonstrict-read-write" />
<id name="Id" type="Int64" ...
</code></pre>
<p>Where the cache "usage" property can be any of the following values:</p>
<ul>
<li><strong>read-write</strong>: assures read committed isolation, makes sure data is consistent but doesn't reduce DB access as much as the other modes,</li>
<li><strong>nonstrict-read-write</strong>: objects with rare writes, slight chance of inconsistency between DB and cache,</li>
<li><strong>read-only</strong>: for data objects that never change, no chance of inconsistency.</li>
</ul>
|
How do I get the name of a python class as a string? <p>What method do I call to get the name of a class?</p>
| <pre><code>In [1]: class test(object):
...: pass
...:
In [2]: test.__name__
Out[2]: 'test'
</code></pre>
|
Best way to convert pdf files to tiff files <p>I have around 1000 pdf filesand I need to convert them to 300 dpi tiff files. What is the best way to do this? If there is an SDK or something or a tool that can be scripted that would be ideal. </p>
| <p>Use Imagemagick, or better yet, Ghostscript.</p>
<p><a href="http://www.ibm.com/developerworks/library/l-graf2/#N101C2">http://www.ibm.com/developerworks/library/l-graf2/#N101C2</a> has an example for imagemagick:</p>
<pre><code>convert foo.pdf pages-%03d.tiff
</code></pre>
<p><a href="http://www.asmail.be/msg0055376363.html">http://www.asmail.be/msg0055376363.html</a> has an example for ghostscript:</p>
<pre><code>gs -q -dNOPAUSE -sDEVICE=tiffg4 -sOutputFile=a.tif foo.pdf -c quit
</code></pre>
<p>I would install ghostscript and read the man page for gs to see what exact options are needed and experiment.</p>
|
Best way to do Visual Studio post build deployment in a team environment? <p>I'm working in a team environment where each developer works from their local desktop and deploys to a virtual machine that they own on the network. What I'm trying to do is set up the Visual Studio solution so that when they build the solution each projects deployment is handled in the post-build event to that developers virtual machine.</p>
<p>What I'd really like to do is give ownership of those scripts to the individual developer as well so that they own their post build steps and they don't have to be the same for everyone.</p>
<p>A couple of questions:</p>
<ul>
<li>Is a post build event the place to execute this type of deployment operation? If not what is the best place to do it?</li>
<li>What software, tools, or tutorials/blog posts are available to assist in developing an automatic deployment system that supports these scenarios?</li>
</ul>
<p><strong>Edit:</strong> MSBuild seems to be the way to go in this situation. Anyone use alternative technologies with any success?</p>
<p><strong>Edit:</strong> If you are reading this question and wondering how to execute a different set of MSBuild tasks for each developer please see this question; <a href="http://stackoverflow.com/questions/78018/executing-different-set-of-msbuild-tasks-for-each-user">Executing different set of MSBuild tasks for each user?</a></p>
| <p>i'd look into MSBuild or ANT</p>
|
JPA Multiple Transaction Managers <p>I have one applicationContext.xml file, and it has two org.springframework.orm.jpa.JpaTransactionManager (each with its own persistence unit, different databases) configured in a Spring middleware custom application.
<br><br>I want to use annotation based transactions (@Transactional), to not mess around with TransactionStatus commit, save, and rollback.<br><br>
A coworker mentioned that something gets confused doing this when there are multiple transaction managers, even though the context file is set configured correctly (the references go to the correct persistence unit.
Anyone ever see an issue?</p>
<hr>
<p>In your config, would you have two transaction managers?
Would you have txManager1 and txManager2?<br><br>
That's what I have with JPA, two different Spring beans that are transaction managers.</p>
| <p>I guess you have 2 choices</p>
<p>If your use-cases never require updates to both databases within the same transaction, then you can use two JpaTransactionManagers, but I'm not sure you will be able to use the @Transactional approach? In this case, you would need to fallback on the older mechanism of using a simple <a href="http://static.springframework.org/spring/docs/2.5.5/api/org/springframework/transaction/interceptor/TransactionProxyFactoryBean.html">TransactionProxyFactoryBean</a> to define transaction boundaries, eg:</p>
<pre><code><bean id="firstRealService" class="com.acme.FirstServiceImpl"/>
<bean id="firstService"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager" ref="firstJpaTm"/>
<property name="target" ref="firstRealService"/>
<property name="transactionAttributes">
<props>
<prop key="insert*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<!-- similar for your second service -->
</code></pre>
<p>If you are require a transaction spanning both databases, then you will need to use a JTA transaction manager. The <a href="http://static.springframework.org/spring/docs/2.5.5/api/org/springframework/orm/jpa/JpaTransactionManager.html">API</a> states:</p>
<blockquote>
<p>This transaction manager is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access. JTA (usually through JtaTransactionManager) is necessary for accessing multiple transactional resources within the same transaction. Note that you need to configure your JPA provider accordingly in order to make it participate in JTA transactions.</p>
</blockquote>
<p>What this means is that you will need to provide a JTA transaction manager. In our application, we use config similar to the following:</p>
<pre><code><tx:annotation-driven transaction-manager="txManager"/>
<bean id="txManager"
class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManagerName" value="appserver/jndi/path" />
</bean>
</code></pre>
<p>If you are deploying within an appserver, then the spring JtaTransactionManager needs to do a lookup to the real XA-compliant JTA transaction manager provided by the appserver. However, you can also use a standalone JTA transaction manager (but I haven't tried this myself yet)</p>
<p>As for configuring the Jpa persistence provider, I'm not that familiar. What JPA persistence provider are you using?</p>
<p>The code above is based on our approach, where we were using native Hibernate as opposed to Hibernate's JPA implementation. In this case, we were able to get rid of the two HibernateTransactionManager beans, and simply ensure that both SessionFactories were injected with the same JTA TM, and then use the tx:annotation-driven element.</p>
<p>Hope this helps</p>
|
When are you supposed to use escape instead of encodeURI / encodeURIComponent? <p>When encoding a query string to be sent to a web server - when do you use <code>escape()</code> and when do you use <code>encodeURI()</code> or <code>encodeURIComponent()</code>:</p>
<p>Use escape:</p>
<pre><code>escape("% +&=");
</code></pre>
<p>OR</p>
<p>use encodeURI() / encodeURIComponent()</p>
<pre><code>encodeURI("http://www.google.com?var1=value1&var2=value2");
encodeURIComponent("var1=value1&var2=value2");
</code></pre>
| <h1>escape()</h1>
<p>Don't use it, as it has been deprecated since ECMAScript v3.</p>
<h1>encodeURI()</h1>
<p>Use encodeURI when you want a working URL. Make this call:</p>
<pre><code>encodeURI("http://www.google.com/a file with spaces.html")
</code></pre>
<p>to get:</p>
<pre>
http://www.google.com/a%20file%20with%20spaces.html
</pre>
<p>Don't call encodeURIComponent since it would destroy the URL and return</p>
<pre>
http%3A%2F%2Fwww.google.com%2Fa%20file%20with%20spaces.html
</pre>
<h1>encodeURIComponent()</h1>
<p>Use encodeURIComponent when you want to encode a URL parameter.</p>
<pre><code>param1 = encodeURIComponent("http://xyz.com/?a=12&b=55")
</code></pre>
<p>Then you may create the URL you need:</p>
<pre><code>url = "http://domain.com/?param1=" + param1 + "&param2=99";
</code></pre>
<p>And you will get this complete URL:</p>
<p><code>http://www.domain.com/?param1=http%3A%2F%2Fxyz.com%2F%Ffa%3D12%26b%3D55&param2=99</code></p>
<p>Note that encodeURIComponent does not escape the ' character. A common bug is to use it to create html attributes such as <code>href='MyUrl'</code>, which could suffer an injection bug. If you are constructing html from strings, either use " instead of ' for attribute quotes, or add an extra layer of encoding (' can be encoded as %27).</p>
<p>For more information on this type of encoding you can check: <a href="http://en.wikipedia.org/wiki/Percent-encoding">http://en.wikipedia.org/wiki/Percent-encoding</a></p>
|
How do you reliably get the Quick Launch folder in XP and Vista? <p>We need to reliably get the Quick Launch folder for both All and Current users under both Vista and XP. I'm developing in C++, but this is probably more of a general Windows API question.</p>
<p>For reference, here is code to get the Application Data folder under both systems:</p>
<pre><code> HRESULT hres;
CString basePath;
hres = SHGetSpecialFolderPath(this->GetSafeHwnd(), basePath.GetBuffer(MAX_PATH), CSIDL_APPDATA, FALSE);
basePath.ReleaseBuffer();
</code></pre>
<p>I suspect this is just a matter of knowing which sub-folder Microsoft uses.</p>
<p>Under Windows XP, the app data subfolder is:</p>
<p>Microsoft\Internet Explorer\Quick Launch</p>
<p>Under Vista, it appears that the sub-folder has been changed to:</p>
<p>Roaming\Microsoft\Internet Explorer\Quick Launch</p>
<p>but I'd like to make sure that this is the correct way to determine the correct location.</p>
<p>Finding the <em>correct</em> way to determine this location is quite important, as relying on hard coded folder names almost always breaks as you move into international installs, etc... The fact that the folder is named 'Roaming' in Vista makes me wonder if there is some special handling related to that folder (akin to the Local Settings folder under XP).</p>
<p>EDIT:
The following msdn article: <a href="http://msdn.microsoft.com/en-us/library/bb762494.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/bb762494.aspx</a> indicates that CSIDL_APPDATA has an equivalent ID of FOLDERID_RoamingAppData, which does seem to support StocksR's assertion that CSIDL_APPDATA does return C:\Users\xxxx\AppData\Roaming, so it should be possible to use the same relative path for CSIDL_APPDATA to get to quick launch (\Microsoft\Internet Explorer\Quick Launch).</p>
<p>So the following algorithm is correct per MS:</p>
<pre><code>HRESULT hres;
CString basePath;
hres = SHGetSpecialFolderPath(this->GetSafeHwnd(), basePath.GetBuffer(MAX_PATH), CSIDL_APPDATA, FALSE);
basePath.ReleaseBuffer();
CString qlPath = basePath + "\\Microsoft\\Internet Explorer\\Quick Launch";
</code></pre>
<p>it would also be a good idea to check hres to ensure that the call to SHGetSpecialFolderPath was successful.</p>
| <p>AppData on vista refers to C:\Users\xxxx\AppData\Roaming not the C:\Users\xxxx\AppData folder it's self.</p>
<p>Also this artical <a href="http://www.microsoft.com/technet/scriptcenter/resources/qanda/sept05/hey0901.mspx" rel="nofollow">http://www.microsoft.com/technet/scriptcenter/resources/qanda/sept05/hey0901.mspx</a> on a microsoft site implies that you simply have to use the path relative to the appdata folder </p>
|
Production, Test, Developer Environments vs Security <p>What are current practices for enabling developers to build systems that contain private data? Can anyone point to a "best practices" guide for that sort of thing?</p>
<p>We have a Catch-22 here in that developers need to write applications that go against systems that have data that is considered "private." The IT administration would like for us developers to not have access to the data (ie. provide a schema or data structure, but not data itself) whereas most developers (myself included) would like to have access to the production data since not having a representative dataset can lead to bad assumptions (eg. the format of data) and bugs later on.</p>
<p>Does anyone have any formalized "best practices" for this type of thing? Especially official guildines from some "BigCo" (eg. Microsoft, IBM) might help since it is needed to convince management.</p>
| <p>My view of the world may be different, as I'm based in the UK, but for the past 20-odd years, I've worked primarily in the public sector on systems handling sensitive data.
The rules are **completely** cut-and-dried. No production data is allowed on the development estate.</p>
<p>As a fundamental principle, we do not want to be responsible for the loss of sensitive data. The users are perfectly good at that, themselves.</p>
<p>Within the past 12 months, my wife has moved from the same regime to one in the private sector where they allow developers access to production data and she's horrified by it. The legal implications (in the UK, at least) can be severe.</p>
<p>Developers don't **need** access to production data. It's simply laziness. Define and create test data to exercise defined test cases (including edge cases) and don't rely on the random-esque nature of production data.</p>
<p>If you **must** use production data (i.e. you manage to convince someone who doesn't know any better that it's acceptable), ensure the data is anonymised **before** it reaches the development estate.</p>
|
What's the best way to return variables from a syncExec? <p>In my SWT Java app I often want to return information from inside a Display.syncExec() call. The best way I've found so far to do this is:</p>
<pre><code>final ArrayList<Integer> result = new ArrayList<Integer>();
GUI.display().syncExec(new Runnable(){ public void run() {
MessageBox mb = /* ... */;
/* set up messagebox */
result.add(mb.open());
}});
if (SWT.OK == result.get(0)) { /* ... */ }
</code></pre>
<p>I think this is allowed because ArrayList is thread-safe, but is there a better container I should be using, or an easier way altogether?</p>
| <p><a href="http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html" rel="nofollow"><code>ArrayList</code> is not thread-safe</a>. You can obtain a thread-safe <code>List</code> with <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#synchronizedList%28java.util.List%29" rel="nofollow"><code>Collections.synchronizedList</code></a>. However, it is much simpler to use an <code>AtomicInteger</code> in your case or <code>AtomicReference</code> in a more general case.</p>
<pre><code>final AtomicInteger resultAtomicInteger = new AtomicInteger();
Display.getCurrent().syncExec(new Runnable() {
public void run() {
MessageBox mb = /* ... */;
/* set up messagebox */
resultAtomicInteger.set(mb.open());
}});
if (SWT.OK == resultAtomicInteger.get()) { /* ... */ }
</code></pre>
|
Free/cheap PowerDesigner alternative? <p>We are using PowerDesigner at work for database modelling. But there is a hell of a price tag on that piece of software. And frankly, all I use is physical diagrams for MS SQL, which is about 1% of what PD knows.</p>
<p>Are there any good alternatives? I know about Visio and MS SQL Diagrams, but looking for other options.</p>
| <p><a href="http://www.sqlpower.ca/page/architect">Power*Architect</a> is the way to go. It's free, open source, and does a really great job helping you build your ERDs. Plus, it works on Windows, Linux, and OSX.</p>
|
Extreme Programming <p>As developers and as professional engineers have you been exposed to the tenants of Extreme Programming as defined in the "version 1" by Kent Beck.
Which of those 12 core principles do you feel you have been either allowed to practice or at least be a part of in your current job or others?</p>
<pre><code>* Pair programming[5]
* Planning game
* Test driven development
* Whole team (being empowered to deliver)
* Continuous integration
* Refactoring or design improvement
* Small releases
* Coding standards
* Collective code ownership
* Simple design
* System metaphor
* Sustainable pace
</code></pre>
<p>From an engineers point of view I feel that the main engineering principles of XP arevastly superior to anything else I have been involved in. What is your opinion?</p>
| <p>We are following these practices you've mentioned:</p>
<ul>
<li>Planning game</li>
<li>Test driven development</li>
<li>Whole team (being empowered to
deliver)</li>
<li>Continuous integration</li>
<li>Refactoring or design improvement</li>
<li>Small releases</li>
<li>Coding standards</li>
<li>Collective code ownership</li>
<li>Simple design</li>
</ul>
<p>And I must say that after one year I can't imagine working differently.</p>
<p>As for Pair programming I must say that it makes sense in certain areas, where there is a very high difficult area or where an initial good design is essential (e.g. designing interfaces). However I don't consider this as very effective. In my opinion it is better to perform code and design reviews of smaller parts, where Pair programming would have made sense.</p>
<p>As for the 'Whole team' practice I must admit that it has suffered as our team grew. It simply made the planning sessions too long, when everybody can give his personal inputs. Currently a core team is preparing the planning game by doing some initial, rough planning.</p>
|
Perl: Use of uninitialized value in numeric lt (<) at /Date/Manip.pm <p>This has me puzzled. This code worked on another server, but it's failing on Perl v5.8.8 with <a href="http://search.cpan.org/dist/Date-Manip" rel="nofollow">Date::Manip</a> loaded from CPAN today.</p>
<pre><code>Warning:
Use of uninitialized value in numeric lt (<) at /home/downside/lib/Date/Manip.pm line 3327.
at dailyupdate.pl line 13
main::__ANON__('Use of uninitialized value in numeric lt (<) at
/home/downsid...') called at
/home/downside/lib/Date/Manip.pm line 3327
Date::Manip::Date_SecsSince1970GMT(09, 16, 2008, 00, 21, 22) called at
/home/downside/lib/Date/Manip.pm line 1905
Date::Manip::UnixDate('today', '%Y-%m-%d') called at
TICKER/SYMBOLS/updatesymbols.pm line 122
TICKER::SYMBOLS::updatesymbols::getdate() called at
TICKER/SYMBOLS/updatesymbols.pm line 439
TICKER::SYMBOLS::updatesymbols::updatesymbol('DBI::db=HASH(0x87fcc34)',
'TICKER::SYMBOLS::symbol=HASH(0x8a43540)') called at
TICKER/SYMBOLS/updatesymbols.pm line 565
TICKER::SYMBOLS::updatesymbols::updatesymbols('DBI::db=HASH(0x87fcc34)', 1, 0, -1) called at
dailyupdate.pl line 149
EDGAR::updatesymbols('DBI::db=HASH(0x87fcc34)', 1, 0, -1) called at
dailyupdate.pl line 180
EDGAR::dailyupdate() called at dailyupdate.pl line 193
</code></pre>
<p>The code that's failing is simply:</p>
<pre><code>sub getdate()
{ my $err; ## today
&Date::Manip::Date_Init('TZ=EST5EDT');
my $today = Date::Manip::UnixDate('today','%Y-%m-%d'); ## today's date
####print "Today is ",$today,"\n"; ## ***TEMP***
return($today);
}
</code></pre>
<p>That's right; <a href="http://search.cpan.org/dist/Date-Manip" rel="nofollow">Date::Manip</a> is failing for <code>"today"</code>.</p>
<p>The line in <a href="http://search.cpan.org/dist/Date-Manip" rel="nofollow">Date::Manip</a> that is failing is:</p>
<pre><code> my($tz)=$Cnf{"ConvTZ"};
$tz=$Cnf{"TZ"} if (! $tz);
$tz=$Zone{"n2o"}{lc($tz)} if ($tz !~ /^[+-]\d{4}$/);
my($tzs)=1;
$tzs=-1 if ($tz<0); ### ERROR OCCURS HERE
</code></pre>
<p>So <a href="http://search.cpan.org/dist/Date-Manip" rel="nofollow">Date::Manip</a> is assuming that <code>$Cnf</code> has been initialized with elements <code>"ConvTZ"</code> or <code>"TZ"</code>. Those are initialized in <code>Date_Init</code>, so that should have been taken care of.</p>
<p>It's only failing in my large program. If I just extract "<code>getdate()</code>" above
and run it standalone, there's no error. So there's something about the
global environment that affects this.</p>
<p>This seems to be a known, but not understood problem. If you search Google for
"Use of uninitialized value date manip" there are about 2400 hits.
This error has been reported with <a href="http://www.lemis.com/grog/videorecorder/mythsetup-sep-2006.html" rel="nofollow">MythTV</a> and <a href="http://www.cpan.org/modules/by-module/Mail/grepmail-4.51.readme" rel="nofollow">grepmail</a>.</p>
| <p>It is a <a href="http://rt.cpan.org/Public/Bug/Display.html?id=29655" rel="nofollow">bug</a> in Date::Manip version 5.48-5.54 for Win32. I've had difficulty with using standard/daylight variants of a timezones, e.g. 'EST5EDT', 'US/Eastern'. The only timezones that appear to work are those without daylight savings, e.g. 'EST'.</p>
<p>It is possible to turn off timezone conversion processing in the Date::Manip module:</p>
<pre><code>Date::Manip::Date_Init("ConvTZ=IGNORE");
</code></pre>
<p><strong>This will have undesired side-effects if you treat dates correctly</strong>. I would not use this workaround unless you are confident you will be never be processing dates from different timezones.</p>
|
Fetch unread messages, by user <p>I want to maintain a list of global messages that will be displayed to all users of a web app. I want each user to be able to mark these messages as read individually. I've created 2 tables; <code>messages (id, body)</code> and <code>messages_read (user_id, message_id)</code>.</p>
<p>Can you provide an sql statement that selects the unread messages for a single user? Or do you have any suggestions for a better way to handle this?</p>
<p>Thanks!</p>
| <p>Well, you could use</p>
<pre><code>SELECT id FROM messages m WHERE m.id NOT IN(
SELECT message_id FROM messages_read WHERE user_id = ?)
</code></pre>
<p>Where ? is passed in by your app.</p>
|
What's a simple method to dump pipe input to a file? (Linux) <p>I'm looking for a little shell script that will take anything piped into it, and dump it to a file.. for email debugging purposes. Any ideas?</p>
| <p>The unix command tee does this.</p>
<pre><code>man tee
</code></pre>
|
VS2008 Setup Project: Shared (By All Users) Application Data Files? <p>fellow anthropoids and lily pads and paddlewheels!</p>
<p>I'm developing a Windows desktop app in C#/.NET/WPF, using VS 2008. The app is required to install and run on Vista and XP machines. I'm working on a Setup/Windows Installer Project to install the app.</p>
<p>My app requires read/modify/write access to a SQLCE database file (.sdf) and some other database-type files related to a third-party control I'm using. These files should be shared among all users/log-ins on the PC, none of which can be required to be an Administrator. This means, of course, that the files can't go in the program's own installation directory (as such things often did before the arrival of Vista, yes, yes!).</p>
<p>I had expected the solution to be simple. <strong>Vista and XP both have shared-application-data folders intended for this purpose.</strong> ("\ProgramData" in Vista, "\Documents and Settings\All Users\Application Data" in XP.) The .NET Environment.GetFolderPath(SpecialFolder.CommonApplicationData) call exists to find the paths to these folders on a given PC, yes, yes!</p>
<p><strong>But I can't figure out how to specify the shared-application-data folder as a target in the Setup project.</strong></p>
<p>The Setup project offers a "Common Files" folder, but that's intended for shared program components (not data files), is usually located under "\Program Files," and has the same security restrictions anything else in "\Program files" does, yes, yes!</p>
<p>The Setup project offers a "User's Application Data" folder, but that's a per-user folder, which is exactly what I'm trying to avoid, yes, yes!</p>
<p>Is it possible to add files to the shared-app-data folder in a robust, cross-Windows-version way from a VS 2008 setup project? Can anyone tell me how?</p>
| <p>I have learned the answer to my question through other sources, yes, yes! Sadly, it didn't fix my problem! What's that make me -- a fixer-upper? Yes, yes!</p>
<p>To put stuff in a sub-directory of the Common Application Data folder from a VS2008 Setup project, here's what you do:</p>
<ol>
<li><p>Right-click your setup project in the Solution Explorer and pick "View -> File System".</p></li>
<li><p>Right-click "File system on target machine" and pick "Add Special Folder -> Custom Folder".</p></li>
<li><p>Rename the custom folder to "Common Application Data Folder." (This isn't the name that will be used for the resulting folder, it's just to help you keep it straight.)</p></li>
<li><p>Change the folder's DefaultLocation property to "[CommonAppDataFolder][Manufacturer]\[ProductName]". Note the similarity with the DefaultLocation property of the Application Folder, including the odd use of a single backslash.</p></li>
<li><p>Marvel for a moment at the ridiculous (yet undeniable) fact that there is a folder property named "Property." </p></li>
<li><p>Change the folder's Property property to "COMMONAPPDATAFOLDER".</p></li>
</ol>
<p>Data files placed in the "Common Application Data" folder will be copied to "\ProgramData\Manufacturer\ProductName" (on Vista) or "\Documents and Settings\All Users\Application Data\Manufacturer\ProductName" (on XP) when the installer is run.</p>
<p>Now it turns out that under Vista, non-Administrators don't get modify/write access to the files in here. So all users get to read the files, but they get that in "\Program Files" as well. So what, I wonder, is the point of the Common Application Data folder?</p>
|
Is there a way to dynamically load a properties file in NAnt? <p>I want to load a different properties file based upon one variable.</p>
<p>Basically, if doing a dev build use this properties file, if doing a test build use this other properties file, and if doing a production build use yet a third properties file.</p>
| <p><strong>Step 1</strong>: Define a property in your NAnt script to track the environment you're building for (local, test, production, etc.).</p>
<pre><code><property name="environment" value="local" />
</code></pre>
<p><strong>Step 2</strong>: If you don't already have a configuration or initialization target that all targets depends on, then create a configuration target, and make sure your other targets depend on it.</p>
<pre><code><target name="config">
<!-- configuration logic goes here -->
</target>
<target name="buildmyproject" depends="config">
<!-- this target builds your project, but runs the config target first -->
</target>
</code></pre>
<p><strong>Step 3</strong>: Update your configuration target to pull in an appropriate properties file based on the environment property.</p>
<pre><code><target name="config">
<property name="configFile" value="${environment}.config.xml" />
<if test="${file::exists(configFile)}">
<echo message="Loading ${configFile}..." />
<include buildfile="${configFile}" />
</if>
<if test="${not file::exists(configFile) and environment != 'local'}">
<fail message="Configuration file '${configFile}' could not be found." />
</if>
</target>
</code></pre>
<p>Note, I like to allow team members to define their own local.config.xml files that don't get committed to source control. This provides a nice place to store local connection strings or other local environment settings.</p>
<p><strong>Step 4</strong>: Set the environment property when you invoke NAnt, e.g.:</p>
<ul>
<li>nant -D:environment=dev</li>
<li>nant -D:environment=test</li>
<li>nant -D:environment=production</li>
</ul>
|
What is the easiest way to adjust EXIF timestamps on photos from multiple cameras in Windows Vista? <p><strong>Scenario:</strong> Several people go on holiday together, armed with digital cameras, and snap away. Some people remembered to adjust their camera clocks to local time, some left them at their home time, some left them at local time of the country they were born in, and some left their cameras on factory time.</p>
<p><strong>The Problem:</strong> Timestamps in the EXIF metadata of photos will not be synchronised, making it difficult to aggregate all the photos into one combined collection.</p>
<p><strong>The Question:</strong> Assuming that you have discovered the deltas between all of the camera clocks, What is the <em>simplest</em> way to correct these timestamp differences in Windows Vista?</p>
| <p>use exiftool. open source, written in perl, but also available as standalone .exe file. author seems to have though of <em>everything</em> exif related. mature code.</p>
<p>examples:</p>
<pre><code>exiftool "-DateTimeOriginal+=5:10:2 10:48:0" DIR
exiftool -AllDates-=1 DIR
</code></pre>
<p>refs:</p>
<ul>
<li><a href="http://www.sno.phy.queensu.ca/~phil/exiftool/" rel="nofollow">http://www.sno.phy.queensu.ca/~phil/exiftool/</a></li>
<li><a href="http://www.sno.phy.queensu.ca/~phil/exiftool/#shift" rel="nofollow">http://www.sno.phy.queensu.ca/~phil/exiftool/#shift</a></li>
</ul>
|
Are there any good Continuous Testing plugins for Eclipse out right now? <p>I've used the <a href="http://groups.csail.mit.edu/pag/continuoustesting/">MIT Continuous testing</a> plugin in the past, but it has long since passed out of date and is no longer compatible with anything approaching a modern release of Eclipse. </p>
<p>Does anyone have a good replacement? Free, naturally, is preferred. </p>
| <p>I found that <a href="http://infinitest.github.com/">Infinitest</a> now has an Eclipse plugin that seems to work pretty well. </p>
|
How do you set up an API key system for your website? <p>Let say that I have a website with some information that could be access externally. Those information need to be only change by the respected client. Example: Google Analytic or WordPress API key. How can I create a system that work like that (no matter the programming language)?</p>
| <p>A number of smart people are working on a standard, and it's called <a href="http://oauth.net/">OAuth</a>. It already has a number of <a href="http://oauth.net/code">sample implementations</a>, so it's pretty easy to get started.</p>
|
What is the best way to create a security architecture? <p>I'm designing a portal's security architecture. The site has pages, videos, pictures, users, databases, file system objects, etc. What is the best way to control access to all of these objects? How would you store permissions? Is a 64-bit database variable enough for storing permissions? </p>
<p>E.g. Windows employs <a href="http://en.wikipedia.org/wiki/Access_control_list" rel="nofollow">ACLs</a> and <a href="http://en.wikipedia.org/wiki/Security_Identifier" rel="nofollow">SIDs</a>. Do you have a more up-to-date solution? </p>
| <p>I don't like idea of storing permissions as flags in one variable.
I'd rather make roles objects in relation many-to-many with users.</p>
<p>For editing rights of the specific object I use an object's method or external function depending on how can I generalise security policies.</p>
<p>For a middle sized portals this approach works very good.</p>
|
In Delphi, How do I get an enumerator from LocalPolicy.CurrentProfile.GloballyOpenPorts in the Firewall API <p>I am writing some code to see if there is a hole in the firewall exception list for <strong>WinXP</strong> and <strong>Vista</strong> for a specific port used by our client software. </p>
<p>I can see that I can use the <code>NetFwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts</code> to get a list of the current Open port exceptions. But i can not figure out how to get that enumerated list in to something that I can use in my Delphi program. </p>
<p>My latest try is listed below. It's giving me an access violation when I use <code>port_list.Item</code>. I know that's wrong, it was mostly wishful thinking on my part. Any help would be appreciated.</p>
<pre><code>function TFirewallUtility.IsPortInExceptionList(iPortNumber: integer): boolean;
var
i, h: integer;
port_list, port: OleVariant;
begin
Result := False;
port_list := mxFirewallManager.LocalPolicy.CurrentProfile.GloballyOpenPorts;
for i := 0 to port_list.Count - 1 do
begin
port := port_list.Item[i];
if (port.PortNumber = iPortNumber) then
begin
Result := True;
break;
end;
end;
end;
</code></pre>
| <p>OK, I think that I have it figured out. </p>
<p>I had to create a type library file of the hnetcfg.dll. I did that when I first started but have learned a lot about the firewall objects since then. It didn't work then, but its working now. You can create your own file from Component|Import Component. And then follow the wizard. </p>
<p>The wrapping code uses exceptions which I normally don't like to do, but I don't know how to tell whether an Interface that is returning an Interface is actually returning data that I can work off of... So that would be an improvement if somebody can point me in the right direction.</p>
<p>And now to the code, with a thanks to Jim for his response.</p>
<pre><code>constructor TFirewallUtility.Create;
begin
inherited Create;
CoInitialize(nil);
mxCurrentFirewallProfile := INetFwMgr(CreateOLEObject('HNetCfg.FwMgr')).LocalPolicy.CurrentProfile;
end;
function TFirewallUtility.IsPortInExceptionList(iPortNumber: integer): boolean;
begin
try
Result := mxCurrentFirewallProfile.GloballyOpenPorts.Item(iPortNumber, NET_FW_IP_PROTOCOL_TCP).Port = iPortNumber;
except
Result := False;
end;
end;
function TFirewallUtility.IsPortEnabled(iPortNumber: integer): boolean;
begin
try
Result := mxCurrentFirewallProfile.GloballyOpenPorts.Item(iPortNumber, NET_FW_IP_PROTOCOL_TCP).Enabled;
except
Result := False;
end;
end;
procedure TFirewallUtility.SetPortEnabled(iPortNumber: integer; sPortName: string; xProtocol: TFirewallPortProtocol);
begin
try
mxCurrentFirewallProfile.GloballyOpenPorts.Item(iPortNumber, CFirewallPortProtocalConsts[xProtocol]).Enabled := True;
except
HaltIf(True, 'xFirewallManager.TFirewallUtility.IsPortEnabled: Port not in exception list.');
end;
end;
procedure TFirewallUtility.AddPortToFirewall(sPortName: string; iPortNumber: Cardinal; xProtocol: TFirewallPortProtocol);
var
port: INetFwOpenPort;
begin
port := INetFwOpenPort(CreateOLEObject('HNetCfg.FWOpenPort'));
port.Name := sPortName;
port.Protocol := CFirewallPortProtocalConsts[xProtocol];
port.Port := iPortNumber;
port.Scope := NET_FW_SCOPE_ALL;
port.Enabled := true;
mxCurrentFirewallProfile.GloballyOpenPorts.Add(port);
end;
</code></pre>
|
How to convert all controls on an aspx webform to a read-only equivalent <p>Has anyone ever written a function that can convert all of the controls on an aspx page into a read only version? For example, if UserDetails.aspx is used to edit and save a users information, if someone with inappropriate permissions enter the page, I would like to render it as read-only. So, most controls would be converted to labels, loaded with the corresponding data from the editable original control.</p>
<p>I think it would likely be a fairly simple routine, ie: </p>
<pre><code>Dim ctlParent As Control = Me.txtTest.Parent
Dim ctlOLD As TextBox = Me.txtTest
Dim ctlNEW As Label = New Label
ctlNEW.Width = ctlOLD.Width
ctlNEW.Text = ctlOLD.Text
ctlParent.Controls.Remove(ctlOLD)
ctlParent.Controls.Add(ctlNEW)
</code></pre>
<p>...is really all you need for a textbox --> label conversion, but I was hoping someone might know of an existing function out there as there are likely a few pitfalls here and there with certain controls and situations.</p>
<p>Update:<br />
- Just setting the ReadOnly property to true is not a viable solution, as it looks dumb having things greyed out like that.
- Avoiding manually creating a secondary view is the entire point of this, so using an ingenious way to display a read only version of the user interface that was built by hand using labels is wat I am trying to avoid.</p>
<p>Thanks!!</p>
| <p>Scott Mitchell posted a good article on this a while back. </p>
<p><a href="http://aspnet.4guysfromrolla.com/articles/012506-1.aspx" rel="nofollow">http://aspnet.4guysfromrolla.com/articles/012506-1.aspx</a></p>
<p>I've used this approach in the past in conjection with css on the 'read only' fields to make them look and work exactly like a label, even though they are in fact text boxes.</p>
|
What to put in a session variable <p>I recently came across a ASP 1.1 web application that put a whole heap of stuff in the session variable - including all the DB data objects and even the DB connection object. It ends up being huge. When the web session times out (four hours after the user has finished using the application) sometimes their database transactions get rolled back. I'm assuming this is because the DB connection is not being closed properly when IIS kills the session.</p>
<p>Anyway, my question is what should be in the session variable? Clearly some things need to be in there. The user selects which plan they want to edit on the main screen, so the plan id goes into the session variable. Is it better to try and reduce the load on the DB by storing all the details about the user (and their manager etc.) and the plan they are editing in the session variable or should I try to minimise the stuff in the session variable and query the DB for everything I need in the Page_Load event?</p>
| <p>This is pretty hard to answer because it's so application-specific, but here are a few guidelines I use:</p>
<ol>
<li>Put as little as possible in the session.</li>
<li>User-specific selections that should only last during a given visit are a good choice</li>
<li>often, variables that need to be accessible to multiple pages throughout the user's visit to your site (to avoid passing them from page to page) are also good to put in the session.</li>
</ol>
<p>From what little you've said about your application, I'd probably select your data from the db and try to find ways to minimize the impact of those queries instead of loading down the session.</p>
|
Redraw screen in terminal <p>How do some programs edit whats being displayed on the terminal (to pick a random example, the program 'sl')? I'm thinking of the Linux terminal here, it may happen in other OS's too, I don't know. I've always thought once some text was displayed, it stayed there. How do you change it without redrawing the entire screen? </p>
| <p>Depending on the terminal you send control seuqences. Common sequences are for example esc[;H to send the cursor to a specific position (e.g. on Ansi, Xterm, Linux, VT100). However, this will vary with the type or terminal the user has ... curses (in conjunction with the terminfo files) will wrap that information for you.</p>
|
Compiling mxml files with ant and flex sdk <p>I am just getting started with flex and am using the SDK (not Flex Builder). I was wondering what's the best way to compile a mxml file from an ant build script. </p>
| <p>The Flex SDK ships with a set of ant tasks. More info at:</p>
<p><a href="http://livedocs.adobe.com/flex/3/html/help.html?content=anttasks_1.html">http://livedocs.adobe.com/flex/3/html/help.html?content=anttasks_1.html</a></p>
<p>Here is an example of compiling Flex SWCs with ant:</p>
<p><a href="http://www.mikechambers.com/blog/2006/05/19/example-using-ant-with-compc-to-compile-swcs/">http://www.mikechambers.com/blog/2006/05/19/example-using-ant-with-compc-to-compile-swcs/</a></p>
<p>mike chambers</p>
|
Absolute Minimum Requirements for Good Software Design <p>I am trying to write a spec for a software application. The application takes inputs from static files (configuration data), files that it obtained by ftp, and "live" data obtained via a TCP socket. It does some stuff and generates output data, which is delivered to somebody else via a TCP socket.</p>
<p>It is not so difficult to write a spec describing what the system should do when nothing goes wrong and even describing what it should do when certain things go wrong.</p>
<p>But recent experience has told me that it might be a good idea to include explicitly what some people might call "no-brainers". Like keep the user-configurable data separate from the software, so when an upgrade is installed, it doesn't clobber the user data. Or have user-configurable levels of error logging. Things like that.</p>
<p>Does anyone have a list of basic requirements that they would want <em>any</em> system to have and that <em>any</em> decent software developer would do more or less automatically?</p>
| <p>Testability: If you make your design testable, everything else will fall in line.</p>
|
Fighting with Protected Mode in Vista <p>Our application commonly used an ActiveX control to download and install our client on IE (XP and prior), however as our user base has drifted towards more Vista boxes with "Protected Mode" on, we are required to investigate.</p>
<p>So going forward, is it worth the headache of trying to use the protected mode API? Is this going to result in a deluge of dialog boxes and admin rights to do the things our app needs to do (write to some local file places, access some other applications, etc)?</p>
<p>I'm half bent on just adding a non-browser based installer app that will do the dirty work of downloading and installing the client, if need be... this would only need to be installed once and in large corporate structures it could be pushed out by IT.</p>
<p>Are there some other ideas I'm missing?</p>
| <p>This client, is it a desktop application and not some software that runs inside the browser? In that case, please just supply a regular download installer application. My personal experience with browser-hosted installers is that they are just confusing and the few I have seen seemed to be poorly coded in some way.</p>
<p>If you use an MSI based installer I'm sure lots of Windows domain administrators will love you too, as Microsoft has tools to deploy MSI based installations onto large sets of machines remotely.</p>
|
Python ReportLab use of splitfirst/splitlast <p>I'm trying to use Python with ReportLab 2.2 to create a PDF report.<br />
According to the <a href="http://www.reportlab.com/docs/userguide.pdf">user guide</a>,</p>
<blockquote>
<p>Special TableStyle Indeces [sic]</p>
<p>In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation. This allows splitting tables with nicer effects around the split.</p>
</blockquote>
<p>I've tried using several style elements, including:</p>
<pre><code>('TEXTCOLOR', (0, 'splitfirst'), (1, 'splitfirst'), colors.black)
('TEXTCOLOR', (0, 'splitfirst'), (1, 0), colors.black)
('TEXTCOLOR', (0, 'splitfirst'), (1, -1), colors.black)
</code></pre>
<p>and none of these seems to work. The first generates a TypeError with the message: </p>
<pre><code>TypeError: cannot concatenate 'str' and 'int' objects
</code></pre>
<p>and the latter two generate TypeErrors with the message:</p>
<pre><code>TypeError: an integer is required
</code></pre>
<p>Is this functionality simply broken or am I doing something wrong? If the latter, what am I doing wrong?</p>
| <p>Well, it looks as if I will be answering my own question.</p>
<p>First, the documentation flat out lies where it reads "In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation." In the current release, the "splitlast" and "splitfirst" row indices break with the aforementioned TypeErrors on the TEXTCOLOR and BACKGROUND commnds.</p>
<p>My suspicion, based on reading the source code, is that only the tablestyle line commands (GRID, BOX, LINEABOVE, and LINEBELOW) are currently compatible with the 'splitfirst' and 'splitlast' row indices. I suspect that all cell commands break with the aforementioned TypeErrors.</p>
<p>However, I was able to do what I wanted by subclassing the Table class and overriding the onSplit method. Here is my code:</p>
<pre><code>class XTable(Table):
def onSplit(self, T, byRow=1):
T.setStyle(TableStyle([
('TEXTCOLOR', (0, 1), (1, 1), colors.black)]))
</code></pre>
<p>What this does is apply the text color black to the first and second cell of the second row of each page. (The first row is a header, repeated by the repeatRows parameter of the Table.) More precisely, it is doing this to the first and second cell of each frame, but since I am using the SimpleDocTemplate, frames and pages are identical.</p>
|
Locked SQL Server Data Files <p>I have an SQL Server database where I have the data and log files stored on an external USB drive. I switch the external drive between my main development machine in my office and my laptop when not in my office. I am trying to use sp_detach_db and sp_attach_db when moving between desktop and laptop machines. I find that this works OK on the desktop - I can detach and reattach the database there no problems. But on the laptop I cannot reattach the database (the database was actually originally created on the laptop and the first detach happened there). When I try to reattach on the laptop I get the following error:</p>
<p>Unable to open the physical file "p:\SQLData\AppManager.mdf". Operating system error 5: "5(error not found)"</p>
<p>I find a lot of references to this error all stating that it is a permissions issue. So I went down this path and made sure that the SQL Server service account has appropriate permissions. I have also created a new database on this same path and been able to succesfully detach and reattach it. So I am confident permissions is not the issue.</p>
<p>Further investigation reveals that I cannot rename, copy or move the data files as Windows thinks they are locked - even when the SQL Server service is stopped. Process Explorer does not show up any process locking the files. </p>
<p>How can I find out what is locking the files and unlock them.</p>
<p>I have verified that the databases do not show up in SSMS - so SQL Server does not still think they exist.</p>
<p><strong>Update 18/09/2008</strong></p>
<p>I have tried all of the suggested answers to date with no success. However trying these suggestions has helped to clarify the situation. I can verify the following:</p>
<ol>
<li>I can successfully detach and reattach the database only when the external drive is attached to the server that a copy of the database is restored to - effectively the server where the database is "created" - lets call this the "Source Server". </li>
<li>I can move, copy or rename the data and log files, after detaching the database, while the external drive is still attached to the Source Server. </li>
<li>As soon as I move the external drive to another machine the data and log files are "locked", although the 2 tools that I have tried - Process Explorer and Unlocker, both find no locking handles attached to the files. </li>
</ol>
<p>NB. After detaching the database I tried both stopping the SQL Server service and shutting down the Source Server prior to moving the external drive - still with no success.</p>
<p>So at this stage all that I can do to move data between desktop and laptop is to make a backup of the data onto the external drive, move the external drive, restore the data from the backup. Works OK but takes a bit more time as the database is a reasonable size (1gb). Anyway this is the only choice I have at this stage even though I was trying to avoid having to go down this path.</p>
| <p>Crazy as it sounds, did you try manually granting yourself perms on the files via right-click / properties / security? I think SQL Server 2005 will set permissions on a detached file exclusively to the principal that did the detach (maybe your account, maybe the account under which the SQL Server service runs) and no-one else can manipulate the file. To get around this I have had to manually grant myself file permissions on MDF and LDF files before moving or deleting them. See also blog post at onupdatecascade.com</p>
|
Which JavaScript library is recommended for neat UI effects? <p>I need a JavaScript library that supports Ajax as well as help me in making simple and neat animation effects <a href="http://www.voidy.com/" rel="nofollow">in a website</a> I am working on.</p>
<p>Which library do you recommend?</p>
| <p>I would definitely recommend JQuery as the easiest to use and the one which requires you to write the least code. <a href="http://jquery.com/" rel="nofollow">http://jquery.com/</a></p>
|
Similar thing to RJS (used in Ruby on Rails) in the Java web app world? <p>In Ruby on Rails, there's RJS templates that help do AJAX by returning javascript code that will be executed in the client browser. How can I do a similar thing in the Java/J2EE world? Is Google Widget Toolkit similar to RJS? What options do I have? </p>
| <p>Yes, I think <a href="http://code.google.com/webtoolkit/" rel="nofollow">Google Web Toolkit</a> is the java equivalent to RJS templates.</p>
|
KVM and Linux wireless bridging? <p>I'm using KVM to run a Windows virtual machine on my Linux box. Networking is accomplished through a tap device, hooked into a bridged Ethernet device, which allows the Windows VM to basically appear like a separate physical computer on my network. This is pretty nice.</p>
<p>However, my understanding is that most, if not all, wireless drivers can't support bridging. I'd really like to be able to roam a little more freely while I'm working -- does anyone know of an effective workaround?</p>
<p>User-mode networking won't work, as I have to use some Windows VPN software that wants lower-level networking access.</p>
| <p>I assume that you could configure your Windows guest to use the host as its default gateway, and set up NAT via the wireless interface on the host. So the signal flow would look like this:</p>
<ol>
<li>Windows software opens connections to a host on the internets.</li>
<li>Windows routes the packet via the default gateway, i.e. the host Linux system.</li>
<li>Linux does NAT magic and routes the packet via its normal routing table (which should use a default gateway via the wireless interface).</li>
</ol>
<p>I have never tried this in combination with bridging though.</p>
|
Publishing vs Copying <p>What is the difference between publishing a website with visual studio and just copying the files over to the server? Is the only difference that the publish files are pre-compiled?</p>
| <p>There is not much difference between "publish", and copying the files. Publish appears in a webapplication. The only difference really is publishing gives you the option to only include html and dll's, where as copying you would need to parse out source code manually. There is no full precompiling in the publish option, as Fully precompiled means no HTML at all; The aspx files are just placeholders; All html is in the compiled binaries.</p>
|
How to check for memory leaks in Guile extension modules? <p>I develop an extension module for Guile, written in C. This extension module embeds a Python interpreter.</p>
<p>Since this extension module invokes the Python interpreter, I need to verify that it properly manages the memory occupied by Python objects. </p>
<p>I found that the Python interpreter is well-behaved in its own memory handling, so that by running valgrind I can find memory leaks due to bugs in my own Python interpreter embedding code, if there are no other interfering factors. </p>
<p>However, when I run Guile under valgrind, valgrind reports memory leaks. Such memory leaks obscure any memory leaks due to my own code. </p>
<p>The question is what can I do to separate memory leaks due to bugs in my code from memory leaks reported by valgrind as due to Guile. Another tool instead of valgrind? Special valgrind options? Give up and rely upon manual code walkthrough?</p>
| <p>You've got a couple options. One is to write a supressions file for valgrind that turns off reporting of stuff that you're not working on. Python has such a file, for example:
<a href="http://svn.python.org/projects/python/trunk/Misc/valgrind-python.supp" rel="nofollow">http://svn.python.org/projects/python/trunk/Misc/valgrind-python.supp</a></p>
<p>If valgrind doesn't like your setup, another possibility is using <code>libmudflap</code>; you compile your program with <code>gcc -fmudflap -lmudflap</code>, and the resulting code is instrumented for pointer debugging. Described in the gcc docs, and here: <a href="http://gcc.gnu.org/wiki/Mudflap_Pointer_Debugging" rel="nofollow">http://gcc.gnu.org/wiki/Mudflap_Pointer_Debugging</a></p>
|
Best C++ IDE for *nix <p>What is the best C++ IDE for a *nix envirnoment? I have heard the C/C++ module of Eclipse is decent as well as Notepad++ but beyond these two I have no real idea. Any thoughts or comments?</p>
| <p>On Ubuntu, some the IDEs that are available in the repositories are:</p>
<ul>
<li><a href="http://www.kdevelop.org/">Kdevelop</a></li>
<li><a href="http://geany.uvena.de/">Geany</a></li>
<li><a href="http://anjuta.sf.net/">Anjuta</a></li>
</ul>
<p>There is also: </p>
<ul>
<li><a href="http://eclipse.org">Eclipse</a> (Recommended you don't install from repositories, due to issues with file/folder permissions) </li>
<li><a href="http://www.codeblocks.org/">Code::blocks</a></li>
</ul>
<p>And of course, everyone's favourite text-based editors:</p>
<ul>
<li>vi/vim</li>
<li>emacs</li>
</ul>
<p>Its true that vim and emacs are very powerful tools, but the learning curve is very steep.. </p>
<p>I really don't like <strong>Eclipse</strong> that much, I find it buggy and a bit too clunky.<br />
I've started using <strong>Geany</strong> as a bare-bones but functional and <em>usable</em> IDE. It has a basic code-completion feature, and is a nice, clean [Gnome] interface.<br />
<strong>Anjuta</strong> I tried for a day, didn't like it at all. I didn't find it as useful as Geany.</p>
<p><strong>Kdevelop</strong> and <strong>code::blocks</strong> get a bunch of good reviews, but I haven't tried them. I use gnome, and I'm yet to see a KDE app that looks good in gnome (sorry, I'm sure its a great program).</p>
<p>If only bloodshed dev-c++ was released under linux. That is a fantastic (but windows-only) program. You could always run it under Wine ;)</p>
<p>To a degree, it comes down to personal preference. My advice is to investigate Kdevelop, Geany and code::blocks as a starting point. </p>
|
What open source virtual private server program do you recommend with windows as host <p>I am looking to have 4 Virtual servers(various linux flavors) running on a Windows server 2003 R2 64 bit edition server located at a datacenter. I can also purchase a 2008 server or 32 bit 2k3 if needed. They would each have their own ip address for networking so that they could be publicly accessed. I do not know much about VPS software but have worked with it before.</p>
| <p><a href="http://technet.microsoft.com/en-gb/bb738033.aspx" rel="nofollow">Virtual Server 2005 R2 SP1</a> is free (registration required) and supports x64 hosts. It does not support x64 guests.</p>
<p>Windows Server 2008 includes Hyper-V, Microsoft's new virtualization technology, which supports x64 guests and multiple virtual processors. There are editions without Hyper-V as well, for marginally less money, to satisfy the anti-trust authorities. The Hyper-V <a href="http://support.microsoft.com/?kbid=950050" rel="nofollow">update</a> has to be downloaded as it was completed after the rest of Windows Server 2008 was released.</p>
<p><a href="http://www.vmware.com/products/server/" rel="nofollow">VMware Server</a> is also free. It supports (experimentally) up to 2 virtual CPUs.</p>
<p>To get best performance you need drivers and patches in the virtual machine which work well with the virtualization environment. In Virtual Server these are called Additions, in Hyper-V they are Integration Components, and for VMware, VMware Tools. Because of the nature of kernel binary compatibility (there are no guarantees), only specific distributions are generally supported.</p>
<ul>
<li><a href="http://technet.microsoft.com/en-us/virtualserver/bb676671.aspx" rel="nofollow">Download Virtual Server Additions for Linux</a></li>
<li><a href="https://connect.microsoft.com/SelfNomination.aspx?ProgramID=1863&pageType=1&SiteID=495" rel="nofollow">Download Hyper-V Linux Integration Components</a></li>
</ul>
|
How can I prevent deformation when rotating about the line-of-sight in OpenGL? <p>I've drawn an ellipse in the XZ plane, and set my perspective slightly up on the Y-axis and back on the Z, looking at the center of ellipse from a 45-degree angle, using gluPerspective() to set my viewing frustrum.</p>
<p><a href="http://www.flickr.com/photos/rampion/2863703051/" rel="nofollow" title="ellipse by rampion, on Flickr"><img src="http://farm4.static.flickr.com/3153/2863703051_a768ed86a9_m.jpg" width="240" height="187" alt="ellipse" /></a></p>
<p>Unrotated, the major axis of the ellipse spans the width of my viewport. When I rotate 90-degrees about my line-of-sight, the major axis of the ellipse now spans the height of my viewport, thus deforming the ellipse (in this case, making it appear less eccentric).</p>
<p><a href="http://www.flickr.com/photos/rampion/2863703073/" rel="nofollow" title="rotated ellipse by rampion, on Flickr"><img src="http://farm4.static.flickr.com/3187/2863703073_24c6549d4b_m.jpg" width="240" height="187" alt="rotated ellipse" /></a></p>
<p>What do I need to do to prevent this deformation (or at least account for it), so rotation about the line-of-sight preserves the perceived major axis of the ellipse (in this case, causing it to go beyond the viewport)?</p>
| <p>It looks like you're using 1.0 as the aspect when you call gluPerspective(). You should use width/height. For example, if your viewport is 640x480, you would use 1.33333 as the aspect argument.</p>
|
linux uptime history <p>How can I get a history of uptimes for my debian box? After a reboot, I dont see an option for the uptime command to print a history of uptimes. If it matters, I would like to use these uptimes for graphing a page in php to show my webservers uptime lengths between boots.</p>
<p>Update:
Not sure if it is based on a length of time or if last gets reset on reboot but I only get the most recent boot timestamp with the last command. last -x also does not return any further info. Sounds like a script is my best bet.</p>
<p>Update:
Uptimed is the information I am looking for, not sure how to grep that info in code. Managing my own script for a db sounds like the best fit for an application.</p>
| <p>Install <a href="https://github.com/rpodgorny/uptimed">uptimed</a>. It does exactly what you want.</p>
<p>Edit:</p>
<p>You can apparantly include it in a PHP page as easily as this:</p>
<pre><code><? system("/usr/local/bin/uprecords -a -B"); ?>
</code></pre>
<p><a href="http://www.robertjohnkaper.com/software/uptimed/example.html">Examples - link broken?</a></p>
|
Parsing HTTP Headers <p>I've had a new found interest in building a small, efficient web server in C and have had some trouble parsing POST methods from the HTTP Header. Would anyone have any advice as to how to handle retrieving the name/value pairs from the "posted" data?</p>
<pre><code>POST /test HTTP/1.1
Host: test-domain.com:7017
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://test-domain.com:7017/index.html
Cookie: __utma=43166241.217413299.1220726314.1221171690.1221200181.16; __utmz=43166241.1220726314.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none)
Cache-Control: max-age=0
Content-Type: application/x-www-form-urlencoded
Content-Length: 25
field1=asfd&field2=a3f3f3
// ^-this
</code></pre>
<p>I see no tangible way to retrieve the bottom line as a whole and ensure that it works every time. I'm not a fan of hard-coding in anything.</p>
| <p>You can retrieve the name/value pairs by searching for newline newline or more specifically \r\n\r\n (after this, the body of the message will start).</p>
<p>Then you can simply split the list by the &, and then split each of those returned strings between the = for name/value pairs. </p>
<p>See the <a href="http://tools.ietf.org/html/rfc2616">HTTP 1.1 RFC</a>.</p>
|
How do you design data models for Bigtable/Datastore (GAE)? <p>Since the Google App Engine Datastore is based on <a href="http://research.google.com/archive/bigtable.html">Bigtable</a> and we know that's not a relational database, how do you design a <strong><em>database schema</em>/*data model*</strong> for applications that use this type of database system?</p>
| <p>Designing a bigtable schema is an open process, and basically requires you to think about:</p>
<ul>
<li>The access patterns you will be using and how often each will be used</li>
<li>The relationships between your types</li>
<li>What indices you are going to need</li>
<li>The write patterns you will be using (in order to effectively spread load)</li>
</ul>
<p>GAE's datastore automatically denormalizes your data. That is, each index contains a (mostly) complete copy of the data, and thus every index adds significantly to time taken to perform a write, and the storage space used.</p>
<p>If this were not the case, designing a Datastore schema would be a lot more work: You would have to think carefully about the primary key for each type, and consider the effect of your decision on the locality of data. For example, when rendering a blog post you would probably need to display the comments to go along with it, so each comment's key would probably begin with the associated post's key.</p>
<p>With Datastore, this is not such a big deal: The query you use will look something like "Select * FROM Comment WHERE post_id = N." (If you want to page the comments, you would also have a limit clause, and a possible suffix of " AND comment_id > last_comment_id".) Once you add such a query, Datastore will build the index for you, and your reads will be magically fast.</p>
<p>Something to keep in mind is that each additional index creates some additional cost: it is best if you can use as few access patterns as possible, since it will reduce the number of indices GAE will construct, and thus the total storage required by your data.</p>
<p>Reading over this answer, I find it a little vague. Maybe a hands-on design question would help to scope this down? :-)</p>
|
ActiveRecord#save_only_valid_attributes <p>I'm looking for a variation on the #save method that will only save
attributes that do not have errors attached to them.
So a model can be updated without being valid overall, and this will
still prevent saving invalid data to the database.</p>
<p>By "valid attributes", I mean those attributes that give nil when calling @model_instance.errors.on(:attribute)</p>
<p>Anyone have an idea of how to accomplish this?</p>
<p>So far, I have the following:</p>
<pre><code>def save_valid_attributes
valid?
update_atrtibutes attributes.inject({}){|k, v, m| m[k] = v unless errors_on(k.to_sym); m}
end
</code></pre>
<p>This works if there's no processing done on assignment, which in my case there is.
For example, I have a database column "start_date", and two methods defined:</p>
<pre><code>def nice_start_date=(startdate)
self.start_date = Chronic.parse(startdate) || startdate
end
def nice_start_date
self.start_date.to_s
end
</code></pre>
<p>These two methods allow me to properly parse the user inputted dates using Chronic before saving. So, second way of doing this, one attribute at a time:</p>
<pre><code>def save_valid_attributes(attrib)
valid?
attrib.each{|(k,v)| send("${k}=", v); save; reload)
end
</code></pre>
<p>The model needs to be reloaded each time since, if one of the dates is invalid and doesn't save, it will prevent all further attributes from saving.</p>
<p>Is there a better way to do this? I'm sure this isn't an uncommon problem in the Rails world, I just can't seem to find anything in the Google universe of knowledge.</p>
| <p>I'm not sure how much luck you will have with this without a lot of messing around.</p>
<p>No matter how DRY and OO and easy your framework makes things ( which is in this case - alot =) you've still got to remember it's running in front of a bog-standard relational database, which has atomic commits as one of it's <em>defining</em> <em>features</em>. It's designed from the ground up to make sure either all of your changes are commited, or none.</p>
<p>You're effectively going to be over riding this standard functionality with something that goes 100% against the grain of how rails + was designed to work. This is likely to lead (as said already) to inconsistent data. </p>
<p>Having said that . . . it's always possible. I would look along the lines of doing manual validation of the attributes you care about, and then using the built-in method <code>object.update_attribute_with_validation_skipping.</code></p>
<p>Good luck! </p>
|
How to Truncate a string in PHP to the word closest to a certain number of characters? <p>I have a code snippet written in PHP that pulls a block of text from a database and sends it out to a widget on a webpage. The original block of text can be a lengthy article or a short sentence or two; but for this widget I can't display more than, say, 200 characters. I could use substr() to chop off the text at 200 chars, but the result would be cutting off in the middle of words-- what I really want is to chop the text at the end of the last <i>word</i> before 200 chars.</p>
| <p>By using the <a href="http://www.php.net/wordwrap">wordwrap</a> function. It splits the texts in multiple lines such that the maximum width is the one you specified, breaking at word boundaries. After splitting, you simply take the first line:</p>
<pre><code>substr($string, 0, strpos(wordwrap($string, $your_desired_width), "\n"));
</code></pre>
<p>One thing this oneliner doesn't handle is the case when the text itself is shorter than the desired width. To handle this edge-case, one should do something like:</p>
<pre><code>if (strlen($string) > $your_desired_width)
{
$string = wordwrap($string, $your_desired_width);
$string = substr($string, 0, strpos($string, "\n"));
}
</code></pre>
<hr>
<p>The above solution has the problem of prematurely cutting the text if it contains a newline before the actual cutpoint. Here a version which solves this problem:</p>
<pre><code>function tokenTruncate($string, $your_desired_width) {
$parts = preg_split('/([\s\n\r]+)/', $string, null, PREG_SPLIT_DELIM_CAPTURE);
$parts_count = count($parts);
$length = 0;
$last_part = 0;
for (; $last_part < $parts_count; ++$last_part) {
$length += strlen($parts[$last_part]);
if ($length > $your_desired_width) { break; }
}
return implode(array_slice($parts, 0, $last_part));
}
</code></pre>
<p>Also, here is the PHPUnit testclass used to test the implementation:</p>
<pre><code>class TokenTruncateTest extends PHPUnit_Framework_TestCase {
public function testBasic() {
$this->assertEquals("1 3 5 7 9 ",
tokenTruncate("1 3 5 7 9 11 14", 10));
}
public function testEmptyString() {
$this->assertEquals("",
tokenTruncate("", 10));
}
public function testShortString() {
$this->assertEquals("1 3",
tokenTruncate("1 3", 10));
}
public function testStringTooLong() {
$this->assertEquals("",
tokenTruncate("toooooooooooolooooong", 10));
}
public function testContainingNewline() {
$this->assertEquals("1 3\n5 7 9 ",
tokenTruncate("1 3\n5 7 9 11 14", 10));
}
}
</code></pre>
<h1><strong>EDIT :</strong></h1>
<p>Special UTF8 characters like 'Ã ' are not handled. Add 'u' at the end of the REGEX to handle it:</p>
<p><code>$parts = preg_split('/([\s\n\r]+)/u', $string, null, PREG_SPLIT_DELIM_CAPTURE);</code></p>
|
Cruise Control .Net vs Team Foundation Build <p>Our team is setting up nightly and continuous integration builds. We own Team Foundation Server and could use Team Foundation Build. I'm more familiar with CC.Net and lean that way but management sees all the money spent on TFS and wants to use it.</p>
<p>Some things I like better about CC.Net is the flexibility of notifications as well as the ease of implementing custom scripts.</p>
<p>If you have experience with both products, which do you prefer and why?</p>
| <p>I've used both. I guess it depends on what your organization values.</p>
<p>Since you are familiar with CC Net, I won't speak much to that. You already know what makes it cool.</p>
<p><strong>Here's what I like about Team Foundation Build:</strong></p>
<ul>
<li>Build Agents. It's very simple to turn any box into a build machine and run a build on it. MSFT got this one right.</li>
<li>Reporting. All relevant build results (test included) are stored in a SQL database and reported on via SQL Server Reporting Services. This is an immensely powerful tool for charting build and test results over time. CC Net doesn't have this built in.</li>
<li>You can do similar customizations via MSBUILD. It's basically the same as using NAnt with CC Net</li>
</ul>
<p><strong>Here's what drives me up the wall about Team Foundation Build:</strong></p>
<ul>
<li>To build C++/CLI projects (or run unit tests...?) the build agent must have VSTS Dev or Team Suite installed. This, friends, is just batsh*t crazy.</li>
<li>It must be connected to the TFS Mothership</li>
</ul>
<p>If you're in a big org with lots of bosses who have huge budgets and love reports (and don't get me wrong, this has huge value) OR you need to scale up to a multi-machine build farm, I'd prefer Team Foundation Build. </p>
<p>If you're a leaner shop, stick with CC Net and grow your own reporting solutions. That's what we did.</p>
<p>Until we got acquired. And got TFS :P</p>
|
What does COINIT_SPEED_OVER_MEMORY do? <p>When calling <code>CoInitializeEx</code>, you can specify the following values for <code>dwCoInit</code>:</p>
<pre><code>typedef enum tagCOINIT {
COINIT_MULTITHREADED = 0x0,
COINIT_APARTMENTTHREADED = 0x2,
COINIT_DISABLE_OLE1DDE = 0x4,
COINIT_SPEED_OVER_MEMORY = 0x8,
} COINIT;
</code></pre>
<p>What does the suggestively titled "speed over memory" value do? Is it ignored these days in COM?</p>
| <p>No idea if it's still used but it was meant to change the balance used by the COM algorithms.</p>
<p>If you had tons of memory and wanted speed at all costs, you would set that flag.</p>
<p>In low-memory environments, leaving that flag off would favor reduced memory usage.</p>
<hr>
<p>As it turns out, the marvellous <a href="http://stackoverflow.com/users/902497/raymond-chen">Raymond Chen</a> (of <a href="http://blogs.msdn.com/b/oldnewthing/" rel="nofollow">"The Old New Thing"</a> fame) has now weighed in on the subject and, despite what that flag was <em>meant</em> to do, it apparently does nothing at all.</p>
<p>See <i><a href="http://blogs.msdn.com/b/oldnewthing/archive/2012/11/08/10366704.aspx" rel="nofollow">What does the COINIT_SPEED_OVER_MEMORY flag to CoInitializeEx do?</a></i> for more details:</p>
<blockquote>
<p>When should you enable this mode? It doesn't matter, because as far as I can tell, there is no code anywhere in COM that changes its behavior based on whether the process has been placed into this mode! It looks like the flag was added when DCOM was introduced, but it never got hooked up to anything. (Or whatever code that had been hooked up to it never shipped.)</p>
</blockquote>
<p>Also <a href="http://archives.neohapsis.com/archives/microsoft/various/dcom/2001-q1/0160.html" rel="nofollow">http://archives.neohapsis.com/archives/microsoft/various/dcom/2001-q1/0160.html</a> from Steve Swartz, one of the original COM+ architects:</p>
<blockquote>
<p>COINIT_SPEED_OVER_MEMORY is ignored by COM.</p>
</blockquote>
|
Poppler programming <p>Poppler is a classic example of something without documentation that you would prefer be documented. This question is language agnostic, just asking about the general idea..
In short, how do you make a PDF viewer control with poppler?<br />
From what I can tell, you'd need to use poppler to render it to some surface, which sounds good up until you ask yourself how the user would select text and such. Does poppler offer a window for its various bindings, or do you have to code it all yourself?</p>
| <p>You have to code it all yourself -- Poppler only handles the PDF part, you have to write the GUI. Look at the code to <a href="http://www.gnome.org/projects/evince/" rel="nofollow">Evince</a> for a good example. </p>
|
Reparenting a Window as a Tab in a GTK Notebook <p>I'm using Mono with GTK# and am trying to display an existing window as a new tab in a GTK.Notebook. I'm currently re-parenting the widget to the notebook as follows:</p>
<pre>
MyWindow myWindow = new MyWindow();
myWindow.Children[0].Reparent(myNotebook)
</pre>
<p>Should I be doing this, or is there a better way to re-use an existing window so that you can display it on a tab?</p>
| <p>Your way is the best way, there's no way to embed windows into tabs without using horrible hacks like <code>GtkPlug</code> (which I'd guess you'd be uninterested in if you're using .NET). Look at the code to <code>gnome-terminal</code> for an example of how to do this.</p>
|
Performance of an large directory structure, networked application <p>I'm trying to find out what the performance of a large directory structure would be if deep directories were to be accessed on a shared, nfs filesystem. The structure would be excessively large, with 4 levels of nested directories, each level containing 1024 directories. (1024 at root, 1024 in a given subdirectory, and so on).</p>
<p>This filesystem would be on a network repository that users would be accessing for their personal information. The data would be replicated on multiple servers and load-balanced, but still, each machine would have a decent load at all times.</p>
<p>If the 4th level contained the information that the users were looking for, how bad would the performance be? If all were accessing different subdirectories? Could this be resolved by caching inode information, or no? </p>
<p>I've been searching on this for a while, but I'm primarily finding information on large files rather than large directory structures. </p>
| <p>I did that at my work once. Don't remember the exact numbers offhand, but I think it was 8 levels deep, 10 subdirectories in each level (user id 87654321 maps to directory 8/7/6/5/4/3/2/1/. Turned out that was not such a great idea, started running into problems with filesystem inode number limits, iirc (10^10 = 10000000000 directories, not good). Switched to more subdirectories per level and many less levels; problems went away. Your situation sounds more manageable, but still, check that your filesystem would support the kinds of file and directory counts that you're anticipating.</p>
|
Provisioning Issue using CrmDeploymentService <p>i've been working on Provision of an organization for quite a few days , and had faced few issues which i was successful in resolving them.Let me explain abt the issues i faced, the MSCrmServices is a process that is running under the Network Service.
When I call the 'Execute' method on the service from a console application
all actions preformed run under the context of the 'Network Service' account.
The Network Service account has not enough rights to create an organization
so many problems occur during the action.</p>
<ul>
<li>Registry access not allowed.</li>
<li>Not the correct SQL Server rights</li>
<li>Not enough AD rights.</li>
<li>...</li>
</ul>
<p>Impersonation doesn't work, the service uses the process account to perform
the actions. The only thing that works is to run the CRMAppPool identity as
an administrator which has the deployment administrator rights (added through
the Deployment manager tool).
But this issues in CRM deployment doesnt seem to faceoff from me :(. now that i have a new issue after changing the Pool identity to the system administrator, the deployment service gives an error saying Unauthorized!!!! and further when i check the log it says..</p>
<blockquote>
<p>Process: w3wp |Organization:00000000-0000-0000-0000-000000000000
|Thread: 1 |Category: Exception |User:
00000000-0000-0000-0000-000000000000 |Level: Error |
CrmException..ctor</p>
<p>at CrmException..ctor(String message, Exception innerException, Int32
errorCode, Boolean isFlowControlException, Boolean enableTrace)</p>
<p>at CrmException..ctor(String message, Int32 errorCode)</p>
<p>at CrmObjectNotFoundException..ctor(BusinessEntityMoniker moniker)</p>
<p>at
BusinessProcessObject.DoRetrievePublishableSingle(BusinessEntityMoniker
moniker, EntityExpression entityExpression, Boolean
includeUnpublished, ExecutionContext context)</p>
<p>at BusinessProcessObject.RetrieveUnpublished(BusinessEntityMoniker
moniker, EntityExpression entityExpression, ExecutionContext context)</p>
<p>at OrganizationUIService.RetrieveUnpublished(BusinessEntityMoniker
moniker, EntityExpression entityExpression, ExecutionContext context)</p>
<p>at OrganizationUIService.RetrieveOldFormXml(BusinessEntityMoniker
moniker, ExecutionContext context)</p>
<p>at OrganizationUIService.ExtractAndSaveFormLabels(IBusinessEntity
entity, ExecutionContext context)</p>
<p>at OrganizationUIService.Create(IBusinessEntity entity,
ExecutionContext context)</p>
<p>at ImportFormXmlHandler.createOrgUI(OrganizationUIService
orgUIService, XmlNode formNode)</p>
<p>at ImportFormXmlHandler.ImportItem()</p>
<p>at ImportHandler.Import()</p>
<p>at ImportHandler.Import()</p>
<p>at RootImportHandler.RunImport()</p>
<p>at ImportXml.RunImport()</p>
<p>at NewOrgUtility.OrganizationImportDefaultData(Guid organizationId,
Version existingDatabaseVersion, String importFile)</p>
<p>at NewOrgUtility.OrganizationImportDefaultData(Guid organizationId,
String importFile)</p>
<p>at NewOrgUtility.ConfigureOrganization(String organizationId, String
organizationName, String userAccountName, String userFirstName, String
userLastName, String userEmail, String languageCode, String
privilegedUserGroup, String sqlAccessGroup, String userGroup, String
reportingGroup, String privilegedReportingGroup, Boolean
grantNetworkServiceAccess, Boolean autoGroupManagement, String
importFileLocation, Boolean sqmOption)</p>
<p>at CreateOrganizationInstaller.Create(Guid organizationId, String
organizationUniqueName, String organizationFriendlyName, String
baseCurrencyCode, String baseCurrencyName, String baseCurrencySymbol,
String initialUserDomainName, String initialUserFirstName, String
initialUserLastName, String sqlServerName, Uri reportServerUrl, String
privilegedUserGroupName, String sqlAccessGroupName, String
userGroupName, String reportingGroupName, String
privilegedReportingGroupName, String applicationPath, String
languageId, Boolean sqmOption, String organizationCollation,
MultipleTenancy multipleTenancy)</p>
<p>at CreateOrganizationInstaller.Create(ICreateOrganizationInfo
organizationInfo)</p>
<p>at OrganizationService.Create(DeploymentEntity entity)</p>
<p>at CreateRequest.Process()</p>
<p>at CrmDeploymentService.Execute(DeploymentServiceRequest request)</p>
<p>at RuntimeMethodHandle._InvokeMethodFast(Object target, Object[]
arguments, SignatureStruct& sig, MethodAttributes methodAttributes,
RuntimeTypeHandle typeOwner)</p>
<p>at RuntimeMethodHandle.InvokeMethodFast(Object target, Object[]
arguments, Signature sig, MethodAttributes methodAttributes,
RuntimeTypeHandle typeOwner)</p>
<p>at RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr,
Binder binder, Object[] parameters, CultureInfo culture, Boolean
skipVisibilityChecks)</p>
<p>at RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr,
Binder binder, Object[] parameters, CultureInfo culture)</p>
<p>at LogicalMethodInfo.Invoke(Object target, Object[] values)</p>
<p>at WebServiceHandler.Invoke()</p>
<p>at WebServiceHandler.CoreProcessRequest()</p>
<p>at SyncSessionlessHandler.ProcessRequest(HttpContext context)</p>
<p>at
CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()</p>
<p>at HttpApplication.ExecuteStep(IExecutionStep step, Boolean&
completedSynchronously)</p>
<p>at ApplicationStepManager.ResumeSteps(Exception error)</p>
<p>at
HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext
context, AsyncCallback cb, Object extraData)</p>
<p>at HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr)</p>
<p>at HttpRuntime.ProcessRequestNoDemand(HttpWorkerRequest wr)</p>
<p>at ISAPIRuntime.ProcessRequest(IntPtr ecb, Int32 iWRType)</p>
</blockquote>
<p>Any idea on this.?</p>
<p>Have anyone of you come across such an issue. I've been trying to resolve this issue but hard luck.</p>
| <p>Edit: Actually you're not alone.</p>
<p><a href="http://www.eggheadcafe.com/software/aspnet/31450420/crmdeploymentservice-crm.aspx" rel="nofollow">http://www.eggheadcafe.com/software/aspnet/31450420/crmdeploymentservice-crm.aspx</a></p>
<p>Hope that helps.</p>
|
How do I register a custom URL protocol in Windows? <p>How do I register a custom protocol with Windows so that when clicking a link in an email or on a web page my application is opened and the parameters from the URL are passed to it?</p>
| <p>I think this is covered in MSDN, please see <a href="http://msdn.microsoft.com/en-us/library/aa767914.aspx" rel="nofollow">Registering an Application to a URL Protocol</a>.</p>
|
Phantom Referenced Objects <p>Phantom References serve for post-mortem operations.
The Java specification states that a <strong>phantom referenced object</strong> will not be deallocated until the phantom-reference itself is cleaned.</p>
<p>My question is: What purpose does this feature (object not deallocated) serve?</p>
<p>(The only idea i came up with, is to allow native code to do post-mortem cleanup on the object, but it isn't much convincing).</p>
| <p>Edit, since I've misunderstand the question first:</p>
<p>Quoted from here <a href="http://www.memorymanagement.org/glossary/p.html" rel="nofollow">http://www.memorymanagement.org/glossary/p.html</a>:</p>
<blockquote>
<p>The Java specification says that the
phantom reference is not cleared when
the reference object is enqueued, but
actually, there's no way in the
language to tell whether that has been
done or not. In some implementations,
JNI weak global references are weaker
than phantom references, and provide a
way to access phantom reachable
objects.</p>
</blockquote>
<p>But I found no other references which would say the same.</p>
|
how XQUERY is actually used? <p>I have been reading lot of XQUERY tutorial on the web site. Almost all of them are teaching me the XQUERY syntax. Let's say i have understood the XQUERY syntax, how am i going to actually implement XQUERY on my web site?</p>
<p>For example, i have book.xml:</p>
<pre><code><?xml version="1.0" encoding="iso-8859-1" ?>
<books>
<book>
<title>Doraemon</title>
<authorid>1</authorid>
</book>
<book>
<title>Ultraman</title>
<authorid>2</authorid>
</book>
</books>
</code></pre>
<p>Then, i have author.xml</p>
<pre><code><?xml version="1.0" encoding="iso-8859-1" ?>
<authors>
<author id="1">Mr A</author>
<author id="2">Mr B</author>
</authors>
</code></pre>
<p>I want to generate HTML which looks like following:</p>
<pre><code><table>
<tr><td>Title</td><td>Author</td></tr>
<tr><td>Doraemon</td><td>Mr A</td></tr>
<tr><td>Ultraman</td><td>Mr B</td></tr>
</table>
</code></pre>
<p>Please show me some example. Or any web site that i can do reference. Thanks very much.</p>
| <pre><code>(: file: titles.xqy :)
<table>
<tr><th>title</th><th>author</th></tr>
{
let $books-doc := doc("books.xml")
let $authors-doc := doc("authors.xml")
for $b in $books-doc//book,
$a in $authors-doc//author
where $a/@id = $b/authorid
return
<tr>
<td>{$b/title/text()}</td>
<td>{$a/text()}</td>
</tr>
}
</code></pre>
<p></p>
|
OpenFileDialog. How about "Specify Directory Dialog"? <p>On a file path field, I want to capture the directory path like:</p>
<pre><code>textbox1.Text = directory path
</code></pre>
<p>Anyone?</p>
| <p>There is a FolderBrowserDialog class that you can use if you want the user to select a folder.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog.aspx</a></p>
<pre><code>DialogResult result = folderBrowserDialog1.ShowDialog();
if (result.Equals(get_DialogResult().OK)) {
textbox1.Text = folderBrowserDialog1.get_SelectedPath();
}
</code></pre>
<p>If all you want is to get the direcotory from a full path, you can do this:</p>
<pre><code>textbox1.Text = Path.GetDirectoryName(@"c:\windows\temp\myfile.txt");
</code></pre>
<p>This will set the Text-property to "c:\windows\temp\"</p>
|
Is anyone using XForms in their web applications? <p>A few years ago we started playing around with <a href="http://www.w3.org/MarkUp/Forms/">XForms</a> from the W3C for a web app which required hundreds of custom forms.</p>
<p>As they aren't currently supported natively by the major browsers, what parsers/tools are you using on your projects today?</p>
<p>I'm not really interested in plugins - this needs to be something server side that emulates XForms.</p>
| <p>We use XForms for creating user interfaces for SOAP-based web services. Currently we settled with <strong>Chiba</strong> XForms engine (<a href="http://chiba.sourceforge.net/" rel="nofollow">http://chiba.sourceforge.net/</a>), but <strong>Orbeon</strong> (<a href="http://www.orbeon.com" rel="nofollow">http://www.orbeon.com/</a>) actually seems more mature. Both are server-side engines, which convert XForms into HTML on the fly. The validation is performed on server side with the help of AJAX. This puts quite high demands on the server, so I wouldn't bet on those engines when creating sites with heavy traffic. Alternatives are well documented on XForms Wikipedia page: <a href="http://en.wikipedia.org/wiki/XForms" rel="nofollow">http://en.wikipedia.org/wiki/XForms</a>.</p>
|
Creating/modifying images in JavaScript <p>Is it possible to <strong>dynamically create and modify images</strong> on a <strong>per pixel level</strong> in JavaScript (on client side)? Or has this to be done with server based languaged, such as PHP? </p>
<p>My use case is as follows:</p>
<ul>
<li>The user opens webpage and loads locally stored image</li>
<li>A preview of the image is displayed</li>
<li>The user can modify the image with a set of sliders (pixel level operations)</li>
<li>In the end he can download the image to his local HDD</li>
</ul>
<p>When searching in the web I just found posts about using IE's filtering method, but didn't find anything about image editing functions in JavaScript.</p>
| <p>Some browsers support the canvas:
<a href="http://developer.mozilla.org/En/Drawing_Graphics_with_Canvas">http://developer.mozilla.org/En/Drawing_Graphics_with_Canvas</a></p>
|
Best way to tackle global hotkey processing in c#? <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="http://stackoverflow.com/questions/48935/how-can-i-register-a-global-hot-key-to-say-ctrlshiftletter-using-wpf-and-ne">How can I register a global hot key to say CTRL+SHIFT+(LETTER) using WPF and .NET 3.5?</a> </p>
</blockquote>
<p>I'd like to have multiple global hotkeys in my new app (to control the app from anywhere in windows), and all of the given sources/solutions I found on the web seem to provide with a sort of a limping solution (either solutions only for one g.hotkey, or solutions that while running create annoying mouse delays on the screen).</p>
<p>Does anyone here know of a resource that can help me achive this, that I can learn from?
Anything?</p>
<p>Thanks ! :)</p>
| <p>The nicest solution I've found is <a href="http://bloggablea.wordpress.com/2007/05/01/global-hotkeys-with-net/">http://bloggablea.wordpress.com/2007/05/01/global-hotkeys-with-net/</a></p>
<pre><code>Hotkey hk = new Hotkey();
hk.KeyCode = Keys.1;
hk.Windows = true;
hk.Pressed += delegate { Console.WriteLine("Windows+1 pressed!"); };
hk.Register(myForm);
</code></pre>
<p>Note how you can set different lambdas to different hotkeys</p>
|
Auto-generating Unit-Tests for legacy Java-code <p>What is the best, preferably free/open source tool for auto-generating Java unit-tests? I know, the unit-tests cannot really serve the same purpose as normal TDD Unit-Tests which document and drive the design of the system. However auto-generated unit-tests can be useful if you have a huge legacy codebase and want to know whether the changes you are required to make will have unwanted, obscure side-effects.</p>
| <p>Not free. Not opensource. But I have found AgitarOne Agitator (<a href="http://www.agitar.com/solutions/products/agitarone.html" rel="nofollow">http://www.agitar.com/solutions/products/agitarone.html</a>) to be REALLY good for automatically generating unit tests AND looking for unwanted obscure side effects</p>
|
How to get the file path from HTML input form in Firefox 3 <p>We have simple HTML form with <code><input type="file"></code>, like shown below:</p>
<pre><code><form>
<label for="attachment">Attachment:</label>
<input type="file" name="attachment" id="attachment">
<input type="submit">
</form>
</code></pre>
<p>In IE7 (and probably all famous browsers, including old Firefox 2), if we submit a file like '//server1/path/to/file/filename' it works properly and gives the full path to the
file and the filename.</p>
<p>In Firefox 3, it returns only 'filename', because of their new 'security feature' to truncate the path, as explained in Firefox bug tracking system (<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=143220">https://bugzilla.mozilla.org/show_bug.cgi?id=143220</a>)</p>
<p>I have no clue how to overcome this 'new feature' because it causes all upload forms in my webapp to stop working on Firefox 3.</p>
<p>Can anyone help to find a single solution to get the file path both on Firefox 3 and IE7?</p>
| <blockquote>
<p>In IE7 (and probably all famous browsers, including old Firefox 2), if we submit a file like '//server1/path/to/file/filename' it works properly and gives the full path to the file and the filename.</p>
<p>I have no clue how to overcome this 'new feature' because it causes all upload forms in my webapp to stop working on Firefox 3.</p>
</blockquote>
<p>There's a major misunderstanding here. Why do you ever need the <em>full</em> file path on the server side? Imagine that I am the client and I have a file at <code>C:\path\to\passwords.txt</code> and I give the full file path to you. How would you as being a server ever get its <em>contents</em>? Do you have an open TCP connection to my local disk file system? Did you test the file upload functionality when you've brought your webapp into production on a different server machine?</p>
<p>It will only work when <em>both</em> the client and server runs at <strong>physically the same</strong> machine, because you will then have the access to the <em>same</em> hard disk file system. This would only occur when you're locally developing your website and thus both the webbrowser (client) and webserver (server) by coincidence runs at the same machine.</p>
<p>That the full file path is being sent in MSIE and other ancient webbrowsers is due to a <em>security bug</em>. The <a href="http://www.w3.org/TR/html401/interact/forms.html" rel="nofollow">W3</a> and <a href="http://www.faqs.org/rfcs/rfc2388.html" rel="nofollow">RFC2388</a> specifications have never mentioned to include the full file path. Only the file name. Firefox is doing its job correctly.</p>
<p>To handle uploaded files, you should not need to know the full file path. You should rather be interested in the full file <strong>contents</strong> which the client has already sent to the server in the request body in case of a <code>multipart/form-data</code> request. Change your form to look like the following as stated in RFC2388:</p>
<pre><code><form action="upload-script-url" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
</code></pre>
<p>How to obtain the contents of the uploaded file in the server side depends on the server side programming language you're using.</p>
<ul>
<li><p><strong>Java/JSP</strong>: you'd like to use <a href="http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html#getPart(java.lang.String)" rel="nofollow"><code>HttpServletRequest#getPart()</code></a> or <a href="http://commons.apache.org/fileupload" rel="nofollow">Apache Commons FileUpload API</a> to parse it. You should end up with an <code>InputStream</code> with the file contents which you in turn can write to any <code>OutputStream</code> to your taste. You can find an example in <a href="http://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet/">this answer</a>.</p></li>
<li><p><strong>Java/JSF</strong>: you'd like to use <a href="https://docs.oracle.com/javaee/7/javaserver-faces-2-2/vdldocs-facelets/h/inputFile.html" rel="nofollow"><code><h:inputFile></code></a> component or any other file upload component provided by the component library you're using. Also here, you'd like to obtain the file contents in flavor of an <code>InputStream</code>. See <a href="http://stackoverflow.com/questions/27677397/how-to-upload-file-using-jsf-2-2-hinputfile-where-is-the-saved-file">this answer</a> for an example.</p></li>
<li><p><strong>PHP</strong>: the file contents is already implicitly stored on the temp disk. You'd like to use <a href="http://php.net/manual/en/function.move-uploaded-file.php" rel="nofollow"><code>move_uploaded_file()</code></a> function to move it to the desired location. See also <a href="http://php.net/manual/en/features.file-upload.post-method.php" rel="nofollow">PHP manual</a>.</p></li>
<li><p><strong>ASP.NET</strong>: no detailed answer from me since I don't do it, but Google has found some examples for me: <a href="https://msdn.microsoft.com/en-us/library/aa478971.aspx" rel="nofollow">ASP.NET example</a>, <a href="https://msdn.microsoft.com/en-us/library/aa479405.aspx" rel="nofollow">ASP.NET 2.0 example</a></p></li>
</ul>
<p>Whenever you want to obtain the file name part of the uploaded file, you should <strong>trim</strong> the full path off from the file name. This information is namely completely irrelevant to you. Also see for example this <a href="http://commons.apache.org/fileupload/faq.html#whole-path-from-IE" rel="nofollow">Apache Commons FileUpload FAQ entry</a></p>
<blockquote>
<h3>Why does FileItem.getName() return the whole path, and not just the file name?</h3>
<p>Internet Explorer provides the entire path to the uploaded file and not just the base file name. Since FileUpload provides exactly what was supplied by the client (browser), you may want to remove this path information in your application. </p>
</blockquote>
|
Easiest way to merge a release into one JAR file <p>Is there a tool or script which easily merges a bunch of <a href="http://en.wikipedia.org/wiki/JAR_%28file_format%29">JAR</a> files into one JAR file? A bonus would be to easily set the main-file manifest and make it executable.</p>
<p>The concrete case is a <a href="http://jrst.labs.libre-entreprise.org/en/user/functionality.html">Java restructured text tool</a>. I would like to run it with something like:</p>
<blockquote>
<p>java -jar rst.jar</p>
</blockquote>
<p>As far as I can tell, it has no dependencies which indicates that it shouldn't be an easy single-file tool, but the downloaded ZIP file contains a lot of libraries.</p>
<pre><code> 0 11-30-07 10:01 jrst-0.8.1/
922 11-30-07 09:53 jrst-0.8.1/jrst.bat
898 11-30-07 09:53 jrst-0.8.1/jrst.sh
2675 11-30-07 09:42 jrst-0.8.1/readmeEN.txt
108821 11-30-07 09:59 jrst-0.8.1/jrst-0.8.1.jar
2675 11-30-07 09:42 jrst-0.8.1/readme.txt
0 11-30-07 10:01 jrst-0.8.1/lib/
81508 11-30-07 09:49 jrst-0.8.1/lib/batik-util-1.6-1.jar
2450757 11-30-07 09:49 jrst-0.8.1/lib/icu4j-2.6.1.jar
559366 11-30-07 09:49 jrst-0.8.1/lib/commons-collections-3.1.jar
83613 11-30-07 09:49 jrst-0.8.1/lib/commons-io-1.3.1.jar
207723 11-30-07 09:49 jrst-0.8.1/lib/commons-lang-2.1.jar
52915 11-30-07 09:49 jrst-0.8.1/lib/commons-logging-1.1.jar
260172 11-30-07 09:49 jrst-0.8.1/lib/commons-primitives-1.0.jar
313898 11-30-07 09:49 jrst-0.8.1/lib/dom4j-1.6.1.jar
1994150 11-30-07 09:49 jrst-0.8.1/lib/fop-0.93-jdk15.jar
55147 11-30-07 09:49 jrst-0.8.1/lib/activation-1.0.2.jar
355030 11-30-07 09:49 jrst-0.8.1/lib/mail-1.3.3.jar
77977 11-30-07 09:49 jrst-0.8.1/lib/servlet-api-2.3.jar
226915 11-30-07 09:49 jrst-0.8.1/lib/jaxen-1.1.1.jar
153253 11-30-07 09:49 jrst-0.8.1/lib/jdom-1.0.jar
50789 11-30-07 09:49 jrst-0.8.1/lib/jewelcli-0.41.jar
324952 11-30-07 09:49 jrst-0.8.1/lib/looks-1.2.2.jar
121070 11-30-07 09:49 jrst-0.8.1/lib/junit-3.8.1.jar
358085 11-30-07 09:49 jrst-0.8.1/lib/log4j-1.2.12.jar
72150 11-30-07 09:49 jrst-0.8.1/lib/logkit-1.0.1.jar
342897 11-30-07 09:49 jrst-0.8.1/lib/lutinwidget-0.9.jar
2160934 11-30-07 09:49 jrst-0.8.1/lib/docbook-xsl-nwalsh-1.71.1.jar
301249 11-30-07 09:49 jrst-0.8.1/lib/xmlgraphics-commons-1.1.jar
68610 11-30-07 09:49 jrst-0.8.1/lib/sdoc-0.5.0-beta.jar
3149655 11-30-07 09:49 jrst-0.8.1/lib/xalan-2.6.0.jar
1010675 11-30-07 09:49 jrst-0.8.1/lib/xercesImpl-2.6.2.jar
194205 11-30-07 09:49 jrst-0.8.1/lib/xml-apis-1.3.02.jar
78440 11-30-07 09:49 jrst-0.8.1/lib/xmlParserAPIs-2.0.2.jar
86249 11-30-07 09:49 jrst-0.8.1/lib/xmlunit-1.1.jar
108874 11-30-07 09:49 jrst-0.8.1/lib/xom-1.0.jar
63966 11-30-07 09:49 jrst-0.8.1/lib/avalon-framework-4.1.3.jar
138228 11-30-07 09:49 jrst-0.8.1/lib/batik-gui-util-1.6-1.jar
216394 11-30-07 09:49 jrst-0.8.1/lib/l2fprod-common-0.1.jar
121689 11-30-07 09:49 jrst-0.8.1/lib/lutinutil-0.26.jar
76687 11-30-07 09:49 jrst-0.8.1/lib/batik-ext-1.6-1.jar
124724 11-30-07 09:49 jrst-0.8.1/lib/xmlParserAPIs-2.6.2.jar
</code></pre>
<p>As you can see, it is somewhat desirable to not need to do this manually.</p>
<p>So far I've only tried AutoJar and ProGuard, both of which were fairly easy to get running. It appears that there's some issue with the constant pool in the JAR files.</p>
<p>Apparently jrst is slightly broken, so I'll make a go of fixing it. The <a href="http://en.wikipedia.org/wiki/Apache_Maven">Maven</a> <code>pom.xml</code> file was apparently broken too, so I'll have to fix that before fixing jrst ... I feel like a bug-magnet :-)</p>
<hr>
<p>Update: I never got around to fixing this application, but I checked out <a href="http://en.wikipedia.org/wiki/Eclipse_%28software%29">Eclipse</a>'s "Runnable JAR export wizard" which is based on a fat JAR. I found this very easy to use for deploying my own code.</p>
<p>Some of the other excellent suggestions might be better for builds in a non-Eclipse environment, oss probably should make a nice build using <a href="http://en.wikipedia.org/wiki/Apache_Ant">Ant</a>. (Maven, so far has just given me pain, but others love it.)</p>
| <p>Ant's <code>zipfileset</code> does the job</p>
<pre><code><jar id="files" jarfile="all.jar">
<zipfileset src="first.jar" includes="**/*.java **/*.class"/>
<zipfileset src="second.jar" includes="**/*.java **/*.class"/>
</jar>
</code></pre>
|
How can I listen to a RoutedEvent from a class that doesn't derive from FrameworkElement ? Can it be done? <p>The question says it all basically. </p>
<p>I want in a </p>
<pre><code>class MyClass
</code></pre>
<p>to listen to a routed event. Can it be done ?</p>
| <p>Actually I wiredup the event the wrong way :|</p>
<p>I had</p>
<pre><code>EventManager.RegisterClassHandler ( typeof ( MyClass )......
</code></pre>
<p>Instead of</p>
<pre><code>EventManager.RegisterClassHandler ( typeof ( TheClassThatOwnedTheEvent )
</code></pre>
<p>So .. my bad.</p>
|
private IP address ranges <p>What are the private IP address ranges?</p>
| <p>You will find the answers to this in <a href="http://www.faqs.org/rfcs/rfc1918.html">RFC 1918</a>. Though, I have listed them below for you.</p>
<pre><code> 10.0.0.0 - 10.255.255.255 (10/8 prefix)
172.16.0.0 - 172.31.255.255 (172.16/12 prefix)
192.168.0.0 - 192.168.255.255 (192.168/16 prefix)
</code></pre>
<p>It is a common misconception that 169.254.0.0/16 is a private IP address block. This is not true. It is link local, basically it is meant to be only used within networks, but it isn't official RFC1918. Additional information about IPv4 addresses can be found in <a href="http://www.faqs.org/rfcs/rfc3300.html">RFC 3300</a>. </p>
<p>On the other hand IPv6 doesn't have an equivalent to RFC1918, but any sort of site-local work should be done in fc00::/7. This is further touched on in <a href="http://www.faqs.org/rfcs/rfc4193.html">RFC 4193</a>.</p>
|
How to retrieve stored procedure return values from a TableAdapter <p>I cannot find an elegant way to get the return value from a stored procedure when using TableAdapters.</p>
<p>It appears the TableAdapter does not support SQL stored procedure return values when using a non-scalar stored procedure call. You'd expect the return value from the auto-generated function would be the return value from the stored procedure but it isn't (it is actually the number of rows affected). Although possible to use 'out' parameters and pass a variable as a ref to the auto generated functions it isn't a very clean solution.</p>
<p>I have seen some ugly hacks on the web to solve this, but no decent solution. Any help would be appreciated.</p>
| <p>The way to get the return value is to use a SqlParameter on the SqlCommand object which has its Direction set to ParameterDirection.ReturnValue. You should check the SelectCommand property of the TableAdapter after calling Fill.</p>
|
How do you add a JavaScript widget to a Wordpress.com hosted blog? <p>I've got a <a href="http://notebooks.readerville.com/">site</a> that provides blog-friendly widgets via JavaScript. These work fine in most circumstances, including self-hosted Wordpress blogs. With blogs hosted at Wordpress.com, however, JavaScript isn't allowed in sidebar text modules. Has anyone seen a workaround for this limitation?</p>
| <p>you could always petition wp to add your widget to their 'approved' list, but who knows how long that would take. you're talking about a way to circumvent the rules they have in place about posting arbitrary script. myspace javascript exploits in particular have increased awareness of the possibility of such workarounds, so you might have a tough time getting around the restrictions - however, here's a classic ones to try:</p>
<p>put the javascript in a weird place, like anywhere that executes a URL. for instance:</p>
<pre><code><div style="background:url('javascript:alert(this);');" />
</code></pre>
<p>sometimes the word 'javascript' gets cut out, but occasionally you can sneak it through as java\nscript, or something similar.</p>
<p>sometimes quotes get stripped out - try String.fromCharCode(34) to get around that. Also, in general, using eval("codepart1" + "codepart2") to get around restricted words or characters.</p>
<p>sneaking in javascript is a tricky business, mostly utilizing unorthodox (possibly un-documented) browser behavior in order to execute arbitrary javascript on a page. Welcome to hacking.</p>
|
How to suppress Terminated message after killing in bash? <p>How can you suppress the <code>Terminated</code> message that comes up after you kill a
process in a bash script?</p>
<p>I tried <code>set +bm</code>, but that doesn't work.</p>
<p>I know another solution involves calling <code>exec 2> /dev/null</code>, but is that
reliable? How do I reset it back so that I can continue to see stderr?</p>
| <p>In order to silence the message, you must be redirecting <code>stderr</code> <strong>at the time the message is generated</strong>. Because the <a href="http://ss64.com/bash/kill.html"><code>kill</code></a> command sends a signal and doesn't wait for the target process to respond, redirecting <code>stderr</code> of the <code>kill</code> command does you no good. The bash builtin <a href="http://ss64.com/bash/wait.html"><code>wait</code></a> was made specifically for this purpose.</p>
<p>Here is very simple example that kills the most recent background command. (<a href="http://stackoverflow.com/a/5163260/117471">Learn more about $! here.</a>)</p>
<pre><code>kill $!
wait $! 2>/dev/null
</code></pre>
<p>Because both <code>kill</code> and <code>wait</code> accept multiple pids, you can also do batch kills. Here is an example that kills all background processes (of the current process/script of course).</p>
<pre><code>kill $(jobs -rp)
wait $(jobs -rp) 2>/dev/null
</code></pre>
<p>I was led here from <a href="http://stackoverflow.com/questions/5719030/bash-silently-kill-background-function-process/5722850">bash: silently kill background function process</a>.</p>
|
override constraint from no action to cascading at runtime <p>I feel like I have a verry basic/stupid question, yet I never saw/read/heard anything in this direction.</p>
<p>Say I have a table <em>users(userId, name)</em> and a table <em>preferences(id, userId, language)</em>. The example is trivial, but could be extended to a situation with multi-level relations and way more tables..
When my UI requests to delete a user I first want to show a warning stating that also its preferences will be deleted. If at some point the database gets extended with more tables and relationships, but the software isn't adapted accordingly (client didn't update) a generic message should be shown.</p>
<p>How can I implement this? The UI cannot know about the whole data structure and should not be bothered to walk down all the relations to manually delete all the depending records.<br />
I would think this would be with constraints.
The constraint would be <em>no action</em> at first so the constraint will throw an error that can be caught by the UI. After the UI receives a confirmation, the constraint should become a <em>cascade</em>.</p>
<p>Somehow I'm feeling like I'm getting this all wrong..</p>
| <p>What I would do is this:</p>
<ol>
<li>The constraint is CASCADE</li>
<li>The application checks if preferences exist.</li>
<li>If they do, show the warning.</li>
<li>If no preferences exist, or the warning is accepted, delete the client.</li>
</ol>
<p>Changing database relationships on the fly is not going to be a good idea!!</p>
<p>Cheers,</p>
<p>RB.</p>
|
What prevents a Thread in C# from being Collected? <p>In .NET, after this code, what mechanism stops the <code>Thread</code> object from being garbage collected?</p>
<pre><code>new Thread(Foo).Start();
GC.Collect();
</code></pre>
<p>Yes, it's safe to assume <strong>something</strong> has a reference to the thread, I was just wandering what exactly. For some reason Reflector doesn't show me <code>System.Threading</code>, so I can't dig it myself (I know MS released the source code for the .NET framework, I just don't have it handy).</p>
| <p>The runtime keeps a reference to the thread as long as it is running. The GC wont collect it as long as anyone still keeps that reference.</p>
|
Is anyone developing facebook apps on Grails <p>I have not seen much support for Grails to develop facebook apps.I was just wondering if people around are developing facebook apps on grails </p>
| <p>Jozef Dransfield:
<a href="http://www.grassr.com/wordpress/?cat=8" rel="nofollow">http://www.grassr.com/wordpress/?cat=8</a></p>
|
Rails or Grails? <p>Grails vs Rails. Which has better support? And which one is a better choice to develop medium size apps with? Most importantly which one has more plug-ins?</p>
| <p>One other thing worth mentioning: the design philosophy of both framework is somewhat different when it comes to the model. Grails is more "domain-oriented" while Rails is more "database-oriented".<br />
In Rails, you essentially start by defining your tables (with field names and their specifics). Then ActiveRecord will map them to Ruby classes or models.<br />
In Grails, it's the reverse: you start by defining your models (Groovy classes) and when you hit run, GORM (Grails ActiveRecord equivalent) will create the related database and tables (or update them). Which may also be why you don't have the concept of 'migrations' in Grails (although I think it will come in some future release).<br />
I don't know if one is better than the other. I guess it depends on your context.</p>
<p>This being said, I'm still myself wondering which one to choose. As Tom was saying, if you're dependent on Java you can still go for JRuby - so Java reuse shouldn't be your sole criterion.</p>
|
Is it possible to print a variable's type in standard C++? <p>For example:</p>
<pre><code>int a = 12;
cout << typeof(a) << endl;
</code></pre>
<p>Expected output:</p>
<pre><code>int
</code></pre>
| <p>C++11 update to a very old question: Print variable type in C++.</p>
<p>The accepted (and good) answer is to use <code>typeid(a).name()</code>, where <code>a</code> is a variable name.</p>
<p>Now in C++11 we have <code>decltype(x)</code>, which can turn an expression into a type. And <code>decltype()</code> comes with its own set of very interesting rules. For example <code>decltype(a)</code> and <code>decltype((a))</code> will generally be different types (and for good and understandable reasons once those reasons are exposed).</p>
<p>Will our trusty <code>typeid(a).name()</code> help us explore this brave new world?</p>
<p>No.</p>
<p>But the tool that will is not that complicated. And it is that tool which I am using as an answer to this question. I will compare and contrast this new tool to <code>typeid(a).name()</code>. And this new tool is actually built on top of <code>typeid(a).name()</code>.</p>
<p><strong>The fundamental issue:</strong></p>
<pre><code>typeid(a).name()
</code></pre>
<p>throws away cv-qualifiers, references, and lvalue/rvalue-ness. For example:</p>
<pre><code>const int ci = 0;
std::cout << typeid(ci).name() << '\n';
</code></pre>
<p>For me outputs:</p>
<pre><code>i
</code></pre>
<p>and I'm guessing on MSVC outputs:</p>
<pre><code>int
</code></pre>
<p>I.e. the <code>const</code> is gone. This is not a QOI (Quality Of Implementation) issue. The standard mandates this behavior.</p>
<p>What I'm recommending below is:</p>
<pre><code>template <typename T> std::string type_name();
</code></pre>
<p>which would be used like this:</p>
<pre><code>const int ci = 0;
std::cout << type_name<decltype(ci)>() << '\n';
</code></pre>
<p>and for me outputs:</p>
<pre><code>int const
</code></pre>
<p><code><disclaimer></code> I have not tested this on MSVC. <code></disclaimer></code> But I welcome feedback from those who do.</p>
<p><strong>The C++11 Solution</strong></p>
<p>I am using <code>__cxa_demangle</code> for non-MSVC platforms as recommend by <a href="http://stackoverflow.com/users/487362/ipapadop">ipapadop</a> in his answer to demangle types. But on MSVC I'm trusting <code>typeid</code> to demangle names (untested). And this core is wrapped around some simple testing that detects, restores and reports cv-qualifiers and references to the input type.</p>
<pre><code>#include <type_traits>
#include <typeinfo>
#ifndef _MSC_VER
# include <cxxabi.h>
#endif
#include <memory>
#include <string>
#include <cstdlib>
template <class T>
std::string
type_name()
{
typedef typename std::remove_reference<T>::type TR;
std::unique_ptr<char, void(*)(void*)> own
(
#ifndef _MSC_VER
abi::__cxa_demangle(typeid(TR).name(), nullptr,
nullptr, nullptr),
#else
nullptr,
#endif
std::free
);
std::string r = own != nullptr ? own.get() : typeid(TR).name();
if (std::is_const<TR>::value)
r += " const";
if (std::is_volatile<TR>::value)
r += " volatile";
if (std::is_lvalue_reference<T>::value)
r += "&";
else if (std::is_rvalue_reference<T>::value)
r += "&&";
return r;
}
</code></pre>
<p><strong>The Results</strong></p>
<p>With this solution I can do this:</p>
<pre><code>int& foo_lref();
int&& foo_rref();
int foo_value();
int
main()
{
int i = 0;
const int ci = 0;
std::cout << "decltype(i) is " << type_name<decltype(i)>() << '\n';
std::cout << "decltype((i)) is " << type_name<decltype((i))>() << '\n';
std::cout << "decltype(ci) is " << type_name<decltype(ci)>() << '\n';
std::cout << "decltype((ci)) is " << type_name<decltype((ci))>() << '\n';
std::cout << "decltype(static_cast<int&>(i)) is " << type_name<decltype(static_cast<int&>(i))>() << '\n';
std::cout << "decltype(static_cast<int&&>(i)) is " << type_name<decltype(static_cast<int&&>(i))>() << '\n';
std::cout << "decltype(static_cast<int>(i)) is " << type_name<decltype(static_cast<int>(i))>() << '\n';
std::cout << "decltype(foo_lref()) is " << type_name<decltype(foo_lref())>() << '\n';
std::cout << "decltype(foo_rref()) is " << type_name<decltype(foo_rref())>() << '\n';
std::cout << "decltype(foo_value()) is " << type_name<decltype(foo_value())>() << '\n';
}
</code></pre>
<p>and the output is:</p>
<pre><code>decltype(i) is int
decltype((i)) is int&
decltype(ci) is int const
decltype((ci)) is int const&
decltype(static_cast<int&>(i)) is int&
decltype(static_cast<int&&>(i)) is int&&
decltype(static_cast<int>(i)) is int
decltype(foo_lref()) is int&
decltype(foo_rref()) is int&&
decltype(foo_value()) is int
</code></pre>
<p>Note (for example) the difference between <code>decltype(i)</code> and <code>decltype((i))</code>. The former is the type of the <em>declaration</em> of <code>i</code>. The latter is the "type" of the <em>expression</em> <code>i</code>. (expressions never have reference type, but as a convention <code>decltype</code> represents lvalue expressions with lvalue references).</p>
<p>Thus this tool is an excellent vehicle just to learn about <code>decltype</code>, in addition to exploring and debugging your own code.</p>
<p>In contrast, if I were to build this just on <code>typeid(a).name()</code>, without adding back lost cv-qualifiers or references, the output would be:</p>
<pre><code>decltype(i) is int
decltype((i)) is int
decltype(ci) is int
decltype((ci)) is int
decltype(static_cast<int&>(i)) is int
decltype(static_cast<int&&>(i)) is int
decltype(static_cast<int>(i)) is int
decltype(foo_lref()) is int
decltype(foo_rref()) is int
decltype(foo_value()) is int
</code></pre>
<p>I.e. Every reference and cv-qualifier is stripped off.</p>
<p><strong>C++14 Update</strong></p>
<p>Just when you think you've got a solution to a problem nailed, someone always comes out of nowhere and shows you a much better way. :-)</p>
<p><a href="http://stackoverflow.com/a/35943472/576911">This answer</a> from <a href="http://stackoverflow.com/users/2969631/jamboree">Jamboree</a> shows how to get the type name in C++14 at compile time. It is a brilliant solution for a couple reasons:</p>
<ol>
<li>It's at compile time!</li>
<li>You get the compiler itself to do the job instead of a library (even a std::lib). This means more accurate results for the latest language features (like lambdas).</li>
</ol>
<p><a href="http://stackoverflow.com/users/2969631/jamboree">Jamboree's</a> <a href="http://stackoverflow.com/a/35943472/576911">answer</a> doesn't quite lay everything out for VS, and I'm tweaking his code a little bit. But since this answer gets a lot of views, take some time to go over there and upvote his answer, without which, this update would never have happened.</p>
<pre><code>#include <cstddef>
#include <stdexcept>
#include <cstring>
#include <ostream>
#ifndef _MSC_VER
# if __cplusplus < 201103
# define CONSTEXPR11_TN
# define CONSTEXPR14_TN
# define NOEXCEPT_TN
# elif __cplusplus < 201402
# define CONSTEXPR11_TN constexpr
# define CONSTEXPR14_TN
# define NOEXCEPT_TN noexcept
# else
# define CONSTEXPR11_TN constexpr
# define CONSTEXPR14_TN constexpr
# define NOEXCEPT_TN noexcept
# endif
#else // _MSC_VER
# if _MSC_VER < 1900
# define CONSTEXPR11_TN
# define CONSTEXPR14_TN
# define NOEXCEPT_TN
# elif _MSC_VER < 2000
# define CONSTEXPR11_TN constexpr
# define CONSTEXPR14_TN
# define NOEXCEPT_TN noexcept
# else
# define CONSTEXPR11_TN constexpr
# define CONSTEXPR14_TN constexpr
# define NOEXCEPT_TN noexcept
# endif
#endif // _MSC_VER
class static_string
{
const char* const p_;
const std::size_t sz_;
public:
typedef const char* const_iterator;
template <std::size_t N>
CONSTEXPR11_TN static_string(const char(&a)[N]) NOEXCEPT_TN
: p_(a)
, sz_(N-1)
{}
CONSTEXPR11_TN static_string(const char* p, std::size_t N) NOEXCEPT_TN
: p_(p)
, sz_(N)
{}
CONSTEXPR11_TN const char* data() const NOEXCEPT_TN {return p_;}
CONSTEXPR11_TN std::size_t size() const NOEXCEPT_TN {return sz_;}
CONSTEXPR11_TN const_iterator begin() const NOEXCEPT_TN {return p_;}
CONSTEXPR11_TN const_iterator end() const NOEXCEPT_TN {return p_ + sz_;}
CONSTEXPR11_TN char operator[](std::size_t n) const
{
return n < sz_ ? p_[n] : throw std::out_of_range("static_string");
}
};
inline
std::ostream&
operator<<(std::ostream& os, static_string const& s)
{
return os.write(s.data(), s.size());
}
template <class T>
CONSTEXPR14_TN
static_string
type_name()
{
#ifdef __clang__
static_string p = __PRETTY_FUNCTION__;
return static_string(p.data() + 31, p.size() - 31 - 1);
#elif defined(__GNUC__)
static_string p = __PRETTY_FUNCTION__;
# if __cplusplus < 201402
return static_string(p.data() + 36, p.size() - 36 - 1);
# else
return static_string(p.data() + 46, p.size() - 46 - 1);
# endif
#elif defined(_MSC_VER)
static_string p = __FUNCSIG__;
return static_string(p.data() + 38, p.size() - 38 - 7);
#endif
}
</code></pre>
<p>This code will auto-backoff on the <code>constexpr</code> if you're still stuck in ancient C++11. And if you're painting on the cave wall with C++98/03, the <code>noexcept</code> is sacrificed as well.</p>
|
PyQt and PyCairo <p>I know it's possible to place a PyCairo surface inside a Gtk Drawing Area. But I think Qt is a lot better to work with, so I've been wondering if there's anyway to place a PyCairo surface inside some Qt component?</p>
| <p>Qt's own OpenGL based surfaces (using QPainter) are known to be much faster than Cairo. Might you explain why you want specifically Cairo in Qt?</p>
<p>For the basics of using QPainter see <a href="http://www.informit.com/articles/article.aspx?p=1174421" rel="nofollow">this excerpt</a> from the book "C++ GUI Programming with Qt4", and while it's C++ code, the PyQt implementation will be parallel.</p>
<p>As for joining Cairo with Qt... <a href="http://arstechnica.com/news.ars/post/20080818-nokia-helps-port-firefox-to-qt.html" rel="nofollow">This article in ArsTechnica</a> sheds some light - it seems nothing that could help you exists currently (iow., nobody tried such marriage).</p>
|
How do I use calculated value date in Sharepoint lists field to find a date+30 days? <p>I have a list I've built in Sharepoint, where one of the fields is a date that the user enters.
I want to add another field, which is a calculated value field that needs to be the date provided by the user + 30 days.
What formula do I need to pass to the calculated value field to achieve that?</p>
| <p>Try this:</p>
<ol>
<li>Create a new Calculated column</li>
<li>In the Forumla box, enter something like this:
=TEXT([existing date column]+30,"yyyy-mm-dd")
You can use any date format string you like instead of "yyyy-mm-dd"</li>
<li>Make the data type "Date and Time"</li>
<li>Make the date and time format "Date Only"</li>
</ol>
|
Is there a way to specify a different session store with Tomcat? <p>Tomcat (version 5 here) stores session information in memory. When clustering this information is periodically broadcast to other servers in the cluster to keep things in sync. You can use a database store to make sessions persistant but this information is only written periodically as well and is only really used for failure-recovery rather than actually replacing the in-memory sessions.</p>
<p>If you don't want to use sticky sessions (our configuration doesn't allow it unfortunately) this raises the problem of the sessions getting out of sync.</p>
<p>In other languages, web frameworks tend to allow you to use a database as the primary session store. Whilst this introduces a potential scaling issue it does make session management very straightforward. I'm wondering if there's a way to get tomcat to use a database for sessions in this way (technically this would also remove the need for any clustering configuration in the tomcat server.xml).</p>
| <p>There definitely is a way. Though I'd strongly vote for sticky sessions - saves so much load for your servers/database (unless something fails)...</p>
<p><a href="http://tomcat.apache.org/tomcat-5.5-doc/config/manager.html" rel="nofollow">http://tomcat.apache.org/tomcat-5.5-doc/config/manager.html</a> has information about SessionManager configuration and setup for Tomcat. Depending on your exact requirements you might have to implement your own session manager, but this starting point should provide some help.</p>
|
Way to Alt-Tab through all applications in Virtual and Host PC <p>I am using VirtualPc 2007 more and more, the one annoyance is "Alt-Tab".</p>
<p>What I want is to be able to use alt-tab to iterate through all of the applications in the host pc and virtual(s) as if they were one long list. Is there a setting or program to do this?</p>
| <p>No. If the VPC is in full screen mode, alt+tab works only within the context of the VPC. If the VPC Screen is not focused, you will get the collection of applications that are in the Host (including the instance of VPC)</p>
|
Best way to handle URLs in a multilingual site in ASP.net <p>I need to do a multilingual website, with urls like</p>
<pre><code>www.domain.com/en/home.aspx for english
www.domain.com/es/home.aspx for spanish
</code></pre>
<p>In the past, I would set up two virtual directories in IIS, and then detect the URL in global.aspx and change the language according to the URL</p>
<pre><code>Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim lang As String
If HttpContext.Current.Request.Path.Contains("/en/") Then
lang = "en"
Else
lang = "es"
End If
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang)
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang)
End Sub
</code></pre>
<p>The solution is more like a hack. I'm thinking about using Routing for a new website. </p>
<p><strong>Do you know a better or more elegant way to do it?</strong></p>
<p>edit: The question is about the URL handling, not about resources, etc.</p>
| <p>I decided to go with the new ASP.net Routing.<br />
Why not urlRewriting? Because I don't want to change the clean URL that routing gives to you.</p>
<p>Here is the code:</p>
<pre><code>Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application startup
RegisterRoutes(RouteTable.Routes)
End Sub
Public Sub RegisterRoutes(ByVal routes As RouteCollection)
Dim reportRoute As Route
Dim DefaultLang As String = "es"
reportRoute = New Route("{lang}/{page}", New LangRouteHandler)
'* if you want, you can contrain the values
'reportRoute.Constraints = New RouteValueDictionary(New With {.lang = "[a-z]{2}"})
reportRoute.Defaults = New RouteValueDictionary(New With {.lang = DefaultLang, .page = "home"})
routes.Add(reportRoute)
End Sub
</code></pre>
<p>Then LangRouteHandler.vb class:</p>
<pre><code>Public Class LangRouteHandler
Implements IRouteHandler
Public Function GetHttpHandler(ByVal requestContext As System.Web.Routing.RequestContext) As System.Web.IHttpHandler _
Implements System.Web.Routing.IRouteHandler.GetHttpHandler
'Fill the context with the route data, just in case some page needs it
For Each value In requestContext.RouteData.Values
HttpContext.Current.Items(value.Key) = value.Value
Next
Dim VirtualPath As String
VirtualPath = "~/" + requestContext.RouteData.Values("page") + ".aspx"
Dim redirectPage As IHttpHandler
redirectPage = BuildManager.CreateInstanceFromVirtualPath(VirtualPath, GetType(Page))
Return redirectPage
End Function
End Class
</code></pre>
<p>Finally I use the default.aspx in the root to redirect to the default lang used in the browser list.<br />
Maybe this can be done with the route.Defaults, but don't work inside Visual Studio (maybe it works in the server)</p>
<pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim DefaultLang As String = "es"
Dim SupportedLangs As String() = {"en", "es"}
Dim BrowserLang As String = Mid(Request.UserLanguages(0).ToString(), 1, 2).ToLower
If SupportedLangs.Contains(BrowserLang) Then DefaultLang = BrowserLang
Response.Redirect(DefaultLang + "/")
End Sub
</code></pre>
<p>Some sources:<br />
* <a href="http://blogs.msdn.com/mikeormond/archive/2008/05/14/using-asp-net-routing-independent-of-mvc.aspx">Mike Ormond's blog</a><br />
* <a href="http://chriscavanagh.wordpress.com/2008/04/25/systemwebrouting-with-webforms-sample/">Chris Cavanaghâs Blog</a><br />
* <a href="http://msdn.microsoft.com/en-us/library/cc668201.aspx">MSDN</a> </p>
|
svn over HTTP proxy <p>I'm on laptop (Ubuntu) with a network that use HTTP proxy (only http connections allowed).<br>
When I use svn up for url like 'http://.....' everything is cool (google chrome repository works perfect), but right now I need to svn up from server with 'svn://....' and I see connection refused.<br>
I've set proxy configuration in /etc/subversion/servers but it doesn't help.<br>
Anyone have opinion/solution?<br></p>
| <p>In <code>/etc/subversion/servers</code> you are setting <code>http-proxy-host</code>, which has nothing to do with <code>svn://</code> which connects to a different server usually running on port 3690 started by <code>svnserve</code> command.</p>
<p>If you have access to the server, you can setup <code>svn+ssh://</code> as <a href="http://svnbook.red-bean.com/en/1.0/ch06s03.html">explained here.</a></p>
<p><strong>Update</strong>: You could also try using <a href="http://search.cpan.org/~book/Net-Proxy-0.12/script/connect-tunnel"><code>connect-tunnel</code></a>, which uses your HTTPS proxy server to tunnel connections:</p>
<pre><code>connect-tunnel -P proxy.company.com:8080 -T 10234:svn.example.com:3690
</code></pre>
<p>Then you would use</p>
<pre><code>svn checkout svn://localhost:10234/path/to/trunk
</code></pre>
|
Boost serialization: specifying a template class version <p>I have a template class that I serialize (call it C), for which I want to specify a version for boost serialization. As BOOST_CLASS_VERSION does not work for template classes. I tried this:</p>
<pre><code>namespace boost {
namespace serialization {
template< typename T, typename U >
struct version< C<T,U> >
{
typedef mpl::int_<1> type;
typedef mpl::integral_c_tag tag;
BOOST_STATIC_CONSTANT(unsigned int, value = version::type::value);
};
}
}
</code></pre>
<p>but it does not compile. Under VC8, a subsequent call to BOOST_CLASS_VERSION gives this error:</p>
<p><code>error C2913: explicit specialization; 'boost::serialization::version' is not a specialization of a class template</code></p>
<p>What is the correct way to do it?</p>
| <pre><code>#include <boost/serialization/version.hpp>
</code></pre>
<p>:-)</p>
|
What files are you allowed to modify in SharePoint 2007? <p>What files can we modify so that our solution is still supported by Microsoft?</p>
<p>Is it allowed to customize error pages?
Can we modify the web.config files to use custom HTTPHandlers?</p>
| <p>You can certainly edit the web.config file for your sites. The one thing that you should be aware of, however, is that when you start editing files manually on the file system, you will have to remember to manually make those changes across all servers in the farm (assuming a farm exists). In addition to this, when you edit files in the 12 hive, it's important to understand that you will be making a change to all SharePoint sites hosted on the server(s) for which the files were edited.</p>
<p>Personally, if I were going to create a custom error page, I would simply add a <customErrors> section to my web.config. I avoid <b>editing</b> any <b>existing</b> files in the 12 hive, but I have <b>added</b> files (though it's rare).</p>
|
Using Yahoo! Pipes <p>Have you used <a href="http://pipes.yahoo.com/pipes/" rel="nofollow">pipes.yahoo.com</a> to quickly and easily do... anything? I've recently created a quick <a href="http://pipes.yahoo.com/kooshmoose/stackoverflow_merge" rel="nofollow">mashup of StackOverflow tags</a> (<a href="http://pipes.yahoo.com/pipes/pipe.run?_id=NIlbqD_E3RGfAAUWpgt1Yg&_render=rss" rel="nofollow">via rss</a>) so that I can browse through new questions in fields I like to follow.</p>
<p>This has been around for some time, but I've just recently revisited it and I'm completely impressed with it's ease of use. It's almost to the point where I could set up a pipe and then give a client privileges to go in and edit feed sources... and I didn't have to write more than a few lines of code.</p>
<p>So, what other practical uses can you think of for pipes?</p>
| <p>It's nice for aggregating feeds, yes, but the other handy thing to do is filtering the feeds. A while back, I created a feed for Digg (before Digg fell into the Fark pit of dispair). I didn't care about the overwhelming Apple and Ubuntu news, so I filtered those keywords out of Technology, which I then combined with Science and World & Business feeds.</p>
<p>Anyway, you can do a lot more than just combine things. If you wanted to be smart about it, you could set up per-subfeed and whole-feed filters to give granular or over-arching filtering abilities as the news changes and you get bored with one topic or another.</p>
|
Connecting to Oracle using PHP <p>I am a PHP Developer, but I am confused on how to connect to a remote Oracle database instance from PHP. I simply need to query a read only database and get some data. Do I need to have the Oracle Instant Client or the extension is enough? Thanks.</p>
| <p>From <a href="http://php.net/manual/en/oci8.setup.php" rel="nofollow">PHP Manual</a></p>
<ul>
<li><p>You will need the Oracle client libraries to use this extension.</p></li>
<li><p>The most convenient way to install all the required files is to use Oracle Instant Client, which is available from <a href="http://www.oracle.com/technology/software/tech/oci/instantclient/" rel="nofollow">Oracle's site</a></p></li>
</ul>
|
Trip time calculation in relational databases? <p>I had this question in mind and since I just discovered this site I decided to post it here.</p>
<p>Let's say I have a table with a timestamp and a state for a given "object" (generic meaning, not OOP object); is there an optimal way to calculate the time between a state and the next occurrence of another (or same) state (what I call a "trip") with a single SQL statement (inner SELECTs and UNIONs aren't counted)?</p>
<p>Ex: For the following, the trip time between Initial and Done would be 6 days, but between Initial and Review it would be 2 days. </p>
<blockquote>
<p>2008-08-01 13:30:00 - Initial<br />
2008-08-02 13:30:00 - Work<br />
2008-08-03 13:30:00 - Review<br />
2008-08-04 13:30:00 - Work<br />
2008-08-05 13:30:00 - Review<br />
2008-08-06 13:30:00 - Accepted<br />
2008-08-07 13:30:00 - Done</p>
</blockquote>
<p>No need to be generic, just say what <a href="http://stackoverflow.com/questions/980813/what-is-sgbd">SGBD</a> your solution is specific to if not generic.</p>
| <p>Here's an Oracle methodology using an analytic function.</p>
<pre><code>with data as (
SELECT 1 trip_id, to_date('20080801 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Initial' step from dual UNION ALL
SELECT 1 trip_id, to_date('20080802 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Work' step from dual UNION ALL
SELECT 1 trip_id, to_date('20080803 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Review' step from dual UNION ALL
SELECT 1 trip_id, to_date('20080804 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Work' step from dual UNION ALL
SELECT 1 trip_id, to_date('20080805 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Review' step from dual UNION ALL
SELECT 1 trip_id, to_date('20080806 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Accepted' step from dual UNION ALL
SELECT 1 trip_id, to_date('20080807 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Done' step from dual )
select trip_id,
step,
dt - lag(dt) over (partition by trip_id order by dt) trip_time
from data
/
1 Initial
1 Work 1
1 Review 1
1 Work 1
1 Review 1
1 Accepted 1
1 Done 1
</code></pre>
<p>These are very commonly used in situations where traditionally we might use a self-join.</p>
|
ORA-00161: transaction branch length 103 is illegal (maximum allowed 64 <p>Error:</p>
<pre><code>ORA-00161: transaction branch length 103 is illegal (maximum allowed 64â¦
</code></pre>
<p>I'm using the DAC from Oracle, any idea if there is a patch for this?</p>
| <p>This looks to be a similar issue for .net 2.0, vista and oracle <a href="http://forums.oracle.com/forums/thread.jspa?threadID=516250" rel="nofollow">http://forums.oracle.com/forums/thread.jspa?threadID=516250</a></p>
|
What alternatives are there to the MATLAB Editor? <p>Some things that I personally find as shortcomings in the MATLAB Editor:</p>
<ul>
<li>virtually no code completion available</li>
<li>does not run OS native (on MacOS) - but in X-Environment (shortcuts, copy&paste problems, keymappings, non intuitive window-managing)</li>
<li>virtually no refactoring tools</li>
</ul>
<p>Are there alternative editors with these features?</p>
| <p>You can use any editor you like in MATLAB by going to </p>
<p>File -> Preferences -> Editor/Debugger</p>
<p>and then change the radio button from 'MATLAB Editor' to 'Text editor' and the command for your editor of choice in there. I use this to launch gedit on my Linux box.</p>
<p>On the Mac-Specific side - it seems that there is a MATLAB bundle for <a href="http://macromates.com/">TextMate</a></p>
<p><a href="http://kjosmoen.org/2007/6/15/bugfixes-in-the-textmate-matlab-bundle">http://kjosmoen.org/2007/6/15/bugfixes-in-the-textmate-matlab-bundle</a></p>
|
How can I get the unique values of an array in .net? <p>Say I've got this array:
MyArray(0)="aaa"
MyArray(1)="bbb"
MyArray(2)="aaa"</p>
<p>Is there a .net function which can give me the unique values? I would like something like this as an output of the function:
OutputArray(0)="aaa"
OutputArray(1)="bbb"</p>
| <p>A solution could be to use LINQ as in the following example:</p>
<pre><code>int[] test = { 1, 2, 1, 3, 3, 4, 5 };
var res = (from t in test select t).Distinct<int>();
foreach (var i in res)
{
Console.WriteLine(i);
}
</code></pre>
<p>That would print the expected:</p>
<pre><code>1
2
3
4
5
</code></pre>
|
What is the difference between TrueType fonts and Type-1 fonts? <p>What is the difference between TrueType fonts and Type-1 fonts?</p>
| <p>The Postscript Type-1 specification was created by Adobe back in 1985 or so. Type-1 fonts are vector based. You can find the specification in "<a href="http://partners.adobe.com/public/developer/en/font/T1_SPEC.PDF">Adobe Type 1. Font Format.</a>".</p>
<p>TrueType fonts were defined by Apple a couple of years earlier so True Type and PostScript were competitors in the 1990s. Microsoft picked up True Type for the native Windows font format in the beginning 1990s (for using PostScript, additional tools like Adobe Type manager were necessary). </p>
<p>Today, Microsoft is fading out support for PostScript fonts. Try using one as an UI font in Vista. Good luck ;-)</p>
<p>As a successor of TrueType, Microsoft (I think together with Adobe) created the Open Type (anytime around 2000) format and Adobe converted their whole font library into the new format (you can still get them as Type-1 fonts). </p>
|
How do I call a SQL Server stored procedure from PowerShell? <p>I have a large CSV file and I want to execute a stored procedure for each line.</p>
<p>What is the best way to execute a stored procedure from PowerShell?</p>
| <p>This answer was pulled from <a href="http://www.databasejournal.com/features/mssql/article.php/3683181">http://www.databasejournal.com/features/mssql/article.php/3683181</a></p>
<p>This same example can be used for any adhoc queries. Let us execute the stored procedure âsp_helpdbâ as shown below.</p>
<pre><code>$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=HOME\SQLEXPRESS;Database=master;Integrated Security=True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "sp_helpdb"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]
</code></pre>
|
C++ does begin/end/rbegin/rend execute in constant time for std::set, std::map, etc? <p>For data types such as std::set and std::map where lookup occurs in logarithmic time, is the implementation required to maintain the begin and end iterators? Does accessing begin and end imply a lookup that could occur in logarithmic time?</p>
<p>I have always assumed that begin and end always occur in constant time, however I can't find any confirmation of this in Josuttis. Now that I'm working on something where I need to be anal about performance, I want to make sure to cover my bases.</p>
<p>Thanks</p>
| <p>They happen in constant time. I'm looking at page 466 of the ISO/IEC 14882:2003 standard:</p>
<p><strong>Table 65 - Container Requiments</strong></p>
<p>a.begin(); <em>(constant complexity)</em></p>
<p>a.end(); <em>(constant complexity)</em></p>
<p><strong>Table 66 - Reversible Container Requirements</strong></p>
<p>a.rbegin(); <em>(constant complexity)</em></p>
<p>a.rend(); <em>(constant complexity)</em></p>
|
Dynamically add CalendarExtender to Textbox subclass server control? <p>I'm trying to create a server control, which inherits from TextBox, that will automatically have a <a href="http://www.asp.net/AJAX/AjaxControlToolkit/Samples/Calendar/Calendar.aspx" rel="nofollow">CalendarExtender</a> attached to it. Is it possible to do this, or does my new control need to inherit from CompositeControl instead? I've tried the former, but I'm not clear during which part of the control lifecycle I should create the new instance of the CalendarExtender, and what controls collection I should add it to. I don't seem to be able to add it to the Page or Form's controls collection, and if I add it to the (TextBox) control's collection, I get none of the pop-up calendar functionality.</p>
| <p>I accomplished this in a project a while back. To do it I created a CompositeControl that contains both the TextBox and the CalendarExtender.</p>
<p>In the <code>CreateChildControls</code> method of the CompositeControl I use code similar to this:</p>
<pre><code>TextBox textbox = new TextBox();
textbox.ID = this.ID + "Textbox";
textbox.Text = this.EditableField.TextValue;
textbox.TextChanged += new EventHandler(HandleTextboxTextChanged);
textbox.Width = new Unit(100, UnitType.Pixel);
CalendarExtender calExender = new CalendarExtender();
calExender.PopupButtonID = "Image1";
calExender.TargetControlID = textbox.ID;
this.Controls.Add(textbox);
this.Controls.Add(calExender);
</code></pre>
<p>Of course make sure that the form containing this CompositeControl has a toolkit script manager.</p>
|
Subsets and Splits