input
stringlengths
51
42.3k
output
stringlengths
18
55k
Access sharepoint list data in SQL <p>I am new to SharePoint development. I have a list, this list has a column that is called <code>Todaysdate</code>. This column needs to be updated daily to today's actual date and since it contains ~20,000 rows I am NOT going to update it manually everyday. Because it's used in a calculation row.</p> <p>My question is can I just use SQL and update the rows in the UserData table that correspond to the <code>datetime</code> column that I need?</p> <p>I can query the list of rows by something similar to</p> <pre><code>Select * from UserData where tp_ListID = 'GUID' </code></pre> <p>but the data contained in the column <code>datetime3</code> is not just the <code>Todaysdate</code> information. How do I return just the <code>Todaysdate</code> info?</p>
<p>You really should not query let alone update the SharePoint content database directly using SQL. It is totally unsupported, so if you break something you are left alone, and the database schema may change with future service packs / releases.<br/> Also as noesgard mentioned it in his comment you do not need it to use today's date in a calculated field, see <a href="http://blogs.msdn.com/cjohnson/archive/2006/03/16/552314.aspx" rel="nofollow">this blog entry</a> on how you can do that.</p>
Cleaning up a database in django before every test method <p>By default when Django runs against sqlite backend it creates a new in memory database for a test. That means for every class that derives from unittest.TestCase, I get a new database. Can this be changed so that it is cleared before every test method is run?</p> <p>Example: I am testing a manager class that provides additional abstraction on top of Django persistent objects. The code looks more-less like that</p> <pre><code>class TestForManager(unittest.TestCase): def testAddingBlah(self): manager = Manager() self.assertEquals(manager.getBlahs(), 0) manager.addBlah(...) self.assertEquals(manager.getBlahs(), 1) def testAddingBlahInDifferentWay(self): manager = Manager() self.assertEquals(manager.getBlahs(), 0) manager.addBlahInDifferentWay(...) self.assertEquals(manager.getBlahs(), 1) </code></pre> <p>Now, the first assertion of second test fails, because the state of the database is preserved between test calls and there already is an instance of <code>Blah</code> in the database.</p>
<p>As always, solution is trivial: use <code>django.test.TestCase</code> not <code>unittest.TestCase</code>. And it works in all major versions of Django!</p>
Is there a way to collapse functions and sub-routines for Classic ASP in Visual Studio 2008? <p>Is there a way to enabling collapsing of functions and sub-routines for Classic ASP in Visual Studio 2008? I'm able to manually go through and specify blocks of code as collapsable, but it would save me a lot of time if there was a way to automatically do this.</p> <p>Otherwise, is there another IDE or text editor that you can think of that supports this?</p>
<p>Notepad++ has a "Function List" plugin:</p> <p><a href="http://sourceforge.net/project/showfiles.php?group_id=189927&amp;package_id=223668" rel="nofollow">http://sourceforge.net/project/showfiles.php?group_id=189927&amp;package_id=223668</a></p> <p>While this doesn't allow you to collapse your Classic ASP functions and sub-routines, it lists them in a side panel and you can click them to jump from function to function.</p>
How do I make a field in MySql auto-incrementing in PHPMyAdmin? <p>I created a field in my table and set it as the index but I can't get it to increase on it s own when a new item is added. How do I do make it do this through PHPMyAdmin?</p>
<p>Select the A_I check box when creating/editing a column.</p>
How do I check if my workstation is locked? <p>Can anyone help with code snippet for checking if the workstation is locked? I tried with getting the document.title, so that when the workstation is locked it returns blank for document.title. This is not working. </p> <p>I am encoding wscript in vbscript which is residing in HTML.</p> <p>Any help with Javascript is also fine. </p>
<p>Normally you should be using a wmi query to look at the event log's security log. Howver, XP doesn't have a lock event ids (vista/win7/2008 does have both lock and unlock event ids). </p> <p>XP DOES have an unlock event, event though. Most people don't realize the unlock event invovles BOTH a logon/logoff events (event ids 528/538, which occur at practically the same time). The Login Type will be EventType 7, and that's how you tell someone is unlocking the workstation. Login Type 7 (whether logon or logoff) is an unlock event.</p> <p>For Vista/Win7/2008 the new workstation lock event id is 4800 wile the updated way of determining an unlock event is event id 4801. However, the source log in post Vista OSes is not the Security log, but the Microsoft-Windows-Security-Auditing log.</p> <p>If you have Win7 your in luck, and should just write a wmi query. XP, I can't see a good way of doing it, unless you want to try idle time. </p>
How to pass a flexible number of ids into a controller in Rails? <p>I'd like to display a comparison page so user can compare the properties of several objects in my database. Any number of objects can be compared. I'd also like it to be bookmarkable (so a 'get').</p> <p>How should I structure my URL / route for the controller? </p> <p>Something like /foo_compare/1_5_22 where I split the ids into 1, 5 and 22 in the controller?</p> <p>Maybe /foo_compare/1/5/22, but how would I set up the route?</p>
<p>I'd prefer </p> <pre><code>/compare?a=1&amp;b=5&amp;c=22 </code></pre> <p>The 1_5_22 is just fugly, and I think that</p> <pre><code>/compare/1/5/22 </code></pre> <p>is a very non-RESTful route.</p>
Is a string property itself threadsafe? <p>String's in C# are immutable and threadsafe. But what when you have a public getter property? Like this:</p> <pre><code>public String SampleProperty{ get; private set; } </code></pre> <p>If we have two threads and the first is calling 'get' and the second is calling 'set' at the "same" time, what will happen?</p> <p>IMHO the set must made a lock to be thread-safe like this:</p> <pre><code>private string sampleField; private object threadSafer = new object(); public String SampleProperty{ get{ return this.sampleField; } private set{ lock(threadSafer){ sampleField = value; } } } </code></pre>
<p>Most of the answers are using the word "atomic" as if atomic changes are all that are needed. They're not, usually.</p> <p>This has been mentioned in the comments, but not usually in the answers - that's the only reason for me providing this answer. (The point about locking at a coarser granularity, to allow things like appending, is entirely valid as well.)</p> <p>Usually you want a reading thread to see the <em>latest</em> value of the variable/property. That <a href="http://pobox.com/~skeet/csharp/threads/volatility.shtml">isn't guaranteed by atomicity</a>. As a quick example, here's a <em>bad</em> way to stop a thread:</p> <pre><code>class BackgroundTaskDemo { private bool stopping = false; static void Main() { BackgroundTaskDemo demo = new BackgroundTaskDemo(); new Thread(demo.DoWork).Start(); Thread.Sleep(5000); demo.stopping = true; } static void DoWork() { while (!stopping) { // Do something here } } } </code></pre> <p><code>DoWork</code> may well loop forever, despite the write to the boolean variable being atomic - there's nothing to stop the JIT from caching the value of <code>stopping</code> in <code>DoWork</code>. To fix this, you either need to lock, make the variable <code>volatile</code> or use an explicit memory barrier. This all applies to string properties as well.</p>
Printing from web applications <p>How do you generate paper-prints from a web application?</p> <p>Specifically I am thinking about more complex paper documents like diplomas, invoices and contracts. Variable number of pages with frames, tables, logos and headers/footers.</p> <p>Today I use custom forms and CSS for certain things and iTextSharp for others (I work with asp.net and MS-SQL), but I think both approaches are time-consuming and hard to make consistent across different documents.</p> <p>Is there a better way to go about it?</p>
<p>IMHO for fixed format printing PDF if the answer</p>
Transaction rollback and web services <p>Given an example of calling two web services methods from a session bean, what if an exception is thrown between the calls to two methods? In the case of not calling the web services the transaction will rollback and no harm done. However, the web service will not rollback. Of course, even with a single web service there is a problem. While this is a generic question I am interested in solutions having to do with EJB session beans.</p> <p>An easy and customized answer would be to add a special "rollback method" to the web service for each "real functionality" method. What I am asking for is some standardized way to do so.</p>
<p>A number of techniques are evolving, but the problem is still sufficiently cutting edge that the standardization process has not yet provided us with a totally portable solution.</p> <p>Option one, you can make the web services transaction aware. This of course assumes you have control over them, although writing a transaction aware proxy for non-transactional services is also an option in some cases.</p> <p>The WS-AT and WS-BA protocols are the leading standards for transactional web services. Unfortunately they specify the protocol only, not the language bindings. In other words, there is no standard API at the programming language level. For Java the nearest thing is JSR-156, but it's not ready yet.</p> <p>Then the problem becomes: how to tie the EJB (i.e. JTA/XA) transaction to the WS one. Since the models used by the WS-AT and XA protocols are closely related, this can be achieved by means of a protocol bridge. Several app servers provide something alone these lines. JBoss presented theirs at JavaOne - see <a href="http://anonsvn.jboss.org/repos/labs/labs/jbosstm/workspace/jhalliday/txbridge/BOF-4182.odp">http://anonsvn.jboss.org/repos/labs/labs/jbosstm/workspace/jhalliday/txbridge/BOF-4182.odp</a></p> <p>Note that the protocol bridging technique can also be used the other way around, to allow an EJB that uses e.g. an XA database backend, to be exposed as a transactional web service.</p> <p>However, the locking model used by two phase commit transactions is really only suitable for short lived transactions in the same domain of control. If your services run in the same company datacenter you'll probably get away with it. For wider distribution, be it geographical or administrative, you probably want to look at WS-BA, a web service transactions protocol specifically designed for such use.</p> <p>WS-BA uses a compensation based model that is harder to program. It's essentially based on the technique you mention: the effect of service methods is undone by calling a compensation method. This can be tricky to get right, but a JBoss intern did a rather nice annotation framework that allows you to define compensation methods with minimal effort and have them driven automatically. It's not standardized, but well worth checking out if you choose this approach: <a href="http://www.jboss.org/jbosstm/baframework/index.html">http://www.jboss.org/jbosstm/baframework</a></p>
How to determine installed IIS version <p>What would the preferred way of programmatically determining which the currently installed version of Microsoft Internet Information Services (IIS) is?</p> <p>I know that it can be found by looking at the MajorVersion key in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W3SVC\Parameters. </p> <p>Would this be the <em>recommended</em> way of doing it, or is there any safer or more beautiful method available to a .NET developer?</p>
<pre><code>public int GetIISVersion() { RegistryKey parameters = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Services\\W3SVC\\Parameters"); int MajorVersion = (int)parameters.GetValue("MajorVersion"); return MajorVersion; } </code></pre>
Setting start node in a umbraco website <p>I have this content structure for a multi language site.</p> <ul> <li>Content <ul> <li>Danish <ul> <li>Forside</li> <li>Om os</li> </ul></li> <li>English <ul> <li>Frontpage</li> <li>About Us</li> </ul></li> </ul></li> </ul> <p>When I start the website it automatically starts in the Danish-node, but I want it to start in "Forside", and as for the english part of the side I want it to start in the node "Frontpage".</p> <p>The nodes "Danish" and "English" are page nodes as well, but are only there as a logical folder structure.</p> <p>Is there any way I can choose which content node my website should start at?</p>
<p>You can use the built-in feature:</p> <ol> <li>Add a property called 'umbracoRedirect' to the document type associated with the 'Danish' node.</li> <li>Set the property to be of type 'Content picker' and save it</li> <li>At 'Danish' node set the property to point to node 'ForSide'.</li> </ol> <p>That should work.</p>
What would you consider good Eclipse support? <p>As part of my job, I'm employed to install and support development tools for the developers in the company. </p> <p>Eclipse is an IDE that a great deal of developers here use, but I don't actively support. With the huge range of plugins and quick release of new versions - I find it hard to keep on top of and would not be able (obviously) to support everything.</p> <p>I do have some experience in Eclipse, but as a developer - what would you consider good support from your workplace in terms of Eclipse?</p>
<ol> <li>Private, in-house plugin central. You are responsible for updating this repo and testing plugin updates first for currently developed projects - so devs do not need to worry about compatibility; they'll just update from in-house plugin repo.</li> <li>Common settings, eg. coding style formatting defined and maintained.</li> </ol>
PHP Arrays, appending depth of array item recursively to an array with the key of 'depth' <p>Per the example array at the very bottom, i want to be able to append the depth of each embedded array inside of the array. for example:</p> <pre> array ( 53 => array ( 'title' => 'Home', 'path' => '', 'type' => '118', 'pid' => 52, 'hasChildren' => 0, ), </pre> <p>Has a depth of one according to the sample array shown below so it should now look like this:</p> <pre> array ( 53 => array ( 'title' => 'Home', 'path' => '', 'type' => '118', 'pid' => 52, 'hasChildren' => 0, 'depth' => 1, ), </pre> <p>and so on...</p> <p>All of the recursive array function attempts i have made are pretty embarrassing. However I have looked at RecursiveArrayIterator which has the getDepth function. I'm confused on how to append it to the current array... any help is VERY much appreciated, thank you.</p> <pre> array ( 'title' => 'Website Navigation', 'path' => '', 'type' => '115', 'pid' => 0, 'hasChildren' => 1, 'children' => array ( 53 => array ( 'title' => 'Home', 'path' => '', 'type' => '118', 'pid' => 52, 'hasChildren' => 0, ), 54 => array ( 'title' => 'Features', 'path' => 'features', 'type' => '374', 'pid' => 52, 'hasChildren' => 1, 'children' => array ( 59 => array ( 'title' => 'artistic', 'path' => 'features/artistic', 'type' => '374', 'pid' => 54, 'hasChildren' => 1, 'children' => array ( 63 => array ( 'title' => 'galleries', 'path' => 'features/artistic/galleries', 'type' => '374', 'pid' => 59, 'hasChildren' => 1, 'children' => array ( 65 => array ( 'title' => 'graphics', 'path' => 'features/artistic/galleries/graphics', 'type' => '118', 'pid' => 63, 'hasChildren' => 0, ), 67 => array ( 'title' => 'mixed medium', 'path' => 'features/artistic/galleries/mixed-medium', 'type' => '118', 'pid' => 63, 'hasChildren' => 0, ), 64 => array ( 'title' => 'overview', 'path' => 'features/artistic/galleries', 'type' => '118', 'pid' => 63, 'hasChildren' => 0, ), 68 => array ( 'title' => 'photography', 'path' => 'features/artistic/galleries/photography', 'type' => '118', 'pid' => 63, 'hasChildren' => 0, ), 66 => array ( 'title' => 'traditional', 'path' => 'features/artistic/galleries/traditional', 'type' => '118', 'pid' => 63, 'hasChildren' => 0, ), ), ), 62 => array ( 'title' => 'overview', 'path' => 'features/artistic', 'type' => '118', 'pid' => 59, 'hasChildren' => 0, ), 69 => array ( 'title' => 'tutorials', 'path' => 'features/artistic/tutorials', 'type' => '374', 'pid' => 59, 'hasChildren' => 1, 'children' => array ( 71 => array ( 'title' => 'by category', 'path' => 'features/artistic/tutorials/by-category/', 'type' => '118', 'pid' => 69, 'hasChildren' => 0, ), 72 => array ( 'title' => 'by date', 'path' => 'features/artistic/tutorials/by-date/', 'type' => '118', 'pid' => 69, 'hasChildren' => 0, ), 70 => array ( 'title' => 'overview', 'path' => 'features/artistic/tutorials', 'type' => '118', 'pid' => 69, 'hasChildren' => 0, ), ), ), ), ), 58 => array ( 'title' => 'overview', 'path' => 'features', 'type' => '118', 'pid' => 54, 'hasChildren' => 0, ), 61 => array ( 'title' => 'projects / labs', 'path' => 'features/projects-labs/', 'type' => '374', 'pid' => 54, 'hasChildren' => 0, ), 60 => array ( 'title' => 'web development', 'path' => 'features/web-development', 'type' => '374', 'pid' => 54, 'hasChildren' => 1, 'children' => array ( 74 => array ( 'title' => 'articles', 'path' => 'features/web-development/articles/', 'type' => '374', 'pid' => 60, 'hasChildren' => 0, ), 73 => array ( 'title' => 'overview', 'path' => 'features/web-development', 'type' => '118', 'pid' => 60, 'hasChildren' => 0, ), 75 => array ( 'title' => 'tutorials', 'path' => 'features/web-development/tutorials', 'type' => '374', 'pid' => 60, 'hasChildren' => 0, ), ), ), ), ), 55 => array ( 'title' => 'Activity', 'path' => 'activity', 'type' => '374', 'pid' => 52, 'hasChildren' => 0, ), 56 => array ( 'title' => 'Blog', 'path' => 'blog', 'type' => '374', 'pid' => 52, 'hasChildren' => 0, ), 57 => array ( 'title' => 'About', 'path' => 'about', 'type' => '374', 'pid' => 52, 'hasChildren' => 1, 'children' => array ( 76 => array ( 'title' => 'the author', 'path' => 'about/the-author', 'type' => '118', 'pid' => 57, 'hasChildren' => 0, ), 77 => array ( 'title' => 'the website', 'path' => 'about/the-website', 'type' => '118', 'pid' => 57, 'hasChildren' => 0, ), ), ), ), ), ); print_r($example); ?> </pre>
<p>I assume there is another array( at the top not included in your example code. Something like this?</p> <pre><code>function array_set_depth($array, $depth = -1) { $subdepth = $depth + 1; if ($depth &lt; 0) { foreach ($array as $key =&gt; $subarray) { $temp[$key] = array_set_depth(($subarray), $subdepth); } } if ($array['hasChildren'] &amp;&amp; isset($array['children'])) { foreach ($array['children'] as $key =&gt; $subarray) { $temp[$key] = array_set_depth($subarray, $subdepth); } $array['children'] = $temp; } $array['depth'] = $depth; return $array; } </code></pre> <p>Example usage, I set your array to the value $a:</p> <pre><code>$b = array_set_depth($a); print_r($b); </code></pre> <p>Edit: </p> <p>To set depth before the children for nice printing you can do this:</p> <pre><code>function array_set_depth($array, $depth = -1) { $subdepth = $depth + 1; if ($depth &lt; 0) { foreach ($array as $key =&gt; $subarray) { $temp[$key] = array_set_depth(($subarray), $subdepth); } return $temp; } $array['depth'] = $depth; if ($array['hasChildren'] &amp;&amp; isset($array['children'])) { foreach ($array['children'] as $key =&gt; $subarray) { $temp[$key] = array_set_depth($subarray, $subdepth); } unset($array['children']); $array['children'] = $temp; } return $array; } </code></pre>
Where should I put Velocity template files for a command line utility built with Maven? <p>I have a small command line utility project that I'm using Maven to manage. The utility is a very simple app to populate a Velocity template and dump the results to a new file. My problem is where to put my Velocity templates. When I put them in <code>src/test/resources/foo/bar/baz</code>, <code>mvn test</code> fails because it can't find the referenced template, even though it is clearly there in <code>target/classes/foo/bar/baz</code>, which is where the <code>.class</code> file for the test and the class under test are located. If I put the template in the top-level directory of the project, the test passes, but then I'm not following the Maven project structure, and I suspect that the actual packaged .jar file wouldn't function. What am I missing?</p> <p>UPDATE:</p> <p><strong>Method under test</strong>:</p> <pre><code>public final void mergeTemplate(final String templateFileName, final Writer writer) throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, IOException, Exception { Velocity.init(); Velocity.mergeTemplate(templateFileName, Charset.defaultCharset().name(), context(), writer); } </code></pre> <p><strong>Test method</strong>:</p> <pre><code>@Test public void testMergeTemplate() throws Exception { final FooGenerator generator = new FooGenerator(); final StringWriter writer = new StringWriter(); generator.mergeTemplate("foo.yaml", writer); Assert.assertEquals("Something went horribly, horribly wrong.", EXPECTED_RESULT, writer.toString().trim()); } </code></pre> <p>The only place I can place <code>foo.yaml</code> and have the tests pass is in the root directory of the project, i.e., as a peer of <code>src</code> and <code>target</code>.</p>
<p>You can programmatically configure TEMPLATE_ROOT as follows:</p> <pre><code>Properties props = new Properties(); props.put("file.resource.loader.path", templateRootDir); VelocityEngine engine = new VelocityEngine(); engine.init(props); engine.evaluate(...); </code></pre>
Read Excel files from C# in 64 bit version server <p>reading excel files from C# working well in 32 bit version server. It is <strong>not</strong> working in <strong>64 bit version</strong> (Windows 2003 server), because excel data connection dll not supported in <strong>64 bit version</strong>. Is any other option available ?</p>
<p>In your project properties set the target platform from 'Any' to 'x86'.</p> <p><strong>Details:</strong></p> <p>In Windows x64 a process may be started as 32bit or 64bit process. A 64bit process can only load 64bit dlls and a 32bit process only 32bit dlls.</p> <p>If your platform target (e.g. specified in the project properties) of your .Net application is set to "Any CPU", the intermediate code will be compiled to 32bit or 64bit code depending on the target platform, i.e. on a x64 system 64bit code will be generated.</p> <p>Therefore the code can no longer load a 32bit dll.</p> <p>If your code loads unmanaged assemblies you should always specify the target platform explicitly</p>
How to create a connection string outside web.config <p>Just thinking about this, is it possible to create a connection string outside the ASP.NET's web.config?</p>
<p>Possibly you're looking for <a href="http://stevenharman.net/blog/archive/2007/06/07/tip-put-connection-strings-in-their-own-configuration-file.aspx" rel="nofollow">configSource</a>?</p>
How would you model a "default child" flag with an ORM? <p><br /> I'm using an ORM (SQLAlchemy, but my question is quite implementation-agnostic) to model a many-to-many relationship between a parent class and its children.. I was wondering, what would be a simple way to express the concept "one of the children is the default/main one"? </p> <p>For example, I'd need to persist the following:<br /> This Person instance has Address X and Y, the main one is Y.</p> <p>I saw this implemented using a "middle" class like "PersonAddressRelation" that would contain "Person", "Address" and the "main" flag, but I think it looks a bit cumbersome.. Is there a better way?</p>
<p>The simplest way would be to have a join table, PersonAddressRelation, and also a DefaultAddress column on the Person table that keys to the Address table.</p>
SQL Sub-Query vs Join Confusion <p>I have a database which is in Access (you can get it <a href="http://cid-84dd6ce2da273835.skydrive.live.com/self.aspx/.Public/Unisa.accdb" rel="nofollow">link text</a>). If I run</p> <pre><code>SELECT DISTINCT Spl.Spl_No, Spl.Spl_Name FROM Spl INNER JOIN Del ON Spl.Spl_No = Del.Spl_No WHERE Del.Item_Name &lt;&gt; 'Compass' </code></pre> <p>It provides the names of the suppliers that have never delivered a compass. However you can supposedly do this with a sub-query. So far myself and a few others have not been able to get it right.</p> <p>I did come close with the following, until we added more suppliers then it stopped working</p> <pre><code>SELECT SPL.SPL_Name FROM SPL LEFT JOIN DEL ON Del.SPL_No = SPL.SPL_No WHERE (DEL.Item_Name&lt;&gt;"Compass") OR (DEL.Item_Name IS NULL) GROUP BY SPL.SPL_Name HAVING COUNT(DEL.SPL_No) = 0 </code></pre> <p>So the question: Is this possible to do with a sub-query.</p>
<p>I think I would go for:</p> <pre><code>SELECT SELECT Spl_No, Spl_Name FROM Spl WHERE Spl_No NOT IN (SELECT Spl_No FROM Del WHERE Item_Name = 'Compass') </code></pre>
How are CSS frameworks used? <p>For some reason, it never dawned on me that there could be frameworks for CSS. I have been working on my own personal site, and I just really hate 'designing' with CSS (I think more then a few programmers might agree with me). Anyways, I understand the benefits of a framework for a language such as Java, PHP, [insert language]. I downloaded a couple different CSS frameworks and couldnt really figure out how to use them. I guess I might be expecting an API or something (which obviously doesnt make sense given the lack of logic in CSS)... </p> <p>Has anyone here used (and would reccomend) a CSS framework? Is it overkill for a relatively simple layout?</p> <p>Please do not post links to other sites, I know how to use Google. I would rather hear the opinions and insights of the community. Thanks.</p>
<p>I used <a href="http://www.yaml.de/en/" rel="nofollow">YAML (Yet Another Multicolumn Layout)</a> in a few projects, because I didn't like to "fight" with the Internet Explorer 6 HACKS. There is a good explanation of how to use it and you can customize it to your needs (as long as you're going to use a multicolumn (2 or 3) layout).</p>
ActiveMQ: Issue with queue lookup <p>I've set up a queue by configuring it in activemq.xml (ActiveMQ version 5.2.0) as described in the <a href="http://activemq.apache.org/configure-startup-destinations.html">documentation</a>.</p> <pre><code>&lt;destinations&gt; &lt;queue physicalName="FOO.BAR" /&gt; &lt;queue physicalName="DUMMY" /&gt; &lt;/destinations&gt; </code></pre> <p>I'm trying to access it from java (on the same host) with the following code:</p> <pre><code>Hashtable properties = new Hashtable(); properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); properties.put(Context.PROVIDER_URL, "tcp://localhost:61616"); context = new InitialContext(properties); factory = (ConnectionFactory) context.lookup("ConnectionFactory"); connection = factory.createConnection(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); queueName = "DUMMY"; // which can be either FOO.BAR or DUMMY dest = (Destination) context.lookup(queueName); </code></pre> <p>I'm receveing the following error, although the queue is visible in jconsole (Tree / org.apache.activemq / Queue):</p> <pre><code>javax.naming.NameNotFoundException: DUMMY </code></pre> <p>Please tell me what I'm doing wrong. Many, many thanks!</p>
<p>Firstly you don't have to <a href="http://activemq.apache.org/how-do-i-create-new-destinations.html">explicitly create any queues in the broker</a> though it does no harm.</p> <p>Also the destinations available in the broker are not auto-magically mapped into a JNDI context for you using some kind of JNDI name.</p> <p>You can do this <a href="http://activemq.apache.org/jndi-support.html">explicitly as described here</a>. If you want auto-magical population of JNDI then use the JNDI naming convention of <em>dynamicQueues/DUMMY</em> as the JNDI name you lookup (as described in the <a href="http://activemq.apache.org/jndi-support.html">Dynamically creating destinations</a>)</p>
Which event in the app's startup sequence is appropriate to trigger loading a config file in AIR/Flex? <p>I am working on a small AIR desktop application and I have some configuration infos that I want to store in a little file that's loaded at some point when the application starts and will be used to set public properties on the root application object. This should work just as if I had public variables declared in an &lt;mx:Script&gt; block at the beginning of my main MXML file.</p> <p>I seem to have the choice of three events that could be used to initiate loading the configuration file:</p> <ul> <li>invoke</li> <li>initialize</li> <li>creationComplete</li> </ul> <p>Did I overlook some more? Which one is appropriate and why? Does it matter at all?</p> <p>Example issues that come to my mind are:</p> <ul> <li>are all components already accessible or will I get NULL references?</li> <li>will some of my settings be overwritten in a phase that's coming after the event?</li> </ul> <p>There's probably more.</p>
<p>If your handler needs to access UI components directly, you should wait for <code>creationComplete</code>; otherwise you'll get NULL references.</p> <p>If you simply want to set properties on the root <code>Application</code> object, <code>initialize</code> seems the best place to do this. If you wait until <code>creationComplete</code>, and if the properties that you set are bound to your controls, then you might get a run-time resize or flicker as those components are updated.</p>
Are there good Java libraries that facilitate building command-line applications? <p>I need to write a simple command-line application in Java. It would be nice to use a library that takes care of parsing commands and takes care of things like flags and optional/mandatory parameters...</p> <p><strong>UPDATE</strong></p> <p>Something that has built-in TAB completion would be particularly great.</p>
<p>I've used the <a href="http://commons.apache.org/cli/">Apache Commons CLI library</a> for command-line argument parsing. It's fairly easy to use and has <a href="http://commons.apache.org/cli/introduction.html">reasonably good documentation</a>.</p> <p>Which library you choose probably comes down to which style of options you prefer ("--gnu-style" or "-javac-style").</p>
SSIS, dtsx and deployment packages <p>I'm just trying to understand SSIS packages a bit better and how they are deployed. Correct me I'm wrong but for any deployment, I believe there needs to be at least two files a .SSISDeploymentManifest and a .dtsx. The .SSISDeploymentManifest acts as the equivalent windows installer package which points to the .dtsx. The dtsx is the actual package of "stuff" that is referenced as an external file some how when you run the installer. When you install it, the package gets added to a list of ssis packages for that instance.</p> <p>My further questions:</p> <ul> <li>If i wanted to keep previous version of the same package, can I just copy the bin directories with the two above files and keep separately should I need to roll back to a previous package?</li> <li>Where are these packages installed to? How does SSIS know where the packagess are?</li> </ul>
<blockquote> <p>Correct me I'm wrong but for any deployment, I believe there needs to be at least two files a .SSISDeploymentManifest and a .dtsx. The .SSISDeploymentManifest acts as the equivalent windows installer package which points to the .dtsx. The dtsx is the actual package of "stuff" that is referenced as an external file some how when you run the installer. When you install it, the package gets added to a list of ssis packages for that instance.</p> </blockquote> <p>Your assumptions are mostly correct. You don't need the deployment manifest, but it can be handy. Also, you don't need to deploy to the SQL Server instance. You have the option to deploy to the file system as well. I'll explain both below.</p> <p>Regarding your 1st question:</p> <h2>Version Control:</h2> <p>Make sure you're developing and checking in your dtsx packages via visual studio. Label your releases in sourcesafe or whatever version control you're using. If you are checking in and labeling, then you should be able to easily roll back to a previous version. As you mention, you also can just save a copy of your old bin directory but naturally put them in dated subfolders or something. However, this does not take the place of proper version control.</p> <p>Regarding your 2nd question: </p> <h2>Deployment:</h2> <p>As the other poster states, you first have a decision to make:</p> <p>a) Deploy packages to the file system b) Deploy packages to MSDB</p> <p>There are benefits to each, and everyone has their preference. I have used both, but I prefer the filesystem because it's more transparent, however there is more to maintain.</p> <p>See this post for much more on this: <a href="http://blogs.conchango.com/jamiethomson/archive/2006/01/05/SSIS_3A00_-Common-folder-structure.aspx" rel="nofollow">http://blogs.conchango.com/jamiethomson/archive/2006/01/05/SSIS_3A00_-Common-folder-structure.aspx</a></p> <p>The code is in the dtsx package. Generally,in order to make your packages portable you also abstract your connection strings and other configurable information into a config file (.dtsconfig) or environment variable (no file needed). See BOL to learn more about configuration. </p> <p>The manifest file contains metadata about which dtsx and config files to install. If you open one, you'll see it's a simple readable xml file. </p> <p>The manifest file makes it easy to hand over to a DBA to deploy (ask them to double-click the manifest file and follow directions, but they'll need instructions. </p> <p>To me, the manifest file is more useful for deploying to SQL Server than to the file system. Really, all it does is make a copy of the dtsx and config files and puts them where you tell it. You could just as easily instruct the DBA to copy your dtsx files to a common folder on the server, and the config files to another folder on the same server. </p> <p>Then when you schedule your jobs using SQL Agent, you specify that you're going to run an SSIS package that is stored on the file system and browse to where it's located. If you're using configurations, then there's a tab to specify where the config file is located. </p> <p>There is so much to know about configuring/deployment/versioning of SSIS packages. But hopefully this will get you started on the right path.</p>
Show joined value on bound field without custom type? <p>I have a GridView bound to an <code>ICollection&lt;UserAnswer&gt;</code> that needs to show two columns:</p> <pre><code>&lt;asp:GridView ID="UserAnswersGridView" runat="server"&gt; &lt;Columns&gt; &lt;asp:BoundField DataField="Question.Name" HeaderText="Question Name" SortExpression="QuestionID" /&gt; &lt;asp:BoundField DataField="Score" HeaderText="Score" SortExpression="Score" /&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; </code></pre> <p>But I get the error:</p> <blockquote> <p>A field or property with the name 'Question.Name' was not found on the selected data source. </p> </blockquote> <p>Each <code>UserAnswer</code> has a <code>QuestionId</code> value which is what I would use to query the question name. In code, I would just call <code>userAssessment.Question.Name</code>, but how would I do this with a bound column in a GridView without creating a new type?</p> <p>For reference this is the method that returns the data:</p> <pre><code>public static ICollection&lt;UserAnswer&gt; GetUserAnswers(Int32 userAssessmentId) { DataContext database = new DataContext(GetConnectionString()); return database.UserAnswers.Where(u =&gt; u.UserAssessmentId == userAssessmentId).ToList(); } </code></pre> <p>Sorry if this explanation isn't very clear!</p>
<p>I believe that <code>GridView</code> only supports properties of the immediate type. Is repeater or anything similar an option? That gives you more flexibility.</p> <p>Alternatively, you can add shim properties to the type via a partial class:</p> <pre><code>namespace YourLinqNamespace { partial class UserAnswer { public string QuestionName {get {return Question.Name;}} } } </code></pre> <p>You can't use this in filters (<code>Where</code> etc), but you should be able to use it on returned objects without issue. Note that you might want to use <code>LoadWith</code> to save the round-trips:</p> <pre><code>DataLoadOptions options = new DataLoadOptions(); options.LoadWith&lt;UserAnswer&gt;(x=&gt;x.Question); database.LoadOptions = options; </code></pre>
Find Java classes implementing an interface <p>Some time ago, I came across a piece of code, that used some piece of standard Java functionality to locate the classes that implemented a given interface. I know the functions were hidden in some non-logical place, but they could be used for other classes as the package name implied. Back then I did not need it, so I forgot about it, but now I do, and I can't seem to find the functions again. Where can these functions be found?</p> <p>Edit: I'm not looking for any IDE functions or anything, but rather something that can be executed within the Java application.</p>
<p>Awhile ago, I put together a package for doing what you want, and more. (I needed it for a utility I was writing). It uses the <a href="http://asm.objectweb.org/">ASM</a> library. You can use reflection, but ASM turned out to perform better.</p> <p>I put my package in an open source library I have on my web site. The library is here: <a href="http://software.clapper.org/javautil/">http://software.clapper.org/javautil/</a>. You want to start with the with <a href="http://software.clapper.org/javautil/api/org/clapper/util/classutil/ClassFinder.html">ClassFinder</a> class.</p> <p>The utility I wrote it for is an RSS reader that I still use every day, so the code does tend to get exercised. I use ClassFinder to support a plug-in API in the RSS reader; on startup, it looks in a couple directory trees for jars and class files containing classes that implement a certain interface. It's a lot faster than you might expect.</p> <p>The library is BSD-licensed, so you can safely bundle it with your code. Source is available.</p> <p>If that's useful to you, help yourself.</p> <p>Update: If you're using Scala, you might find <a href="http://software.clapper.org/classutil/">this library</a> to be more Scala-friendly.</p>
How to find WITH RECOMPILE metadata in SQL Server (2005)? <p>How do you find which SPs are declared WITH RECOMPILE, either in INFORMATION_SCHEMA, sys.objects or some other metadata?</p> <p>(I'm adding some code to my system health monitoring and want to warn on ones which are declared that way where it is not justifiable.)</p> <p><strong>Note: I'm not looking for general text search for 'WITH RECOMPILE' - I can already do that, but it will give false positive for any commented or literal versions of the text.</strong></p>
<p>For a quick and dirty way I would use:</p> <pre><code>SELECT o.name FROM syscomments c INNER JOIN sys.objects o ON o.object_id = c.id WHERE c.text LIKE '%WITH RECOMPILE%' </code></pre> <p>That's probably not a good idea for use in an actual application though. If I have a few minutes I'll try to dig up a cleaner way. The above will also catch procs that have that string commented out, it uses the MS SQL Server specific table syscomments, etc.</p>
Can't add domain users to Reporting Services 2008 <p>I have <code>SSRS 2008</code> setup on the database server.<br> The server is part of the domain.<br> Reporting Services is running under <code>NetworkService</code>.<br> When I try to add a domain user using the web interface (<code>Site Settings</code> --> <code>Security</code> --> <code>New Role Assignment</code>), the page posts back but the user is not in the list.<br> The server's log file contains the following Unhandled Exception:</p> <blockquote> <p>ui!ReportManager_0-1!954!01/12/2009-10:14:52:: Unhandled exception: System.Security.Principal.IdentityNotMappedException: Some or all identity references could not be translated. at System.Security.Principal.SecurityIdentifier.Translate(IdentityReferenceCollection sourceSids, Type targetType, Boolean forceSuccess) at System.Security.Principal.SecurityIdentifier.Translate(Type targetType) at System.Security.Principal.WindowsIdentity.GetName() at System.Security.Principal.WindowsIdentity.get_Name() at ReportingServicesHttpRuntime.RsWorkerRequest.GetServerVariable(String name) at System.Web.Security.WindowsAuthenticationModule.OnEnter(Object source, EventArgs eventArgs) at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously)</p> </blockquote> <p>Any one have an idea on how to fix this?</p>
<p>got to home then on properties and then add the user with roles whatever you want to gives.</p>
Does Java have native support for events, similar to that of C#? <p>I'm a bit confused from what I've heard Java doesn't do events.</p> <p>But I know that it does GUI events.</p> <p>Am I missing something? Does java have an event handling mechanism?</p> <p>I'm aware that I can implement a publisher subscriber pattern, but I'm looking for native support within Java.</p> <p>I seem to remember something about Java Adding events in either Java 5 or 6 but I can't remember where I heard this and I may be making it up.</p> <p>Basically I'm wrapping a device in a java class the device throws events, and I'm looking for the most logical way of exposing this. I come mostly from a .Net Background and I'm looking for something like the events in .Net (C#)</p> <p>Any help would be appreciated.</p>
<p>As you already stated, you can do the exact same thing with the publisher-subscriber/Observer pattern. It just requires a bit more legwork.</p> <p>And no, Java does not have native support for events, like C# does with delegates.</p>
javascript - accessing private member variables from prototype-defined functions <p>Is there any way to make "private" variables (those defined in the constructor), available to prototype-defined methods?</p> <pre><code>TestClass = function(){ var privateField = "hello"; this.nonProtoHello = function(){alert(privateField)}; }; TestClass.prototype.prototypeHello = function(){alert(privateField)}; </code></pre> <p>This works:</p> <pre><code>t.nonProtoHello() </code></pre> <p>but this doesn't:</p> <pre><code>t.prototypeHello() </code></pre> <p>I'm used to defining my methods inside the constructor, but am moving away from that for a couple reasons.</p> <hr> <p>Thanks sktrdie,</p> <p>That works, it would be nice not to have to create the <code>this.accessPrivateField</code>. If my "hello" function is defined inside the constructor, <code>privateField</code> is in the scope chain of the function, so I can treat <code>privateField</code> as I would a private field in java. It's a little more cumbersome to set up accessors (<code>this.accessPrivateField</code>), and then, <code>privateField</code> isn't really private any more.</p> <p>I know javascript isn't java, but I like java!</p>
<p>No, there's no way to do it. That would essentially be scoping in reverse. </p> <p>Methods defined inside the constructor have access to private variables because all functions have access to the scope in which they were defined. </p> <p>Methods defined on a prototype are not defined within the scope of the constructor, and will not have access to the constructor's local variables.</p> <p>You can still have private variables, but if you want methods defined on the prototype to have access to them, you should define getters and setters on the <code>this</code> object, which the prototype methods (along with everything else) <em>will</em> have access to. For example:</p> <pre><code>function Person(name, secret) { // public this.name = name; // private var secret = secret; // public methods have access to private members this.setSecret = function(s) { secret = s; } this.getSecret = function() { return secret; } } // Must use getters/setters Person.prototype.spillSecret = function() { alert(this.getSecret()); }; </code></pre>
Python: Is there a way to determine the encoding of text file? <p>I know there is something buried in <a href="http://stackoverflow.com/questions/90838/how-can-i-detect-the-encoding-codepage-of-a-text-file">here</a>. But I was just wondering if there is an actual way built into Python to determine text file encoding?</p> <p>Thanks for your help :)</p> <p>Edit: As a side question, it can be ignored if you want but why is the type of encoding not put into the file so it could be detected easier?</p>
<p>Correctly detecting the encoding all times is <strong>impossible</strong>.</p> <p>(From chardet FAQ:)</p> <blockquote> <p>However, some encodings are optimized for specific languages, and languages are not random. Some character sequences pop up all the time, while other sequences make no sense. A person fluent in English who opens a newspaper and finds “txzqJv 2!dasd0a QqdKjvz” will instantly recognize that that isn't English (even though it is composed entirely of English letters). By studying lots of “typical” text, a computer algorithm can simulate this kind of fluency and make an educated guess about a text's language.</p> </blockquote> <p>There is the <a href="http://pypi.python.org/pypi/chardet">chardet</a> library that uses that study to try to detect encoding. chardet is a port of the auto-detection code in Mozilla. </p> <p>You can also use <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Beautiful%20Soup%20Gives%20You%20Unicode,%20Dammit">UnicodeDammit</a>. It will try the following methods:</p> <ul> <li>An encoding discovered in the document itself: for instance, in an XML declaration or (for HTML documents) an http-equiv META tag. If Beautiful Soup finds this kind of encoding within the document, it parses the document again from the beginning and gives the new encoding a try. The only exception is if you explicitly specified an encoding, and that encoding actually worked: then it will ignore any encoding it finds in the document.</li> <li>An encoding sniffed by looking at the first few bytes of the file. If an encoding is detected at this stage, it will be one of the UTF-* encodings, EBCDIC, or ASCII.</li> <li>An encoding sniffed by the <a href="http://pypi.python.org/pypi/chardet">chardet</a> library, if you have it installed.</li> <li>UTF-8</li> <li>Windows-1252 </li> </ul>
Link to download Cassini source code? <p>Does any one know from where can I download source code for Cassini. I tried the link <a href="http://www.asp.net/Projects/Cassini/Download" rel="nofollow">http://www.asp.net/Projects/Cassini/Download</a> but this page does not exist now.</p>
<p>You can download it <a href="http://blogs.msdn.com/dmitryr/archive/2008/10/03/cassini-for-framework-3-5.aspx">here</a> there are also older versions on the website for the 2.0 framework for instance.</p>
Are constant C expressions evaluated at compile time or at runtime? <p>If I write a <em>#define</em> that performs an operation using other preprocessor constants, is the final value computed each time the macro appears at runtime? Does this depend on optimizations in the compiler, or is it covered under a standard?</p> <p>Example:</p> <pre><code>#define EXTERNAL_CLOCK_FREQUENCY 32768 #define TIMER_1_S EXTERNAL_CLOCK_FREQUENCY #define TIMER_100_MS TIMERB_1_S / 10 </code></pre> <p>Will the operation <em>32768 / 10</em> occur at runtime every time I use the TIMER_100_MS macro?</p> <p>I would like to avoid the following:</p> <pre><code>#define EXTERNAL_CLOCK_FREQUENCY 32768 #define TIMER_1_S EXTERNAL_CLOCK_FREQUENCY #define TIMER_100_MS 3276 </code></pre> <hr> <h3>Summary</h3> <p>A compiler is required to be able to evaluate constant integral expressions because they are necessary for calculating things like array sizes at compile time. However, the standard only says they "can" -- not "must" -- do so. Therefore, only a brain-dead compiler would not evaluate a constant integral expressions at compile time, but a simple check of the assembly output for an unconventional compiler would verify each case.</p>
<p>Macros are simply textual substitution, so in your example writing <code>TIMER_100_MS</code> in a program is a fancy way of writing <code>32768 / 10</code>.</p> <p>Therefore, the question is when the compiler would evaluate <code>32768 / 10</code>, which is a constant integral expression. I don't think the standard requires any particular behavior here (since run-time and compile-time evaluation is indistinguishable in effect), but any halfway decent compiler will evaluate it at compile time.</p>
How to add external data to an XML? <p>I've got an XML Schema and an XML instance that is valid to that schema.</p> <p>This XML instance contains some data.</p> <p>I'd like to extend the XML instance with further data(my own meta-data per XML element in the XML instance) while keeping it valid to the provided schema.</p> <p>The real use-case is that I've my own control that gets its data via XML and I'd like to generate a new XML that somehow keeps additional meta-data that is related to the control's serialization.</p> <p>Couple of my solutions were to keep another document with a list of "XPath,Mode,Color" that I load in the second pass after loading the XML.</p> <p>Another solution was to add id's to the XML nodes and this way referencing the nodes from another document (instead of using XPath).</p> <p>And another idea was to somehow add attributes (that are in my namespace per element) to the data XML instance but problem is that I'll probably have trouble validating the XML with the new attributes later when trying to load it back again. (because the attributes I add to the XML are not defined in his schema)</p> <p>Do you have a better solution for this problem? Which of the solutions you would vote on? (Please explain.)</p> <p>Thanks!</p>
<p>It's not clear from your question if the additional meta-data is generated once, or need to be stored and used in subseqeunt loads.</p> <p>You may consider using XSLT to generte the new XML with the meta-data. If the new data is failry straight forward and deduced from the original XML, you can use XSLT to easily generate meta-data per node. If it's predictable and consistent, you can repeat the process whenever you load the data and get the same new XML. If it's not predictable, for example, if you need to create the XSLT on the fly, you may still be able to store the XSL once its generated, and then use that over time to re-generate the same new XML from original XML.</p> <p>Per your suggested solutions:</p> <ol> <li>Referncing by XPATH: good if the original XML doesn't change and you can built definitive XPATHs.</li> <li>Referencing by node id: good, but you'll need to add ids to the original XML if you don't have already, and you will need to update the ids if the original changes (so you may need an id counter to assign ID, or otherwise use generated GUID as ids).</li> <li>If you want to add the meta-data to the original XML, you can either update the schema or create a new one for 'updated docs' (and change the schema reference in the XML document).</li> </ol> <p>Regards, Inbar</p>
Linux C++ Debugger <p>I'm looking for the perfect Linux C++ debugger. I don't expect success, but the search should be informative.</p> <p>I am a quite capable gdb user but STL and Boost easily crush my debugging skills. It not that I can't get into the internals of a data structure, it's that it takes so long I usually find another way( "when in doubt, print it out" ).</p> <p>The macro language for gdb is weird and not very adaptive. Just look at the code for the stanford gdb utils to print out stl structures. </p> <p>In short I'm unhappy with what I've got.</p> <p>I recently stumbled upon <a href="http://zero-bugs.com">Zero Bugs</a>. It looks like a silver bullet. What do the current Zero Bugs users think of it?</p> <p>Has anyone found other good solutions to the Linux C++ Debugger problem?</p>
<p>A development branch of gdb (part of gdb's <a href="http://sourceware.org/gdb/wiki/ProjectArcher" rel="nofollow">Project Archer</a>) adds Python support to gdb (to replace gdb's macros). There's a series of blog postings <a href="http://tromey.com/blog/?p=494" rel="nofollow">starting here</a> that extensively covers getting started with Python-enabled gdb and offers several tutorials on using Python for defining new gdb commands and pretty printing of C++ data structures.</p>
How to SendKeys F12 from current .NET form/application <p>I am pretty sure the following button-activated form code should raise a Control-F12 in my C# application:</p> <p>SendKeys("^{F12}");</p> <p>But it does not appear to go on up to the windows shell and activate another program that is listening for it. My keyboard does work. It seems like the sendkeys is getting intercepted somewhere and not sent on in a way that actually simulates the key stroke. Any help?</p>
<p>SendKeys is not capable of sending keys outside of the active application.</p> <p>To really and truly simulate a keystroke systemwide, you need to P/Invoke either <code>keybd_event</code> or <code>SendInput</code> out of <code>user32.dll</code>. (According to MSDN <code>SendInput</code> is the "correct" way but <code>keybd_event</code> works and is simpler to P/Invoke.)</p> <p>Example (I <em>think</em> these key codes are right... the first in each pair is the <code>VK_</code> code, and the second is the make or break keyboard scan code... the "2" is <code>KEYEVENTF_KEYUP</code>)</p> <pre><code>[DllImport("user32.dll")] private static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo); ... keybd_event(0xa2, 0x1d, 0, 0); // Press Left CTRL keybd_event(0x7b, 0x58, 0, 0); // Press F12 keybd_event(0x7b, 0xd8, 2, 0); // Release F12 keybd_event(0xa2, 0x9d, 2, 0); // Release Left CTRL </code></pre> <p>The alternative is to activate the application you're sending to before using SendKeys. To do this, you'd need to again use P/Invoke to find the application's window and focus it.</p>
Uri.AbsolutePath messes up path with spaces <p>In a WinApp I am simply trying to get the absolute path from a Uri object:</p> <pre><code>Uri myUri = new Uri(myPath); //myPath is a string //somewhere else in the code string path = myUri.AbsolutePath; </code></pre> <p>This works fine if no spaces in my original path. If spaces are in there the string gets mangled; for example 'Documents and settings' becomes 'Documents%20and%20Setting' etc.</p> <p>Any help would be appreciated!</p> <p><strong>EDIT:</strong> LocalPath instead of AbsolutePath did the trick!</p>
<p>This is the way it's supposed to be. That's called URL encoding. It applies because spaces are not allowed in URLs.</p> <p>If you want the path back with spaces included, you must call something like:</p> <pre><code>string path = Server.URLDecode(myUri.AbsolutePath); </code></pre> <p>You shouldn't be required to import anything to use this in a web application. If you get an error, try importing System.Web.HttpServerUtility. Or, you can call it like so:</p> <pre><code>string path = HttpContext.Current.Server.URLDecode(myUri.AbsolutePath); </code></pre>
What's the best way to get the DropDown event of a ComboBox in a DataGridView <p>Say I have a DataGridView in which I dynamically build up a ComboBox column and add values to it. What's the best approach to trapping when the user clicks on the drop down button to show the drop down list. If I simply use CellClick on the DataGridView, I get that event even if the user doesn't actually click on the drop down button.</p> <p>So far what I've done is basically inherit from DataGridViewComboBoxCell and overrode the DropDownWidthProperty. In the getter I fire off a DropDown event. This works, but feels very "hacky". Any other suggestions?</p> <pre><code> using System; using System.Windows.Forms; public class DataGridViewEventComboBoxCell : DataGridViewComboBoxCell { private bool dropDownShown = false; public event EventHandler BeforeDropDownShown; private void OnBeforeDropDownShown() { if (this.BeforeDropDownShown != null) { this.BeforeDropDownShown(this, new EventArgs()); } } public override int DropDownWidth { get { if (!dropDownShown) //this boolean is here because I only need to trap it the very first time { this.OnBeforeDropDownShown(); dropDownShown = true; } return base.DropDownWidth; } set { base.DropDownWidth = value; } } } </code></pre>
<p>try EditingControlShowing</p>
Request.Form sometimes returns the value of a checkbox, other times doesn't <p>Anyone know what's wrong with this? I have some Classic ASP code that checks for the value of a checkbox, like so:</p> <pre><code>&lt;!-- HTML page: page1.asp ---&gt; &lt;input id="useBilling" name="useBilling" value="Y" type="checkbox" /&gt; </code></pre> <p>And in my code page (let's call it page2.asp):</p> <pre><code>' code useBilling = Request.Form("useBilling") ' useBilling should be "Y" here If useBilling = "Y" Then ' using billing info Else ' not using billing info End If </code></pre> <p>The problem is that sometimes, even when I check the checkbox, it's passing an empty string to Request.Form and the wrong code is being executed. I've placed a few Response.Write calls to trace it (this is VBScript, remember) and sometimes it says the value is "Y" but later when I check the value in the conditional, it's empty.</p> <p>Been wracking my brain trying to figure out why the hell this isn't working, because everything seems to be right, just Request.Form sometimes picks up the value and sometimes doesn't, even when it's checked. Hell, sometimes I'll test it by commenting out the execution code and it will say the value is "Y" then when I uncomment the executing code, it's mysteriously empty again.</p> <p><strong>EDIT:</strong> Weirdly enough, if I include a Response.End tag in the conditional, it will operate as I expect, but when I remove the Response.End it no longer finds the checkbox's value (returns empty) even though a minute ago (with Response.End uncommented) it output a test message that says "Okay, the checkbox was checked". With Response.End commented out, it says "The checkbox wasn't checked".</p> <p>I even try outputting the value of the checkbox (which should be "Y" if it's checked, and nothing if it's not). And, sure enough if the conditional includes Response.End it will output "Y" and if I remove Response.End, it's empty. </p>
<blockquote> <p>Been wracking my brain trying to figure out why the hell this isn't working, because everything seems to be right, just Request.Form sometimes picks up the value and sometimes doesn't, even when it's checked.</p> </blockquote> <p>Not a direct answer, but just to be totally clear: Request.Form("useBilling") will <em>always</em> return an empty value if the checkbox isn't checked. From your "even when I check the checkbox" wording I wasn't quite sure if you were expecting a value there when it wasn't checked. From your code, I think you get it.</p> <p>As for the issue, I've never seen that happen before despite using ASP for 10+ years (please kill me.) That doesn't mean you're hallucinating, just that I haven't seen it. Interesting!</p> <p>I wonder if perhaps your HTML (perhaps the form tag in particular) may be malformed. Do you have overlapping tags or a missing closing form tag or anything?</p> <p>I'd also be extremely curious to see the output of Request.Form when things are misbehaving, ie:</p> <pre><code>If useBilling = "Y" Then Response.Write "Cool, it works!" Else Response.Write "Something's weird. " &amp; Request.Form End If </code></pre>
JSF Multiple Partial Validations Scenario <p>In JSF, is it possible to solve the following validation / updating scenario using the validation framework of JSF (aka validators, immediate, required, etc.)?</p> <pre><code>+-- Form ----------------------------------------------------+ | | | Field A: |____________|v| | | Field B: |____________|v| | | Field C: |____________|v| Button: [Update C using A and B] | | Field D: |____________|v| Button: [Update D using B and C] | | | | More Fields: ... | | | | Button : [Submit All] | +------------------------------------------------------------+ </code></pre> <p>Where all fields are drop downs and where pressing the [Update C] button would only cause A, B and C to validate but not the rest, pressing the [Update D] button would only cause fields B, C and D to validate and pressing [Submit All] button would cause all fields to validate.</p>
<p>Technically, yes, it is possible to do this with validators/immediate. However, it wouldn't be particularly simple.</p> <p>If you add validators, the logic in <em>[Update C using A and B]</em> will only run if all validators pass or if its immediate attribute has been set to true. If its immediate attribute has been set to true, the button logic cannot read the submitted component values using <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/component/ValueHolder.html#getValue()" rel="nofollow">getValue</a> or any object the component is bound to; it must use <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/component/EditableValueHolder.html#getSubmittedValue()" rel="nofollow">getSubmittedValue</a> (a bad idea).</p> <p>A better approach would be to do your validation logic in a managed bean to which all the controls are bound. You can put the validation logic in whatever methods your buttons are bound to. Use the <em>[Submit All]</em> button to save your validated data in your database/persistence store/whatever.</p>
Local html file AJAX Call and jQuery Woes <p>I'm working on a offline version of a website using jQuery and some xml files. I'm running in to a problem in jQuery when I do a $.ajax call on a xml file jQuery throws a error.</p> <p>When I look at the error I can tell its loading the XML file because its in the error's responceText property. It seams to work just fine in Firefox.</p> <p>This is how my call looks</p> <pre><code>$.ajax({ type: "GET", url: "Modules/" + ModuleID + "/ModuleContent.xml", dataType: "xml", success: function(x) { xml = x; ProcessXML(); }, error: function(x) { alert(x.responceText); } }); </code></pre> <p>When I run this on a web server it works just fine. Its only when I run it from the file its self when I have this problem.</p> <p>Any ideas on how I can make this work in IE?</p> <p>Edit: I found the answer to my problem. <a href="http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests">Here</a></p>
<p>From the <a href="http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests" rel="nofollow">link</a> that the OP posted with the answer:</p> <blockquote> <p>When loading XML files locally, e.g. a CD-ROM etc., the data received by Internet Explorer is plain-text, not text/xml. In this case, use the dataType parameter to load the xml file as text, and parse the returned data within the succes function</p> </blockquote> <pre><code> $.ajax({ url: "data.xml", dataType: ($.browser.msie) ? "text" : "xml", success: function(data){ var xml; if (typeof data == "string") { xml = new ActiveXObject("Microsoft.XMLDOM"); xml.async = false; xml.loadXML(data); } else { xml = data; } // Returned data available in object "xml" } }); </code></pre> <p>This worked for me as well.</p>
Is switching app.config at runtime possible? <p>Is there a way at runtime to switch out an applications app.config (current.config to new.config, file for file). I have a backup/restore process which needs to replace its own application.exe.config file. I have seen this <a href="http://stackoverflow.com/questions/242568/is-it-possible-to-switch-application-configuration-file-at-runtime-for-net-appli">post</a> but it does not answer how to do this at runtime.</p>
<p>Turns out I can swap the .config file for the new one and do a ConfigurationManager.RefreshSection(...) for each section. It will update from the new .config file.</p>
Element.appendChild() chokes in IE <p>I have the following javascript:</p> <pre><code> css = document.createElement('style'); css.setAttribute('type', 'text/css'); css_data = document.createTextNode(''); css.appendChild(css_data); document.getElementsByTagName("head")[0].appendChild(css); </code></pre> <p>for some reason, in IE only, it chokes on "css.appendChild(css_data);" Giving the error: "Unexpected call to method or property access"</p> <p>What's going on?</p>
<p>Try instead:</p> <pre><code>var css = document.createElement('style'); css.setAttribute('type', 'text/css'); var cssText = ''; if(css.styleSheet) { // IE does it this way css.styleSheet.cssText = cssText } else { // everyone else does it this way css.appendChild(document.createTextNode(cssText)); } document.getElementsByTagName("head")[0].appendChild(css); </code></pre>
SMO scripting objects and security <p>I have a customer that has a SQL database on a hosted server; call the db "myDatabase".<br> <br />The hosting co. has locked down object explorer - I can't see myDatabase in the database listed (I see tempdb and master). However, if I "use myDatabase" and then "select * from myTable", all works fine.</p> <p>Since we have no access to object explorer, I can't right click and generate scripts. I thought that I might be able to use SMO to accomplish what I want, but when I attempt something similar to this:</p> <pre><code>Server myServer = new Server(conn); Database myDB = server.Databases["myDatabase"]; Table myTbl = myDB.Tables["myTable"]; </code></pre> <p>It fails - myDB is null (when I iterate through the databases collection, as expected, I only see master and tempdb - the db's I can see in object explorer). It obviously has to do with security - if I can't see the table in object explorer, it won't let me access it through SMO. Anyone have any ideas of a workaround or alternate method to allow me to generate a script?</p> <p>Thx!</p>
<p>I haven't looked at the SMO code, but have you tried using the constructor on the database object? Maybe you can access it directly.</p> <pre><code>Database myDB = new Database(myServer, "myDatabase"); </code></pre>
matching a line that doesn't contain specific text with regular expressions <p>I want to do the following with regular expressions but not sure how to do it. I want it to match <code>one two</code> when <code>one two</code> is the beginning of the line unless the string contains <code>three</code> anywhere after <code>one two</code>.</p>
<p>You need a <a href="http://www.perl.com/doc/manual/html/pod/perlre.html#item__pattern_">negative lookahead assertion</a> - something like this:</p> <pre><code>/^one two(?!.*three)/m </code></pre> <p>Here's <a href="http://www.regular-expressions.info/lookaround.html">a tutorial on lookahead/lookbehind assertions</a></p> <p>Note: I've added the 'm' modifier so that ^ matches the start of a line rather than the start of the whole string.</p>
What do you think about Microsoft Oslo MGraph? <p>MGraph is a great textual data format brought by Microsoft "Oslo".</p> <p>Do you think it has a chance to get as broad as XML is today?</p> <p>Example (Google Geocode):</p> <pre><code>{ name = "waltrop, lehmstr 1d", Status { code = 200, request: "geocode" }, Placemark [ { id = "p1", address = "Lehmstraße, 45731 Waltrop, Deutschland", AddressDetails { Country {CountryNameCode = "DE", CountryName = "Deutschland", AdministrativeArea { AdministrativeAreaName = "Nordrhein-Westfalen", SubAdministrativeArea = { SubAdministrativeAreaName = "Recklinghausen", Locality { LocalityName = "Waltrop", Thoroughfare { ThoroughfareName = "Lehmstraße" }, PostalCode = { PostalCodeNumber = "45731" }}}}}, Accuracy = 6 }, ExtendedData { LatLonBox { north = 51.6244226, south = 51.6181274, east = 7.4046111, west = 7.3983159 } }, Point { coordinates [ 7.4013350, 51.6212620, 0 ] } } ] } </code></pre> <p>Mode information here: <a href="http://startbigthinksmall.wordpress.com/2008/12/10/mgraph-the-next-xml/" rel="nofollow">Microsoft "Oslo" MGraph - the next XML?</a></p>
<p><strong>Here are part of <a href="http://blog.jclark.com/2008/11/some-thoughts-on-oslo-modeling-language.html" rel="nofollow">James Clark's thoughts on M</a></strong>:</p> <p>" I see several major things missing in M, whose absence might be acceptable for a database application of M, but which would be a significant barrier for other applications of M. Most fundamental is order. M has two types of compound value, collections and entities, and they are both unordered. In XML, unordered is the poor relation of ordered. Attributes are unordered, but attributes cannot have structured values. Elements have structure but there's no way in the instance to say that the order of child elements is not significant. The lack of support for unordered data is clearly a weakness of XML for many applications. On the other hand, order is equally crucial for other applications. Obviously, you can fake order in M by having index fields in entities and such like. But it's still faking it. A good modeling language needs to support both ordered and unordered data in a first class way. This issue is perhaps the most fundamental because it affects the data model.</p> <p>Another area where M seems weak is identity. In the abstract data model, entities have identity independently of the values of their fields. But the type system forces me to talk about identity in an SQL-like way by creating artificial fields that duplicate the inherent identity of the entity. Worse, scopes for identity are extents, which are flat tables. Related to this is support for hierarchy. A graph is a more general data model than a tree, so I am happy to have graphs rather than trees. But when I am dealing with trees, I want to be able to say that the graph is a tree (which amounts to specifying constraints on the identity of nodes in the graph), and I want to be able to operate on it as a tree, in particular I want hierarchical paths.</p> <p>One of the strengths of XML is that it handles both documents and data. This is important because the world doesn't neatly divide into documents and data. You have data that contains documents and document that contain data. The key thing you need to model documents cleanly is mixed text. How are you going to support documents in M? The lack of support for order is a major problem here, because ordered is the norm for documents.</p> <p>A related issue is how M and XML fit together. I believe there's a canonical way to represent an M value as an XML document. But if you have data that's in XML how do you express it in M? In many cases, you will want to translate your XML structure into an M structure that cleanly models your data. But you might not always want to take the time to do that, and if your XML has document-like content, it is going to get ugly. You might be better off representing chunks of XML as simple values in M (just as in the JSON world, you often get strings containing chunks of HTML). M should make this easy. You could solve this elegantly with RELAX NG (I know this isn't going to happen given Microsoft's commitment to XSD, but it's an interesting thought experiment): provide a function that allows you to constrain a simple value to match a RELAX NG pattern expressed in the compact syntax (with the compact syntax perhaps tweaked to harmonize with the rest of M's syntax) and use M's repertoire of simple types as a RELAX NG datatype library.</p> <p>Finally, there's the issue of standardization. The achievement of XML in my mind isn't primarily a technical one. It's a social one: getting a huge range of communities to agree to use a common format. Standardization was the critical factor in getting that agreement. XML would not have gone anywhere as a single vendor format. It was striking that the talks about Oslo at the PDC made several mentions of open source, and how Microsoft was putting the spec under its Open Specification Promise so as to enable open source implementations, but no mentions of standardization. I can understand this: if I was Microsoft, I certainly wouldn't be keen to repeat the XSD or OOXML experience. But open source is not a substitute for standardization.</p> <p> "</p> <p>Read <a href="http://blog.jclark.com/2008/11/some-thoughts-on-oslo-modeling-language.html" rel="nofollow"><strong>here</strong></a> James Clark's blog article on the <a href="http://msdn.microsoft.com/en-us/library/dd285282.aspx" rel="nofollow">Oslo Modelling language</a>.</p>
Maven install folder structure problem j2ee (spring, struts ..) <p>i'm using maven 2.1-SNAPSHOT as eclipse plugin. My project structure is like this:</p> <p>src/main/java<br> &nbsp;&nbsp; -model<br> &nbsp;&nbsp; -service<br> &nbsp;&nbsp; -action<br> src/test/java<br> &nbsp;&nbsp; empty atm<br> src/main/resources<br> &nbsp;&nbsp; empty atm<br> src/test/resources<br> &nbsp;&nbsp; empty atm<br> src/main/webapp<br> &nbsp;&nbsp; -js<br> &nbsp;&nbsp;&nbsp;&nbsp;-dojo<br> &nbsp;&nbsp; -META-INF<br> &nbsp;&nbsp; -WEB-INF<br> &nbsp;&nbsp;&nbsp;&nbsp; web.xml <br> &nbsp;&nbsp;&nbsp;&nbsp; appcontext.xml<br> &nbsp;&nbsp;&nbsp;&nbsp; struts.xml<br> &nbsp;&nbsp; index.jsp</p> <p>I'm having trouble understanding the build process and where to put which file. I use as Application Server Jetty but i want to deploy my project on tomcat as well (so i have set up in my pom packaging war).</p> <p>When i run my project with the maven:install command my target folder looks like this: myproject.war<br> war<br> &nbsp;&nbsp; not relevant<br> test-classes<br> &nbsp;&nbsp; empty atm<br> myproject<br> &nbsp;&nbsp; js<br> &nbsp;&nbsp; META-INF<br> &nbsp;&nbsp; WEB-INF<br> &nbsp;&nbsp; index.jsp<br> classes<br> &nbsp;&nbsp; model<br> &nbsp;&nbsp; service<br> &nbsp;&nbsp; action<br></p> <p>My problem is that i need in the classes folder my persistence.xml which i have in META-INF. And struts.xml too i guess. I'm not sure about dojo either if it is right there. And honestly i don't know if this structure is right at all. I also dont know how to configure that the output changes. </p> <p>I hope somebody can help me i really want to understand this process how it should be right, maybe there are even nice ressources to lookup to get better at these things. Thanks in advance kukudas</p>
<p>I believe files that you want deployed to the classpath go in the <code>resources/</code> folder.</p> <p>Take a look at the <a href="http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html" rel="nofollow">Maven in 5 Minutes guide</a>, along with the <a href="http://maven.apache.org/guides/getting-started/index.html" rel="nofollow">Getting Started</a> guide.</p>
Has anyone successfully connected to MySQL from Ruby? <p>I'm starting to get a bit desperate in my attempts to get a ruby script to connect to MySQL.</p> <p>I've given up on DBI, as I just don't seem to be able to get it to work no matter what I do. I figured I might have more luck with just using mysql.rb from ruby-mysql. However, in using that I get the following error:</p> <pre><code>./mysql.rb:453:in `read': Client does not support authentication protocol requested by server; consider upgrading MySQL client (Mysql::Error) </code></pre> <p>I gather from <a href="http://www.ocsinventory-ng.org/index.php?mact=News,cntnt01,detail,0&amp;cntnt01articleid=3&amp;cntnt01returnid=77" rel="nofollow">googling that error message</a> that this means my version of MySQL is too recent and doesn't support old-style passwords. I'm on a shared server and don't have root access, so I can't make the changes recommended to the MySQL config.</p> <p>My version, btw, is:</p> <pre><code>mysql Ver 14.7 Distrib 4.1.22, for pc-linux-gnu (i686) using readline 4.3 </code></pre> <p>Has anyone succeeded in getting ruby to connect to MySQL? I've been trying under Windows, since I have admin access on my Windows machine, but if there's a way to do it without root access on Linux, that'd be even better.</p>
<p>There is a good summary of how to do this here: <a href="http://rubylearning.com/satishtalim/ruby_activerecord_and_mysql.html" rel="nofollow">http://rubylearning.com/satishtalim/ruby_activerecord_and_mysql.html</a></p>
Can one access TestContext in an AssemblyCleanup method? <p>In Microsoft's UnitTesting namespace (<code>Microsoft.VisualStudio.TestTools.UnitTesting</code>) there are <code>AssemblyInitialize</code> and <code>AssemblyCleanup</code> attributes you can apply to static methods and they will be called before and after all tests respectively.</p> <pre><code>[AssemblyInitialize] static public void AssemblyInitialize(TestContext testCtx) { // allocate resources } [AssemblyCleanup] static public void AssemblyCleanup() { // free resources } </code></pre> <p>My question: is it possible and <em>safe</em> to access the <code>TestContext</code> within <code>AssemblyCleanup()</code>? If not, is storing resource references as static members a reasonable alternative or could that cause problems as well?</p> <p>Additionally/optionally: what is the reasoning behind <em>not</em> passing a reference to the <code>TestContext</code> to clean-up methods?</p>
<p>I'm accessing a static property on the same class and it seems to be working fine. I'll update this answer if I encounter any problems. I am <em>not</em>, however, accessing the <code>TestContext</code> so I'm curious if that would work too.</p>
What's your ideal C# project built upon? <p>I'm starting a new personal project on the side, so this is the first time I'll be able to start from the ground up on a larger project since ASP.NET 2.0 was first released. I'd like this to also be a good learning experience for me, so right now I'm planning on building this upon ASP.NET MVC, Castle ActiveRecord, and Ninject. I'm most comfortable with MbUnit for unit testing and CruiseControl for CI so right now they are the front runners.</p> <p>But what would be your first additions once you click "New Solution"? Open Source, commercial, whatever. I have an open mind if they look like they can make it do what it do.</p>
<p><a href="http://www.asp.net/mvc/" rel="nofollow"><strong>Web Framework: MVC</strong></p> <p>Just a better way to make web applications</p> <p><a href="http://www.hibernate.org/343.html" rel="nofollow"><strong>OR/M: NHibernate</strong></a></p> <p>Nothing really beats it in performance or features</p> <p><a href="http://jquery.com/" rel="nofollow"><strong>Javascript: JQuery</strong></a></p> <p>Been using it before it got all cool. JQuery to me seems less like a framework, and more like a natural extension to the javascript language</p> <p><a href="http://www.castleproject.org/container/index.html" rel="nofollow"><strong>IoC: Castle Windsor</strong></a></p> <p>Most mature of the .net IoC containers</p> <p><a href="http://www.jetbrains.com/teamcity/" rel="nofollow"><strong>CI: TeamCity</strong></a></p> <p>Once you try it, you will never want to go back</p> <p><a href="http://www.nunit.org/index.php" rel="nofollow"><strong>Testing: NUnit</strong></a></p> <p>They are all pretty head to head in features, I prefer the tooling (resharper) and syntax (been using it forever now)</p> <p><a href="http://ayende.com/projects/rhino-mocks.aspx" rel="nofollow"><strong>Mocking: Rhino Mocks</strong></a></p> <p>Again, I like to go for maturity, especially in open source projects</p> <p>In Hanselman <a href="http://www.hanselman.com/altnetgeekcode/" rel="nofollow">ALT.net Geek Code</a>, that translates to </p> <p>IOC(CW):MOC(RM):TDD(NU):SCC(Svn):ORM(NH):XPP(++):DDD(T+):JSL(Jq):CIS(TC):GoF(++)</a></p>
How do I send users to a different "site" in Apache while also using mod_proxy? <p>I have a web site that I administer that uses Apache 2.0 on the front with Tomcat 6 on the back-end (with mod_proxy proxying the connection between the two).</p> <p>I want to be able to use the same VirtualHost to also access the phpMyAdmin application running on the box. So, for example, www.mywebsite.com will pass all traffic to Tomcat, but www.mywebsite.com/myadmin (with obvious security) will pass traffic to phpMyAdmin. </p>
<p>How about using <a href="http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html" rel="nofollow"><code>mod_rewrite</code></a> instead of mod_proxy?</p> <p>You can use the <code>P</code> modifier to send certain request (i.e. all those that aren't to /phpmyadmin*) through a proxy. This actually uses mod_proxy internally.</p> <p>Something like this (not tested):</p> <pre><code> RewriteCond %{REQUEST_URI} !^/phpmyadmin RewriteRule ^.*$ http://tomcat/$0 [P,L] </code></pre>
Can someone explain this template code that gives me the size of an array? <pre><code>template&lt;typename T, size_t n&gt; size_t array_size(const T (&amp;)[n]) { return n; } </code></pre> <p>The part that I don't get is the parameters for this template function. What happens with the array when I pass it through there that gives <code>n</code> as the number of elements in the array?</p>
<p>Well, first you have to understand that trying to get a value out of an array can give you a pointer to its first element:</p> <pre><code>int a[] = {1, 2, 3}; int *ap = a; // a pointer, size is lost int (&amp;ar)[3] = a; // a reference to the array, size is not lost </code></pre> <p>References refer to objects using their exact type or their base-class type. The key is that the template takes arrays by reference. Arrays (not references to them) as parameters do not exist in C++. If you give a parameter an array type, it will be a pointer instead. So using a reference is necessary when we want to know the size of the passed array. The size and the element type are automatically deduced, as is generally the case for function templates. The following template</p> <pre><code>template&lt;typename T, size_t n&gt; size_t array_size(const T (&amp;)[n]) { return n; } </code></pre> <p>Called with our previously defined array <code>a</code> will implicitly instantiate the following function:</p> <pre><code>size_t array_size(const int (&amp;)[3]) { return 3; } </code></pre> <p>Which can be used like this:</p> <pre><code>size_t size_of_a = array_size(a); </code></pre> <hr> <p>There's a variation I made up some time ago <em>[Edit: turns out someone already had that same idea <a href="http://blogs.msdn.com/the1/archive/2004/05/07/128242.aspx">here</a>]</em> which can determine a value at compile time. Instead of returning the value directly, it gives the template a return type depending on <code>n</code>:</p> <pre><code>template&lt;typename T, size_t n&gt; char (&amp; array_size(const T (&amp;)[n]) )[n]; </code></pre> <p>You say if the array has <code>n</code> elements, the return type is a reference to an array having size <code>n</code> and element type <code>char</code>. Now, you can get a compile-time determined size of the passed array:</p> <pre><code>size_t size_of_a = sizeof(array_size(a)); </code></pre> <p>Because an array of <code>char</code> having <code>n</code> elements has sizeof <code>n</code>, that will give you the number of elements in the given array too. At compile time, so you can do</p> <pre><code>int havingSameSize[sizeof(array_size(a))]; </code></pre> <p>Because the function never is actually called, it doesn't need to be defined, so it doesn't have a body. Hope I could clear the matter up a little bit.</p>
IronPython Webframework <p>There seem to be many excellent web frameworks for Python. Has anyone used any of these (Pylons, Web2Py, Django) with IronPython?</p>
<p>Django <a href="http://unbracketed.org/2008/mar/16/pycon-2008-django-now-plays-dark-side/">has been run on IronPython</a> before, but as a proof-of-concept. I know the IronPython team are interested in Django support as a metric for Python-compatibility.</p> <p>Somewhat related is the possibility to use <a href="http://haacked.com/archive/2008/09/23/refreshing-asp.net-dynamic-language-support.aspx">IronPython with ASP.NET and ASP.NET MVC</a>, which is probably more mature.</p>
DomainKeys Sendmail DNS <p>What steps do I have to take to configure my sendmail server to implement domainkeys properly?</p> <p>Also what do I have to do on the DNS end?</p>
<p>There are detailed descriptions on the web. For example:</p> <ul> <li><a href="http://www.elandsys.com/resources/sendmail/domainkeys.html" rel="nofollow">http://www.elandsys.com/resources/sendmail/domainkeys.html</a></li> <li><a href="http://www.erikberg.com/notes/milters.html" rel="nofollow">http://www.erikberg.com/notes/milters.html</a></li> <li><a href="http://www.technoids.org/dk-milter.html/" rel="nofollow">http://www.technoids.org/dk-milter.html/</a></li> </ul>
Read single value from query result <p>I am trying to return the result that I found in my query to the ASP.net table. How do I do that? I already have the query, I am just having trouble getting the count result back. </p> <pre><code>string configMan.ConnString["connect"].ToString(); iDB2Conn temp = new iDB2Conn string query = "select Count(*) as total from test"; ... </code></pre> <p>this is where I am having trouble.</p>
<p>This is where the SqlCommand object comes in handy.</p> <pre><code>int result = 0; using(SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand sql = new SqlCommand("SELECT COUNT(*) FROM test", conn); result = (int)sql.ExecuteScalar(); } </code></pre>
How to cope with slow feedback when pair programming? <p>I work in an Extreme Programming team, pair programming every day. Recently more and more often I get to do stuff that gives slow feedback, on order of 3 minutes. For example: change some thing, recompile, run and see wheather the performance is improved. I see it coroding the quality of pair programming, and I think it affects pairs more that solo programmers. If I am alone I can do sth else, but what if I am pair programming? How would you deal with it?</p>
<p>If you could do something else alone, why not when pairing? Maybe simpler action items could be taken off an issue list while waiting? A 3 minute wait would be too long for me to keep the brain in the "flow-mode". So being disrupted anyway (and your partner as well), can't you just do something else with your partner?</p> <p>However, in your situation, I'd not work in any environment where I have 3 minutes pauses after a change. So the question is: can't you develop and debug that code in a smaller environment, broil it to perfection and then reintegrate those pieces into the main stream ?</p>
Friend scope in C++ <p>If I have three classes, A, B, C. A and B are friends (bidirectionally). Also, B and C are friends (bidirectionally). A has a pointer to B and B has a pointer to C. Why can't A access C's private data through the pointer?</p> <p>Just to clarify: This is a pure theoretical C++ language question, not a design advice question.</p>
<h3>Friendship in C++ is not transitive:</h3> <p>John is a friend of mine and he can use my wireless connection any time (I trust him).<br> John's friend Tim though is a waster and though John is my friend I do not include Tim as a friend, and thus I don't let him use my wireless connection.</p> <h3>Friendship is NOT inherited</h3> <p>Also John's children are a bunch of hooligans so I don't trust them either they are definitely not my friends nor are my own children who I trust as far as I could throw them.</p> <p>Though our children can not directly accesses the wireless they can get access to it if they go through us. So John's children can access my wireless if they access it via John (ie they are supervised and <strong>protected</strong> by John).</p> <h3>Also, friendship is not symmetric.</h3> <p>John has a goverment job so he unfortunately is not allowed to trust anyone, especially when it comes to wireless.</p> <h3>You are always your own best friend.</h3> <p>This allows things like copy constructors where you can access the private member of another object even though there is no real accesses.</p> <p>So I am also automatically friends with all my clones :-) as they are just other instances of myself.</p>
Exclude a column from being sorted using jQuery tablesorter <p>I am looking for a way to exclude a single column from being sorted using jQuery's tablesorter plugin. Specifically, I have a fairly large table and would like to keep a "row number" column fixed so that it is easy to see what position in the table a particular row is, after sorting.</p> <p>For example:</p> <pre><code># name ----------- 1 papaya 2 apple 3 strawberry 4 banana </code></pre> <p>When sorted on the name column, should result in:</p> <pre><code># name ----------- 1 apple 2 banana 3 papaya 4 strawberry </code></pre> <p>Thanks.</p>
<p>For those who find this while looking for a way to exclude a column from being sortable (i.e. clickable header on the column), the below example excludes column 4 (zero-indexed) from being sorted):</p> <pre><code>$("table").tablesorter({ headers: {4: {sorter: false}} }); </code></pre>
How can I make cygwin autocomplete windows paths? <p>I don't want to type /cygdrive/c/path/to/stuff, especially when using tools that don't know anything about cygwin. Is there a way to configure cygwin to autocomplete "c:\path\to\stuff" or even "c:/path/to/stuff"?</p>
<p>For tools that can't understand cygwin paths, you'll need to convert them to windows paths. The <code>cygpath</code> utility can do this for you:</p> <pre><code>notepad $(cygpath -w /cygdrive/c/path/to/stuff) </code></pre> <p>You can probably create aliases or wrapper scripts for commonly-used windows executables.</p>
Type to use to represent a byte in ANSI (C89/90) C? <p>Is there a standards-complaint method to represent a byte in ANSI (C89/90) C? I know that, most often, a char happens to be a byte, but my understanding is that this is not guaranteed to be the case. Also, there is stdint.h in the C99 standard, but what was used before C99?</p> <p>I'm curious about both 8 bits specifically, and a "byte" (sizeof(x) == 1).</p>
<p><code>char</code> is always a <strong>byte</strong> , but it's not always an <strong>octet</strong>. A byte is the smallest addressable unit of memory (in most definitions), an octet is 8-bit unit of memory.</p> <p>That is, <code>sizeof(char)</code> is always <strong>1</strong> for all implementations, but <code>CHAR_BIT</code> macro in <code>limits.h</code> defines the size of a byte for a platform and it is not always 8 bit. There are platforms with 16-bit and 32-bit bytes, hence <code>char</code> will take up more bits, but it is still a byte. Since required range for <code>char</code> is at least -127 to 127 (or 0 to 255), it will be <em>at least</em> 8 bit on all platforms.</p> <blockquote> <h1>ISO/IEC 9899:TC3</h1> <h2>6.5.3.4 The sizeof operator</h2> <ol> <li>...</li> <li>The sizeof operator yields the size (<strong>in bytes</strong>) of its operand, which may be an expression or the parenthesized name of a type. [...]</li> <li>When applied to an operand that has type <code>char</code>, <code>unsigned char</code>, or <code>signed char</code>, (or a qualified version thereof) the result is <strong>1</strong>. [...]</li> </ol> </blockquote> <p>Emphasis mine.</p>
Java synchronized static methods: lock on object or class <p>The Java Tutorials say: "it is not possible for two invocations of synchronized methods on the same object to interleave." </p> <p>What does this mean for a <code>static method</code>? Since a static method has no associated object, will the synchronized keyword lock on the class, instead of the object?</p>
<p>Just to add a little detail to Oscar's (pleasingly succinct!) answer, the relevant section on the Java Language Specification is <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.3.6">8.4.3.6, 'synchronized Methods'</a>:</p> <blockquote> <p>A synchronized method acquires a monitor (§17.1) before it executes. For a class (static) method, the monitor associated with the Class object for the method's class is used. For an instance method, the monitor associated with this (the object for which the method was invoked) is used. </p> </blockquote>
Oracle: How to create an element in a specific namespace with XMLElement() <p>In Oracle, you can use the <a href="http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/functions230.htm#i1129193" rel="nofollow">XMLElement()</a> function to create an element, as in:</p> <pre><code>XMLElement('name', 'John') </code></pre> <p>But how to create an element in a specific namespace? For instance, how to create the following element:</p> <pre><code>&lt;my:name xmlns:my="http://www.example.com/my"&gt;John&lt;/my:name&gt; </code></pre>
<p>You can also use XMLAttribute:</p> <pre><code>select xmlelement("my:name", xmlattributes('http://www.example.com/my' as "xmlns:my"), 'John' ) from dual </code></pre> <p>Will return:</p> <pre><code>&lt;my:name xmlns:my="http://www.example.com/my"&gt;John&lt;/my:name&gt; </code></pre> <p>You can also check that Oracle recognizes this as a namespace (other than you are not getting a <em>namespace prefix "my" is not declared</em> error):</p> <pre><code>select xmlelement("my:name", xmlattributes('http://www.example.com/my' as "xmlns:my"), 'John' ).getnamespace() from dual </code></pre> <p>Will return:</p> <pre><code>http://www.example.com/my </code></pre>
Visual Studio designer moving controls and adding grid columns when form is opened <p>The first time I try to open a particular form many of the controls (those with anchors on the right side and/or the bottom) are shifted and my grids automatically regain all the columns from their datasource which (the columns) I had previously removed.</p> <p>I have read elsewhere it is recommended to copy the 'good' designer code into the constructor after the InitializeComponent method. This doesn't seem to be a good long term solution, eg what if a user makes future design changes?</p> <p>Any suggestions/workarounds? Is this a Visual Studio 2008 bug?</p>
<p>I found deleting the controls and adding them back in works. Not just cut and paste, but adding the controls back from scratch. This seems to be related to where to designer code is written in the InitialiseComponent method.</p> <p>This link describes some issues with anchoring and derived forms: <a href="http://weblogs.asp.net/rweigelt/archive/2003/09/24/28984.aspx" rel="nofollow">http://weblogs.asp.net/rweigelt/archive/2003/09/24/28984.aspx</a></p>
Where does Rails store data created by saving activerecord objects during tests? <p>Where does Rails store data created by saving activerecord objects during tests?</p> <p>I thought I knew the answer to that question: obviously in the <strong>_test database</strong>. But it looks like this is <strong>not true</strong>!</p> <p>I used this system to test what's happening to saved ActiveRecord data during rspec tests:</p> <p>$ rails -d mysql test</p> <p>$ cd test</p> <p>$ nano config/database.yml ...</p> <p>... create mysql databases test_test, test_development, test_production</p> <p>$ script/generate rspec</p> <p>$ script/generate rspec_model foo</p> <p>edit Foo migration:</p> class CreateFoos <p>$ rake db:migrate</p> <p>edit spec/models/foo_spec.rb:</p> <pre> require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe Foo do before(:each) do @valid_attributes = { :bar => 12345 } end it "should create a new instance given valid attributes" do foo = Foo.new(@valid_attributes) foo.save puts "sleeping..." sleep(20) end end </pre> <p>$ rake spec</p> <p>When you see "sleeping...", change to another open terminal with a mysql session conneted to the test_test database and do:</p> <pre> mysql> select * from foos; Empty set (0.00 sec) </pre> <p>Why doesn't the mysql session show any records in the test_test database while the test is running?</p>
<p>Items in the test database are erased by default after each test is run, by design. This is done to make sure that each of your tests has its own sandbox to play in that doesn't cause any interactions with the tests before it.</p> <p>Again, this is by design. You don't want tests that are manipulating the same set of data (or rely on synchronous execution), because there is no guarantee of execution order.</p> <p>However, I believe if you modify you test/test_helper.rb file to say this:</p> <pre><code>self.use_transactional_fixtures = false </code></pre> <p>instead of</p> <pre><code>self.use_transactional_fixtures = true </code></pre> <p>It will cause the data in your test database to persist. </p> <p>ALSO: My advice is specifically designed to work with Test::Unit, not RSpec. However, I imagine that there is a similar setting your spec_helper.rb you should be looking for.</p>
the level of a treeview in WPF? <p>In a WinForms application, the level of a treeview is given by node.level<br /> What is the corresponding one in WPF?</p> <p>Thanks! </p>
<p>The direct answer to your question is that there is no level property in WPF.</p> <p>There is no one to one relationship between the winforms controls and wpf control. Because the underlying architecture and usage is totally different in both. In WPF you will bind a heirarchical data(LinkedList kind of Datastructure) to a TreeView and define a HeirarchicalDataTemplate to the Treeview.ItemTemplate property</p>
WCF and embedded systems <p>I am working on a project that involves an embedded system which runs a non-microsoft OS with a C program for the application and am developing .NET software for its end user applications. For remote configuring with the .NET software (which can go across firewalls), I am considering using WCF. I know only a little about WCF so far but I've read that it is supposed to be interoperable with environments other than .NET. The embedded environment has an HTTP stack but no built in support for web services. Does anyone have any experience with this kind of thing or know if it would be appropriate at all? If so please provide some advice or point me in the right direction.</p> <p>Thanks!</p>
<p>WCF is interoperable because it's accessed over HTTP. Visual Studio can help you build client libraries very quickly for WCF, but client access to WCF doesn't require anything other than HTTP calls with the proper payload. If you're looking at a remote server call and your built-in support in your embedded environment is basic HTTP, look at building your server-side as REST-formatted methods. Your debugger will thank you.</p>
i want to find all if statements in C# code which are not followed by brackets. Through regex <p>I want to find all <code>if</code> statements and <code>for</code> statements which are not followed by curly brackets '<code>{</code>'. When you write a single line in an <code>if</code> statement you do not mostly enclose it in curly brackets, so I want to find all those <code>if</code> and <code>for</code> statements.</p> <p>Please help!</p> <p>Like I want to capture this statement</p> <pre><code>if (childNode.Name == "B") return TokenType.Bold; </code></pre> <p>but not these kinds</p> <pre><code>if (childNode.Name == "B") { return TokenType.Bold; } </code></pre> <p>I want to do it with regex.</p>
<p>Since the underlying mathematics disallow a perfect match, you could go for a good heuristic like "find all '<code>if</code>' followed by a semicolon without an intervening open brace:</p> <pre><code>/\&lt;if\&gt;[^{]*;/ </code></pre> <p>where <code>\&lt;</code> and <code>\&gt;</code> are begin-of-word and end-of-word as applicable to your regex dialect. Also take care to ignore all newlines in the input, some regex processors need to be told to do that.</p> <p><hr /></p> <p>You might want to look at <a href="http://code.msdn.microsoft.com/sourceanalysis" rel="nofollow">StyleCop</a> too. This is a tool which runs a big set of various checks on your source code. This check is already there.</p>
Monitor a process's network usage? <p>Is there a way in C# or C/C++ &amp; Win32 to monitor a certain process's network usage (Without that application being built by you obviously)? I would like to monitor just 1 process for like an hour or so, then return the bytes used by only that process, such as limewire for example.</p> <p>Is it possible? I know netstat -e on windows will tell you total bytes sent/received, but that is for all processes.</p> <p>edit: If i can't return just one processes usage, how can i get the bytes sent/received by the entire system? as netstat displays except i just want the integers.</p> <p>eg:</p> <pre> netstat -e Received Sent Bytes 2111568926 1133174989 Unicast packets 3016480 2711006 Non-unicast packets 3122 1100 Discards 0 0 Errors 0 0 Unknown protocols 0 </pre> <p>I just want to get 2 variables, like rec = 2111568926 and sent = 1133174989</p>
<p>It's possible, but if I'm not mistaken you'll have to create a network driver to filter all network traffic and than figure out which process created the traffic.</p> <p>Microsoft has an free application for it called <a href="http://blogs.technet.com/netmon/archive/2008/09/17/network-monitor-3-2-has-arrived.aspx" rel="nofollow">Microsoft Network Monitor 3.2</a> (<a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=f4db40af-1e08-4a21-a26b-ec2f4dc4190d&amp;DisplayLang=en" rel="nofollow">download</a>). According to the release notes it also has an api to use.</p> <blockquote> <p>Network Monitor API: Create your own applications that capture, parse and analyze network traffic!</p> </blockquote> <p><a href="http://blogs.technet.com/netmon/archive/2008/10/29/intro-to-the-network-monitor-api.aspx" rel="nofollow">Here is a blog post about these API's</a>.</p> <p>In my opinion you should use this API (or another API such as WinPcap) to filter the traffic instead of writing your own device driver.</p>
Delphi fast file copy <p>I'm writing an app that supposed to copy a bunch of files from one place to another. When I'm using TFileStream for the copy it is 3-4 times slower than copying the files with the OS.</p> <p>I also tried to copy with a buffer, but that was too slow aswell.</p> <p>I'm working under Win32, anyone got some insights on this matter?</p>
<p>There are a few options.</p> <ol> <li>You could call CopyFile which uses the <a href="http://msdn.microsoft.com/en-us/library/aa363851(VS.85).aspx">CopyFileA</a> windows API</li> <li>You could call the api which explorer uses (the windows api <a href="http://msdn.microsoft.com/en-us/library/bb762164(VS.85).aspx">SHFileOperation</a>). An example of calling that function can be found on <a href="http://www.scip.be/index.php?Page=ArticlesDelphi08&amp;Lang=EN">SCIP.be</a></li> <li>You could write your own function which uses a buffer.</li> </ol> <p>If you know the kind of files your going to copy, the 3th method will normally outperform the others. Because the windows API's are more tuned for overall best case (small files, large files, files over network, files on slow drives). You can tune your own copy function more to fit your needs.</p> <p>Below is my own buffered copy function (i've stripped out the GUI callbacks):</p> <pre><code>procedure CustomFileCopy(const ASourceFileName, ADestinationFileName: TFileName); const BufferSize = 1024; // 1KB blocks, change this to tune your speed var Buffer : array of Byte; ASourceFile, ADestinationFile: THandle; FileSize: DWORD; BytesRead, BytesWritten, BytesWritten2: DWORD; begin SetLength(Buffer, BufferSize); ASourceFile := OpenLongFileName(ASourceFileName, 0); if ASourceFile &lt;&gt; 0 then try FileSize := FileSeek(ASourceFile, 0, FILE_END); FileSeek(ASourceFile, 0, FILE_BEGIN); ADestinationFile := CreateLongFileName(ADestinationFileName, FILE_SHARE_READ); if ADestinationFile &lt;&gt; 0 then try while (FileSize - FileSeek(ASourceFile, 0, FILE_CURRENT)) &gt;= BufferSize do begin if (not ReadFile(ASourceFile, Buffer[0], BufferSize, BytesRead, nil)) and (BytesRead = 0) then Continue; WriteFile(ADestinationFile, Buffer[0], BytesRead, BytesWritten, nil); if BytesWritten &lt; BytesRead then begin WriteFile(ADestinationFile, Buffer[BytesWritten], BytesRead - BytesWritten, BytesWritten2, nil); if (BytesWritten2 + BytesWritten) &lt; BytesRead then RaiseLastOSError; end; end; if FileSeek(ASourceFile, 0, FILE_CURRENT) &lt; FileSize then begin if (not ReadFile(ASourceFile, Buffer[0], FileSize - FileSeek(ASourceFile, 0, FILE_CURRENT), BytesRead, nil)) and (BytesRead = 0) then ReadFile(ASourceFile, Buffer[0], FileSize - FileSeek(ASourceFile, 0, FILE_CURRENT), BytesRead, nil); WriteFile(ADestinationFile, Buffer[0], BytesRead, BytesWritten, nil); if BytesWritten &lt; BytesRead then begin WriteFile(ADestinationFile, Buffer[BytesWritten], BytesRead - BytesWritten, BytesWritten2, nil); if (BytesWritten2 + BytesWritten) &lt; BytesRead then RaiseLastOSError; end; end; finally CloseHandle(ADestinationFile); end; finally CloseHandle(ASourceFile); end; end; </code></pre> <p>Own functions:</p> <pre><code>function OpenLongFileName(const ALongFileName: String; SharingMode: DWORD): THandle; overload; begin if CompareMem(@(ALongFileName[1]), @('\\'[1]), 2) then { Allready an UNC path } Result := CreateFileW(PWideChar(WideString(ALongFileName)), GENERIC_READ, SharingMode, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0) else Result := CreateFileW(PWideChar(WideString('\\?\' + ALongFileName)), GENERIC_READ, SharingMode, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); end; function OpenLongFileName(const ALongFileName: WideString; SharingMode: DWORD): THandle; overload; begin if CompareMem(@(WideCharToString(PWideChar(ALongFileName))[1]), @('\\'[1]), 2) then { Allready an UNC path } Result := CreateFileW(PWideChar(ALongFileName), GENERIC_READ, SharingMode, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0) else Result := CreateFileW(PWideChar('\\?\' + ALongFileName), GENERIC_READ, SharingMode, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); end; function CreateLongFileName(const ALongFileName: String; SharingMode: DWORD): THandle; overload; begin if CompareMem(@(ALongFileName[1]), @('\\'[1]), 2) then { Allready an UNC path } Result := CreateFileW(PWideChar(WideString(ALongFileName)), GENERIC_WRITE, SharingMode, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0) else Result := CreateFileW(PWideChar(WideString('\\?\' + ALongFileName)), GENERIC_WRITE, SharingMode, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); end; function CreateLongFileName(const ALongFileName: WideString; SharingMode: DWORD): THandle; overload; begin if CompareMem(@(WideCharToString(PWideChar(ALongFileName))[1]), @('\\'[1]), 2) then { Allready an UNC path } Result := CreateFileW(PWideChar(ALongFileName), GENERIC_WRITE, SharingMode, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0) else Result := CreateFileW(PWideChar('\\?\' + ALongFileName), GENERIC_WRITE, SharingMode, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); end; </code></pre> <p>The code is a bit longer that necessary, because I included a retry mechanism to support a wifi connection problem I had.</p> <p>So this part </p> <pre><code> if BytesWritten &lt; BytesRead then begin WriteFile(ADestinationFile, Buffer[BytesWritten], BytesRead - BytesWritten, BytesWritten2, nil); if (BytesWritten2 + BytesWritten) &lt; BytesRead then RaiseLastOSError; end; </code></pre> <p>could be written as</p> <pre><code> if BytesWritten &lt; BytesRead then begin RaiseLastOSError; end; </code></pre>
How to create a compeletely transparent window with MFC? <p>I want to create a completely transparent window with MFC, but I don't know how to do this. Can you tell me the way? </p> <p>Thank you very much!</p>
<p>You can use layered windows for transparency effects. See <a href="http://msdn.microsoft.com/en-us/library/ms997507.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms997507.aspx</a>. Be sure to set the WS_EX_LAYERED bit and to use UpdateLayeredWindow. This allows you to trap messages even though the window isn't visible to the user.</p>
asp.net: moving from session variables to cookies <p>My forms are losing session variables on shared hosting very quickly (webhost4life), and I think I want to replace them with cookies. Does the following look reasonable for tracking an ID from form to form:</p> <pre><code>if(Request.Cookies["currentForm"] == null) return; projectID = new Guid(Request.Cookies["currentForm"]["selectedProjectID"]); Response.Cookies["currentForm"]["selectedProjectID"] = Request.Cookies["currentForm"]["selectedProjectID"]; </code></pre> <p>Note that I am setting the Response cookie in all the forms after I read the Request cookie. Is this necessary? Do the Request cookies copy to the Response automatically?</p> <p>I'm setting no properties on the cookies and create them this way:</p> <pre><code>Response.Cookies["currentForm"]["selectedProjectID"] = someGuid.ToString(); </code></pre> <p>The intention is that these are temporary header cookies, not persisted on the client any longer than the browser session. I ask this since I don't often write websites.</p>
<p>Before changing any code, I would investigate why session variables are disappearing.</p> <p>Perhaps it is as simple as changing the timeout setting in the web.config?</p> <p>Here's a list of the session state settings in the config file: <a href="http://msdn.microsoft.com/en-us/library/h6bb9cz9.aspx" rel="nofollow">Session Element on MSDN</a></p> <p>====================================================</p> <p>Oh yeah, one other thing to try in relation to your comment:</p> <p>If my memory serves me, we had some issues in the past when deploying to a web garden/farm where multiple web sites on the same server would "clash". To get round this we explicitly names the cookie as so:</p> <pre><code>&lt;authentication mode="Forms" &gt; &lt;forms loginUrl="your-login-page.aspx" cookieless="AutoDetect" name=".A-NAME-WHICH-IS-UNIQUE" /&gt; &lt;/authentication&gt; </code></pre> <p>Name: Optional attribute. Specifies the HTTP cookie to use for authentication. If multiple applications are running on a single server and each application requires a unique cookie, you must configure the cookie name in each Web.config file for each application.</p> <p>The default is ".ASPXAUTH". From here <a href="http://msdn.microsoft.com/en-us/library/1d3t3c61.aspx" rel="nofollow">link text</a></p>
What can cause a .NET process/thread to terminate unexpectedly? <p>I'm trying to gather a complete listing of the reasons a .NET process or thread to terminate, even though the main() method is guarded by a try...catch clause.</p> <p>One such reason is Thread.Abort() (unless you call Thread.ResetAbort). Do you know of more reasons?</p>
<p>StackOverflowException cannot be handled by your code. </p> <p>A StackOverflowException typically occurs when you have an endless loop which lets your call-stack grow until the usual stack size (1MB) is exceeded.</p> <p>There are more exceptions where you cannot recover from. <a href="http://weblogs.asp.net/tgraham/archive/2004/06/07/150225.aspx" rel="nofollow">ExecutionEngineException </a> seems to be one of them.</p>
Tablet PC Autocomplete <p>I have been trying to implement the autocomplete functionality mentioned <a href="http://msdn.microsoft.com/en-us/library/ms695043%28VS.85%29.aspx" rel="nofollow">here</a>.</p> <p>The problem is I am developing on a windows xp machine and I cant seem to find the right dlls used to develop this feature.</p> <p>Using vista for development is not an option, but the production environment is on a Vista Tablet PC. I have downloaded and installed the Tablet PC SDK version 1.7 to no avail (still cant find the libraries).</p> <p>The implementation seems to use COM libraries. The examples are all written in C++ and I am developing in .NET.</p> <p>Has anyone ever successfully implemented this feature? If so, how did you go about doing it?</p> <p>Any help will be appreciated </p> <p>Here is an image showing what I am trying to achieve </p> <p><img src="http://i.msdn.microsoft.com/ms695043.ba59a513-e538-4092-89a6-6d691424dc3d%28en-us,VS.85%29.jpg" alt="alt text" /></p>
<p>There is no need to call the DLLs directly. As long as your solution is based on .NET Framework 3.0 or above you just need to enable AutoComplete mode on the specific textbox. Deploying your solution to Vista should enable the functionality.</p> <p>However, one caveat is that the autocomplete integration is for Vista and above only. You will therefore be unable to debug this aspect of your project on an XP machine - you'll have to remotely debug on your Vista Tablet PC. The Tablet PC SDK does not include down-level compatibility for this option on XP as it's baked into the Vista OS.</p> <p>I hope this helps.</p>
Undo in a transactional database <p>I do not know how to implement undo property of user-friendly interfaces using a transactional database.</p> <p>On one hand it is advisable that the user has multilevel (infinite) undoing possibility as it is stated <a href="http://stackoverflow.com/questions/125269/how-would-you-handle-users-who-dont-read-dialog-boxes">here</a> in the answer. Patterns that may help in this problem are <a href="http://en.wikipedia.org/wiki/Memento_pattern" rel="nofollow">Memento</a> or <a href="http://en.wikipedia.org/wiki/Command_pattern" rel="nofollow">Command</a>.</p> <p>However, using a complex database including triggers, ever-growing sequence numbers, and uninvertable procedures it is hard to imagine how an undo action may work at different points than transaction boundaries. In other words, undo to a point when the transaction committed for the last time is simply a rollback, but how is it possible to go back to different moments?</p> <p><strong>UPDATE</strong> (based on the answers so far): I do not necessarily want that the undo works when the modification is already committed, I would focus on a running application with an open transaction. Whenever the user clicks on save it means a commit, but before save - during the same transaction - the undo should work. I know that using database as a persistent layer is just an implementation detail and the user should not bother with it. But if we think that "The idea of undo in a database and in a GUI are fundamentally different things" and we do not use undo with a database then the infinite undoing is just a buzzword. I know that "rollback is ... not a user-undo". </p> <p>So how to implement a client-level undo given the "cascading effects as the result of any change" inside the same transaction?</p>
<p>The idea of undo in a database and in a GUI are fundamentally different things; the GUI is going to be a single user application, with low levels of interaction with other components; a database is a multi-user application where changes can have cascading effects as the result of any change.</p> <p>The thing to do is allow the user to try and apply the previous state as a new transaction, which may or may not work; or alternatively just don't have undos after a commit (similar to no undos after a save, which is an option in many applications).</p>
How do I upgrade PHP 5.1 to 5.2 on SUSE 10.1 using the yast command line only? <p>How do I upgrade PHP 5.1 to 5.2 from the SUSE 10.1 command line? Is there a package manager command to do it automatically?</p> <p>Actually I need JSON support to use the JavaScript-RTE and believe it's in PHP 5.2 only.</p>
<p>How about using <a href="http://en.opensuse.org/Zypper" rel="nofollow">zypper</a>?</p> <p>I got this, already having latest available.</p> <pre><code>aansari:~ # zypper in php Downloading repository 'openSUSE-11.0-Updates' metadata [done] Building repository 'openSUSE-11.0-Updates' cache [done] Reading installed packages... 'php5' providing 'php' is already installed. Nothing to do. aansari:~ # </code></pre>
Improving our dev environment at work <p>In the near future i will get some 2 weeks for moving and improving our development environment at work.</p> <p>We mainly develop one large PHP/MySQL project with 2-10 developers.</p> <p>At the moment we have one dev server, running apache with mod_userdir, each dev has a /public_html folder in his (samba-accessible) home. For VCS and Project Management/Issuetracking we use Subversion and Trac. Testing/Deployment takes some manual steps, not much automation there.</p> <p>My plans for the new setup include the following changes to the existing stuff:</p> <ul> <li>Continuous Integration</li> <li>Integrate CI to Trac, create/find a plugin which offers to start actions after success or failure of the build progress (i.e. deploy to staging/live)</li> <li>Create automated deployment-scripts (one-click)</li> <li>Integrate (<a href="http://www.stack.nl/~dimitri/doxygen/">Doxygen</a>)-Documentation into the build-progress and somehow into Trac</li> <li>Add <a href="http://stackoverflow.com/questions/438398/subversion-as-version-incrementor-at-each-commit">automatic versioning</a></li> <li>Add another layer of monitoring (local nagios monitoring our production-system-nagios)</li> <li>Add a nightly running MySQL Replication Slave, which can then by the developers be used to test stuff on up2date data</li> <li>Review the backup plans</li> <li>Document how and why I set everything up in this way</li> </ul> <p>Do you have any tipps/hints what can be improved further? Anything we should do in a different way?</p>
<p>I would make sure that you write your automated deployment scripts in such a way that they can be used by your continuous integration tool. <a href="http://hudson-ci.org/">Hudson</a> (and CruiseControl I suspect) basically wrap these scripts and provide a nifty front-end. </p> <p>Hundson is easy to install and comes with a <a href="http://hudson.gotdns.com/wiki/display/HUDSON/Trac+Plugin">Trac plugin</a>, SVN, CVS, Git plugins and a <a href="http://hudson.gotdns.com/wiki/display/HUDSON/Doxygen+Plugin">Doxygen</a> plugin and others for almost anything you can think of. Caveat: I haven't used all these plugins and they may not do exactly what you want...</p> <p>If you have a budget for CI software then TeamCity is well worth a look (or are you using <a href="http://bitten.edgewall.org/">Bitten</a>?).</p> <p>You've a great opportunity, so good luck!</p>
(ProjectEuler) Sum Combinations <p>From <a href="http://projecteuler.net/">ProjectEuler.net</a>:</p> <p><strong>Prob 76: How many different ways can one hundred be written as a sum of at least two positive integers?</strong></p> <p>I have no idea how to start this...any points in the right direction or help? I'm not looking for how to do it but some <strong>hints</strong> on how to do it.</p> <p>For example 5 can be written like:</p> <pre><code>4 + 1 3 + 2 3 + 1 + 1 2 + 2 + 1 2 + 1 + 1 + 1 1 + 1 + 1 + 1 + 1 </code></pre> <p>So 6 possibilities total.</p>
<p><a href="http://mathworld.wolfram.com/PartitionFunctionP.html">Partition Numbers</a> (or Partition Functions) are the key to this one.</p> <p>Problems like these are usually easier if you start at the bottom and work your way up to see if you can detect any patterns.</p> <ul> <li>P(1) = 1 = {[1]}</li> <li>P(2) = 2 = {[2], [1 + 1]}</li> <li>P(3) = 3 = {[3], [2 + 1], [1 + 1 + 1]}</li> <li>P(4) = 5 = {[4], [3 + 1], [2 + 2], [2 + 1 + 1], [1 + 1 + 1 + 1]}</li> <li>P(5) = 7 ...</li> <li>P(6) = 11 ...</li> <li>P(7) = 15 ...</li> <li>P(8) = 22 ...</li> <li>P(9) = 30 ...</li> </ul> <p>Hint: See if you can build P(N) up from some combination of the results prior to P(N).</p>
Deploy PowerBuilder application <p>I'm trying to deploy the examples project that comes with PowerBuilder 9 IDE to an .exe file. </p> <ol> <li>Full build - passed successfully.</li> <li><p>Deploy - fails with the following error:</p> <p>"The current library list is different than the library list contained within this project. The project library list has been updated. specify build options for the updated list and try again."</p></li> </ol> <p>How can I overcome this?</p> <p>Thanks in advance</p>
<p>By the time you've seen this message, PowerBuilder has updated your library list in the project (assuming you've got the project open in the project painter). Just hit Deploy again to start the build. Remember to hit Save before you close the painter, or else you'll go through the same dance next time.</p> <p>Good luck,</p> <p>Terry.</p>
How do I write a query that outputs the row number as a column? <p>How do I write a query that outputs the row number as a column? This is DB2 SQL on an iSeries.</p> <p>eg if I have</p> <p>table Beatles:</p> <pre><code>John Paul George Ringo </code></pre> <p>and I want to write a statement, without writing a procedure or view if possible, that gives me</p> <pre><code>1 John 2 Paul 3 George 4 Ringo </code></pre>
<pre><code>SELECT ROW_NUMBER() OVER (ORDER BY beatle_name ASC) AS ROWID, * FROM beatles </code></pre>
Open File Dialogue box in JavaScript <p>how can I get an "open file dialogue" box in JavaScript? ::)</p> <p><strong>Edit:</strong> </p> <p>Duplicate of <a href="http://stackoverflow.com/questions/408735/javascript-file-uploads">JavaScript file uploads</a> by the same person.</p>
<p>Javascript cannot open files. (Leastways not in any cross browser secure way).</p> <p>Possibly you'd be interested in <code>&lt;input type="file" /&gt;</code> (an intro <a href="http://www.cs.tut.fi/~jkorpela/forms/file.html" rel="nofollow">here</a>).</p>
How to unregister an event handler in Internet Explorer 6? <p>I am registering a function with the onload method of a html form, I need to unregister this event hander function on unload of the form. How do I do it in Internet Explorer 6?</p>
<p>if you have added the onload in your HTML or via JavaScript</p> <pre><code>&lt;form onload="blah()"&gt; </code></pre> <p>or</p> <pre><code>myForm.onload = blah; </code></pre> <p>then</p> <pre><code>myForm.onload = null; </code></pre> <p>should do it<br /> if you've used attachEvent</p> <pre><code>myForm.attachEvent( 'onload', blah ); </code></pre> <p>use</p> <pre><code>myForm.detachEvent( 'onload', blah ); </code></pre> <p><strong>EDIT</strong><br /> I'm not sure forms have onload events tho, are you sure?</p>
Is this a bug in string.TrimEnd? <pre><code>"\u4000\f".TrimEnd(new char[0]) </code></pre> <p>is equal to <code>"\u4000"</code>. </p> <p>I am passing an empty array, so according to the MSDN documentation nothing should be removed and <code>"\u4000\f"</code> should be returned. Is there a reason for this behaviour?</p> <p>EDIT: Clarified expected behaviour</p> <p>EDIT: Apparently, this changed in 3.5, I was looking at the 2.0 documentation page.</p>
<p>the documentation says "If trimChars is null (Nothing in Visual Basic) or an <em>empty array</em>, white-space characters are removed instead. "<br /> So no, not a bug.</p>
ASP.NET MVC application controller constructor problem <p>I've created an application controller abstract class that my controllers derive from (As described in the following <a href="http://www.asp.net/Learn/mvc/tutorial-13-cs.aspx" rel="nofollow">article</a>)</p> <p>The following is an example of what my code looks like</p> <pre><code>public abstract class ApplicationController : Controller { private ProjectDataContext datacontext = new ProjectDataContext(); protected ProjectDataContext DataContext { get { return datacontext; } } public ApplicationController() { ViewData["OpenTasks"] = DataContext.Tasks.Where(t =&gt; t.UserId == this.UserId).Count(); } } </code></pre> <p>This produces the following error which i have determined is due to the "Where" lamda expression:</p> <p><strong><em>If the controller doesn't have a controller factory, ensure that it has a parameterless public constructor.</em></strong></p> <p>this error is produced whichever way i write the LINQ query and the only way to compile the application is by removing the "Where" clause as follows. </p> <pre><code>ViewData["OpenTasks"] = DataContext.Tasks.Count(); </code></pre> <p>any ideas what the problem is or how to resolve this as i need to execute the query against the user and not return all entries.</p> <p>thanks in advance</p>
<p>Try this instead of using the constructor:-</p> <pre><code>public abstract class ApplicationController : Controller { private ProjectDataContext datacontext = new ProjectDataContext(); protected ProjectDataContext DataContext { get { return datacontext; } } protected override void Initialize(System.Web.Routing.RequestContext requestContext) { base.Initialize(RequestContext); ViewData["OpenTasks"] = DataContext.Tasks.Where(t =&gt; t.UserId == this.UserId).Count(); } } </code></pre> <p>Its quite likely that the current user ID is dependand on the RequestContext</p>
Localization of a WinForms app and later UI changes <p>I am using VS2008 to develop a WinForms 2.0 application. I have read about how to localize my app in the Visual Studio by setting the Localizable property to true in the designer etc.</p> <p>I would like to ask about your experience, how does it work when I translate the app into several languages and then make changes to the user interface. For example, I add some buttons, delete some other controls from a form etc. I know it isn't best practice, but sometimes I have to localize the app in the middle of development and then continue to add new features. Does it all work or will I end with some corrupted resource files or such?</p> <p>The reason I am asking is that I had used Borland C++ Builder before, which had big problems when I changed UI in an already localized app.</p>
<p>I've never heard of editing localized forms causing problems, after answering questions for 3 years in the MSDN Windows Forms forum. Microsoft isn't Borland.</p>
How to get jquery ui tabs working? <p>At <a href="http://docs.jquery.com/UI/Tabs#Example" rel="nofollow">http://docs.jquery.com/UI/Tabs#Example</a> there is a short HTML example of how to use JQuery UI Tabs.</p> <ul> <li>I put the HTML in a local index.htm file.</li> <li>I downloaded all the CSS and Javascript files, and saved them in local files:</li> <li>but the closest I can get is the same example without any color in the tabs.</li> <li>I've looked around for images, etc. but can't find any.</li> <li>I can even have everything local EXCEPT the CSS file which I get off their server and THEN it works, so it is something in the CSS file that I'm not getting.</li> </ul> <p>What am I not copying locally that the online CSS file has? Has anyone gotten this JQuery UI Tabs to work and have a zip file that works locally?</p>
<p>If your problem is that everything seems to run but the DIVs do not disappear as they should then you have probably run into the same problem I did.</p> <p>You need to define the class .ui-tabs-hide so that it hides the element. Basically jQuery uses this to hide the elements, rather than doing it manually with display: none. The reason for this is so that it doesn't mess with your display's default setting, which could be block, inline or anything. By adding and removing the class it gives you a more control.</p> <pre><code>.ui-tabs-hide { display: none } </code></pre>
"SelectAll" checkbox not working when back button on the browser is clicked <p>I have the following html page:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;script&gt; var check = 0; function doNow() { void(d=document); void(el=d.getElementsByTagName('INPUT')); for(i=0;i&lt;el.length;i++) { if(check == 0) void(el[i].checked=1) else void(el[i].checked=0) } if(check == 0) check = 1; else check = 0; } &lt;/script&gt; &lt;HR&gt; &lt;form&gt; &lt;INPUT TYPE="CHECKBOX" name="DG1"&gt;DG1 &lt;INPUT TYPE="CHECKBOX" name="DG2"&gt;DG2 &lt;INPUT TYPE="CHECKBOX" name="DG3"&gt;DG3 &lt;INPUT TYPE="CHECKBOX" name="DG4"&gt;DG4 &lt;INPUT TYPE="CHECKBOX" name="DG5"&gt;DG5 &lt;input type=button onclick="doNow()" value="CheckBox All Now"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>If "CheckBox All Now" is clicked all checkboxes are checked. Then, if "Back" button or "Refresh" button is pressed. The "CheckBox All now" has to clicked twice to uncheck all checkboxes.</p> <p>Please let me know how to handle "CheckBox All Now" in case of "Refresh" or "Back".</p> <p>Thanks in Advance, Mahesh.</p>
<p>It's because when the page is reloaded, the Javascript is parsed and your declaration </p> <pre><code>var check = 0; </code></pre> <p>unsurprisingly causes the check variable to be reset to zero at this point. Thus after the page is reinitialised, the first click of the button will enable all checkboxes. It seems that the issue here stems from a difference in how the form renderer remembers state, and how the Javascript engine remembers "state". The latter can't really be "fixed" the way you want as the script essentially needs to be run every time.</p> <p>What you might choose to do is pull the initial "checked" state out of the controls themselves. Your current code explicitly assumes that the checkboxes will all be unchecked initially (this is basically what you're saying by "check = 0"; this variable is storing the state of the checkboxes as far as the Javascript is aware). Instead, you might change the line to:</p> <pre><code>var check = document.getElementsByTagName('INPUT')[0].checked; </code></pre> <p>Of course, this wouldn't work in the current location as it is declared before the form is defined. You would either need to register this as a closure to be run once the document has loaded, or alternatively pull this line out and put it in &lt;script&gt; tags that occur after the form element in the document (this isn't the cleanest way to do it but works for quick-and-dirty development; registration of functions within the head is the way to go in general).</p> <p>I've tested both approaches and they work. I'm sure that there will be other potential solutions to this issue that come up with other peoples' answers!</p> <p><strong>EDIT</strong>: Big edit after thinking about this for a while. The fundamental issue here is that the <code>check</code> variable gets out-of-sync with the actual checkboxes themselves - what I described above is a way to avoid this when the page is reloaded/reinitialised.</p> <p>However, you will still have other issues. What happens if the user manually clicks all of the checkboxes? They will now be active, but your check variable will still be <strong>0</strong>, and so click the "check all" button will activate them all (which will have no effect). If I clicked this button with all checkboxes checked, I would expect it to behave consistently, regardless of how those checkboxes got to that state (which should be irrelevant).</p> <p>Also, what happens if some of your checkboxes are checked and some are unchecked? What is the button <em>meant</em> to do in that situation?</p> <p>The best solution overall would probably be to remove the <code>check</code> variable altogether, and instead work it out on demand at thstart of every <code>doNow</code> call. That is, inspect the array of checkboxes, read their current values and from this derive what the checkboxes should be set to. (This might be really simply if, for example, the functionality turns out to be that every checkbox should simply be individually inverted - it depends on the actual functional requirements.)</p> <p>(Also, as a coding style issue, the part of your code that says</p> <pre><code> if(check == 0) void(el[i].checked=1) else void(el[i].checked=0)</code></pre> <p>can simply be replaced by</p> <pre><code>el[i].checked = (1 - check);</code></pre> <p>and asides from the fact that we're hopefully getting rid of this variable, it ought to be a boolean rather than an integer as it only has two states.)</p>
Is it alright to add custom Html attributes? <p>I have a site I'm working on where I want to mark if a row of data has been changed. If something has been changed in that row I would mark it with a custom attribute like so.</p> <pre><code>&lt;tr&gt; &lt;td isDirty="true"&gt; ....row data &lt;td&gt; &lt;/tr&gt; </code></pre> <p>This works great with jQuery and it doesn't add to much code to my page.</p> <p>But is this really the correct way of doing something like this and what are the downsides?</p> <p>I guess another way of doing this would be like this, but it seems like over kill.</p> <pre><code>&lt;tr&gt; &lt;td&gt; ....row data &lt;input id="isDirty" type="hidden" value="true" /&gt; &lt;td&gt; &lt;/tr&gt; </code></pre>
<p>Why don't you use the jQuery data capability?</p> <p>Your example will be (I don't know the condition to select proper td):</p> <pre><code>$("tr td").data("isDirty", true); </code></pre> <p>take a look at <a href="http://docs.jquery.com/Core/data#name">documentation</a></p>
How to configure Tomcat to use Windows NTLM authentication? <p>I would like to use NTLM authentication with Tomcat so that Iexplorer send automatically both the user id+pwd to webapp. Is this possible? </p> <p>With "BASIC" authentication IE pops up the usual pwd dialog but I want to skip this dialog. ( Note, I use JNDIReal/ldap)</p>
<p>Yes, it's now possible with Waffle Tomcat Authenticator that supports Negotiate (NTLM v1, v2, etc., and Kerberos).</p> <ul> <li>Tutorial: <a href="http://code.dblock.org/ShowPost.aspx?id=103" rel="nofollow">http://code.dblock.org/ShowPost.aspx?id=103</a></li> <li>Waffle: <a href="http://dblock.github.io/waffle/" rel="nofollow">http://dblock.github.io/waffle/</a></li> </ul> <p>Waffle works on <strong>windows server only</strong></p>
Has anyone used smartwin (a Windows C++ GUI OS library)? <p>I am considering using <a href="http://smartwin.sourceforge.net/" rel="nofollow">smartwin</a> for a Windows platform only C++ project but notice that there has not been a release for 18months since 2.0rc5 was released i.e. it appears that it is no longer maintained.</p> <p>After playing with it seems pretty good, I like it's use of templates, signals/slots (via boost) and it will meet the project needs but I would like some experiences of other users who are currently using it to help me weight it up?</p>
<p>Have you looked at <a href="http://en.wikipedia.org/wiki/Qt_%28toolkit%29" rel="nofollow">Qt</a> instead? I think it has a lot of the features you're looking for, and would be <em>much</em> better supported, both in developer tools and framework maturity.</p>
Shell script user prompt/input <p>This is a crude korn shell script that someone else wrote. I don't know much about using shell syntax and I'm not even sure if this is possible.</p> <p>Is there any way for me to run this file and be prompted for the date so that I don't have to manually go into the script and change it each time?</p> <p>For example, I wan to replace the "1/12/09" with a variable that is taken from a user prompt.</p> <pre><code>#!/bin/ksh ./clear_old ./rooms_xls.pl 1/12/09 cd doors ./doors_xls.pl 1/12/09 </code></pre>
<p>If you want to be prompted (as opposed to passing the date in as a parameter), use the following logic (or something similar):</p> <pre><code>date= while [ -z $date ] do echo -n 'Date? ' read date done </code></pre> <p>That loop will continue to prompt for the date until the user enters something (anything) other than a simple RETURN.</p> <p>If you want to add some simple validation, and you're using a version of KSH that's KSH93 or better, do something like this:</p> <pre><code>date= while [ -z $date ] do echo -n 'Date? ' read date if [[ $date =~ ^[0-9]{1,2}/[0-9]{1,2}/[0-9]{1,4}$ ]] then break fi date= done </code></pre> <p>See <a href="http://docs.oracle.com/cd/E23824_01/html/821-1461/ksh93-1.html#scrolltoc" rel="nofollow">the ksh93 man page</a> for more info.</p>
Does anyone have any useful resources to share or tips to offer for developing a MUD? <p>As a hobby project I am trying to create a ROM (Diku-Merc based) derivative. (Now defunct) I would appreciate it if anybody has done something similar and has some useful resources to share or tips to offer. I'm finding that a lot the resources such as mailing lists are no longer active and many links are dead.</p> <p>I've picked ROM because that is what I am familiar as a player, but the source is more complicated than anything I have come across and I wouldn't mind picking a code base that was easier to understand. Any recommendations before I dive in in earnest would also be appreciated. </p> <p>As for mudding communities in general I don't know of much beyond the <a href="http://www.mudconnect.com/">mud connector </a>because I've always been in more of a user/player role than developer. A forgiving and active place where I can get answers to my questions is what I value most.</p>
<p>After extensive research I've decided to go with a <a href="http://www.tbamud.com/">tba</a> code base. I may elaborate later but very broadly</p> <ul> <li>Coding experience is more important than experience as a player and this has convinced me to abandon my roots. I wanted a well documented, reasonably modern, managable code base undergoing active development and this seems to fit the bill.</li> </ul> <p>Anyways muds are truly a labour of love and you have to have a few screws loose if you plan to run one. Moreover the glory days have passed (it seems like there many muds shut down en masse around 2000) and in my opinion the community is largely inactive and fragmented. An exerpt from from some of the tba docs sums this up nicely:</p> <blockquote> <p>So, you're sure you want to run your own MUD? If you're already an old hand at playing MUDs and you've decided you want to start one of your own, here is our advice: sleep on it, try several other MUDs first. Work your way up to an admin position and see what running a MUD is really about. It is not all fun and games. You actually have to deal with people, you have to babysit the players, and be constantly nagged about things you need to do or change. Running a MUD is extremely time consuming if you do it well, if you are not going to do it well then don't bother. Just playing MUDs is masochistic enough, isn't it? Or are you trying to shave that extra point off your GPA, jump down that one last notch on your next job evaluation, or get rid of that pesky Significant Other for good? If you think silly distractions like having friends and seeing daylight are preventing you from realizing your full potential in the MUD world, being a MUD Administrator is the job for you.</p> </blockquote> <p>Anyways I don't have any high hopes for success, but this is something I will find interesting, improve my code-fu and will keep me busy for many years to come :D</p>
How to see SOAP data my client application sends? <p>I have a project where I have created web service proxy classes with wsdl.exe and then simply create an instance of that class (inherits System.Web.Services.Protocols.SoapHttpClientProtocol) and call the method that should send a SOAP message. I'm using Visual Studio 2008 if that matters. And I'm trying this in my development machine without access to actual web service that is located inside of customer's intranet. So, the sending will of course not succeed and I will not get any response back but all I would like to see is the exact content of SOAP messages this solution creates and tries to send. How do I see that?</p>
<p>Use <a href="http://www.fiddler2.com/fiddler2/" rel="nofollow">fiddler</a>.</p>
What are some best practices / conventions / guidelines for ASP.NET or C#? <p>Long ago I read a great book on C# and Visual Basic best practices:</p> <p><em>Practical Guidelines and Best Practices for Microsoft Visual Basic and Visual C# Developers</em> by Francesco Balena, Giuseppe Dimauro</p> <p><img src="http://www.dotnet2themax.com/Books/PracticalGuidelines_Cover.gif" alt="alt text" /></p> <p>This book was very helpful to me in its time, which dates back to ASP.NET 1.1. Please list some current best practices for ASP.NET, C#, and Visual Basic. And if you've read the book, what are some best practices or guidelines within it that you feel have been outdated?</p>
<p>For C# and .Net in general I'd highly recommend picking up Krzysztof Cwalina and Brad Adams' book "<a href="http://rads.stackoverflow.com/amzn/click/0321545613" rel="nofollow">Framework Design Guidelines</a>". That book along with running my code against FxCop and the ReSharper Code Analysis has really helped me keep my code clean and lean</p>
Can a VBA function in Excel return a range? <p>I seem to be getting a type mismatch error when trying to do something like this:</p> <p>In new workbook:</p> <pre><code>A1 B1 5 4 Function Test1() As Integer Dim rg As Range Set rg = Test2() Test1 = rg.Cells(1, 1).Value End Function Function Test2() As Range Dim rg As Range Set rg = Range("A1:B1") Test2 = rg End Function </code></pre> <p>Adding =Test1() should return 5 but the code seems to terminate when returning a range from test2(). Is it possible to return a range?</p>
<p>A range is an object. Assigning objects requires the use of the SET keyword, and looks like you forgot one in your Test2 function:</p> <pre><code>Function Test1() As Integer Dim rg As Range Set rg = Test2() Test1 = rg.Cells(1, 1).Value End Function Function Test2() As Range Dim rg As Range Set rg = Range("A1:B1") Set Test2 = rg '&lt;-- Don't forget the SET here' End Function </code></pre>
Function pointer to class member function problems <p>First of all I have to admit that my programming skills are pretty limited and I took over a (really small) existing C++ OOP project where I try to push my own stuff in. Unfortunately I'm experiencing a problem which goes beyond my knowledge and I hope to find some help here. I'm working with a third party library (which cannot be changed) for grabbing images from a camera and will use some placeholder names here. </p> <p>The third party library has a function "ThirdPartyGrab" to start a continuous live grab and takes a pointer to a function which will be called every time a new frame arrives. So in a normal C application it goes like this:</p> <pre><code>ThirdPartyGrab (HookFunction); </code></pre> <p>"HookFunction" needs to be declared as: </p> <pre><code>long _stdcall HookFunction (long, long, void*); </code></pre> <p>or "BUF_HOOK_FUNCTION_PTR" which is declared as</p> <pre><code>typedef long (_stdcall *HOOK_FUNCTION_PTR) (long, long, void*); </code></pre> <p>Now I have a C++ application and a class "MyFrameGrabber" which should encapsulate everything I do. So I put in the hook function as a private member like this:</p> <pre><code>long _stdcall HookFunction (long, long, void*); </code></pre> <p>Also there is a public void function "StartGrab" in my class which should start the Grab. Inside I try to call:</p> <pre><code>ThirdPartyGrab (..., HookFunction, ...); </code></pre> <p>which (not surprisingly) fails. It says that the function call to MyFrameGrabber::HookFunction misses the argument list and I should try to use &amp;MyFrameGrabber::HookFunction to create a pointer instead. However passing "&amp;MyFrameGrabber::HookFunction" instead results in another error that this cannot be converted to BUF_HOOK_FUNCTION_PTR. </p> <p>After reading through the <a href="http://www.parashift.com/c++-faq-lite/pointers-to-members.html" rel="nofollow">C++ FAQ function pointers</a> I think I understand the problem but can't make up a solution. I tried to make the hook function static but this also results in a conversion error. I also thought of putting the hook function outside of the class but I need to use class functions inside the hook function. Is there another way or do I need to change my whole concept? </p> <p>EDIT 14.01.08: I tested the singleton workaround since I cannot change the third party library and the void pointer is only for data that is used inside the hook function. Unfortunately it didn't worked out of the box like I hoped.... I don't know if the static function needs to be in a separate class so I put it in my "MyFrameGrabber" class:</p> <pre><code>static MyFrameGrabber&amp; instance() { static MyFrameGrabber _instance; return _instance; } long Hook(long, long, void*); // Implementation is in a separate cpp file </code></pre> <p>In my cpp file I have the call_hook function:</p> <pre><code>long MFTYPE call_hook(long x, MIL_ID y, void MPTYPE *z) { return MyFrameGrabber::instance().Hook(x,y,z); } void MyFrameGrabber::grab () { ThirdPartyGrab(..., call_hook, ...); } </code></pre> <p>But this gives me an error in <code>static MatroxFrameGrabber _instance;</code> that no matching standard constructor is found. That's correct because my MyFrameGrabber constructor looks like this:</p> <pre><code>MyFrameGrabber (void* x, const std::string &amp;y, int z, std::string &amp;zz); </code></pre> <p>I tried to put in an empty constructor <code>MyFrameGrabber();</code> but this results in a linker error. Should I pass empty parameters to the MyFrameGrabber constructor in the singleton? Or do I need to have a separate Hook Class and if yes how could I access MyFrameGrabber functions? Thanks in advance. </p> <p>SECOND EDIT 15.01.08: I applied the changes and it compiles and links now. Unfortunately I cannot test this at runtime yet because it's a DLL and I have no Debug Caller Exe yet and there are other problems during initialization etc. I will mark the post as answer because I'm sure this is the right way to do this.</p>
<p>Your private member method has an implicit <code>this</code> pointer as first argument. If you write that out, it's obvious that the function signatures do not match.</p> <p>You need to write a static member function, which can be passed as the callback-function to the library. The last argument to the <code>HookFunction</code>, a <code>void*</code>, looks to me very much like a cookie, where one can pass ones own pointer in.</p> <p>So, all in all, it should be something like this:</p> <pre> class MyClass { long MyCallback(long, long) { // implement your callback code here } static long __stdcall ThirdPartyGrabCallback(long a, long b, void* self) { return reinterpret_cast&lt;MyClass*&gt;(self)->MyCallback(a, b); } public: void StartGrab() { ThirdPartyGrab(..., &MyClass::ThirdPartyGrabCallback, ..., this, ...); } }; </pre> <p>This of course only works if the <code>void*</code> argument is doing what I said. The position of the <code>this</code> in the <code>ThirdPartyGrab()</code> call should be easy to find when having the complete function signature including the parameter names available.</p>
best way to programmatically modify excel spreadsheets <p>I'm looking for a library that will allow me to programatically modify Excel files to add data to certain cells. My current idea is to use named ranges to determine where to insert the new data (essentially a range of 1x1), then update the named ranges to point at the data. The existing application this is going to integrate with is written entirely in C++, so I'm ideally looking for a C++ solution (hence why <a href="http://stackoverflow.com/questions/292551/modifying-excel-spreadsheet-with-net">this thread</a> is of limited usefulness). If all else fails, I'll go with a .NET solution if there is some way of linking it against our C++ app.</p> <p>An ideal solution would be open source, but none of the ones I've seen so far (<a href="http://myxls.in2bits.org/">MyXls</a> and <a href="http://members.wibs.at/herz/xlsstream/www/index.html">XLSSTREAM</a>) seem up to the challenge. I like the looks of <a href="http://www.aspose.com/categories/file-format-components/aspose.cells-for-.net-and-java/default.aspx">Aspose.Cells</a>, but it's for .NET or Java, not C++ (and costs money). I need to support all Excel formats from 97 through the present, including the XLSX and XLSB formats. Ideally, it would also support formats such as OpenOffice, and (for output) PDF and HTML.</p> <p>Some use-cases I need to support:</p> <ul> <li>reading and modifying any cell in the spreadsheet, including formulas</li> <li>creating, reading, modifying named ranges (the ranges themselves, not just the cells)</li> <li>copying formatting from a cell to a bunch of others (including conditional formatting) -- we'll use one cell as a template for all the others we fill in with data.</li> </ul> <p>Any help you can give me finding an appropriate library would be great. I'd also like to hear some testimonials about the various suggestions (including the ones in my post) so I can make more informed decisions -- what's easy to use, bug-free, cheap, etc?</p>
<p>The safest suggestion is to just use OLE. It uses the COM, which does not require .NET at all.</p> <p><a href="http://en.wikipedia.org/wiki/OLE_Automation" rel="nofollow">http://en.wikipedia.org/wiki/OLE_Automation</a> &lt;--about halfway down is a C++ example.</p> <p>You may have to wrap a few functionalities into functions for usability, but it's really not ugly to work with.</p> <p>EDIT: Just be aware that you need a copy of Excel for it to work. Also, there's some first-party .h files that you can find specific to excel. (it's all explained in the Wikipedia article)</p>
How do you create a JavaScript Date object with a set timezone without using a string representation <p>I have a web page with three dropdowns for day, month and year. If I use the JavaScript Date constructor that takes numbers then I get a Date object for my current timezone:</p> <pre><code>new Date(xiYear, xiMonth, xiDate) </code></pre> <p>Give the correct date but it thinks that date is GMT+01:00 due to daylight savings time.</p> <p>The problem here is that I then give this Date to an Ajax method and when the date is deserialised on the server it has been converted to GMT and so lost an hour which moves the day back by one. Now I could just pass the day, month, and year individually into the Ajax method but it seems that there ought to be a better way.</p> <p>The accepted answer pointed me in the right direction, however just using <code>setUTCHours</code> by itself changed:</p> <pre><code>Apr 5th 00:00 GMT+01:00 </code></pre> <p>to</p> <pre><code>Apr 4th 23:00 GMT+01:00 </code></pre> <p>I then also had to set the UTC date, month and year to end up with</p> <pre><code>Apr 5th 01:00 GMT+01:00 </code></pre> <p>which is what I wanted</p>
<p>using <code>.setUTCHours()</code> it would be possible to actually set dates in UTC-time, which would allow you to use UTC-times throughout the system.</p> <p><strike>You cannot set it using UTC in the constructor though, unless you specify a date-string.</strike></p> <p>Using <code>new Date(Date.UTC(year, month, day, hour, minute, second))</code> you can create a Date-object from a specific UTC time.</p>
How can I mix COUNT() and non-COUNT() columns without losing information in the query? <p>I started with a query:</p> <pre><code>SELECT strip.name as strip, character.name as character from strips, characters, appearances where strips.id = appearances.strip_id and characters.id = appearances.character.id and appearances.date in (...) </code></pre> <p>Which yielded me some results:</p> <pre><code>strip | character 'Calvin &amp; Hobbes' | 'Calvin' 'Calvin &amp; Hobbes' | 'Hobbes' 'Pearls Before Swine' | 'Pig' 'Pearls Before Swine' | 'Rat' 'Pearls Before Swine' | 'Hobbes' # a guest appearance 'Pearls Before Swine' | 'Calvin' # a guest appearance </code></pre> <p>Then I wanted to also get the <code>COUNT</code> of the number of times a character is used (in any strip) within the result set. So I tried:</p> <pre><code>SELECT count(character.id), strip.name as strip, character.name as character from strips, characters, appearances where strips.id = appearances.strip_id and characters.id = appearances.character.id and appearances.date in (...) </code></pre> <p>But that gave me</p> <pre><code>[ERROR 11:20:17] Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause </code></pre> <p>So I tried:</p> <pre><code>SELECT count(character.id), strip.name as strip, character.name as character from strips, characters, appearances where strips.id = appearances.strip_id and characters.id = appearances.character.id and appearances.date in (...) group by character.id </code></pre> <p>Which gave me</p> <pre><code>count | strip | character 4 | 'Calvin &amp; Hobbes' | 'Calvin' 4 | 'Calvin &amp; Hobbes' | 'Hobbes' 2 | 'Pearls Before Swine' | 'Pig' 2 | 'Pearls Before Swine' | 'Rat' </code></pre> <p>That is, I lose all the extra information about exactly which characters appear in which strips.</p> <p>What I'd like to get is this:</p> <pre><code>count | strip | character 4 | 'Calvin &amp; Hobbes' | 'Calvin' 4 | 'Calvin &amp; Hobbes' | 'Hobbes' 2 | 'Pearls Before Swine' | 'Pig' 2 | 'Pearls Before Swine' | 'Rat' 4 | 'Pearls Before Swine' | 'Calvin' 4 | 'Pearls Before Swine' | 'Hobbes' </code></pre> <p>But I can't seem to figure it out. I'm on MySQL if it matters. Perhaps it'll just take two queries.</p>
<p>Does mySQL support analytic functions? Like:</p> <pre><code>SELECT foo.bar, baz.yoo, count(baz.yoo) over (partition by foo.bar) as yoo_count from foo, bar where foo.baz_id = baz.id and baz.id in (...) </code></pre> <p>Alternatively:</p> <pre><code>SELECT foo.bar, baz.yoo, v.yoo_count from foo, bar, ( select foo.baz_id, count(*) as yoo_count from foo group by foo.baz_id ) as v where foo.baz_id = baz.id and baz.id in (...) and v.baz_id = foo.baz_id; </code></pre>
Fixing the timezone on Solaris 10 <p>I have no ideas how to fix this. In my /etc/TIMEZONE file the TZ variable has the correct value (Canada/Eastern) and still it's showing a -1 hour lag. Where else should I be looking?</p>
<p>You should check what your hardware clock is. I would suggest doing this:</p> <ul> <li>Set the UTC time correctly. i.e. (5 AM in the example):</li> </ul> <p>$ date -u -s "05:00"</p> <p>Thursday, April 29, 2010 05:00:00 AM UTC</p> <ul> <li>Set the hardware clock accordingly (tod for SPARC and rtc for x86):</li> </ul> <p>$ rtc -c (the '-c' argument sets the DST correctly)</p> <ul> <li>Check the date again:</li> </ul> <p>$ date</p> <p>Thursday, April 29, 2010 02:00:11 AM ART</p> <p>Regards,</p> <p>Leandro.</p>
Visual Source Safe Version 8 <p>My issue is that when I check a project out of SS I sometimes do not get the latest version of the project, and when I check a project into SS the .frx files are corrupt.</p>
<p>Are you tied to SS? Can you not use a more modern repository? Subversion would be a good start. Getting that started is very easy to do, a lot easier than I think people think.</p> <p>If not, then you have to run a tool to find out what the corruption is and then try to clean it or reset it. You may also check the server time as sometimes that caused problems. The server time should be the same as the development machines I believe. </p>
T-SQL: Selecting rows to delete via joins <p>Scenario:</p> <p>Let's say I have two tables, TableA and TableB. TableB's primary key is a single column (BId), and is a foreign key column in TableA.</p> <p>In my situation, I want to remove all rows in TableA that are linked with specific rows in TableB: Can I do that through joins? Delete all rows that are pulled in from the joins?</p> <pre><code>DELETE FROM TableA FROM TableA a INNER JOIN TableB b ON b.BId = a.BId AND [my filter condition] </code></pre> <p>Or am I forced to do this:</p> <pre><code>DELETE FROM TableA WHERE BId IN (SELECT BId FROM TableB WHERE [my filter condition]) </code></pre> <p>The reason I ask is it seems to me that the first option would be much more effecient when dealing with larger tables.</p> <p>Thanks!</p>
<pre><code>DELETE TableA FROM TableA a INNER JOIN TableB b ON b.Bid = a.Bid AND [my filter condition] </code></pre> <p>should work</p>