input
stringlengths
51
42.3k
output
stringlengths
18
55k
How do I make an onclientclick post back using jquery? asp.net <p>I need help. I want to recreate the the update panel postback without using a update panel to do the postback. What is the generic method for doing this?</p> <p>For example, on stackoverflow, when you vote up or down on a question it does a postback to update the database and I would bet they didn't use an update panel.</p> <p>What do I have?</p> <p>I have a table with table data. When I click on the "td" item as a whole column, I want to do a update to the database and also update a gridview on the page it self. The gridview shows all the currently clicked items in the table because it was updated via "our method"...</p> <p>Please help, looking for a good generic method I could use for a lot of async postbacks without update panel.</p> <p>Looking for a good tutorial of some sorts?</p> <p>Thanks guys. Scott.</p>
<p>The way that Stack Overflow works differs in two important ways from that CodeProject article.</p> <ul> <li><p>Stack Overflow is making its AJAX request against an ASP.NET MVC controller action, not a standalone ASPX page. You might consider this as the MVC analogue of an ASP.NET AJAX page method. In both cases, the ASPX method will lag behind in terms of performance.</p></li> <li><p>Stack Overflow's AJAX request returns a JSON serialized result, not arbitrary plaintext or HTML. This makes handling it on the client side more standardized and generally cleaner.</p></li> </ul> <p>For example: when I voted this question up an XmlHttpRequest request was made to /questions/171000/vote, with a "voteTypeId" of 2 in the POST data.</p> <p>The controller that handled the request added my vote to a table somewhere and then responded with this JSON:</p> <pre><code>{"Success":true,"NewScore":1,"Message":"","LastVoteTypeId":2} </code></pre> <p>Using that information, this JavaScript takes care of updating the client-side display:</p> <pre><code>var voteResult = function(jClicked, postId, data) { if (data.Success) { jClicked.parent().find("span.vote-count-post").text(data.NewScore); if (data.Message) showFadingNotification(jClicked, data.Message); } else { showNotification(jClicked, data.Message); reset(jClicked, jClicked); if (data.LastVoteTypeId) { selectPreviousVote(jClicked, data.LastVoteTypeId); } } }; </code></pre> <p>If you're using WebForms, the example of calling page methods that you found on my blog is definitely in the right ballpark.</p> <p>However, I would suggest that you consider a web service for any centralized functionality (like this voting example), instead of page methods. Page methods seem to be slightly easier to write, but they also have some reuse drawbacks and tend to provide an illusion of added security that isn't really there.</p> <p>This is an example of doing the same thing you found, but with web services (the comments on this post actually led to the post you found):</p> <p><a href="http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/">http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/</a></p>
Accepting client certificates from any CA <p>I am setting up support for users to sign in with client certificates. Unfortunately IIS refuses to acknowledge any certificate not chained to an installed CA (<a href="http://support.microsoft.com/kb/257587" rel="nofollow" title="Description of the Server Authentication Process During the SSL Handshake">see this article</a>).</p> <p>As the feature is implemented only for users´ convenience, it would be great to allow any client certificate. Is there any way to accomplish this?</p> <p>My server is running Windows Server 2003 and IIS 6, but the behaviour is no different on my IIS 7 running locally. If IIS 7 could be customized to support any client certificate, I would be able to change though (given no solution for IIS 6 is available).</p>
<p>I think the normal way is for you to issue the certificates to them, and then for you to set up IIS to accept your cert as a root.</p>
Any Substitute API for Win32API? <p>I need an API that can make menus like Win32API,<br> But something simpler and better than WinAPI.<br> That can make GUI, with text zones, buttons etc...like an average Windows program.(Windows GUI Style)<br> Can anyone recommand on one like it? Thanks.</p>
<p><a href="http://www.wxwidgets.org/" rel="nofollow">wxWidgets</a>:</p> <blockquote> <p>wxWidgets lets developers create applications for Win32, Mac OS X, GTK+, X11, Motif, WinCE, and more using one codebase. It can be used from languages such as C++, Python, Perl, and C#/.NET. Unlike other cross-platform toolkits, wxWidgets applications look and feel native. This is because wxWidgets uses the platform's own native controls rather than emulating them. It's also extensive, free, open-source, and mature. </p> </blockquote>
Autostart spring app <p>So is there a way to initialize and start a command line Spring app without writing a main method. It seems like all such main methods have the same form</p> <pre><code>public static void main(final String[] args) throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("context.xml", Boot.class); FooService fooService = (FooService) ctx.getBean("fooService"); fooService.bar(); } </code></pre> <p>I suppose that's not complicated, but has someone found a way to provide a way to just specify the <code>context.xml</code> at the command line or, better yet, in a manifest file?</p> <p>The goal here is to simplify the creation of spring applications as executable jars. I hope that I can specify some utility class as the <code>Main-Class</code> in the manifest. I suppose I would also need to specify the starting point for the app, a bean and a method on it where begins the process.</p>
<p>I'll try to answer the question as I understand it: </p> <blockquote> <p>How to package a jar containing a spring configuration such as I just need to use <code>java -jar myjar.jar</code>?</p> </blockquote> <p>The code snippet you have in your question simply works. You don't have to parameterise the <code>context.xml</code>. You just need to bundle your code and its dependencies (spring, etc.) in a single jar with a proper manifest entry for the main class in a jar file.</p> <p>I personaly use <a href="http://maven.apache.org" rel="nofollow">maven 2</a> and here is a <a href="http://maven.apache.org/pom.html" rel="nofollow">pom.xml</a> I would use that do just that:</p> <pre><code>&lt;project&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.stackoverflow&lt;/groupId&gt; &lt;artifactId&gt;stackoverflow-autostart-spring-app&lt;/artifactId&gt; &lt;version&gt;0.1&lt;/version&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring&lt;/artifactId&gt; &lt;version&gt;2.5.2&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;archive&gt; &lt;manifest&gt; &lt;mainClass&gt;com.stackoverflow.spring.autostart.Autostart&lt;/mainClass&gt; &lt;/manifest&gt; &lt;/archive&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-shade-plugin&lt;/artifactId&gt; &lt;executions&gt; &lt;execution&gt; &lt;phase&gt;package&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;shade&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>This is assuming some package name for the java code, the source code being in the <code>src/main/java</code> directory and the file <code>context.xml</code> in the <code>src/main/resources</code> directory.</p> <p>So in this <code>pom.xml</code> there are several important points:</p> <ol> <li>the spring dependency (speaks for itself I believe)</li> <li>the configuration of the <a href="http://maven.apache.org/plugins/maven-jar-plugin/" rel="nofollow">maven jar plugin</a>, that adds the main class as a manifest entry</li> <li>the <a href="http://maven.apache.org/plugins/maven-shade-plugin/" rel="nofollow">maven shade plugin</a>, which is the plugin responsible for gathering all the dependencies/classes and packaging them into one single jar.</li> </ol> <p>The executable jar will be available at <code>target\stackoverflow-autostart-spring-app-0.1.jar</code> when running <code>mvn package</code>.</p> <p><strike>I have this code all working on my box but just realised that I can't attach a zip file here. Anyone know of place I could do so and link here?</strike></p> <p>I created a <a href="http://github.com/sleberrigaud/sof" rel="nofollow">git repository at github</a> with the code related to this question if you want to check it out.</p> <p>Hope this helps.</p>
PHP access to iTunes tags in an RSS feed <p>I need to get access to the iTunes tags in an RSS feed using PHP. I've used simplepie before for podcast feeds, but I'm not sure how to get the iTunes tags using it. Is there a way to use simplepie to do it or is there a better way?</p> <p><hr /></p> <p>Okay I tried Simple XML.</p> <p>All this (the code below) seems to work</p> <pre><code>$feed = simplexml_load_file('http://sbhosting.com/feed/'); $channel = $feed-&gt;channel; $channel_itunes = $channel-&gt;children('http://www.itunes.com/dtds/podcast-1.0.dtd'); $summary = $channel_itunes-&gt;summary; $subtitle = $channel_itunes-&gt;subtitle; $category = $channel_itunes-&gt;category; $owner = $channel_itunes-&gt;owner-&gt;name; </code></pre> <p>Now I need to get the itunes categories. The seem to be represented in several ways. In this case I get the follow XML:</p> <pre><code>&lt;itunes:category text="Technology"/&gt; &lt;itunes:category text="Technology"&gt; &lt;itunes:category text="Software How-To"/&gt; &lt;/itunes:category&gt; </code></pre> <p>I would expect to be able to get the category with something like this:</p> <pre><code>$category_text = $channel_itunes-&gt;category['text']; </code></pre> <p>But that does not seem to work.</p> <p>I've seen other ways to represent the category that I really don't know who to get.</p> <p>For example:</p> <p>Technology Business Education</p> <p>Is this a media thing or a itunes thing or both?</p> <p>Thanks For Your Help. G</p>
<p>This code works for me:</p> <pre><code>//$pie is a SimplePie object $iTunesCategories=$pie-&gt;get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES,'category'); if ($iTunesCategories) { foreach ($iTunesCategories as $iTunesCategory) { $category=$iTunesCategory['attribs']['']['text']; $subcat=$iTunesCategory['child']["http://www.itunes.com/dtds/podcast-1.0.dtd"]['category'][0]['attribs']['']['text']; if ($subcat) { $category.=":$subcat"; } //do something with $category } } </code></pre>
Which is fastest in PHP- MySQL or MySQLi? <p>I'd like to know if anyone has any first-hand experience with this dichotomy. A few blogs say the mysql extension is faster than mysqli. Is this true?</p> <p>And I'm only asking about speed. I know mysqli has features that are not present in the older extension.</p>
<p>The MySQL extension is very slightly faster than MySQLi in most benchmarks I've seen reported. The difference is so slight, however, that this should probably not be your criterion for deciding between the two.</p> <p>Other factors dwarf the difference in performance between mysql and mysqli. Using mod_php or FastCGI, a bytecode cache like APC, or using data caching judiciously to reduce database hits, are far more beneficial for overall performance of PHP scripts than the choice of MySQL extension.</p> <p>Don't be penny wise and pound foolish! :-)</p>
RegEx: Grabbing values between quotation marks <p>I have a value like this:</p> <pre class="lang-none prettyprint-override"><code>"Foo Bar" "Another Value" something else </code></pre> <p>What regex will return the values enclosed in the quotation marks (e.g. <code>Foo Bar</code> and <code>Another Value</code>)?</p>
<p>I've been using the following with great success:</p> <pre><code>(["'])(?:(?=(\\?))\2.)*?\1 </code></pre> <p>It supports nested quotes as well.</p> <p>For those who want a deeper explanation of how this works, here's an explanation from user <a href="http://stackoverflow.com/users/20713/ephemient">ephemient</a>:</p> <blockquote> <p>([""']) match a quote; ((?=(\?))\2.) if backslash exists, gobble it, and whether or not that happens, match a character; *? match many times (non-greedily, as to not eat the closing quote); \1 match the same quote that was use for opening.</p> </blockquote>
Getting 256 colors out of ruby-ncurses <p>I've got 256 colors working great in my terminal (<a href="http://www.frexx.de/xterm-256-notes/">test scripts here</a>), but it stops working when I use ncurses (via Ruby-ncurses). Printing the escape sequences given on that page works fine, but when I initialize ncurses 'puts' stops working and I can't output the colors with any of the various ncurses color changing/string output functions I've found. What gives?</p>
<p>I am not sure if this would be all the story, but make sure your terminal capabilities do indeed provide for the 256 colors description.</p> <p>What is the TERM environment variable value? Try setting it to xterm-256color and rerun it. ncurses should then get the proper color escape sequences.</p> <p>You can also test the terminal capabilities and terminal color output with the program we use at SXEmacs development:</p> <p><a href="http://www.triatlantico.org/tmp/tty-colors.c">http://www.triatlantico.org/tmp/tty-colors.c</a></p> <p>Compile with gcc -o tty-colors tty-colors.c -lncurses</p> <p>EDIT: Note that just because the scripts that are found on the net output the 256 colors, that is not "all set". Curses programs rely on terminfo and termcap and the TERM environment variable to find out how to interact with the terminal. So in order for a curses app to be able to use the 256 colors one should set the TERM variable to an existing terminal name which supports 256 colors. The C program above will show you <em>what</em> ncurses thinks about your terminal, not just output the xterm sequences like most scripts do [even the one from X.org]</p>
Best way to track page views <p>I'm working on a e-commerce system and I would like to track the product page views, but I'm not sure of the best way to do that... My boss suggested that I should count one view for the first time a user opens a product page and then store a cookie saying it was already viewed, but what if the user doesn't accept cookies? Another option would be to store the user's IP address, but what if a lot of different users in the same company opens the product pages? Just one view would be counted?</p> <p>Any suggestions?</p> <p>thanks!</p>
<p>Is this something you want to build into your application, or could you achieve your goal by simply using one of the free web log statistics tools? (Such as <a href="http://awstats.sourceforge.net/" rel="nofollow">AWStats</a>)</p> <p>There is a round-up of free tools <a href="http://www.hongkiat.com/blog/top-14-free-web-statistics-tools/" rel="nofollow">here</a>.</p>
Find out which remote branch a local branch is tracking <blockquote> <p><strong>See also:</strong><br> <a href="http://stackoverflow.com/questions/4950725/how-do-i-get-git-to-show-me-which-branches-are-tracking-what">how do I get git to show me which branches are tracking what?</a> </p> </blockquote> <p>How can I find out which remote branch a local branch is tracking?</p> <p>Do I need to parse git config output, or is there a command that would do this for me?</p>
<p>Here is a command that gives you the tracking branch:</p> <pre><code>$ git branch -vv main aaf02f0 [main/master: ahead 25] Some other commit * master add0a03 [jdsumsion/master] Some commit </code></pre> <p>You have to wade through the SHA and any long-wrapping commit messages, but it's quick to type and I get the tracking branches aligned vertically in the 3rd column.</p>
Is it possible to deploy an already built Drupal site? <p>I'm a Drupal newbie. Is it possible to set up everything and deploy Drupal on the server? I mean things like putting in the content, setting up the modules, etc..., then you put it all up to the production server?</p>
<p>Ofcourse. </p> <ul> <li>copy all the files</li> <li>edit the database credentials (sites/default/settings.php)</li> <li>export the database content via mysqldump or phpMyAdmin (supposing you use MySQL)</li> <li>import the database content at the target server</li> </ul> <p>I've done it a several times.</p>
Coming up to speed on the programming environment <p>I'm not a full-time software guy. In fact, in the last ten years, 90 % of my work was either on the hardware or doing low-level (embedded) code.</p> <p>But the other 10% involves writing shell scripts for development tools, making kernel changes to add special features, and writing GUI applications for end-users.</p> <p>The problem is that I find myself facing significant holes in my knowledge, often because it's been years since I've done "X", and I've either forgotten, or the environment has changed.</p> <p>Every so often, there are threads on TheDailyWTF.com along the lines of "WTF: the guy spent all day writing tons of code, when he could have called foobar() in library baz". I've been there myself, because I don't remember much beyond the #include &lt;stdio.h&gt; stuff (for example), and my quick search somehow missed the right library.</p> <p>What methods have you found effective to crash-learn and/or crash-refresh yourself in programming environments that you rarely touch?</p>
<ul> <li>Ask developers you know that work in the environment that you are interested in.</li> <li>Search the web a lot.</li> <li>Ask specific questions in relevant IRC channels (Freenode is great).</li> <li>Ask specific questions on StackOverflow and other sites.</li> </ul> <p>There really isn't any substitue for being "in the daily flow" of the programming environment in question. Having a good feel for the current state of the art is something you only get from experience, as I'm sure you can verify in you own areas of expertise.</p>
Greasemonkey: love it or hate it? <p>As users, we love the power of Greasemonkey. As developers, it can complicate things.</p> <p>Some <a href="http://dean.edwards.name/weblog/2005/03/ungreased/" rel="nofollow">people</a> advocate defensively disabling user scripts; others are willing to die to defend them.</p> <p>Is there a middle ground? How can we reduce the threat of an evolutionary arms race between users and unscrupulous advertisers?</p>
<p>Any control you think you have over which user agents your site visitors use is illusory. However, the vast majority will be using vanilla IE/Firefox/Safari. But, if you've a site where the audience has adopted a Greasemonkey script en masse, then treat that as a strong vote from your users that the site needs to change!</p>
Making locking easier in MTAs <p>In multi-threaded code, when an instance may be read or written by multiple threads, they need to be locked on to perform these operations safely.</p> <p>To avoid the repetition of creating an object to lock on and writing a bunch of lock statements through code, I've created a generic class to handle the locking. </p> <p>Am I missing anything, conceptually? This should work, right?</p> <pre><code>public class Locked&lt;T&gt; where T : new() { private readonly object locker = new object(); private T value; public Locked() : this(default(T)) { } public Locked(T value) { this.value = value; } public T Get() { lock (this.locker) { return this.value; } } public void Set(T value) { lock (this.locker) { this.value = value; } } } </code></pre> <p>And an example of it being used in a class:</p> <pre><code>private Locked&lt;bool&gt; stopWorkerThread = new Locked&lt;bool&gt;(); public void WorkerThreadEntryPoint() { while (true) { if (this.stopWorkerThread.Get()) { break; } </code></pre> <p>Also, how would I test something like this, in an automated way (e.g. create a unit test)?</p> <p>Lastly, what can I do to implement a ++ and -- operator, to avoid this:</p> <pre><code> this.runningThreads.Set(this.runningThreads.Get() + 1); </code></pre>
<p>That only locks for the duration of the get/set; of course, in many common cases this will be atomic anyway, simply due to to data size.</p> <p>However, in reality most locks need to span more than this, in the same way that collections locking over just the Add etc don't help much - a caller typically needs a single lock to span the "is it there? if so update, else add" sequence.</p> <p>For something as simple as a bool, "volatile" might solve the problem a lot more simply - especially if it is just for a loop exit.</p> <p>You might also want to consider [MethodImpl(MethodImplOptions.Synchronized)] - although personally I prefer a private lock object (like you have used) to prevent issues with external people locking on the object (the above uses "this" as the lock).</p> <p>For unit testing this, you'd need something to prove it broken first - which would be hard since the operations are so small (and already atomic for most data types). One of the other things it avoids (that volatile also fixes) is caching in a register, but again that is an optimisation and hard to force to prove it is broken.</p> <p>If you are interested in a lock-wrapper, you might consider existing code like <a href="http://www.yoda.arachsys.com/csharp/miscutil/usage/locking.html" rel="nofollow">this</a>.</p>
Interface "recursion" and reference counting <p>I have a small problem with interfaces. Here it is in Pseudo code :</p> <pre><code>type Interface1 = interface end; Interface2 = interface end; TParentClass = class(TInterfacedObject, Interface1) private fChild : Interface2; public procedure AddChild(aChild : Interface2); end; TChildClass = class(TInterfacedObject, Interface2) private fParent : Interface2; public constructor Create(aPArent : Interface1); end; </code></pre> <p>Can anyone see the flaw? I need the child to have a reference to it's parent, but the reference counting doesn't work in this situation. If I create a ParentClass instance, and add a child, then the parent class is never released. I can see why. How do I get round it?</p>
<p>A reference-counted reference has two semantics: it acts as a share of ownership as well as a means of navigating the object graph.</p> <p>Typically, you don't need <strong>both</strong> of these semantics on all links in a cycle in the graph of references. Perhaps only parents own children, and not the other way around? If that is the case, you can make the child references to the parent <em>weak links</em>, by storing them as pointers, like this:</p> <pre><code>TChildClass = class(TInterfacedObject, Interface2) private fParent : Pointer; function GetParent: Interface1; public constructor Create(aPArent : Interface1); property Parent: Interface1 read GetParent; end; function TChildClass.GetParent: Interface1; begin Result := Interface1(fParent); end; constructor TChildClass.Create(AParent: Interface1); begin fParent := Pointer(AParent); end; </code></pre> <p>This is safe if the root of the tree of instances is guaranteed to be kept alive somewhere, i.e. you are not relying on only keeping a reference to a branch of the tree and still being able to navigate the whole of it.</p>
Double buffer child controls in custom control (C#) <p>I want to double buffer a custom control which contains buttons. I have tried various ways to double buffer the control; SetStyle, BufferedGraphicsContext, and drawing to a bitmap. These all work fine for the custom drawing of the control, but none of them handle drawing the button to a back buffer. How do I achieve this?</p>
<p>Technically you can't, and you really shouldn't need to if they're standard .NET WinForms buttons.</p> <p>The buttons themselves control that through the protected DoubleBuffered property. The only way to access this would be to derive a new class from S.W.F.Button, and implement code to enable the DoubleBuffered property on instances of that class (I'd probably do that in the constructor). Finally, use objects of that new class on your form instead of S.W.F.Buttons. </p> <p>However, as I recall, buttons are purely drawn from WinAPI; they are not GDI+. As a result, you shouldn't <em>need</em> to double-buffer their drawing. That said, I don't know your usage scenario and I don't know what symptoms your app is displaying, so I could be wrong. :)</p> <p>You might consider checking out the book <a href="http://www.apress.com/book/view/9781590594391" rel="nofollow">Pro .NET 2.0 Windows Forms and Custom Controls in C#</a>. All of this was summarized from information in that book.</p>
Problem using the ASP.NET FileUpload control in an UpdatePanel? <p>I'm running into an issue where I have a FileUpload control in an UpdatePanel. When I attempt to save changes and upload the file, no file is found. If I remove the UpdatePanel everything seems to work fine. </p> <p>Any ideas why this might be happening? And is there a work-around?</p> <p><img src="http://farm4.static.flickr.com/3086/2914877750_0a68e10ffd.jpg?v=0" alt="Screenshot" /></p>
<p>To upload a file you need to perform a full ASP.NET page postback, it does not operate over the partial postback method.</p> <p>You'll need to register the button which "uploads" your file as a PostBackTrigger of the UpdatePanel's triggers.</p> <p>There are lots of free (and non-free) AJAX file upload solutions, or you can easily create one, it's just a matter of putting your file upload control within an iframe and submitting the iframe page back to the server. It isn't <em>really</em> ajax, but it gives a visual impression of AJAX.</p>
How can I find the method that called the current method? <p>When logging in C#, how can I learn the name of the method that called the current method? I know all about <code>System.Reflection.MethodBase.GetCurrentMethod()</code>, but I want to go one step beneath this in the stack trace. I've considered parsing the stack trace, but I am hoping to find a cleaner more explicit way, something like <code>Assembly.GetCallingAssembly()</code> but for methods.</p>
<p>Try this:</p> <pre><code>using System.Diagnostics; // Get call stack StackTrace stackTrace = new StackTrace(); // Get calling method name Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name); </code></pre> <p>It is from <em><a href="http://www.csharp-examples.net/reflection-calling-method-name/">Get Calling Method using Reflection [C#]</a></em>.</p>
How do you develop against OpenID locally <p>I'm developing a website (in Django) that uses OpenID to authenticate users. As I'm currently only running on my local machine I can't authenticate using one of the OpenID providers on the web. So I figure I need to run a local OpenID server that simply lets me type in a username and then passes that back to my main app.</p> <p>Does such an OpenID dev server exist? Is this the best way to go about it?</p>
<p>The libraries at <a href="http://openidenabled.com/" rel="nofollow">OpenID Enabled</a> ship with examples that are sufficient to run a local test provider. Look in the examples/djopenid/ directory of the python-openid source distribution. Running that will give you an instance of <a href="http://openidenabled.com/python-openid/trunk/examples/server/" rel="nofollow">this test provider</a>.</p>
GPSID - Poll Driver V2.0 <p>On the page <a href="http://msdn.microsoft.com/en-us/library/bb202066.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/bb202066.aspx</a></p> <p>If references something called "POLL Driver V2" however this is the only place I can see that talks about this. I'm extermely interested in the <code>GPSSetDeviceParam: GPS_QUERY_FIX</code> call but after searching for about 2 hours on this, I couldn't find any information.</p> <p>Can someone point me in the right direction on this?</p>
<p>According to MS, GPSID - Poll Driver v2.0 are not made available to ISV's in WM6.1. They are evaluating including this in a future version of the OS.</p> <p>My solution along the same lines was to create a Windows CE notification that fires at a predetermined interval. Then when my app receives the notification, I set the power mode to "Unattended". To make this work however you will need to set the power requirements in the registry for the GPDO to D0 when in the "Unattended" power mode.</p> <p>HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Power\State\Unattended</p> <p>gpd0: = 0</p> <p>Using the SetPowerRequirement or SetDevicePower = D0 does not accomplish the same thing.</p>
Why does FileSystemWatcher create multiple change events when I copy a file to the directory <p>I've written a small test application using the .Net FileSystemWatcher to keep an eye on a directory. When I copy a large-ish (a few Mb) file into that directory I get the following events listed (see screenshot - and ignore the Delete event to begin with).</p> <p><img src="http://robinwilson.homelinux.com/FSW.png" alt="alt text" /></p> <p>I get a created event (as expected), but then two changed events (about 0.7 seconds apart). Why is this? This would cause major problems in the application I am planning to develop - as I'd try and do things with the file twice (presumably once before it has finished being written to!). Is there anything I can do to stop this happening? From what I've read on StackOverflow and elsewhere, you should just get one changed event once the file has been changed and then closed. Why am I getting two?</p>
<p>According to the <a href="http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx" rel="nofollow">documentation</a> (see the first bullet point under <em>Events and Buffer Sizes</em>):</p> <blockquote> <p><strong>Common file system operations might raise more than one event.</strong> For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised. <strong>Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events.</strong> Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by FileSystemWatcher.</p> </blockquote>
How do I elegantly print the date in RFC822 format in Perl? <p>How can I elegantly print the date in RFC822 format in Perl?</p>
<pre><code>use POSIX qw(strftime); print strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time())) . "\n"; </code></pre>
How to remove paths from tabs in Visual Studio 2008? <p>Is there a way to stop the path showing in a source code tab in Visual Studio 2008?</p> <p>Currently when developing an ASP.NET site, I get the path from the root plus the filename - truncated when it gets too long. So something like:</p> <blockquote> <p>MyDir/MyPage.aspx</p> </blockquote> <p>for a short path and filename, or:</p> <blockquote> <p>MyDir/MyLong...yPage.aspx</p> </blockquote> <p>for a longer path and filename.</p> <p>I'd prefer to see just the filename (ie just MyPage.aspx), allowing more tabs to show at once and making it easier to see which files I have open without using the drop-down list or Crtl-Tab to show the full set.</p> <p>In VS2005, I just get the filename - no path however long it is. Oddly in VS2003 I get the path and filename. I've scoured the options and I can't find a setting that lets me change what appears in the tabs. Searching suggests that other people have similar issues (although which version it occurs in appears to differ) but no-one could identify an option to change what appears.</p> <p>Can anyone point me in the right direction to get rid of the paths in the tabs (or confirm that it can't be changed to save me wasting more time searching)?</p>
<p>In my copy of VS 2008 I just get the filename, not the path. I wonder whether it's a "web site" vs "web application" thing. Which one are you working in? Can you create a project of the other type and see if it still happens? (I'm working in a web application where I get filename-only.)</p>
What is the state of the art user interface for browsing complex version control system history? <p>When using Mercurial I sometimes find that it is hard to understand the relationship between changesets when there are thousands of changesets, and sometimes ten or more active branches at any one time. Currently, I use <a href="http://www.logilab.org/project/hgview/screenshots?selected=4873">hgview</a> which is okay, and while it makes a reasonable attempt to represent the parent relationships it is still basically one dimensional. I imagine something making use of graph visualisation programs such as <a href="http://www.graphviz.org/">GraphViz</a> might work nicely, or perhaps something more wacky.</p> <p>Currently I'm working on projects with around 30,000 revisions, and I expect that number to grow significantly; if 100 full time developers really grok distributed version control and start committing regularly and sharing their full development history then we could end up dealing with millions of revisions. A browser which doesn't have to load the entire history in to RAM every time you want to look at it therefore becomes necessary</p> <p>I'm interested in good history browsers for any version control systems as well, especially if there is a chance I can port them to Mercurial.</p>
<p>the <code>gitk(1)</code> tool for git is what I use at work. Note that it takes a <code>git rev-list</code> constraint so you can limit what you see. You definitely want to begin doing such selective picking in the long run when the amount of commits go up.</p>
Same class, different namespaces, a way to simplify? <p>I'm working with a webservice that offers almost duplicated code across two namesspaces. Lets say for example PigFeet and HorseFeet, both namespaces contain a Feet class and other code that works with the Feet class requires it to be part of that same namespace.</p> <p>Right now In my code I'm forced to do something like this:</p> <pre><code>if( _animalType == AnimalType.Pig ) { //namespace is pigfeet PigFeet.Feet feet = new Feet(); feet.WashFeet(); } if( _animalType == AnimalType.Horse ) { //namespace is horsefeet HorseFeet.Feet feet = new Feet(); feet.WashFeet(); } </code></pre> <p>This is leaving me with lots of duplicated code. Is there a way to choose a namespace more dynamically?</p>
<p>In your namespace imports you can assign an <a href="http://msdn.microsoft.com/en-us/library/aa664765(VS.71).aspx" rel="nofollow">alias</a> to a specific namespace or member.</p> <pre><code>using PigFeet = PigFeet.Feet; using HorseFeet = HorseFeet.Feet; //now your sample code should look something like if( _animalType == AnimalType.Pig ) { //namespace is pigfeet PigFeet feet = new PigFeet(); feet.WashFeet(); } if( _animalType == AnimalType.Horse ) { //namespace is horsefeet HorseFeet feet = new HorseFeet(); feet.WashFeet(); } </code></pre>
Asp.net Project Ideas? <p>I've recently decided to step-up my knowledge in ASP.NET (I haven't coded in ASP.NET for about 2 years or so, and much has changed since then). I want to work with the new MVC framework, try jQuery, LINQ to SQL and basically just to catch up with most of the up-to-date features.</p> <p>To do that, I want to start a nice project in ASP.NET, a serious web application from scratch with the MVC framework. My only problem is.. what should I build? I hate to code stuff that already exist on the web and I just want to make some nice web application (If it's something useful I might publish it like stuff such as Stackoverflow.com ;) or just share its source.</p> <p>Any thoughts?</p>
<p>A wiki-like/sof-like web site that <strong>allows people to consider the pros and cons of making a decision</strong>.</p> <p><strong>Brainstorming</strong></p> <p>The user sees a form with a field for the title of the decision, and two quick-entry text fields. One on the left side of the screen for pros, and the other one on the right side for cons. Each time the user enters a pro or con, it flies to some kind of visual outline and a new blank text field takes its place.</p> <p><strong>Evaluating</strong></p> <p>When the user clicks on a pro/con on the visual outline, he can either drag it to an "importance tagger" or assign it with a custom contextual menu that appears. The visual outline automatically adjusts its view accordingly, so that the pros and cons considered more important are always the most visible.</p> <p><strong>Socializing</strong></p> <p>People gain reputation based on their contributions to publicly-visible decisions. People can also indicate "this decision helper was useful to me", so you can have popular decisions à la digg. People can also see how many people decided for or against something. People can also see the decision-making trends over time for a given decision.</p> <p>Of course, Stack Overflow already allows for some of these ideas.</p>
How to track third-party sources with ClearCase without a headache? <p>First of all: I am not an experienced ClearCase user, but I have lots of experience with other VCS and *nix command-line tools. WIth ClearCase, I use command-line tool ("cleartool") working in a Unix shell.</p> <p>Problem: I have a small set of sources stored in the ClearCase. Once in a while a fresh .tgz with the same sources comes in and I have to update sources in the repository (process could not be changed so that other party will use ClearCase).</p> <p>Now I do the following:</p> <ol> <li>Extract tgz into, say, "~/new_src"</li> <li>"ct setview ..." and cd to the place where the sources are (say, "/vobs/src")</li> <li>I compare the sources with "diff -Naurb . ~/new_src", examine diff's output and: <ol> <li>Copy new files to the /vobs/src and do "cleartool mkelem" on them</li> <li>Checkout changed files, copy new sources over and commit them</li> <li>Do "cleartool mkdir" for new dirs and populate them</li> </ol></li> </ol> <p>This process is slowly driving me crazy since in almost any other version control system I would just checkout the sources, copy new sources over, examine diffs, add new files and then commit the whole lot. Or, better yet, use tags/branches, though they are really not needed in this case - I need to have an up-to-date version of the sources in the repo, that's all.</p> <p>I tried to checkout everything (using "cleartool co -nc <code>find .</code>"), copy new sources over, and commit changed files/add new files afterward. But this requires parsing of the "cleartool ls" output and is even messier.</p> <p>I could miss something obvious, but several forays into Google tell me that I'm not. However, I'd like to hear it from ClearCase powerusers - is there any hope for clueless like me or not? :)</p>
<p>I just want to be sure:</p> <p>You do know about <strong><a href="http://stackoverflow.com/questions/138321/how-can-i-use-clearcase-to-add-to-source-control-recursively#144310">clearfsimport</a></strong>, right ?</p> <p>Because after reading (may be too quickly) your question, that command may be what you are after...</p> <p>That is what I thought... If you need more details, leave a comment to this answer. I will monitor those.</p>
Typing generic values (C#) <p>When I try this with a generic class where this.value is T:</p> <pre><code>if (this.value.GetType() == typeof(int)) { ((int)this.value)++; } else { throw new InvalidOperationException ("T must be an int to perform this operation"); } </code></pre> <p>I get a compile-time error: "Cannot convert type 'T' to 'int'"</p> <p>What should I do to perform an integral operation on this.value when it's an int?</p> <p>Note that this is just an example. The code does type conversions with generics, and "int" is just an example of one type for T. </p>
<p>Unfortunately, it is very hard to convince the compiler about specific T implementations. One (nasty) approach is to cast to object in the middle (note this will box and unbox value-types):</p> <pre><code>int i = (int)(object)this.value; i++; this.value = (T)(object)i; </code></pre> <p>Ugly but it works. In .NET 3.5 I have some better wrappers for generic arithmetic, <a href="http://www.yoda.arachsys.com/csharp/miscutil/usage/genericoperators.html">here</a>. The Operator class is part of <a href="http://www.yoda.arachsys.com/csharp/miscutil/">MiscUtil</a>; at the simplest level, I suspect AddAlternative would work very well:</p> <pre><code>this.value = Operator.AddAlternative(this.value, 1); </code></pre> <p>This should infer the implicit &lt;T,int&gt; automatically, or you can add them yourself:</p> <pre><code>this.value = Operator.AddAlternative&lt;T,int&gt;(this.value, 1); </code></pre> <p><strong>Benefit</strong>: This is preferable to the original code as it doesn't actually care about the original T - it will work for any type (even your own) that supports "T +(T,int)".</p> <p>I think there is also a ChangeType hiding around somewhere in there...</p> <p>[edit] Collin K and others make a valid remark about the architectural implications - but being pragmatic there are times when the T really does matter that much... but I'd agree with avoiding this type of specialization unless <em>really</em> necessary. That said (as per my comment on Collin's post), the ability to perform things like basic arithmetic (increment, Int32 division, etc) on (for example) a Matrix&lt;T&gt; [for T in decimal/float/int/double/etc] is often highly valuable.</p>
Speeding Up Python <p>This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:</p> <ul> <li><p><strong>Firstly</strong>: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?</p></li> <li><p><strong>Secondly</strong>: When writing a program from scratch in python, what are some good ways to greatly improve performance?</p></li> </ul> <p>For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?</p>
<p>Regarding "Secondly: When writing a program from scratch in python, what are some good ways to greatly improve performance?"</p> <p>Remember the Jackson rules of optimization: </p> <ul> <li>Rule 1: Don't do it.</li> <li>Rule 2 (for experts only): Don't do it yet.</li> </ul> <p>And the Knuth rule:</p> <ul> <li>"Premature optimization is the root of all evil."</li> </ul> <p>The more useful rules are in the <a href="http://www.cs.cmu.edu/~jch/java/rules.html">General Rules for Optimization</a>.</p> <ol> <li><p>Don't optimize as you go. First get it right. Then get it fast. Optimizing a wrong program is still wrong.</p></li> <li><p>Remember the 80/20 rule.</p></li> <li><p>Always run "before" and "after" benchmarks. Otherwise, you won't know if you've found the 80%.</p></li> <li><p>Use the right algorithms and data structures. This rule should be first. Nothing matters as much as algorithm and data structure.</p></li> </ol> <p><strong>Bottom Line</strong></p> <p>You can't prevent or avoid the "optimize this program" effort. It's part of the job. You have to plan for it and do it carefully, just like the design, code and test activities.</p>
Add (external) relationship (tagging) to existing Hibernate entities <p>I need to add a new many-to-many relationship to an existing Hibernate entity. I do not want to touch the original Hibernate entity bean or its configuration. What I am adding is a "tagging" feature that can be viewed as an external contribution and not part of the entity's data itself.</p> <p>I want to have a simple join table with only two columns, the entity primary key, and the tag id.</p> <p>Can I use Hibernate to manage this table without introducting a new (artificial) entity type that contains a single tag mapping?</p> <p>Or am I misguided and should actually want to have this "relationship-entity", so that I can add attributes (such as timestamps) later?</p>
<p>The idea behind Hibernate is being able to traverse a Java object tree from a given starting point. If you want to define a many-to-many relationship from the original object to a tag object, you can still define it on the tag object, and it will properly allow you to get a list of the original objects that have that tag.</p> <p>The drawback is that you won't be able to query the original object for it's list of tags (that would require an annotation to reverse the relationship and an accessor that returned a list of Set of tag objects). You will however be able to retrieve a list of the original objects that marked with a given tag.</p> <p>Here's an example ... Let's assume that the object to be tagged is a Post. If so, here's the code to add a many-to-many relationship to the Tag, so that you can look up a list of Posts that have a specific Tag:</p> <pre><code>@ManyToMany @JoinTable( name = "TAG-POST", joinColumns = {@JoinColumn(name = "TAG-ID")}, inverseJoinColumns = {@JoinColumn(name = "POST-ID")} ) private Set&lt;Posts&gt; posts = new HashSet&lt;Post&gt;(); </code></pre> <p>Normally, you'd also want to be able to look up all the Tags related to a Post, but you can leave out the reverse mapping. If you do need the reverse mapping, you'll need to add something like this to your Post object:</p> <pre><code>@ManyToMany(mappedBy = "tags") private Set&lt;Tag&gt; tags = new HashSet&lt;Tag&gt;(); </code></pre> <p>Now you can also look up the tags that are related to a Post.</p> <p>After rereading your post (and viewing your comment), I realize that you're also interested in skipping the creation of a Tag entity. If there is nothing but tag name, you could conceivably only use the table you've described, but you need to shift your mindset a bit. What you're really describing is a one-to-many relationship between the Post and its Tag entries. In this case, you'll need to map a post to a series of tag records, that have two columns ... a POST-ID and a TAG-NAME. Without altering the original object, you can still query the table for a list of Posts with a specific TAG-NAME or for a list of TAG-NAME rows that are related to a specific Post.</p> <p>Note that this doesn't actually eliminate an entity ... You won't have the Tag entity, but the many-to-many lookup table will have to be created as a many-to-one relationship, which makes it an entity itself. This approach does however use one less table.</p>
Can anyone think of some good reasons *not* to use an Object-Oriented DBMS to back a website? <p>Say you're coding some kind of web application. Something where people can contribute content, e.g. a simple photo-sharing site.</p> <p>How many good reasons can you think of to <em>not</em> go with an object-oriented database (e.g. db4o)?</p>
<p>An OODBMS is better if you only need to access your data through your objects. If your solution requires additional pathways to your data (e.g. ad-hoc queries, reporting, other applications that need data access but can't make use of your objects), then a traditional RDBMS system is better.</p> <p>Note: OODBMSes have made a lot of improvement in this area.</p>
2.9999999999999999 >> .5? <p>I heard that you could right-shift a number by .5 instead of using Math.floor(). I decided to check its limits to make sure that it was a suitable replacement, so I checked the following values and got the following results in Google Chrome:</p> <pre><code> 2.5 >> .5 == 2; 2.9999 >> .5 == 2; 2.999999999999999 >> .5 == 2; // 15 9s 2.9999999999999999 >> .5 == 3; // 16 9s </code></pre> <p>After some fiddling, I found out that the highest possible value of two which, when right-shifted by .5, would yield 2 is 2.9999999999999997779553950749686919152736663818359374999999¯ (with the 9 repeating) in Chrome and Firefox. The number is 2.9999999999999997779¯ in IE.</p> <p>My question is: what is the significance of the number .0000000000000007779553950749686919152736663818359374? It's a very strange number and it really piqued my curiosity.</p> <p>I've been trying to find an answer or at least some kind of pattern, but I think my problem lies in the fact that I really don't understand the bitwise operation. I understand the idea in principle, but shifting a bit sequence by .5 doesn't make any sense at all to me. Any help is appreciated.</p> <p>For the record, the weird digit sequence changes with 2^x. The highest possible values of the following numbers that still truncate properly:</p> <pre> for 0: 0.9999999999999999444888487687421729788184165954589843749¯ for 1: 1.9999999999999999888977697537484345957636833190917968749¯ for 2-3: x+.99999999999999977795539507496869191527366638183593749¯ for 4-7: x+.9999999999999995559107901499373838305473327636718749¯ for 8-15: x+.999999999999999111821580299874767661094665527343749¯ ...and so forth </pre>
<p>Actually, you're simply ending up doing a floor() on the first operand, without any floating point operations going on. Since the left shift and right shift bitwise operations only make sense with integer operands, the JavaScript engine is converting the two operands to integers first:</p> <pre><code>2.999999 &gt;&gt; 0.5 </code></pre> <p>Becomes:</p> <pre><code>Math.floor(2.999999) &gt;&gt; Math.floor(0.5) </code></pre> <p>Which in turn is:</p> <pre><code>2 &gt;&gt; 0 </code></pre> <p>Shifting by 0 bits means "don't do a shift" and therefore you end up with the first operand, simply truncated to an integer.</p> <p>The SpiderMonkey source code has:</p> <pre><code>switch (op) { case JSOP_LSH: case JSOP_RSH: if (!js_DoubleToECMAInt32(cx, d, &amp;i)) // Same as Math.floor() return JS_FALSE; if (!js_DoubleToECMAInt32(cx, d2, &amp;j)) // Same as Math.floor() return JS_FALSE; j &amp;= 31; d = (op == JSOP_LSH) ? i &lt;&lt; j : i &gt;&gt; j; break; </code></pre> <p>Your seeing a "rounding up" with certain numbers is due to the fact the JavaScript engine can't handle decimal digits beyond a certain precision and therefore your number ends up getting rounded up to the next integer. Try this in your browser:</p> <pre><code>alert(2.999999999999999); </code></pre> <p>You'll get 2.999999999999999. Now try adding one more 9:</p> <pre><code>alert(2.9999999999999999); </code></pre> <p>You'll get a 3.</p>
C# .NET 3.0/3.5 features in 2.0 using Visual Studio 2008 <p>What are some of the new features that can be used in .NET 2.0 that are specific to C# 3.0/3.5 after upgrading to Visual Studio 2008? Also, what are some of the features that aren't available?</p> <p><strong>Available</strong></p> <ul> <li>Lambdas</li> <li>Extension methods (by declaring an empty System.Runtime.CompilerServices.ExtensionAttribute)</li> <li>Automatic properties</li> <li>Object initializers</li> <li>Collection Initializers</li> <li>LINQ to Objects (by implementing IEnumerable extension methods, see <a href="http://www.albahari.com/nutshell/linqbridge.aspx" rel="nofollow">LinqBridge</a>)</li> </ul> <p><strong>Not Available</strong></p> <ul> <li>Expression trees</li> <li>WPF/Silverlight Libraries</li> </ul>
<p>You can use any new C# 3.0 feature that is handled by the compiler by emitting 2.0-compatible IL and doesn't reference any of the new 3.5 assemblies:</p> <ul> <li>Lambdas (used as <code>Func&lt;..&gt;</code>, not <code>Expression&lt;Func&lt;..&gt;&gt;</code> )</li> <li>Extension methods (by declaring an empty System.Runtime.CompilerServices.ExtensionAttribute)</li> <li>Automatic properties</li> <li>Object Initializers</li> <li>Collection Initializers </li> <li>LINQ to Objects (by implementing IEnumerable&lt;T&gt; extension methods, see <a href="http://www.albahari.com/nutshell/linqbridge.aspx" rel="nofollow">LinqBridge</a>)</li> </ul>
Apache POI HWPF - Output a table to Microsoft Word <p>I've been Googling for quite awhile and haven't found a definitive answer. Is it possible to output a table using Apache POI? It looks like it hasn't been implemented, since the main developer stopped working on it like 5 years ago.</p> <p>Is there an open source alternative to POI that can do this?</p>
<p>I think you're right in that Apache POI is dead in the water. Clearly it wasn't glamourous enough.</p> <p>The only alternative that I'm aware of is <a href="http://itextdocs.lowagie.com/tutorial/rtf/index.php" rel="nofollow">iText</a>, which can generate RTF documents, which MS Word (and every other similar application) can read. It includes full table support.</p> <p>And, of course, iText can generate PDF also.</p>
python dictionary update method <p>I have a list string tag.</p> <p>I am trying to initialize a dictionary with the key as the tag string and values as the array index.</p> <pre><code>for i, ithTag in enumerate(tag): tagDict.update(ithTag=i) </code></pre> <p>The above returns me {'ithTag': 608} <em>608 is the 608th index</em></p> <p>My problem is that while the i is being interpreted as a variable, Python is treating the "ithTag" as a string instead of a variable.</p> <p>I'm confused, it is kind of hard to google these kind of specific questions. I hope I worded the title of this question correctly,</p> <p>Thanks!</p>
<p>You actually want to do this:</p> <pre><code>for i, tag in enumerate(tag): tagDict[tag] = i </code></pre> <p>The .update() method is used for updating a dictionary using another dictionary, not for changing a single key/value pair.</p>
How to check if PHP array is associative or sequential? <p>PHP treats all arrays as associative, so there aren't any built in functions. Can anyone recommend a fairly efficient way to check if an array contains only numeric keys?</p> <p>Basically, I want to be able to differentiate between this:</p> <pre><code>$sequentialArray = array('apple', 'orange', 'tomato', 'carrot'); </code></pre> <p>and this:</p> <pre><code>$assocArray = array('fruit1' =&gt; 'apple', 'fruit2' =&gt; 'orange', 'veg1' =&gt; 'tomato', 'veg2' =&gt; 'carrot'); </code></pre>
<p>You have asked two questions that are not quite equivalent:</p> <ul> <li>Firstly, how to determine whether an array has only numeric keys</li> <li>Secondly, how to determine whether an array has <em>sequential</em> numeric keys, starting from 0</li> </ul> <p>Consider which of these behaviours you actually need. (It may be that either will do for your purposes.)</p> <p>The first question (simply checking that all keys are numeric) is <a href="http://stackoverflow.com/a/4254008/1709587">answered well by Captain kurO</a>.</p> <p>For the second question (checking whether the array is zero-indexed and sequential), you can use the following function:</p> <pre class="lang-php prettyprint-override"><code>function isAssoc(array $arr) { if (array() === $arr) return false; return array_keys($arr) !== range(0, count($arr) - 1); } var_dump(isAssoc(array('a', 'b', 'c'))); // false var_dump(isAssoc(array("0" =&gt; 'a', "1" =&gt; 'b', "2" =&gt; 'c'))); // false var_dump(isAssoc(array("1" =&gt; 'a', "0" =&gt; 'b', "2" =&gt; 'c'))); // true var_dump(isAssoc(array("a" =&gt; 'a', "b" =&gt; 'b', "c" =&gt; 'c'))); // true </code></pre>
MinGW library converted to Windows library gives odd link in VC++6 <p>I used the MinGW <code>.a</code> to Windows <code>.lib</code> transformation process as detailed in a thread on the gmp-discuss list, as below (acting against a library created with --disable-shared --enable-static.) </p> <pre><code>cp libgmp.a gmp.a ranlib gmp.a mv gmp.a gmp.lib </code></pre> <p>I now have a <code>.lib</code> file against which VC++6 seems to have no difficulty linking. What concerns me now is warning messages I'm getting from the link phase:</p> <pre><code>LINK : warning LNK4049: locally defined symbol "___mb_cur_max" imported LINK : warning LNK4049: locally defined symbol "__pctype" imported LINK : warning LNK4049: locally defined symbol "__iob" imported </code></pre> <p>At this point in the proceedings these make no difference to the running of my DLL (which wraps certain GMP functionality). But is that good enough? Will having these three symbols from <code>libgmp.a</code> linked in to my Windows DLL end up biting me later on? </p>
<p>Someone else had a similar problem and <a href="http://opensees.berkeley.edu/community/viewtopic.php?t=2267" rel="nofollow">the fix</a> was relatively simple.</p>
How can I change the 259 char limit inside WinForms Treeview LabelEdit? <p>My VB.Net Winforms app is a tool to allow hierarchical data to be edited in a tree, then stored in a database. I am using a treeview control.</p> <p>Content is drag-dropped from other documents onto the treenodes, or the nodes can be edited directly.</p> <p>if I edit the database field directly, and enter a bit of content (a thousand characters long or more!), the treeview will happily display it.. but, when I drag drop, the data is being truncated at 259 characters. If I edit directly, the maximum edit 'window' is also 259 characters. </p> <p>259 seems like a really strange number to stop at, so I am wondering - where does this size come from, and can I change it programmatically?</p>
<p>I would recommend taking a different approach. You probably don't want to show your users all 10000 or characters of a document anyway in their TreeNode, so create an custom data storage class with properties like Name and Content to store the document and it's title. Add your content to the Content property and a title or something meaningful to the Name property then add the object to the Tag property of the TreeNode object. </p> <pre><code>Dim mynode As New TreeNode Dim SomeBigCustomObject as New MyContentStorageObject(name,content) mynode.Text = SomeBigCustomObject.Name mynode.Tag = SomeBigCustomObject TreeView1.Nodes.Add(mynode) </code></pre> <p>You can then get the object back when a node is selected (using the AfterSelect event) like this:</p> <pre><code>dim ContentStorageObject As MyContentStorageObject = CType(e.Node.Tag, MyContentStorageObject) dim content as string = ContentStorageObject.Content </code></pre> <p>If you need to edit the text, I would then either pop up a editor dialog or send the data that is stored in Content to an textbox on your form for editing. Your users will probably appreciate not having to type it all in the treeview node editor.</p> <p>That's a real quick and dirty explanation, but the essence is "use the .Tag property". Good luck.</p>
Flush disk write cache <p>When the policy for a disk in Windows XP and Vista is set to enable write caching on the hard disk, is there a way to flush a file that has just been written, and ensure that it has been committed to disk?</p> <p>I want to do this programmatically in C++.</p> <p>Closing the file does perform a flush at the application level, but not at the operating system level. If the power is removed from the PC after closing the file, but before the operating system has flushed the disk write cache, the file is lost, even though it was closed.</p>
<p>.NET FileStream.Flush() will NOT flush the Windows cache for that file content; Flush() only flushes the .NET internal file buffer. In .NET 4.0, Microsoft fixed the problem by adding an optional parameter to Flush() which if set true causes FlushFileSystemBuffers to be called. In .NET 3.5 and below your only choice is to call FlushFileBuffers via pinvoke. See MSDN's<a href="http://msdn.microsoft.com/en-us/library/2bw4h516%28v=VS.90%29.aspx">FileStream.Flush</a> community comment for how to do this.</p>
Why is there no RAII in .NET? <p>Being primarily a C++ developer the absence of <a href="http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization">RAII (Resource Acquisition Is Initialization)</a> in Java and .NET has always bothered me. The fact that the onus of cleaning up is moved from the class writer to its consumer (by means of <code>try finally</code> or .NET's <a href="http://blogs.msdn.com/cyrusn/archive/2005/05/10/415956.aspx"><code>using</code> construct</a>) seems to be markedly inferior.</p> <p>I see why in Java there is no support for RAII since all objects are located on the heap and the garbage collector inherently doesn't support deterministic destruction, but in .NET with the introduction of value-types (<code>struct</code>) we have the (seemingly) perfect candidate for RAII. A value type that's created on the stack has a well defined scope and C++ destructor semantics can be used. However the CLR does not permit a value-type to have a destructor.</p> <p>My random searches found one argument that if a value-type is <a href="http://www.csharphelp.com/archives/archive100.html">boxed</a> it falls under the jurisdiction of the garbage collector and therefore its destruction becomes non-deterministic. I feel that this argument isn't strong enough, the benefits of RAII are big enough to say that a value-type with a destructor cannot be boxed (or used as a class member).</p> <p><strong>To cut a long story short my question is</strong>: are there any other reasons value types can not be used in order to introduce RAII to .NET? (or do you think my argument about RAII's obvious advantages are flawed?)</p> <p><strong>Edit:</strong> I must have not phrased the question clearly since the first four answers have missed the point. I <em>know</em> about <code>Finalize</code> and its non-deterministic characteristics, I know about the <code>using</code> construct and I feel these two options are inferior to RAII. <code>using</code> is one more thing the consumer of a class must remember (how many people forgot to put a <code>StreamReader</code> in a <code>using</code> block?). My question is a philosophical one about the language design, why is it the way it is and can it be improved?</p> <p>For instance with a generic deterministically destructible value-type I can make the <code>using</code> and <code>lock</code> keywords redundant (achievable by library classes):</p> <pre><code> public struct Disposer&lt;T&gt; where T : IDisposable { T val; public Disposer(T t) { val = t; } public T Value { get { return val; } } ~Disposer() // Currently illegal { if (val != default(T)) val.Dispose(); } } </code></pre> <p><hr /></p> <p>I can't help but end with a apropos quotation which I once saw but can't currently find its origin.</p> <blockquote> <p>You can take my deterministic destruction when my cold dead hand goes out of scope. --<em>Anon</em></p> </blockquote>
<p>A better title would be "Why is there no RAII in C#/VB". C++/CLI (The evolution of the abortion that was Managed C++) has RAII in the exact same sense as C++. It's all just syntax sugar for the same finalisation pattern that the rest of the CLI languages use (Destructors in managed objects for C++/CLI are effectively finalisers), but it is there.</p> <p>You might like <a href="http://blogs.msdn.com/hsutter/archive/2004/07/31/203137.aspx">http://blogs.msdn.com/hsutter/archive/2004/07/31/203137.aspx</a></p>
What ways are there of drawing 3D trees using Java and OpenGL? <p>I know how to draw basic objects using JOGL or LWJGL to connect to OpenGL. What I would like is something that can generate some kind of geometry for trees, similar to what SpeedTree is famous for. Obviously I don't expect the same quality as SpeedTree.</p> <p>I want the trees to not look repetitive. Speed is not a concern, I do not expect to need more than 100 trees on screen at one time. </p> <p>Are there free tree-drawing libraries available in Java? Or sample code or demos? Is there anything in other languages which I could port or learn from?</p>
<p><a href="http://arbaro.sourceforge.net/" rel="nofollow">http://arbaro.sourceforge.net/</a></p> <p><a href="http://www.propro.ru/go/Wshop/povtree/povtree.html" rel="nofollow">http://www.propro.ru/go/Wshop/povtree/povtree.html</a></p> <p>Non java: <a href="http://www.aust-manufaktur.de/austt.html" rel="nofollow">http://www.aust-manufaktur.de/austt.html</a></p>
Java: Serializing unknown Arraysize <p>If I safe an Array and reload it, is there a possibility to get the size if its unknown? Thanks</p>
<p>What do you mean by "unknown"? You can get the length of any java array with the length field.</p> <pre><code>int[] myArray = deserializeSomeArray(); int size = myArray.length; </code></pre>
AutoPostback with TextBox loses focus <p>A <code>TextBox</code> is set to <code>AutoPostback</code> as changing the value should cause a number of (display-only) fields to be recalculated and displayed.<br> That works fine.</p> <p>However, when the field is tabbed out of, the focus briefly moves on to the next field, then disappears when the page is redrawn so there is no focus anywhere. </p> <p>I want the focus to be on the new field, not the textbox I've just changed. Is there a way to work out which field had the focus and force it to have it again when the page is redrawn? </p>
<p>This is "by design". If you are using ASP.NET 2.0+ you can try calling the Focus method of your TextBox once the postback occurs (preferably in the TextChanged event of the TextBox).</p> <p>I am not sure if there is any built-in way to track focus but I found <a href="http://www.codeproject.com/KB/aspnet/MainatinFocusASPNET.aspx" rel="nofollow">this</a> article in CodeProject which should do the trick.</p>
Why can't c++ ifstreams read from devices? <p>I knew I should never have started using c++ io, the whole "type safety" argument is a red herring (does anyone <em>really</em> find that it's one of their most pressing problems?). Anyhow, I did, and discovered a strange difference between ifstreams and FILE*s and plain old file descriptors: ifstreams cannot read from a device. Can anyone think of a reason why?</p> <pre><code>const char* path = "/dev/disk3"; char b; // this works FILE* f= fopen(path, "rb"); int i = fread(&amp;b, 1, 1, f); // returns 1, success! // this does not work ifstream cf(path, ios::binary); cf.read(&amp;b, 1); bool good = cf.good(); // returns false, failure. </code></pre>
<p>Works fine for me, its not a problem inherent to c++ stream file I/O as you seem to think.</p> <p>Maybe try adding <code>ios::in</code> to the openmode flags. According to 27.8.1.6 of the standard, it is required to or with ios::in so this probably won't do anything.</p> <p>Try checking which bit is actually set - instead of calling good(), try checking bad(), eof(), and fail() individually. This might give a clue as to what the error was.</p>
Multiple instances of a java web application sharing a resource <p>I have a web service, that takes an input xml message, transforms it, and then forwards it to another web service.</p> <p>The application is deployed to two web logic app servers for performance, and resilience reasons.</p> <p>I would like a single website monitoring page that allows two things</p> <ul> <li><p>ability to stop/ start forwarding of messages</p></li> <li><p>ability to monitor throughput of number of messages in the last hour etc. Number of different senders into the webservice etc.</p></li> </ul> <p>I was wondering what the best way to implement this was.</p> <p>My current idea is to have an in memory database (eg Debry or HSQL) replicating data to share the information between the two (or more) instances of my application that are running in different instances of the app server. I imagine I would have to setup some sort of master/ slave configuration.</p> <p>I would love a link to an article that discusses how to solve this problem.</p> <p>(Note, this is a simple spring application using spring MVC)</p> <p>thanks,</p> <p>David.</p>
<p>This sounds like a good match for <a href="http://java.sun.com/javase/technologies/core/mntr-mgmt/javamanagement/" rel="nofollow">Java Management Extensions (JMX)</a></p> <ul> <li>JMX allows you to expose certain operations (eg: start/stop forwarding messages)</li> <li>JMX allows you to monitor certain performance indicators (eg: moving average of messages processed)</li> </ul> <p>Spring has good support for exposing beans as JMX MBeans. See <a href="http://static.springframework.org/spring/docs/2.5.5/reference/jmx.html" rel="nofollow">here</a> for more information.</p> <p>Then you could use an open-source web-based JMX console, such as <a href="http://www.jmanage.org/" rel="nofollow">jManage</a></p> <p>Hope this helps.</p>
Incorporating shareware restrictions in C++ software <p>I wish to implement my software on a shareware basis, so that the user is given a maximum trial period of (say) 30 days with which to try out the software. On purchase I intend the user to be given a randomly-generated key, which when entered enables the software again.</p> <p>I've never been down this route before, so any advice or feedback or pointers to 'standard' ways of how this is done would be much appreciated.</p> <p>I do not anticipate users cheating by changing the system date or anything like that, though this is probably worth considering. Apologies if this topic has appeared before.</p>
<p>With regards to a random-generated key, how will you verify a key is legit or if a key is bogus if it is actually random? Have a look at the article "<a href="http://www.brandonstaggs.com/2007/07/26/implementing-a-partial-serial-number-verification-system-in-delphi/" rel="nofollow">Implementing a Partial Serial Number Verification System</a>" as it is quite good and is easy to implement in any language.</p> <p>With regards to time trials, as basic solution would be to compare your main executable files creation time to the current system time and act on the difference. This assumes your installer sets the files creation time to the time of install as opposed to preserving the time you compiled it! :)</p>
JRE Upgrade <p>Is there anyway to upgrade the installed JRE in the system? We are having 1.5.0_08 installed in out HP Unix system.We have to upgrade this to 1.5.0_15.Is there a way to patch up the existing JRE and upgrade to a newer version.Or can this only be achieved by installing the newer JRE and set this in the system PATH.</p> <p>Thanks for your time.</p> <p>Regards, Vivek</p>
<p>What's usually done is to have multiple JRE installed in separate directories (JRE_1_5_10, JRE_1_5_16, JRE_1_6_3, ...) and use some symlinks as references as JRE_1_5 that will point to the latest version of JRE 1.5, same for JRE_1_6, and eventually, JRE that will point to the latest version of the JRE.</p> <p>Doing so, you just need to update the symlinks when you choose to use a newer version and always refer to the symlinks for systems that are "upgradable".</p>
Is abstracting data type (sometimes) a good idea? <p>There are numerous times you have an interface that accepts similar type arguments that have a separate domain logic meaning:</p> <pre><code>public static class Database { public static bool HasAccess(string userId, string documentId) { return true; } } </code></pre> <p>Now it's quite easy to have someone key documentId instead of userId and vice versa. One could prevent that by abstracting the data type of the arguments:</p> <pre><code>public class UserId { public string Value { get; internal set; } public static implicit operator string(UserId id) { return id.Value; } } public class DocumentId { public string Value { get; internal set; } public static implicit operator string(DocumentId id) { return id.Value; } } public static class Database { public static bool HasAccess(UserId userId, DocumentId documentId) { return true; } } </code></pre> <p>This way you get a nice compiler warning if you type in arguments out of order:</p> <pre><code>UserId e = new UserId() { Value = "a" }; DocumentId d = new DocumentId() { Value = "b" }; Database.HasAccess(d, e); </code></pre> <p>You also get the ability to change abstracted type in without affecting the rest of the system but that's not very likely. Would abstracting type be a good idea to get more type safety?</p> <p>The question relates to C# solutions but short descriptions in other languages is welcome.</p> <p>EDIT: Removed the implicit cast from string and pointing finger at the C# tag.</p>
<p>I think you answered your own question - better data integrity and validation, better system</p>
Python - Py2exe can't build .exe using the 'email' module <p>py2exe does not work with the standard email module</p> <p>Hello. I am trying to use py2exe for converting a script into an exe. The build process shows this:</p> <p><hr /></p> <p>The following modules appear to be missing</p> <h2>['email.Encoders', 'email.Generator', 'email.Iterators', 'email.MIMEBase', 'email.MIMEMultipart', 'email.MIMEText', 'email.Utils', 'email.base64MIME']</h2> <p>The executable does not work. The referenced modules are not included. I researched this on the Internet and I found out that py2exe has a problem with the Lazy import used in the standard lib email module. Unfortunately I have not succeeded in finding a workaround for this problem. Can anyone help?</p> <p>Thank you,</p> <p>P.S. Imports in the script look like this:</p> <p>Code: Select all import string,time,sys,os,smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email import Encoders</p>
<p>Have a look at this question <a href="http://stackoverflow.com/questions/169897/how-to-package-twisted-program-with-py2exe">how-to-package-twisted-program-with-py2exe</a> it seems to be the same problem.</p> <p>The answer given there is to explicitly include the modules on the command line to py2exe.</p>
Recursive Rails Nested Resources <p>I have a Rails application for project management where there are Project and Task models. A project can have many tasks, but a task can also have many tasks, ad infinitum.</p> <p>Using nested resources, we can have /projects/1/tasks, /projects/1/tasks/new, /projects/1/tasks/3/edit etc.</p> <p>However, how do you represent the recursive nature of tasks RESTfully? I don't want go another level deep, so perhaps the following would do:</p> <pre><code>map.resources :tasks do |t| t.resources :tasks end </code></pre> <p>That would give me the following urls:</p> <pre><code>/tasks/3/tasks/new /tasks/3/tasks/45/edit </code></pre> <p>Or perhaps when it comes to an individual task I can just use /tasks/45/edit</p> <p>Is this a reasonable design?</p> <p>Cam</p>
<p>Going anywhere beyond a single nested route is generally considered a bad idea.</p> <p>From page 108 of <strong>The Rails Way</strong>:</p> <p><a href="http://weblog.jamisbuck.org/2007/2/5/nesting-resources">"*Jamis Busk a very influential figure in the Rails community, almost as much as David himself. In February 2007, vis his blog, he basically told us that deep nesting was a <em>bad</em> thing, and proposed the following rule of thumb: Resources <strong>should never</strong> be nested more than one level deep.*"</a></p> <p>Now some would argue with this (which is discussed on page 109) but when you're talking about nesting tasks with tasks it just doesn't seem to make much sense.</p> <p>I would approach your solution a different way and like it was mentioned above, a project should have many tasks but for a task to have many tasks doesn't seem correct and maybe those should be re-named as sub-tasks or something along those lines.</p>
Writing a language for the Windows Scripting Host (WSH) <p>Has anyone had any experience targetting <code>WSH</code> in the way that <code>VBScript</code>, <code>JScript</code>, <code>PerlScript</code>, <code>xbScript</code> and <code>ForthScript</code> (among other) do, such that the language can be used from the command line and embedded in server-side web pages? Where do I go to get that kind of information? </p>
<p>These are called <a href="http://msdn.microsoft.com/en-us/library/xawadt95(VS.85).aspx">Windows Script Engines</a> and are implemented by exposing the engine via COM. There is a lot documentation on <a href="http://msdn.microsoft.com/en-us/library/t9d4xf28(VS.85).aspx">MSDN</a>, and the actual interfaces are fairly straight forward.</p>
Spring webflow : Move through view states <p>Within a spring webflow, i need to implement a navigation bar that will allow to "step back" or resume the flow to one of the previous view.</p> <p>For example :</p> <ul> <li>View 1 = login</li> <li>View 2 = My informations</li> <li>View 3 = My messages</li> <li>View 4 = Close session</li> </ul> <p>For this example, i would like to return back to view 2 from the view 4 page.</p>
<p>It depends how you're going about doing this. If you're doing this within a single flow, you'll have something like this:</p> <pre><code>&lt;view-state id="loginView" view="login.jsp"&gt; &lt;action-state bean="someBean" method="login" /&gt; &lt;transition on="success" to="informationView" /&gt; &lt;/view-state&gt; &lt;view-state id="informationView" view="information.jsp"&gt; &lt;render-actions&gt; &lt;action-state bean="someBean" method="retrieveInformation" /&gt; &lt;/render-actions&gt; &lt;transition on="forward" to="messageView" /&gt; &lt;transition on="back" to="loginView" /&gt; &lt;/view-state&gt; &lt;view-state id="messageView" view="message.jsp"&gt; &lt;render-actions&gt; &lt;action-state bean="someBean" method="retrieveMessage" /&gt; &lt;/render-actions&gt; &lt;transition on="forward" to="closeView" /&gt; &lt;transition on="back" to="informationView" /&gt; &lt;/view-state&gt; &lt;view-state id="closeView" view="logout.jsp"&gt; &lt;transition on="jumpBack" to="informationView" /&gt; &lt;/view-state&gt; </code></pre> <p>The "jumpBack" transition on "closeView" will jump you back to view state #2, which is your information view.</p> <p>With sub-flows it is tricky. You'd need to chain it: call a subflow, and if an event is signaled that states you need to end your flow with a specific state, immediately do so.</p> <p>For example, say that your flow chain is login->information->message->close.</p> <p>On the close flow, the end-state would be "returnToInformation".</p> <p>The message flow has a transition on="returnToInformation" to="returnToInformation".</p> <p>"returnToInformation" is also an end-state in the message flow.</p> <p>Then, the information flow has a transition on="returnToInformation" to="displayInformationPage", which would then re-display the information page.</p>
Using VS 2005 to design abstract forms <p>There's a famous bug in Visual Studio that prevents you from using the form designer on a subclass of an abstract form. </p> <p>This problem has already been elucidated and solved most elegantly by <a href="http://www.urbanpotato.net/default.aspx/document/2001" rel="nofollow" title="Please read this page for a description of the problem and its solution.">Urban Potato</a>; that's not the part I'm having trouble with. The trouble is, I have duplicated the technique described by Urban Potato, and included it in my project (which happens to be pretty big), and now every time I try to open the designer of my derived form, I get that Microsoft "frightfully sorry, old chap, but I'm going to have to kill you now" message (reminiscent of Otto in <em>A Fish Called Wanda</em>) that says "Microsoft Visual Studio 2005 has encountered a problem and needs to close. We are sorry for the inconvenience."</p> <p>But here's the <strong>real</strong> kicker: if you just ignore that message, and stuff it away beyond the bottom right corner of the screen, you can carry on working, perfectly normally! Just don't click the "Send Error Report" or "Don't Send" buttons, coz then VS <strong>does</strong> close.</p> <p>Still, this phenomenon is highly annoying, and I'd very much like to be able to work without the feeling that my IDE is just <em>looking</em> for some really nasty way to get back at me for pooh-poohing its sage advice to quit now - or else.</p> <p>Further useful info: this same behavior can be duplicated on all other computers in my office; it's nothing specific to my machine. Obviously something in the project/code is upsetting the IDE, but at least I know the design pattern works, coz after I ignore the crash message, the designer works perfectly well. I just don't know where to start looking for the thing that is causing this problem.</p> <p>Any ideas?</p> <p>Thanks!</p>
<p>If it were me, I'd try attaching a debugger (maybe another instance of Visual Studio) to the instance that throws the error dialog, and see if the stack trace gives you any insights into what's causing the error.</p>
Log4Net "Could not find schema information" messages <p>I decided to use <a href="http://logging.apache.org/log4net/index.html">log4net</a> as a logger for a new webservice project. Everything is working fine, but I get a lot of messages like the one below, for every log4net tag I am using in my <code>web.config</code>:</p> <blockquote> <p>Could not find schema information for the element 'log4net'...</p> </blockquote> <p>Below are the relevant parts of my <code>web.config</code>:</p> <pre class="lang-xml prettyprint-override"><code> &lt;configSections&gt; &lt;section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /&gt; &lt;/configSections&gt; &lt;log4net&gt; &lt;appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"&gt; &lt;file value="C:\log.txt" /&gt; &lt;appendToFile value="true" /&gt; &lt;rollingStyle value="Size" /&gt; &lt;maxSizeRollBackups value="10" /&gt; &lt;maximumFileSize value="100KB" /&gt; &lt;staticLogFileName value="true" /&gt; &lt;layout type="log4net.Layout.PatternLayout"&gt; &lt;conversionPattern value="%date [%thread] %-5level: %message%newline" /&gt; &lt;/layout&gt; &lt;/appender&gt; &lt;logger name="TIMServerLog"&gt; &lt;level value="DEBUG" /&gt; &lt;appender-ref ref="RollingFileAppender" /&gt; &lt;/logger&gt; &lt;/log4net&gt; </code></pre> <p>Solved:</p> <ol> <li>Copy every log4net specific tag to a separate <code>xml</code>-file. Make sure to use <code>.xml</code> as file extension.</li> <li>Add the following line to <code>AssemblyInfo.cs</code>:</li> </ol> <pre class="lang-cs prettyprint-override"><code>[assembly: log4net.Config.XmlConfigurator(ConfigFile = "xmlFile.xml", Watch = true)] </code></pre> <p><a href="http://stackoverflow.com/users/20774/nemo">nemo</a> added:</p> <blockquote> <p>Just a word of warning to anyone follow the advice of the answers in this thread. There is a possible security risk by having the log4net configuration in an xml off the root of the web service, as it will be accessible to anyone by default. Just be advised if your configuration contains sensitive data, you may want to put it else where.</p> </blockquote> <hr> <p>@wcm: I tried using a separate file. I added the following line to <code>AssemblyInfo.cs</code></p> <pre class="lang-cs prettyprint-override"><code>[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)] </code></pre> <p>and put everything dealing with log4net in that file, but I still get the same messages.</p>
<p>You can bind in a schema to the <code>log4net</code> element. There are a few floating around, most do not fully provide for the various options available. I created the following xsd to provide as much verification as possible: <a href="http://csharptest.net/downloads/schema/log4net.xsd">http://csharptest.net/downloads/schema/log4net.xsd</a></p> <p>You can bind it into the xml easily by modifying the <code>log4net</code> element:</p> <pre><code>&lt;log4net xsi:noNamespaceSchemaLocation="http://csharptest.net/downloads/schema/log4net.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; </code></pre>
Sharing Test code in Maven <p>How can you depend on test code from another module in Maven? </p> <p>Example, I have 2 modules:</p> <ul> <li>Base</li> <li>Main</li> </ul> <p>I would like a test case in Main to extend a base test class in Base. Is this possible?</p> <p>Update: Found an <a href="http://stackoverflow.com/questions/174560/sharing-test-code-in-maven#174670">acceptable answer</a>, which involves creating a test jar.</p>
<p>I recommend using type instead of classifier. It tells Maven a bit more explicitly what you are doing (and I've found that m2eclipse and q4e both like it better).</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;com.myco.app&lt;/groupId&gt; &lt;artifactId&gt;foo&lt;/artifactId&gt; &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt; &lt;type&gt;test-jar&lt;/type&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; </code></pre>
How to set property to Guid in aspx page <p>I have the following code in one of my aspx pages:</p> <pre><code>&lt;% foreach (Dependency dep in this.Common.GetDependencies(this.Request.QueryString["Name"])) { %&gt; &lt;ctl:DependencyEditor DependencyKey='&lt;%= dep.Key %&gt;' runat="server" /&gt; &lt;% } %&gt; </code></pre> <p>When I run it, I get the following error: <pre><strong>Parser Error Message:</strong> Cannot create an object of type 'System.Guid' from its string representation '&lt;%= dep.Key %>' for the 'DependencyKey' property.</pre></p> <p>Is there any way that I can create a control and pass in a Guid in the aspx page? I'd really hate to have to loop through and create these controls in the code behind just because of that...</p> <p>NOTE: The Key property on the Dependency object <em>is</em> a Guid.</p>
<p>The key property of the Dependency object may be a Guid, but is the DependencyKey Property of the DependencyEditor a Guid too? If not it should be, otherwise the correct TypeConverter won't be invoked upon assignment. </p> <p>If I'm not mistaken, you could also use dep.Key.ToString() also.</p>
Is there a way to disable a SQL Server trigger for just a particular scope of execution? <p>In SQL Server 2005, is there a way for a trigger to find out what object is responsible for firing the trigger? I would like to use this to disable the trigger for one stored prodecure.</p> <p>Is there any other way to disable the trigger only for the current transaction? I could use the following code, but if I'm not mistaken, it would affect concurrent transactions as well - which would be a bad thing.</p> <pre><code>DISABLE TRIGGER { [ schema_name . ] trigger_name [ ,...n ] | ALL } ON { object_name | DATABASE | ALL SERVER } [ ; ] ENABLE TRIGGER { [ schema_name . ] trigger_name [ ,...n ] | ALL } ON { object_name | DATABASE | ALL SERVER } [ ; ] </code></pre> <p>If possible, I would like to avoid the technique of having a "NoTrigger" field in my table and doing a <code>NoTrigger = null</code>, because I would like to keep the table as small as possible.</p> <p>The reason I would like to avoid the trigger is because it contains logic that is important for manual updates to the table, but my stored procedure will take care of this logic. Because this will be a highly used procedure, I want it to be fast.</p> <blockquote> <p>Triggers impose additional overhead on the server because they initiate an implicit transaction. As soon as a trigger is executed, a new implicit transaction is started, and any data retrieval within a transaction will hold locks on affected tables.</p> </blockquote> <p>From: <a href="http://searchsqlserver.techtarget.com/tip/1,289483,sid87_gci1170220,00.html#trigger">http://searchsqlserver.techtarget.com/tip/1,289483,sid87_gci1170220,00.html#trigger</a></p>
<p>I just saw this article recently highlighted on the SQL Server Central newsletter and it appears to offer a way which you may find useful using the Context_Info on the connection:</p> <p><a href="http://www.mssqltips.com/tip.asp?tip=1591">http://www.mssqltips.com/tip.asp?tip=1591</a></p> <p><hr /></p> <p>EDIT by Terrapin:</p> <p>The above link includes the following code:</p> <pre><code>USE AdventureWorks; GO -- creating the table in AdventureWorks database IF OBJECT_ID('dbo.Table1') IS NOT NULL DROP TABLE dbo.Table1 GO CREATE TABLE dbo.Table1(ID INT) GO -- Creating a trigger CREATE TRIGGER TR_Test ON dbo.Table1 FOR INSERT,UPDATE,DELETE AS DECLARE @Cinfo VARBINARY(128) SELECT @Cinfo = Context_Info() IF @Cinfo = 0x55555 RETURN PRINT 'Trigger Executed' -- Actual code goes here -- For simplicity, I did not include any code GO </code></pre> <p>If you want to prevent the trigger from being executed you can do the following:</p> <pre><code>SET Context_Info 0x55555 INSERT dbo.Table1 VALUES(100) </code></pre>
What is the best way to validate a credit card in PHP? <p>Given a credit card number and no additional information, what is the best way in PHP to determine whether or not it is a valid number?</p> <p>Right now I need something that will work with American Express, Discover, MasterCard, and Visa, but it might be helpful if it will also work with other types.</p>
<p>There are three parts to the validation of the card number:</p> <ol> <li><strong>PATTERN</strong> - does it match an issuers pattern (e.g. VISA/Mastercard/etc.)</li> <li><strong>CHECKSUM</strong> - does it actually check-sum (e.g. not just 13 random numbers after "34" to make it an AMEX card number)</li> <li><strong>REALLY EXISTS</strong> - does it actually have an associated account (you are unlikely to get this without a merchant account)</li> </ol> <h2>Pattern</h2> <ul> <li>MASTERCARD Prefix=51-55, Length=16 (Mod10 checksummed)</li> <li>VISA Prefix=4, Length=13 or 16 (Mod10)</li> <li>AMEX Prefix=34 or 37, Length=15 (Mod10)</li> <li>Diners Club/Carte Prefix=300-305, 36 or 38, Length=14 (Mod10)</li> <li>Discover Prefix=6011,622126-622925,644-649,65, Length=16, (Mod10)</li> <li>etc. (<a href="http://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29">detailed list of prefixes</a>)</li> </ul> <h2>Checksum</h2> <p>Most cards use the Luhn algorithm for checksums:</p> <p><a href="http://en.wikipedia.org/wiki/Luhn_algorithm">Luhn Algorithm described on Wikipedia</a></p> <p>There are links to many implementations on the Wikipedia link, including PHP:</p> <pre><code>&lt;? /* Luhn algorithm number checker - (c) 2005-2008 shaman - www.planzero.org * * This code has been released into the public domain, however please * * give credit to the original author where possible. */ function luhn_check($number) { // Strip any non-digits (useful for credit card numbers with spaces and hyphens) $number=preg_replace('/\D/', '', $number); // Set the string length and parity $number_length=strlen($number); $parity=$number_length % 2; // Loop through each digit and do the maths $total=0; for ($i=0; $i&lt;$number_length; $i++) { $digit=$number[$i]; // Multiply alternate digits by two if ($i % 2 == $parity) { $digit*=2; // If the sum is two digits, add them together (in effect) if ($digit &gt; 9) { $digit-=9; } } // Total up the digits $total+=$digit; } // If the total mod 10 equals 0, the number is valid return ($total % 10 == 0) ? TRUE : FALSE; } ?&gt; </code></pre>
LINQ - which layer should LINQ typically fall into, DAL? <p>just wanted to gather different ideas and perspectives as to which layer should (and why) LINQ fall into?</p>
<p>LINQ = Language INtegrated Queries. This is the query extensions that allows you to query anything from databases to lists/collections to XML. The query language is useful in any layer.</p> <p>However, a lot of people refer to LINQ to SQL as just "LINQ". In that context, a combined BLL/DAL makes sense when you're using L2S and that's where you do LINQ queries against your database. That does of course not exclude doing subsequent queries against the results from those same queries in new (Linq to objects) queries in higher layers...</p>
How can I convert HTML to Textile? <p>I'm scraping a static html site and moving the content into a database-backed CMS. I'd like to use Textile in the CMS. </p> <p>Is there a tool out there that converts HTML into Textile, so I can scrape the existing site, convert the HTML to Textile, and insert that data into the database?</p>
<p>I know this is an old question, but I found myself trying to do this the other day and not finding anything useful, until I found <a href="http://johnmacfarlane.net/pandoc/" rel="nofollow">Pandoc</a>. It can convert loads of other markup formats as well - it's quite brilliant.</p>
Ratio of time spent on coding versus unit testing <p>What is a typical estimate for coding unit tests given an estimate for coding new functionality? Is this different for estimates to maintain code?</p>
<p>My time is about equal between time for unit testing and time for functional code.</p> <p>Some people would look at this and say that is a waste of time, but if your only other option is to run the app and step through all the possible paths the app can take, then the time spent on unit testing is actually less than the time you would spend on developer testing. Of course if you don't do much developer testing, then you will spend the time in fixing bugs that come back from QA.</p> <p>Either way the time spent writing unit test actually saves time from the amount I would spend on the project.</p> <p>When it comes time to maintain the code (slight changes, small additions in functionality), there might be a difference. If the code being changed is already fully covered and your changes do not require changes to the tests, then your time is 0. Otherwise obviously it is not, probably closer to equal again.</p> <p>But, your time savings in testing time is MUCH larger; you've already created the tests to cover the rest of the code, so you would uncover any incidental changes flowing from your change without any new code or walking the app.</p>
How to output CDATA using ElementTree <p>I've discovered that cElementTree is about 30 times faster than <code>xml.dom.minidom</code> and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree.</p> <p>Can it be done?</p>
<p>After a bit of work, I found the answer myself. Looking at the ElementTree.py source code, I found there was special handling of XML comments and preprocessing instructions. What they do is create a factory function for the special element type that uses a special (non-string) tag value to differentiate it from regular elements.</p> <pre><code>def Comment(text=None): element = Element(Comment) element.text = text return element </code></pre> <p>Then in the <code>_write</code> function of ElementTree that actually outputs the XML, there's a special case handling for comments:</p> <pre><code>if tag is Comment: file.write("&lt;!-- %s --&gt;" % _escape_cdata(node.text, encoding)) </code></pre> <p>In order to support CDATA sections, I create a factory function called <code>CDATA</code>, extended the ElementTree class and changed the <code>_write</code> function to handle the CDATA elements.</p> <p>This still doesn't help if you want to parse an XML with CDATA sections and then output it again with the CDATA sections, but it at least allows you to create XMLs with CDATA sections programmatically, which is what I needed to do.</p> <p>The implementation seems to work with both ElementTree and cElementTree.</p> <pre><code>import elementtree.ElementTree as etree #~ import cElementTree as etree def CDATA(text=None): element = etree.Element(CDATA) element.text = text return element class ElementTreeCDATA(etree.ElementTree): def _write(self, file, node, encoding, namespaces): if node.tag is CDATA: text = node.text.encode(encoding) file.write("\n&lt;![CDATA[%s]]&gt;\n" % text) else: etree.ElementTree._write(self, file, node, encoding, namespaces) if __name__ == "__main__": import sys text = """ &lt;?xml version='1.0' encoding='utf-8'?&gt; &lt;text&gt; This is just some sample text. &lt;/text&gt; """ e = etree.Element("data") cdata = CDATA(text) e.append(cdata) et = ElementTreeCDATA(e) et.write(sys.stdout, "utf-8") </code></pre>
C++ thread/process identifier <p>Is there a <em>portable</em> way of getting thread and/or process identifier (string, int, ...) with C++?</p>
<p>You have a few ways, but all imply the use of an external library abstracting the thread for you.</p> <p>Among the popular choices, two are:</p> <ol> <li>The <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/thread.html">Boost.Thread</a> library. This is the most portable but imply working with Boost, which is a HUGE library</li> <li>The <a href="http://www.trolltech.com">Qt</a> library. This is less portable and imply to work with Qt, a big library.</li> </ol> <p>If you already use any on these two libraries, I would recommend sticking with it. Otherwise, look at what other tools they provide and make a choice.</p>
How do I slice an array in Excel VBA? <p>What function can I use in Excel VBA to slice an array?</p>
<blockquote> <p><strong>Application.WorksheetFunction.Index(array, row, column)</strong></p> </blockquote> <p>If you specify a zero value for row or column, then you'll get the entire column or row that is specified.</p> <p>Example:</p> <blockquote> <p>Application.WorksheetFunction.Index(array, 0, 3)</p> </blockquote> <p>This will give you the entire 3rd column.</p> <p>If you specify both row and column as non-zero, then you'll get only the specific element. There is no easy way to get a smaller slice than a complete row or column.</p> <p><strong>Limitation</strong>: There is a limit to the array size that <code>WorksheetFunction.Index</code> can handle if you're using a newer version of Excel. If <code>array</code> has more than 65,536 rows or 65,536 columns, then it throws a "Type mismatch" error. If this is an issue for you, then see <a href="http://stackoverflow.com/a/24843721/119775">this more complicated answer</a> which is not subject to the same limitation.</p> <p>Here's the function I wrote to do all my 1D and 2D slicing:</p> <pre><code>Public Function GetArraySlice2D(Sarray As Variant, Stype As String, Sindex As Integer, Sstart As Integer, Sfinish As Integer) As Variant ' this function returns a slice of an array, Stype is either row or column ' Sstart is beginning of slice, Sfinish is end of slice (Sfinish = 0 means entire ' row or column is taken), Sindex is the row or column to be sliced ' (NOTE: 1 is always the first row or first column) ' an Sindex value of 0 means that the array is one dimensional 3/20/09 ljr Dim vtemp() As Variant Dim i As Integer On Err GoTo ErrHandler Select Case Sindex Case 0 If Sfinish - Sstart = UBound(Sarray) - LBound(Sarray) Then vtemp = Sarray Else ReDim vtemp(1 To Sfinish - Sstart + 1) For i = 1 To Sfinish - Sstart + 1 vtemp(i) = Sarray(i + Sstart - 1) Next i End If Case Else Select Case Stype Case "row" If Sfinish = 0 Or (Sstart = LBound(Sarray, 2) And Sfinish = UBound(Sarray, 2)) Then vtemp = Application.WorksheetFunction.Index(Sarray, Sindex, 0) Else ReDim vtemp(1 To Sfinish - Sstart + 1) For i = 1 To Sfinish - Sstart + 1 vtemp(i) = Sarray(Sindex, i + Sstart - 1) Next i End If Case "column" If Sfinish = 0 Or (Sstart = LBound(Sarray, 1) And Sfinish = UBound(Sarray, 1)) Then vtemp = Application.WorksheetFunction.Index(Sarray, 0, Sindex) Else ReDim vtemp(1 To Sfinish - Sstart + 1) For i = 1 To Sfinish - Sstart + 1 vtemp(i) = Sarray(i + Sstart - 1, Sindex) Next i End If End Select End Select GetArraySlice2D = vtemp Exit Function ErrHandler: Dim M As Integer M = MsgBox("Bad Array Input", vbOKOnly, "GetArraySlice2D") End Function </code></pre>
Safe to Run LogParser Against Live Production IIS Log? <p>Is it safe to run LogParser against our live production IIS log file?</p> <p>Currently, I have been copying it over to another location and then running LogParser 2.2 against the log file.</p> <p>Instead, I would really like to run it against the live data so that I can see changes to it immediately, however, I am a little concerned that it might cause issues.</p> <p>Does anyone know if querying the live IIS logs would cause a problem?</p>
<p>It shouldn't cause any problems as I don't believe it locks the file. Why would it be a problem to copy the file though just to make sure? Even if you just copy it to a local folder, a batch file could make that easy, to copy the file and run it through logparser.</p> <p>But it should be fine against live files.</p>
How do I convert a file's format from Unicode to ASCII using Python? <p>I use a 3rd party tool that outputs a file in Unicode format. However, I prefer it to be in ASCII. The tool does not have settings to change the file format.</p> <p>What is the best way to convert the entire file format using Python?</p>
<p>You can convert the file easily enough just using the <code>unicode</code> function, but you'll run into problems with Unicode characters without a straight ASCII equivalent.</p> <p><a href="http://www.peterbe.com/plog/unicode-to-ascii">This blog</a> recommends the <code><a href="http://www.python.org/doc/2.5.2/lib/module-unicodedata.html">unicodedata </a></code> module, which seems to take care of roughly converting characters without direct corresponding ASCII values, e.g.</p> <pre><code>&gt;&gt;&gt; title = u"Klüft skräms inför på fédéral électoral große" </code></pre> <p>is typically converted to </p> <pre><code>Klft skrms infr p fdral lectoral groe </code></pre> <p>which is pretty wrong. However, using the <code>unicodedata</code> module, the result can be much closer to the original text:</p> <pre><code>&gt;&gt;&gt; import unicodedata &gt;&gt;&gt; unicodedata.normalize('NFKD', title).encode('ascii','ignore') 'Kluft skrams infor pa federal electoral groe' </code></pre>
I want to use an LDAP client here at work to talk to Active Directory. How can I discover on my own the IP I should be aiming at? <p>I know I could just ask, but that would involve bureaucratic entanglements.</p>
<p>Try ping or nslookup _ldap._tcp. with your AD Domain (e.g. _ldap._tcp.test.com) in a console (cmd.exe) - this should give you the AD Server IP.</p> <pre><code>_ldap._tcp.* </code></pre> <p>Is a general SRV entry made by your active directory server for locating LDAP (AD) servers in your domain. Your domain itself should match your Windows Login Domain. If this isn't the case right-click on your "My Computer" Icon on your Desktop or in your Explorer and click Properties. In the System Properties there is a Tab showing your Computer Name and its Network ID, which also contains its DOMAIN/WORKGROUP name. This is what you should append to the resource locator above.</p> <p>Btw. how did you get access to that machine without your Domain Login? :)</p> <p>Edit: The FOOAD name would be the "old" Domain name, and foo.something.something the new DNS based name - this should give you the server address. Also try the suggestion by Almond, which is more specific regarding the requested service.</p>
Watch for addition of a referenced library to a project (Visual Studio 2008 plug-in) <p>I am hoping someone can help me with this. What I have been looking around for but can't seem to find is if there is someway to add an event, or anything else that will allow a visual studio plug-in to watch for an external reference to be added to a currently open solution / project? </p> <p>Or even better yet would anyone happen to know of an add-in that automatically adds all controls from a referenced dll into the visual studio toolbox?</p> <p>Thanks.</p>
<p>Not exactly what you asked, but I've written a Visual Studio 2008 Integration Package, and if I recall correctly I could override the "add reference" method, as well as inherit the "reference node" and thus change its behavior, for example its constructor.</p> <p>This functionality might be missing from an add-in (which is more limited than an integration package), so you might consider writing a package instead.</p>
Unmanaged Threads Spring Quartz Websphere Hibernate <p>It appears that our implementation of using Quartz - JDBCJobStore along with Spring, Hibernate and Websphere is throwing unmanaged threads. </p> <p>I have done some reading and found a tech article from IBM stating that the usage of Quartz with Spring will cause that. They make the suggestion of using CommnonJ to address this issue.</p> <p>I have done some further research and the only examples I have seen so far all deal with the plan old JobStore that is not in a database.</p> <p>So, I was wondering if anyone has an example of the solution for this issue.</p> <p>Thanks</p>
<p>We have a working solution for this (two actually).</p> <p>1) Alter the quartz source code to use a WorkManager daemon thread for the main scheduler thread. It works, but requires changing quarts. We didn't use this though since we didn't want maintain a hacked version of quartz. (That reminds me, I was going to submit this to the project but completely forgot)</p> <p>2) Create a WorkManagerThreadPool to be used as the quartz threadpool. Implement the interface for the quartz ThreadPool, so that each task that is triggered within quartz is wrapped in a commonj Work object that will then be scheduled in the WorkManager. The key is that the WorkManager in the WorkManagerThreadPool has to be initialized before the scheduler is started, from a Java EE thread (such as servlet initialization). The WorkManagerThreadPool must then create a daemon thread which will handle all the scheduled tasks by creating and scheduling the new Work objects. This way, the scheduler (on its own thread) is passing the tasks to a managed thread (the Work daemon).</p> <p>Not simple, and unfortunately I do not have code readily available to include. </p>
How is your Development Environment Set up? <p>Curious to know how people set up their personal and/or work development environment, in terms of:</p> <p>Do you just have all of your developer tools (for example Visual Studio, SSMS, etc.) installed on your main operating system;<br> Do you use Virtual Machines to have a separate "clean" dev environment that consists only of the OS and one compiler you're working with;<br> Do you have multiple OS's in a multi-boot system;<br> Do you remote connect to a separate machine with your developer tools installed on there</p>
<p>It all depends on the type of the job i guess. Here is how my setup is:</p> <ol> <li>The main PC. The one on my desk. Has everything on it.</li> <li>The secondary machine. Runs Vista.</li> <li>A bunch of "Clean" VMs for testing. Typically 2 machines of each OS we support.</li> <li>A build machine. VM with no installed product. Just source code and some compilers.</li> <li>A dedicated "Server" to host the server app and the DB. [Our product is a client-server thingy]</li> </ol> <p>[On top of that, my primary and sec machines have the server and DB running too.]</p> <p>EDIT: By "clean" i mean that they only have a freshly installed OS on them, nothing else. These are non-persistent and go back to clean state on shutdown.</p>
Swing: Is there a way to differentiate between a user-caused ItemEvent and an application-caused one? <p>I'm working with a combobox in a Swing-based application, and I'm having a hard time figuring out what to do to differentiate between an ItemEvent that is generated from a user event vs one caused by the application. </p> <p>For instance, Lets say I have a combobox, '<code>combo</code>' and I'm listening for itemStateChanged events with my ItemListener, '<code>listener</code>'. When either a user changes the selection to item 2 or I execute the line (pseudocode):</p> <p><code>combo.setSelection(2)</code></p> <p>.. it seems like I'm not able to tell these events apart. </p> <p>That said, I'm no Swing expert by any means, so I thought I would ask. </p> <p>Thanks!</p>
<p>Whether the user selects Item 2, or the API calls setSelection(2), <b>the event will appear the same</b>.</p> <p>The solution to your problem might be in re-thinking what you want the itemStateChanged code to do when the selection changes. Why would your app work differently under each condition? Maybe there are similarities that you can use to your advantage.</p> <p><b>Be careful when using flags</b>. The itemStateChanged event will occur on the Event Dispatch Thread, which is a different thread than the one on which you'd set the state of the flag. This would mean that using a flag may not be 100% reliable.</p>
Flex : Filter a datagrid using a combobox value that is contained in a datafield <p>I have a filter in a combobox with a number of entries. Instead of filtering the datagrid with an exact match, I would like to take the selected value and only display records where the selected value is contained in the datafield. For example: the user selects a value of "New" and the datagrid displays records where the contents of the record could be "New User", "New Person", "This one is New" etc. I think that I need to use RegExp, but I cant work out how to get it to work. Thanks in advance, S... </p>
<p>Something like this should work:</p> <pre><code> public function filter(item:Object):Boolean{ var result:Boolean=false; if (item.name.toUpperCase().indexOf(cbo.selectedLabel.toUpperCase()) &gt;= 0) result=true; return result; } </code></pre> <p>This filter function will search the name attribute(or whatever you want to filter on) of the object passed in with the combobox's currently selected label and if it finds that value it will return true. So if it finds the word "New" anywhere in the string it will show up in the datagrid. IE: "New Person", "New User" will both show up once filtered.</p> <p>Hope this is what you are looking for.</p>
What is the best way to create user help documentation for an Excel VBA solution? <p>VBA solutions can vary widely in size. </p> <p>I would like to add <strong>user help</strong> documentation to all solutions but the level of effort to create and deploy the <strong>help</strong> needs to match the size of the solution.</p>
<p>You should check the <a href="http://www.mztools.com/v3/mztools3.aspx" rel="nofollow">VBA version of MZ-Tools</a>. It is an add-in for VBA that can automatically generate documentation from your code (function name, parameters, comments, subject, etc.). You can also use it to automatically generate line numbers, onError labels, etc. More on the automatic documenting feature can be found <a href="http://www.mztools.com/v3/onlinehelp/index.html?html_xml_documentation.htm" rel="nofollow">here</a>.</p> <p>It is free, easy, and very efficient. Once you notice how much you save time by using it, please do like me: donate. </p>
Irregular shaped Windows Form (C#) <p>What is the easiest way to do this? Is it possible with managed code?</p> <p>Thanks for your time.</p>
<pre><code>this.BackgroundImage = //Image this.FormBorderStyle = FormBorderStyle.None; this.Width = this.BackgroundImage.Width; this.Height = this.BackgroundImage.Height; this.TransparencyKey = Color.FromArgb(0, 255, 0); //Contrast Color </code></pre> <p>This allows you to create a form based on an image, and use transparency index to make it seem as though the form is not rectangular.</p>
What's a good Web Crawler tool <p>I need to index a whole lot of webpages, what good webcrawler utilities are there? I'm preferably after something that .NET can talk to, but that's not a showstopper.</p> <p>What I really need is something that I can give a site url to &amp; it will follow every link and store the content for indexing.</p>
<p>HTTrack -- <a href="http://www.httrack.com/">http://www.httrack.com/</a> -- is a very good Website copier. Works pretty good. Have been using it for a long time.</p> <p>Nutch is a web crawler(crawler is the type of program you're looking for) -- <a href="http://lucene.apache.org/nutch/">http://lucene.apache.org/nutch/</a> -- which uses a top notch search utility lucene.</p>
Nano hacks: most useful tiny programs you've coded or come across <p>It's the first <a href="http://oreilly.com/catalog/opensources/book/larry.html" rel="nofollow">great virtue</a> of programmers. All of us have, at one time or another automated a task with a bit of throw-away code. Sometimes it takes a couple seconds tapping out a one-liner, sometimes we spend an exorbitant amount of time automating away a two-second task and then never use it again.</p> <p>What tiny hack have you found useful enough to <b>reuse</b>? To make go so far as to make an alias for?</p> <p>Note: before answering, please check to make sure it's not already on <a href="http://stackoverflow.com/questions/68372/what-is-your-single-most-favorite-command-line-trick-using-bash">favourite command-line tricks using BASH</a> or perl/ruby one-liner questions. </p>
<p>i found this on dotfiles.org just today. it's very simple, but clever. i felt stupid for not having thought of it myself.</p> <pre><code>### ### Handy Extract Program ### extract () { if [ -f $1 ] ; then case $1 in *.tar.bz2) tar xvjf $1 ;; *.tar.gz) tar xvzf $1 ;; *.bz2) bunzip2 $1 ;; *.rar) unrar x $1 ;; *.gz) gunzip $1 ;; *.tar) tar xvf $1 ;; *.tbz2) tar xvjf $1 ;; *.tgz) tar xvzf $1 ;; *.zip) unzip $1 ;; *.Z) uncompress $1 ;; *.7z) 7z x $1 ;; *) echo "'$1' cannot be extracted via &gt;extract&lt;" ;; esac else echo "'$1' is not a valid file" fi } </code></pre>
NUnit assembly not found <p>I've used NUnit before, but not in a while, and never on this machine. I unzipped version 2.4.8 under Program Files, and I keep getting this error when trying to load my tests.</p> <blockquote> <p>Could not load file or assembly 'nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77' or one of its dependencies. The system cannot find the file specified**</p> </blockquote> <p>In order to simplify the problem, I've compiled the most basic possible test file.</p> <pre><code>using NUnit.Framework; namespace test { [TestFixture] public class Tester { [Test] public void ATest() { Assert.IsTrue( false, "At least the test ran!" ); } } } </code></pre> <p>I've added "C:\Program Files\NUnit-2.4.8-net-2.0\bin" to my PATH (and rebooted). Note that if I copy the test assembly into that folder, then</p> <pre> C:\Program Files\NUnit-2.4.8-net-2.0\bin>nunit-console test.dll </pre> <p>works, but</p> <pre> C:\Program Files\NUnit-2.4.8-net-2.0\bin>nunit-console c:\dev\nunit_test\test.dll </pre> <p>and</p> <pre> C:\dev\nunit_test>nunit_console test.dll </pre> <p>fail with the above error.</p> <p>Presumably I could get around this by copying the NUnit.Framework dll into my project's bin folder, but I don't remember having to do this in the past. Moreover, I get the same error in the GUI. Shouldn't the GUI know where the framework is located (that is, in the same folder)?</p> <p>@Scott, I'm not using Visual Studio. I use the following line to compile the test project.</p> <pre> %windir%\Microsoft.NET\Framework\v2.0.50727\csc.exe /r:"C:\Program Files\NUnit-2.4.8-net-2.0\bin\nunit.framework.dll" /t:library /out:test.dll test.cs </pre> <p>@devio, I tried both the msi and the zip with the same result.</p>
<p>Make sure you have added a reference to nunit.framework. If you have, then make sure the properties of that reference have the copy local property set to true.</p>
java 1.5 to 1.4 <p>What is the best way to convert existing jar (without source) written in java 1.5 into java 1.4.x?</p>
<p>Take a look at <a href="http://retroweaver.sourceforge.net/index.html">Retroweaver</a>. It will convert the classes or jar so that it can be run using a 1.4 JRE. Depending on the 1.5 features used, you won't need any additional retroweaver run-time.</p> <p>Retroweaver uses byte code enhancement. It sounds mysterious but it works. </p>
Is it worthwhile to use a bit vector/array rather than a simple array of bools? <p>When I want an array of flags it has typically pained me to use an entire byte (or word) to store each one, as would be the result if I made an array of <code>bool</code>s or some other numeric type that could be set to 0 or 1. But now I wonder whether using a structure that is more space-efficient is worth it given the (albeit hopefully very slight) additional overhead of shifting and bit testing.</p> <p>In my company we use Rogue Wave tools (though hopefully not for much longer) and it's their <code>RWBitVec</code> that I've used for this purpose up until now.</p>
<p>It's mostly about saving memory. If your array of bools is large enough that a 8x improvement on storage space is meaningful, then by all means, use a bitarray.</p> <p>Note that the memory access is pretty expensive compared to the shift/and, so the bitarray approach is slightly faster than the array-of-chars. Basically it comes down to memory versus programmer time. Remember that premature optimization is a waste of time. I'd use whichever approach is the easiest to develop, and then refactor only after it shows that it's a primary performance bottleneck.</p>
TCustomDataSet C++ Builder <p>I'm looking for an example of a TCustomDataSet implementation in C++ beyond the TTextDataset example that ships as an example project within C++ Builder.</p> <p>The TTextDataset is hard to learn from because the code is not documented very well and it only shows a single field example.</p> <p>I've created my own class that descends TDataSet and it mostly works however, the GUI controls (grids mostly) don't work 100% for certain use cases.</p> <p>Anyone have some good links on this topic...</p> <p>Here is a link to the example code I used to study from: <a href="http://195.19.138.139:3000/p/SOFTWARE/temp/CBuilder5/Examples/DBTasks/TextData/textdataset.cpp" rel="nofollow">http://195.19.138.139:3000/p/SOFTWARE/temp/CBuilder5/Examples/DBTasks/TextData/textdataset.cpp</a></p>
<p>I have a couple of examples. but unfortunately they are in Delphi, but you should get the idea: <a href="http://dn.codegear.com/article/20587" rel="nofollow">Example 1</a> <a href="http://www.carterconsulting.org.uk/Articles/cdspt3.PDF" rel="nofollow">Example 2</a></p> <p>The second one goes into a bit more explanation and is one I used to base a custom dataset on that did binding to UI (In delphi).</p>
Ruby and duck typing: design by contract impossible? <p>Method signature in Java:</p> <pre><code>public List&lt;String&gt; getFilesIn(List&lt;File&gt; directories) </code></pre> <p>similar one in ruby</p> <pre><code>def get_files_in(directories) </code></pre> <p>In the case of Java, the type system gives me information about what the method expects and delivers. In Ruby's case, I have <strong>no</strong> clue what I'm supposed to pass in, or what I'll expect to receive.</p> <p>In Java, the object must formally implement the interface. In Ruby, the object being passed in must respond to whatever methods are called in the method defined here. </p> <p>This seems highly problematic:</p> <ol> <li>Even with 100% accurate, up-to-date documentation, the Ruby code has to essentially expose its implementation, breaking encapsulation. "OO purity" aside, this would seem to be a maintenance nightmare.</li> <li>The Ruby code gives me <strong>no</strong> clue what's being returned; I would have to essentially experiment, or read the code to find out what methods the returned object would respond to.</li> </ol> <p>Not looking to debate static typing vs duck typing, but looking to understand how you maintain a production system where you have almost no ability to design by contract.</p> <h3>Update</h3> <p>No one has really addressed the exposure of a method's internal implementation via documentation that this approach requires. Since there are no interfaces, if I'm not expecting a particular type, don't I have to itemize every method I might call so that the caller knows what can be passed in? Or is this just an edge case that doesn't really come up?</p>
<p>What it comes down to is that <code>get_files_in</code> is a bad name <em>in Ruby</em> - let me explain.</p> <p>In java/C#/C++, and especially in objective C, the function arguments <em>are part of the name</em>. In ruby they are not.<br /> The fancy term for this is <a href="http://en.wikipedia.org/wiki/Method_overloading">Method Overloading</a>, and it's enforced by the compiler.</p> <p>Thinking of it in those terms, you're just defining a method called <code>get_files_in</code> and you're not actually saying what it should get files in. The arguments are <em>not</em> part of the name so you can't rely on them to identify it.<br /> Should it get files in a directory? a drive? a network share? This opens up the possibility for it to work in all of the above situations.</p> <p>If you wanted to limit it to a directory, then to take this information into account, you should call the method <code>get_files_in_directory</code>. Alternatively you could make it a method on the <code>Directory</code> class, which <a href="http://www.ruby-doc.org/core/">Ruby already does for you</a>.</p> <p>As for the return type, it's implied from <code>get_files</code> that you are returning an array of files. You don't have to worry about it being a <code>List&lt;File&gt;</code> or an <code>ArrayList&lt;File</code>>, or so on, because everyone just uses arrays (and if they've written a custom one, they'll write it to inherit from the built in array).</p> <p>If you only wanted to get one file, you'd call it <code>get_file</code> or <code>get_first_file</code> or so on. If you are doing something more complex such as returning <code>FileWrapper</code> objects rather than just strings, then there is a really good solution:</p> <pre><code># returns a list of FileWrapper objects def get_files_in_directory( dir ) end </code></pre> <p>At any rate. You can't enforce contracts in ruby like you can in java, but this is a subset of the wider point, which is that you can't enforce <em>anything</em> in ruby like you can in java. Because of ruby's more expressive syntax, you instead get to more clearly write english-like code which tells other people what your contract is (therein saving you several thousand angle brackets).</p> <p>I for one believe that this is a net win. You can use your newfound spare time to write some <a href="http://rspec.info">specs and tests</a> and come out with a much better product at the end of the day.</p>
Design Pattern for implementing plugins in your application? <p>What is the standard way for allowing and implementing a plugin system for your application?</p> <p>In my last application I made a simple interface for all plugins that they must implement. I then load all assemblies in the apps directory and toss out any that don't implement that interface.</p> <p>One of the methods in the interface is a DoWork() method that periodically gets called on all loaded assemblies to perform any actions the plugins may have.</p> <p>What is the "proper" way to do a plugin system? Do you just create an Interface for plugins? Should you periodically call a particular method in all plugins? Is there a more sophisticated way?</p> <p><hr /></p> <p>EDIT:</p> <p>Thank you Matt Hamilton for the reference to the System.Addin namespace. This will most likely be the way I implement my plugins. However, I am still curious about plugin architecture in general and wouldn't mind some background on the best way they should be designed, implmemented.. how you should call on them once loaded, etc.</p>
<p>Check out the System.AddIn namespace as per <a href="http://stackoverflow.com/questions/14278/how-to-load-plugins-in-net#14305">this response</a> to a similar question.</p>
Skipping the 'CompressResources' build step for XCode iPhone apps <p>Is it possible to set an iPhone XCode project to skip the 'CompressResources' build step?</p> <p>Specifically, I want to skip the stage where it runs pngcrush on all of my .png files, many of which don't survive the experience in a form which my app can read.</p> <p><strong>Edit:</strong> the version of pngcrush used creates png files which contain a non-standard 'mandatory, private' chunk which explicitly prevents decoding. I've modified my png reader to handle these files, but I'd still like a per-project method of skipping this step. One of the other side effects of pngcrush is that it doesn't save the colour value of transparent pixels, so alpha-ed textures show fringing at smaller mip levels.</p> <p>The iphone png format is described here: <a href="http://modmyi.com/wiki/index.php/Iphone_PNG_images">http://modmyi.com/wiki/index.php/Iphone_PNG_images</a>. In short,</p> <ul> <li>Skip the CgBI chunk</li> <li>Skip the zlib headers</li> <li>Swap BGR to RGB channel order</li> </ul> <p><strong>Edit:</strong> It appears it also premultiplies the alpha, so:</p> <ul> <li>Divide by alpha</li> </ul>
<p>You can add "IPHONE_OPTIMIZE_OPTIONS=-skip-PNGs" to your project settings to prevent the png mangling, but be careful with it, you might need to optimize the icon and Default.png separately then.</p>
How to use a function-based index on a column that contains NULLs in Oracle 10+? <p>Lets just say you have a table in Oracle:</p> <pre><code>CREATE TABLE person ( id NUMBER PRIMARY KEY, given_names VARCHAR2(50), surname VARCHAR2(50) ); </code></pre> <p>with these function-based indices:</p> <pre><code>CREATE INDEX idx_person_upper_given_names ON person (UPPER(given_names)); CREATE INDEX idx_person_upper_last_name ON person (UPPER(last_name)); </code></pre> <p>Now, given_names has no NULL values but for argument's sake last_name does. If I do this:</p> <pre><code>SELECT * FROM person WHERE UPPER(given_names) LIKE 'P%' </code></pre> <p>the explain plan tells me its using the index but change it to:</p> <pre><code>SELECT * FROM person WHERE UPPER(last_name) LIKE 'P%' </code></pre> <p>it doesn't. The Oracle docs say that to use the function-based index will only be used when several conditions are met, one of which is ensuring there are no NULL values since they aren't indexed.</p> <p>I've tried these queries:</p> <pre><code>SELECT * FROM person WHERE UPPER(last_name) LIKE 'P%' AND UPPER(last_name) IS NOT NULL </code></pre> <p>and</p> <pre><code>SELECT * FROM person WHERE UPPER(last_name) LIKE 'P%' AND last_name IS NOT NULL </code></pre> <p>In the latter case I even added an index on last_name but no matter what I try it uses a full table scan. Assuming I can't get rid of the NULL values, how do I get this query to use the index on UPPER(last_name)?</p>
<p>The index can be used, though the optimiser may have chosen not to use it for your particular example:</p> <pre><code>SQL&gt; create table my_objects 2 as select object_id, object_name 3 from all_objects; Table created. SQL&gt; select count(*) from my_objects; 2 / COUNT(*) ---------- 83783 SQL&gt; alter table my_objects modify object_name null; Table altered. SQL&gt; update my_objects 2 set object_name=null 3 where object_name like 'T%'; 1305 rows updated. SQL&gt; create index my_objects_name on my_objects (lower(object_name)); Index created. SQL&gt; set autotrace traceonly SQL&gt; select * from my_objects 2 where lower(object_name) like 'emp%'; 29 rows selected. Execution Plan ---------------------------------------------------------- ------------------------------------------------------------------------------------ | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| ------------------------------------------------------------------------------------ | 0 | SELECT STATEMENT | | 17 | 510 | 355 (1)| | 1 | TABLE ACCESS BY INDEX ROWID| MY_OBJECTS | 17 | 510 | 355 (1)| |* 2 | INDEX RANGE SCAN | MY_OBJECTS_NAME | 671 | | 6 (0)| ------------------------------------------------------------------------------------ </code></pre> <p>The documentation you read was presumably pointing out that, just like any other index, all-null keys are not stored in the index.</p>
Any viewstate implementation for JSP-Servlet app? <p>Do you know any implementation / technique which would provide similar behavior as Viewstate provides in ASP.NET. (Serializing the data into hidden field within the HTML form).</p> <p>I am using only JSP, Servlet, and Spring MVC.</p>
<p>I think the <a href="http://www.stripesframework.org/" rel="nofollow">Stripes</a> framework provides that.</p>
What are the alternatives to using Expand in a LINQ to ADO.net Data Service Query? <p>I am wondering if there are any alternatives to using the Expand key word when performing an LINQ to ADO.net Data Services query. The expand method does get me the data I am interested in, but it requires me to know all of the sub-objects that I am going to be working with in advance. My absolute preference would be that those sub-objects would be lazy loaded for me when I access them, but this doesn't look to be an option (I could add this lazy loading to the get on that sub-object property, but it gets wiped out when I do an update of the data service reference).</p> <p>Does anyone have any suggestions/best practices/alternatives for this situation? Thanks.</p> <p>===== Example Code using Member that has a MailingAddress =====</p> <p>Works: </p> <pre><code>var me = (from m in ctx.Member.Expand("MailingAddress") where m.MemberID == 10000 select m).First(); MessageBox.Show(me.MailingAddress.Street); </code></pre> <p>Would Prefer (would really like if this then went and loaded the MailingAddress)</p> <pre><code>var me = (from m in ctx.Member where m.MemberID == 10000 select m).First(); MessageBox.Show(me.MailingAddress.Street); </code></pre> <p>Or at least (note: something similar to this, with MailingAddressReference, works on the server side if I do so as LINQ to Entities in a Service Operation)</p> <pre><code>var me = (from m in ctx.Member where m.MemberID == 10000 select m).First(); if (!(me.MailingAddress.IsLoaded())) me.MailingAddress.Load() MessageBox.Show(me.MailingAddress.Street); </code></pre>
<p>Loading sub-objects via ADO.net Data Services seem to have two choices:</p> <h2>Eager Loading</h2> <p>Accomplished by .Expand("[MemberVariableName]") on the LINQ to Data Services example</p> <pre><code>var me = (from m in ctx.Member.Expand("MailingAddress") where m.MemberID == 10000 select m).First(); MessageBox.Show(me.MailingAddress.Street); </code></pre> <h2>Lazy Loading</h2> <p>Accomplished by calling .LoadProperty on the context and passing it the variable and the property that should be lazy loaded.</p> <pre><code>var me = (from m in ctx.Member where m.MemberID == 10000 select m).First(); ctx.LoadProperty(myMember, "MailingAddresses"); MessageBox.Show(me.MailingAddress.Street); </code></pre>
How do I estimate SQL Server index sizes <p>While estimating straight row and table sizes are fairly simple math, we find it challenging to guess just how much space each index will occupy (for a given table size). What areas can we learn to calculate a better estimate and growth rate for indexes?</p>
<p>An index leaf has a preamble identifying the data page (7 bytes plus some directory information for variable length columns, if any) plus a copy of the key value (s) which will be the same size as the table data for those columns. There's one for each row in the table. The higher up levels of the index are much smaller, usually less than 1% of the leaves unless you are indexing a very wide key.</p> <p>The fill factor leaves some space free so that updates and inserts do not generate excessive leaf splitting traffic.</p> <p>EDIT: <a href="http://msdn.microsoft.com/en-us/library/ms189051.aspx">This MSDN link</a> describes the page-level structures, although it's a bit light on the format of the individual index rows. <a href="https://www.blackhat.com/presentations/bh-usa-07/Fowler/Presentation/bh-usa-07-fowler.pdf">This presentation</a> goes into the physical format of disk log entries and data pages to some extent. <a href="http://www.valdosta.edu/~sfares/cs499/cs499.d.chapter11.a.wi8.html">This one</a> more detail and includes the index data structures. Numeric and fixed length columns have the size it says on the box; you would have to estimate the average size of varchar columns. </p> <p>For reference, some documents on Oracle's block format can be found <a href="http://www.orafaq.com/papers/dissassembling_the_data_block.pdf">Here</a> and <a href="http://download.oracle.com/docs/cd/B10501_01/server.920/a96524/c03block.htm#2595">Here</a>.</p>
SecurityException thrown when app starts from remote folder <p>I have an app written in C# that lies on a network share. When I run it from a local drive, everything works fine. When I start it from the remote share, calls like</p> <pre><code>try { System.Reflection.Assembly.GetExecutingAssembly(); System.IO.Directory.GetCurrentDirectory(); } </code></pre> <p>throw a SecurityException 'Request failed'.</p> <p>What causes this, what is the difference between an app that is started locally and one that is started from a remote location?</p>
<p>This is due to <a href="http://msdn.microsoft.com/en-us/library/930b76w0.aspx" rel="nofollow">CAS</a>; code started from the local machine has much more trust than code in the intranet, which in turn has more trust that code from the internet.</p> <p>IIRC, with the latest SP (3.5SP1?) if you have <em>mapped</em> the share (i.e. as F:) it is trusted; otherwise you will need to either:</p> <p>a: apply a <a href="http://msdn.microsoft.com/en-us/library/cb6t8dtz(VS.80).aspx" rel="nofollow">caspol</a> change to all clients (yeuck)</p> <p>b: use <a href="http://msdn.microsoft.com/en-us/library/t71a733d(VS.80).aspx" rel="nofollow">ClickOnce</a> to deploy the app, and run the .application instead (yay!)</p> <p>The point is that ClickOnce allows you to sign the app and state your security policy (even if you demand full trust).</p>
Lock / Prevent edit of source files on Linux using C++ <p>How can I programmatically lock/unlock, or otherwise prevent/enable editing, a source file on Linux using C++.</p> <p>I want to be able to lock source file so that if I open it in an editor it will not allow me to save back to the same source file.</p> <p>I am thinking of maybe changing the permissions to read-only (and change it back to read-write later): how do I do that from C++?</p>
<p>Try man fchmod:</p> <pre> NAME chmod, fchmod - change permissions of a file SYNOPSIS #include &lt;sys/types.h&gt; #include &lt;sys/stat.h&gt; int chmod(const char *path, mode_t mode); int fchmod(int fildes, mode_t mode); </pre>
Best language for a non-programmer tech support person to learn <p>I have a colleague that handles tech support, and her role involves a lot of transforming ASCII files from one format to another and occasionally reporting on them. The formats tend to be largely plain text with an occasional bit of XML. She regularly gets me to write small scripts to do these transformatsions, and also batch files for repeating the operation for collections of files in different locations. Currently she uses Crystal Reports to do much of this but it is a bit of a dog.</p> <p>Could anyone recommend a language, or alternative tool, that she could learn to become more self reliant in this role. It must primarily be very easy to learn at a starting out level, be good at manipulating text files, and run in a Windows environment. Ideally, it would also be freely available, such that she could pass her scripts onto her end users.</p>
<p>I would recommend Python for tasks like this. </p> <p>Syntactically it is clear and it handles reading, manipulating test files well. Also it provides excellent support for XML. </p>
LINQ to XML gets no data with schema set <p>I am trying to get some XML data with LINQ, but running into a problem.</p> <p>I am using a schema, which is set in the attribute xmlns ...</p> <pre><code>&lt;CarsForSale xmlns="http://schemas.sharplogic.net/CarSales.xsd"&gt; &lt;CarForSale&gt; </code></pre> <p>There are many CarForSale elements.</p> <p>When the schema is set and I do this...</p> <pre><code>XElement doc = XElement.Load(HttpContext.Current.Server.MapPath("App_Data/XML/CarsForSale.xml")); var cars2 = from d in doc.Descendants("CarForSale") select d; </code></pre> <p>Then I get in the results i get Enumeration yielded no results </p> <p>Strip the xmlns out of the XML file and the data comes back as expected??</p> <p>Any ideas?</p> <p>Thx</p>
<p>You need to prepend the namespace:</p> <pre><code>var ns = "http://schemas.sharplogic.net/CarSales.xsd"; var cars2 = from d in doc.Descendants(ns + "CarForSale") select d; </code></pre> <p>otherwise search by local name:</p> <pre><code>var cars2 = from d in doc.Descendants() where d.Name.LocalName == "CarForSale" select d; </code></pre>
Questions about exporting and importing flatfiles (txt, csv) in SQL Server 2005 <ol> <li>What's the best delimiter to use when exporting data?</li> <li>What's the best way to work with NULL data if you have an INT field in the table?</li> </ol>
<p>I'm not sure what the asker (nice name, :JPnoui38f) is trying to do. Sql Server management Studio has the ability to dump your data in a number of different ways. You don't have to worry about how to handle nulls or what delimeter to use. The tools take care of that.</p> <p>Here's an <a href="http://www.databasejournal.com/features/mssql/article.php/3580216" rel="nofollow">article about the Import/Export wizard</a>. Another option is the <a href="http://www.microsoft.com/downloads/details.aspx?familyid=56E5B1C5-BF17-42E0-A410-371A838E570A" rel="nofollow">database publishing wizard</a>, which dumps your data to sql scripts.</p>
Accessing python egg's own metadata <p>I've produced a python egg using setuptools and would like to access it's metadata at runtime. I currently got working this:</p> <pre><code>import pkg_resources dist = pkg_resources.get_distribution("my_project") print(dist.version) </code></pre> <p>but this would probably work incorrectly if I had multiple versions of the same egg installed. And if I have both installed egg and development version, then running this code from development version would pick up version of the installed egg. </p> <p>So, how do I get metadata for <em>my</em> egg not some random matching egg installed on my system? </p>
<p>I am somewhat new to Python as well, but from what I understand: </p> <p>Although you can install multiple versions of the "same" egg (having the same name), only one of them will be available to any particular piece of code at runtime (based on your discovery method). So if your egg is the one calling this code, it must have already been selected as <em>the</em> version of <code>my_project</code> for this code, and your access will be to your own version.</p>
Compiling in c++ with mysql, pthreads and gtk <p>Have someone ever done this before???</p> <p>I am trying to use MinGW to compile a program using the MySQL libraries. I keep getting the message that the function 'rint' is redefined. Ok it's true that the function is in both files config-win.h, from MySQL and math.h from the standard library, but both of them are suppose to be libraries with no problems.</p> <p>After breaking my head a while i tried even this, that wont compile: </p> <pre><code>#include &lt;iostream&gt; #include &lt;my_global.h&gt; #include &lt;mysql.h&gt; using namespace std; int main() { cout &lt;&lt; "Hello World!!!" &lt;&lt; endl; // prints Hello World!!! return 0; } </code></pre> <p>And this is the command as well as the output i issue for compiling</p> <p><strong>i586-mingw32msvc-cc -I/usr/include/mysql probando.cpp -w</strong></p> <pre><code>In file included from /usr/include/mysql/my_global.h:73, from probando.cpp:10: /usr/include/mysql/config-win.h: In function ‘double rint(double)’: /usr/include/mysql/config-win.h:229: error: redefinition of ‘double rint(double)’ /usr/lib/gcc/i586-mingw32msvc/4.2.1-sjlj/../../../../i586-mingw32msvc/include/math.h:635: error: ‘double rint(double)’ previously defined here </code></pre> <p>I have tested it both in WindowsXP with MinGW, with the MySQL libraries properly transformed in .a libraries and in Linux (the output is from Linux, pretty much the same than in Windows) with MinGW32.</p> <p>People... I am running out of options... Any clues?? Has someone worked before with MySQL and MinGW?? May it work with Cygwin?? </p> <p>Thanks in advance if you take the time to answer.</p>
<p>Also a guess, but it appears as if math.h AND config-win.h have a function called rint, make sure that there aren't two functions with the same names. </p> <p>BTW, because I am not entirely sure, I'm making this community editable, feel free to edit this post if I am incorrect.</p>
Is there a way to get DateTime value from timestamp type column? <p>I need a select from table which does not have column that tells when row was inserted, only <code>timestamp</code> column (values like: 0x0000000000530278). Some data was imported to the table yesterday and now I need to find out what exactly was imported :(</p> <p>Is there a way to do it using only <code>timestamp</code> info? <a href="http://www.sqlhacks.com/index.php/Dates/Timestamp">Here</a> I found that:</p> <ul> <li>Timestamp is a 8 bytes sequential Hex number, that has nothing to do with neither the date nor the time.</li> <li>To get the current value of timestamp, use: @@DBTS.</li> </ul> <p>Perhaps there is a way to find what was <code>timestamp</code> value around specific time? That would help to form a select. Or maybe there is a well known solution?</p>
<p>The Transact-SQL timestamp data type is a binary data type with no time-related values.</p> <p>So to answer your question: <em>Is there a way to get DateTime value from timestamp type column?</em></p> <p>The answer is: <em>No</em></p>
How do I embed a Google map into a Flash website? <p>I would like to include a Google map in a Flash site I am building. I would like to retain as much of the zoom, print, copy/send url, direction functionality as is practically possible. Please could somebody advise the best way to do this? Thanks.</p>
<p>See <a href="http://code.google.com/apis/maps/documentation/flash/" rel="nofollow">Google Maps API for Flash</a></p> <blockquote> <p>This API lets Flex developers embed Google Maps in Flash applications. Similar to the JavaScript version, this ActionScript API provides a number of utilities for manipulating and adding content to maps through a variety of services, enabling you to embed robust, interactive maps applications on your website.</p> </blockquote>
DDD and Asynchronous Repositories <p>We're working on a rich client (written in Flex) that is connected to a Java backend, using both RMI and JMS. I was thinking about implementing the client in a DDD fashion so that it has Repositories for the CRUD operations on the domain objects.</p> <p>The problem is however that all backend communication happens asynchronous and there is no way for me to force the client for waiting to continue untill it received a response. That means that, at a low level, I can call a method on a Remote Object and I get a AsyncToken as a return value. I can then listen to events on the asynctoken to see whether the call has passed or failed. This however breaks the main idea behind a repository, to hide the technical details from the client.</p> <p>There might be 2 options I guess:</p> <ol> <li>have the methods on the repository return the asynctoken, which seems like a messy solution to me</li> <li>have the methods return an empty collection (for a findAll for instance) that will get filled when the response is received.</li> </ol> <p>Both have pros and cons and I would like to get some input from you guys.</p> <p>(taking this further, what would be good caching strategies? Dependind on the situation, I don't want the repository to call the server each time I request all entities from it. How would that affect the signature of the methods on the repository.)</p>
<p>Flex and Flash Remoting is inherently asynchronous so fighting against that paradigm is going to give you a ton of trouble. Our service delegates return AsyncToken from every method and we've never had a problem with it.</p> <p>If you want to ensure that the application doesn't render a new view or perform some other logic until the result/fault comes back, you could do the following:</p> <ol> <li>Attach an event listener for a custom event that will invoke your "post result/fault code"</li> <li>Make the async call</li> <li>Handle the result/fault</li> <li>Dispatch the custom event to trigger your listener from #1</li> </ol> <p>Bear in mind this going to lead to a lot of annoying boilterplate code every time you make an async call. I would consider very carefully whether you really need a synchronous execution path.</p>
What is the best way to remember technical knowledge in the organization <ul> <li>Do we use a company wiki?</li> <li>how about you save the technical documents as part of source control and then have links to them from various source files (to understand how this works see article ... in directory...)</li> </ul> <p>what are the pros and cons of these and other methods? any good tools for this purpose?</p> <p><strong>If you recommend a wiki,</strong> what Wikis would you recommend to use? internal? hosted? free? paid?</p>
<p>I'd recommend using a wiki. It works extremely well as a central documentation source and has built-in revision control. Also you can reference the docs in the code via URLs.</p>
IP subnet verification in JSP <p>I have the following JSP code, that protects my web page and displays it only to know IP's</p> <pre><code>String ip_h = request.getRemoteAddr(); String host_h = request.getRemoteHost(); String iplist[] = new String[1]; iplist[0] = "127.0.0.1"; iplist[1] = "10.217.106.248"; int count = iplist.length; boolean flag = false; int zz = 0; //return; System.out.println(host_h); while ( (flag==false) &amp;&amp; ( zz &lt; count) ) { if (ip_h.equals(iplist[zz]) || host_h.equals(iplist[zz]) ) { flag = true; } zz++; } </code></pre> <p>However, I would to rather check for subnet ranges, i.e. all users belonging to 10.217.0.0/16 are allowed.</p> <p>How do I do this?</p>
<p>IP addresses (at least, IPv4 addresses) are really intended to be represented as 32-bit integers. If you convert the IP address to an integer first, checking subnet ranges becomes a relatively simple matter of checking (in your example) whether the first 16 bits match the first 16 bits of the range. </p>
User configurable security in multi-tenant ASP.NET website <p>We are building a multi-tenant website in ASP.NET, and we must let each customer configure their own security model. They must be able to define their own roles, and put users in those roles. What is the best way to do this?</p> <p>There are tons of simple examples of page_load events that have code like:</p> <pre><code> if (!user.InGroup("Admin") Response.Redirect("/NoAccess.aspx"); </code></pre> <p>But that hard codes the groups and permissions in the code. How can I make it user configurable?</p>
<p>Perhaps put the configurable roles in a DB table, where you store the roles and tenant, and then the PagePermissions in another table, for example:</p> <pre><code>Table "Role" RoleId, TenantId, Role Table "PagePermissions" PageId, RoleId Table "UserRoles" UserId, RoleId </code></pre> <p>Then in the page load check whether the User is in a RoleId that has permissions for that page, for example:</p> <pre><code>Select PageId FROM UserRoles UR INNER JOIN PagePermissions PP ON UR.RoleId = PP.RoleID WHERE UR.Userid = @UserId AND PP.PageID = @PageId </code></pre> <p>If there are no rows returned then deny the user.</p>